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 $package_re $component_re $deliberately_re
56 $distro_re $versiontag_re $series_filename_re
57 $extra_orig_namepart_re
60 $ffq_refprefix $gdrlast_refprefix
61 initdebug enabledebug enabledebuglevel
63 $debugprefix *debuglevel *DEBUG
64 shellquote printcmd messagequote
65 $negate_harmful_gitattrs
66 changedir git_slurp_config_src
67 gdr_ffq_prev_branchinfo
69 # implicitly uses $main::us
70 %EXPORT_TAGS = ( policyflags => [qw(NOFFCHECK FRESHREPO NOCOMMITCHECK)],
71 playground => [qw(record_maindir $maindir $local_git_cfg
72 $maindir_gitdir $maindir_gitcommon
74 ensure_a_playground)]);
75 @EXPORT_OK = ( @{ $EXPORT_TAGS{policyflags} },
76 @{ $EXPORT_TAGS{playground} } );
81 our $package_re = '[0-9a-z][-+.0-9a-z]*';
82 our $component_re = '[0-9a-zA-Z][-+.0-9a-zA-Z]*';
83 our $deliberately_re = "(?:TEST-)?$package_re";
84 our $distro_re = $component_re;
85 our $versiontag_re = qr{[-+.\%_0-9a-zA-Z/]+};
86 our $branchprefix = 'dgit';
87 our $series_filename_re = qr{(?:^|\.)series(?!\n)$}s;
88 our $extra_orig_namepart_re = qr{[-0-9a-z]+};
89 our $git_null_obj = '0' x 40;
90 our $ffq_refprefix = 'ffq-prev';
91 our $gdrlast_refprefix = 'debrebase-last';
93 # policy hook exit status bits
94 # see dgit-repos-server head comment for documentation
95 # 1 is reserved in case something fails with `exit 1' and to spot
96 # dynamic loader, runtime, etc., failures, which report 127 or 255
97 sub NOFFCHECK () { return 0x2; }
98 sub FRESHREPO () { return 0x4; }
99 sub NOCOMMITCHECK () { return 0x8; }
104 our $negate_harmful_gitattrs =
105 "-text -eol -crlf -ident -filter -working-tree-encoding";
106 # ^ when updating this, alter the regexp in dgit:is_gitattrs_setup
108 our $forkcheck_mainprocess;
110 sub forkcheck_setup () {
111 $forkcheck_mainprocess = $$;
114 sub forkcheck_mainprocess () {
115 # You must have called forkcheck_setup or setup_sigwarn already
116 getppid != $forkcheck_mainprocess;
119 sub setup_sigwarn () {
121 $SIG{__WARN__} = sub {
122 confess $_[0] if forkcheck_mainprocess;
128 open DEBUG, ">/dev/null" or die $!;
132 open DEBUG, ">&STDERR" or die $!;
137 sub enabledebuglevel ($) {
138 my ($newlevel) = @_; # may be undef (eg from env var)
142 return unless $newlevel;
143 $debuglevel = $newlevel;
148 print DEBUG $debugprefix, @_ or die $! if $debuglevel>0;
151 sub messagequote ($) {
157 s{[\000-\037\177]}{ sprintf "\\x%02x", ord $& }ge;
164 defined or confess 'internal error' foreach @_;
167 if (!length || m{[^-=_./:0-9a-z]}i) {
174 return join ' ', @out;
179 my $intro = shift @_;
180 print $fh $intro," " or die $!;
181 print $fh shellquote @_ or die $!;
182 print $fh "\n" or die $!;
186 my $extraprefix = shift @_;
187 printcmd(\*DEBUG,$debugprefix.$extraprefix,@_) if $debuglevel>0;
190 sub dep14_version_mangle ($) {
192 # DEP-14 patch proposed 2016-11-09 "Version Mangling"
194 $v =~ s/\.(?=\.|$|lock$)/.#/g;
198 sub debiantag_old ($$) {
199 my ($v,$distro) = @_;
200 return "$distro/". dep14_version_mangle $v;
203 sub debiantag_new ($$) {
204 my ($v,$distro) = @_;
205 return "archive/$distro/".dep14_version_mangle $v;
208 sub debiantags ($$) {
209 my ($version,$distro) = @_;
210 map { $_->($version, $distro) } (\&debiantag_new, \&debiantag_old);
213 sub server_branch ($) { return "$branchprefix/$_[0]"; }
214 sub server_ref ($) { return "refs/".server_branch($_[0]); }
216 sub stat_exists ($) {
219 return 0 if $!==&ENOENT;
224 $::us // ($0 =~ m#[^/]*$#, $&);
228 my $s = "error: @_\n";
230 my $prefix = _us().": ";
231 $s =~ s/^/$prefix/gm;
240 my ($dir) = @_; # does not create parents
241 return if mkdir $dir;
242 return if $! == EEXIST;
243 die "mkdir $dir: $!";
248 defined $d or fail "getcwd failed: $!";
252 sub executable_on_path ($) {
254 return 1 if $program =~ m{/};
255 my @path = split /:/, ($ENV{PATH} // "/usr/local/bin:/bin:/usr/bin");
256 foreach my $pe (@path) {
257 my $here = "$pe/$program";
258 return $here if stat_exists $here && -x _;
263 our @signames = split / /, $Config{sig_name};
265 sub waitstatusmsg () {
267 return "terminated, reporting successful completion";
268 } elsif (!($? & 255)) {
269 return "failed with error exit status ".WEXITSTATUS($?);
270 } elsif (WIFSIGNALED($?)) {
271 my $signum=WTERMSIG($?);
272 return "died due to fatal signal ".
273 ($signames[$signum] // "number $signum").
274 ($? & 128 ? " (core dumped)" : ""); # POSIX(3pm) has no WCOREDUMP
276 return "failed with unknown wait status ".$?;
280 sub failedcmd_report_cmd {
281 my $intro = shift @_;
282 $intro //= "failed command";
283 { local ($!); printcmd \*STDERR, _us().": $intro:", @_ or die $!; };
286 sub failedcmd_waitstatus {
288 return "failed to fork/exec: $!";
290 return "subprocess ".waitstatusmsg();
292 return "subprocess produced invalid output";
297 # Expects $!,$? as set by close - see below.
298 # To use with system(), set $?=-1 first.
300 # Actual behaviour of perl operations:
301 # success $!==0 $?==0 close of piped open
302 # program failed $!==0 $? >0 close of piped open
303 # syscall failure $! >0 $?=-1 close of piped open
304 # failure $! >0 unchanged close of something else
305 # success trashed $?==0 system
306 # program failed trashed $? >0 system
307 # syscall failure $! >0 unchanged system
308 failedcmd_report_cmd undef, @_;
309 fail failedcmd_waitstatus();
315 failedcmd @_ if system @_;
319 my ($first_shell, @cmd) = @_;
320 return qw(sh -ec), $first_shell.'; exec "$@"', 'x', @cmd;
323 sub cmdoutput_errok {
324 confess Dumper(\@_)." ?" if grep { !defined } @_;
326 open P, "-|", @_ or die "$_[0] $!";
329 { local $/ = undef; $d = <P>; }
331 if (!close P) { printdebug "=>!$?\n"; return undef; }
333 if ($debuglevel > 0) {
336 my $more = (length $' ? '...' : ''); #');
337 $dd =~ s{[^\n -~]|\\}{ sprintf "\\x%02x", ord $& }ge;
338 printdebug "=> \`$dd'",$more,"\n";
344 my $d = cmdoutput_errok @_;
345 defined $d or failedcmd @_;
349 sub link_ltarget ($$) {
351 lstat $old or return undef;
353 $old = cmdoutput qw(realpath --), $old;
355 my $r = link $old, $new;
356 $r = symlink $old, $new if !$r && $!==EXDEV;
357 $r or die "(sym)link $old $new: $!";
362 my $h = Digest::SHA->new(256);
364 return $h->hexdigest();
367 sub git_rev_parse ($) {
368 return cmdoutput qw(git rev-parse), "$_[0]~0";
371 sub git_cat_file ($;$) {
372 my ($objname, $etype) = @_;
373 # => ($type, $data) or ('missing', undef)
374 # in scalar context, just the data
375 # if $etype defined, dies unless type is $etype or in @$etype
376 our ($gcf_pid, $gcf_i, $gcf_o);
378 my ($gtype, $data) = @_;
380 $etype = [$etype] unless ref $etype;
381 confess "$objname expected @$etype but is $gtype"
382 unless grep { $gtype eq $_ } @$etype;
384 return ($gtype, $data);
387 my @cmd = qw(git cat-file --batch);
388 debugcmd "GCF|", @cmd;
389 $gcf_pid = open2 $gcf_o, $gcf_i, @cmd or die $!;
391 printdebug "GCF>| ", $objname, "\n";
392 print $gcf_i $objname, "\n" or die $!;
394 printdebug "GCF<| ", $x;
395 if ($x =~ m/ (missing)$/) { return $chk->($1, undef); }
396 my ($type, $size) = $x =~ m/^.* (\w+) (\d+)\n/ or die "$objname ?";
398 (read $gcf_o, $data, $size) == $size or die "$objname $!";
400 $x eq "\n" or die "$objname ($_) $!";
401 return $chk->($type, $data);
404 sub git_get_symref (;$) {
405 my ($symref) = @_; $symref //= 'HEAD';
406 # => undef if not a symref, otherwise refs/...
407 my @cmd = (qw(git symbolic-ref -q HEAD));
408 my $branch = cmdoutput_errok @cmd;
409 if (!defined $branch) {
410 $?==256 or failedcmd @cmd;
417 sub git_for_each_ref ($$;$) {
418 my ($pattern,$func,$gitdir) = @_;
419 # calls $func->($objid,$objtype,$fullrefname,$reftail);
420 # $reftail is RHS of ref after refs/[^/]+/
421 # breaks if $pattern matches any ref `refs/blah' where blah has no `/'
422 # $pattern may be an array ref to mean multiple patterns
423 $pattern = [ $pattern ] unless ref $pattern;
424 my @cmd = (qw(git for-each-ref), @$pattern);
425 if (defined $gitdir) {
426 @cmd = ('sh','-ec','cd "$1"; shift; exec "$@"','x', $gitdir, @cmd);
428 open GFER, "-|", @cmd or die $!;
432 printdebug "|> ", $_, "\n";
433 m#^(\w+)\s+(\w+)\s+(refs/[^/]+/(\S+))$# or die "$_ ?";
434 $func->($1,$2,$3,$4);
436 $!=0; $?=0; close GFER or die "$pattern $? $!";
439 sub git_get_ref ($) {
440 # => '' if no such ref
443 s{^refs/}{[r]efs/} or die "$refname $_ ?";
444 return cmdoutput qw(git for-each-ref --format=%(objectname)), $_;
447 sub git_for_each_tag_referring ($$) {
448 my ($objreferring, $func) = @_;
449 # calls $func->($tagobjid,$refobjid,$fullrefname,$tagname);
450 printdebug "git_for_each_tag_referring ",
451 ($objreferring // 'UNDEF'),"\n";
452 git_for_each_ref('refs/tags', sub {
453 my ($tagobjid,$objtype,$fullrefname,$tagname) = @_;
454 return unless $objtype eq 'tag';
455 my $refobjid = git_rev_parse $tagobjid;
457 !defined $objreferring # caller wants them all
458 or $tagobjid eq $objreferring
459 or $refobjid eq $objreferring;
460 $func->($tagobjid,$refobjid,$fullrefname,$tagname);
464 sub git_check_unmodified () {
465 foreach my $cached (qw(0 1)) {
466 my @cmd = qw(git diff --quiet);
467 push @cmd, qw(--cached) if $cached;
470 $!=0; $?=-1; system @cmd;
475 ? "git index contains changes (does not match HEAD)"
476 : "working tree is dirty (does not match HEAD)";
483 sub is_fast_fwd ($$) {
484 my ($ancestor,$child) = @_;
485 my @cmd = (qw(git merge-base), $ancestor, $child);
486 my $mb = cmdoutput_errok @cmd;
488 return git_rev_parse($mb) eq git_rev_parse($ancestor);
490 $?==256 or failedcmd @cmd;
497 printdebug "CD $newdir\n";
498 chdir $newdir or confess "chdir: $newdir: $!";
501 sub git_slurp_config_src ($) {
503 # returns $r such that $r->{KEY}[] = VALUE
504 my @cmd = (qw(git config -z --get-regexp), "--$src", qw(.*));
507 local ($debuglevel) = $debuglevel-2;
511 open GITS, "-|", @cmd or die $!;
514 printdebug "=> ", (messagequote $_), "\n";
516 push @{ $r->{$`} }, $'; #';
520 or ($!==0 && $?==256)
525 sub gdr_ffq_prev_branchinfo ($) {
527 # => ('status', "message", [$symref, $ffq_prev, $gdrlast])
529 # branch message is undef
530 # weird-symref } no $symref,
531 # notbranch } no $ffq_prev
532 return ('detached', 'detached HEAD') unless defined $symref;
533 return ('weird-symref', 'HEAD symref is not to refs/')
534 unless $symref =~ m{^refs/};
535 my $ffq_prev = "refs/$ffq_refprefix/$'";
536 my $gdrlast = "refs/$gdrlast_refprefix/$'";
537 printdebug "ffq_prev_branchinfo branch current $symref\n";
538 return ('branch', undef, $symref, $ffq_prev, $gdrlast);
541 # ========== playground handling ==========
545 # $maindir user's git working tree
546 # playground area in .git/ where we can make files, unpack, etc. etc.
547 # playtree git working tree sharing object store with the user's
548 # inside playground, or identical to it
552 # $local_git_cfg hash of arrays of values: git config from $maindir
554 # expected calling pattern
559 # must be run in directory containing .git
560 # assigns to $maindir if not already set
561 # also calls git_slurp_config_src to record git config
562 # in $local_git_cfg, unless it's already set
564 # fresh_playground SUBDIR_PATH_COMPONENTS
565 # e.g fresh_playground 'dgit/unpack' ('.git/' is implied)
566 # default SUBDIR_PATH_COMPONENTS is playground_subdir
567 # calls record_maindir
568 # sets up a new playground (destroying any old one)
569 # returns playground pathname
570 # caller may call multiple times with different subdir paths
571 # createing different playgrounds
573 # ensure_a_playground SUBDIR_PATH_COMPONENTS
574 # like fresh_playground except:
575 # merely ensures the directory exists; does not delete an existing one
579 # changedir playground
582 # playtree_setup $local_git_cfg
583 # # ^ call in some (perhaps trivial) subdir of playground
587 # ----- maindir -----
589 # these three all go together
592 our $maindir_gitcommon;
596 sub record_maindir () {
597 if (!defined $maindir) {
598 $maindir = must_getcwd();
599 if (!stat "$maindir/.git") {
600 fail "cannot stat $maindir/.git: $!";
603 # we fall back to this in case we have a pre-worktree
604 # git, which may not know git rev-parse --git-common-dir
605 $maindir_gitdir = "$maindir/.git";
606 $maindir_gitcommon = "$maindir/.git";
608 $maindir_gitdir = cmdoutput qw(git rev-parse --git-dir);
609 $maindir_gitcommon = cmdoutput qw(git rev-parse --git-common-dir);
612 $local_git_cfg //= git_slurp_config_src 'local';
615 # ----- playgrounds -----
617 sub ensure_a_playground_parent ($) {
620 $spc = "$maindir_gitdir/$spc";
621 my $parent = dirname $spc;
622 mkdir $parent or $!==EEXIST
623 or fail "failed to mkdir playground parent $parent: $!";
627 sub ensure_a_playground ($) {
629 $spc = ensure_a_playground_parent $spc;
630 mkdir $spc or $!==EEXIST or fail "failed to mkdir a playground $spc: $!";
634 sub fresh_playground ($) {
636 $spc = ensure_a_playground_parent $spc;
638 mkdir $spc or fail "failed to mkdir the playground $spc: $!";
642 # ----- playtrees -----
644 sub playtree_setup (;$) {
645 my ($t_local_git_cfg) = @_;
646 $t_local_git_cfg //= $local_git_cfg;
647 # for use in the playtree
648 # $maindir must be set, eg by calling record_maindir or fresh_playground
649 runcmd qw(git init -q);
650 runcmd qw(git config gc.auto 0);
651 foreach my $copy (qw(user.email user.name user.useConfigOnly
652 core.sharedRepository
653 core.compression core.looseCompression
654 core.bigFileThreshold core.fsyncObjectFiles)) {
655 my $v = $t_local_git_cfg->{$copy};
657 runcmd qw(git config), $copy, $_ foreach @$v;
659 # this is confusing: we have
660 # . playtree, not a worktree, has .git/, our cwd
661 # $maindir might be a worktree so
662 # $maindir_gitdir contains our main working "dgit", HEAD, etc.
663 # $maindir_gitcommon the shared stuff, including .objects
664 rmtree('.git/objects');
665 symlink "$maindir_gitcommon/objects",'.git/objects' or die $!;
666 ensuredir '.git/info';
667 open GA, "> .git/info/attributes" or die $!;
668 print GA "* $negate_harmful_gitattrs\n" or die $!;