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 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#[^/]*$#, $&);
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 @_;
318 sub cmdoutput_errok {
319 confess Dumper(\@_)." ?" if grep { !defined } @_;
321 open P, "-|", @_ or die "$_[0] $!";
324 { local $/ = undef; $d = <P>; }
326 if (!close P) { printdebug "=>!$?\n"; return undef; }
328 if ($debuglevel > 0) {
331 my $more = (length $' ? '...' : ''); #');
332 $dd =~ s{[^\n -~]|\\}{ sprintf "\\x%02x", ord $& }ge;
333 printdebug "=> \`$dd'",$more,"\n";
339 my $d = cmdoutput_errok @_;
340 defined $d or failedcmd @_;
344 sub link_ltarget ($$) {
346 lstat $old or return undef;
348 $old = cmdoutput qw(realpath --), $old;
350 my $r = link $old, $new;
351 $r = symlink $old, $new if !$r && $!==EXDEV;
352 $r or die "(sym)link $old $new: $!";
357 my $h = Digest::SHA->new(256);
359 return $h->hexdigest();
362 sub git_rev_parse ($) {
363 return cmdoutput qw(git rev-parse), "$_[0]~0";
366 sub git_cat_file ($;$) {
367 my ($objname, $etype) = @_;
368 # => ($type, $data) or ('missing', undef)
369 # in scalar context, just the data
370 # if $etype defined, dies unless type is $etype or in @$etype
371 our ($gcf_pid, $gcf_i, $gcf_o);
373 my ($gtype, $data) = @_;
375 $etype = [$etype] unless ref $etype;
376 confess "$objname expected @$etype but is $gtype"
377 unless grep { $gtype eq $_ } @$etype;
379 return ($gtype, $data);
382 my @cmd = qw(git cat-file --batch);
383 debugcmd "GCF|", @cmd;
384 $gcf_pid = open2 $gcf_o, $gcf_i, @cmd or die $!;
386 printdebug "GCF>| ", $objname, "\n";
387 print $gcf_i $objname, "\n" or die $!;
389 printdebug "GCF<| ", $x;
390 if ($x =~ m/ (missing)$/) { return $chk->($1, undef); }
391 my ($type, $size) = $x =~ m/^.* (\w+) (\d+)\n/ or die "$objname ?";
393 (read $gcf_o, $data, $size) == $size or die "$objname $!";
395 $x eq "\n" or die "$objname ($_) $!";
396 return $chk->($type, $data);
399 sub git_get_symref (;$) {
400 my ($symref) = @_; $symref //= 'HEAD';
401 # => undef if not a symref, otherwise refs/...
402 my @cmd = (qw(git symbolic-ref -q HEAD));
403 my $branch = cmdoutput_errok @cmd;
404 if (!defined $branch) {
405 $?==256 or failedcmd @cmd;
412 sub git_for_each_ref ($$;$) {
413 my ($pattern,$func,$gitdir) = @_;
414 # calls $func->($objid,$objtype,$fullrefname,$reftail);
415 # $reftail is RHS of ref after refs/[^/]+/
416 # breaks if $pattern matches any ref `refs/blah' where blah has no `/'
417 # $pattern may be an array ref to mean multiple patterns
418 $pattern = [ $pattern ] unless ref $pattern;
419 my @cmd = (qw(git for-each-ref), @$pattern);
420 if (defined $gitdir) {
421 @cmd = ('sh','-ec','cd "$1"; shift; exec "$@"','x', $gitdir, @cmd);
423 open GFER, "-|", @cmd or die $!;
427 printdebug "|> ", $_, "\n";
428 m#^(\w+)\s+(\w+)\s+(refs/[^/]+/(\S+))$# or die "$_ ?";
429 $func->($1,$2,$3,$4);
431 $!=0; $?=0; close GFER or die "$pattern $? $!";
434 sub git_get_ref ($) {
435 # => '' if no such ref
438 s{^refs/}{[r]efs/} or die "$refname $_ ?";
439 return cmdoutput qw(git for-each-ref --format=%(objectname)), $_;
442 sub git_for_each_tag_referring ($$) {
443 my ($objreferring, $func) = @_;
444 # calls $func->($tagobjid,$refobjid,$fullrefname,$tagname);
445 printdebug "git_for_each_tag_referring ",
446 ($objreferring // 'UNDEF'),"\n";
447 git_for_each_ref('refs/tags', sub {
448 my ($tagobjid,$objtype,$fullrefname,$tagname) = @_;
449 return unless $objtype eq 'tag';
450 my $refobjid = git_rev_parse $tagobjid;
452 !defined $objreferring # caller wants them all
453 or $tagobjid eq $objreferring
454 or $refobjid eq $objreferring;
455 $func->($tagobjid,$refobjid,$fullrefname,$tagname);
459 sub git_check_unmodified () {
460 foreach my $cached (qw(0 1)) {
461 my @cmd = qw(git diff --quiet);
462 push @cmd, qw(--cached) if $cached;
465 $!=0; $?=-1; system @cmd;
470 ? "git index contains changes (does not match HEAD)"
471 : "working tree is dirty (does not match HEAD)";
478 sub is_fast_fwd ($$) {
479 my ($ancestor,$child) = @_;
480 my @cmd = (qw(git merge-base), $ancestor, $child);
481 my $mb = cmdoutput_errok @cmd;
483 return git_rev_parse($mb) eq git_rev_parse($ancestor);
485 $?==256 or failedcmd @cmd;
492 printdebug "CD $newdir\n";
493 chdir $newdir or confess "chdir: $newdir: $!";
496 sub git_slurp_config_src ($) {
498 # returns $r such that $r->{KEY}[] = VALUE
499 my @cmd = (qw(git config -z --get-regexp), "--$src", qw(.*));
502 local ($debuglevel) = $debuglevel-2;
506 open GITS, "-|", @cmd or die $!;
509 printdebug "=> ", (messagequote $_), "\n";
511 push @{ $r->{$`} }, $'; #';
515 or ($!==0 && $?==256)
520 sub gdr_ffq_prev_branchinfo ($) {
522 # => ('status', "message", [$symref, $ffq_prev, $gdrlast])
524 # branch message is undef
525 # weird-symref } no $symref,
526 # notbranch } no $ffq_prev
527 return ('detached', 'detached HEAD') unless defined $symref;
528 return ('weird-symref', 'HEAD symref is not to refs/')
529 unless $symref =~ m{^refs/};
530 my $ffq_prev = "refs/$ffq_refprefix/$'";
531 my $gdrlast = "refs/$gdrlast_refprefix/$'";
532 printdebug "ffq_prev_branchinfo branch current $symref\n";
533 return ('branch', undef, $symref, $ffq_prev, $gdrlast);
536 # ========== playground handling ==========
540 # $maindir user's git working tree
541 # playground area in .git/ where we can make files, unpack, etc. etc.
542 # playtree git working tree sharing object store with the user's
543 # inside playground, or identical to it
547 # $local_git_cfg hash of arrays of values: git config from $maindir
549 # expected calling pattern
554 # must be run in directory containing .git
555 # assigns to $maindir if not already set
556 # also calls git_slurp_config_src to record git config
557 # in $local_git_cfg, unless it's already set
559 # fresh_playground SUBDIR_PATH_COMPONENTS
560 # e.g fresh_playground 'dgit/unpack' ('.git/' is implied)
561 # default SUBDIR_PATH_COMPONENTS is playground_subdir
562 # calls record_maindir
563 # sets up a new playground (destroying any old one)
564 # returns playground pathname
565 # caller may call multiple times with different subdir paths
566 # createing different playgrounds
568 # ensure_a_playground SUBDIR_PATH_COMPONENTS
569 # like fresh_playground except:
570 # merely ensures the directory exists; does not delete an existing one
574 # changedir playground
577 # playtree_setup $local_git_cfg
578 # # ^ call in some (perhaps trivial) subdir of playground
582 # ----- maindir -----
584 # these three all go together
587 our $maindir_gitcommon;
591 sub record_maindir () {
592 if (!defined $maindir) {
593 $maindir = must_getcwd();
594 if (!stat "$maindir/.git") {
595 fail "cannot stat $maindir/.git: $!";
598 # we fall back to this in case we have a pre-worktree
599 # git, which may not know git rev-parse --git-common-dir
600 $maindir_gitdir = "$maindir/.git";
601 $maindir_gitcommon = "$maindir/.git";
603 $maindir_gitdir = cmdoutput qw(git rev-parse --git-dir);
604 $maindir_gitcommon = cmdoutput qw(git rev-parse --git-common-dir);
607 $local_git_cfg //= git_slurp_config_src 'local';
610 # ----- playgrounds -----
612 sub ensure_a_playground_parent ($) {
615 $spc = "$maindir_gitdir/$spc";
616 my $parent = dirname $spc;
617 mkdir $parent or $!==EEXIST
618 or fail "failed to mkdir playground parent $parent: $!";
622 sub ensure_a_playground ($) {
624 $spc = ensure_a_playground_parent $spc;
625 mkdir $spc or $!==EEXIST or fail "failed to mkdir a playground $spc: $!";
629 sub fresh_playground ($) {
631 $spc = ensure_a_playground_parent $spc;
633 mkdir $spc or fail "failed to mkdir the playground $spc: $!";
637 # ----- playtrees -----
639 sub playtree_setup (;$) {
640 my ($t_local_git_cfg) = @_;
641 $t_local_git_cfg //= $local_git_cfg;
642 # for use in the playtree
643 # $maindir must be set, eg by calling record_maindir or fresh_playground
644 runcmd qw(git init -q);
645 runcmd qw(git config gc.auto 0);
646 foreach my $copy (qw(user.email user.name user.useConfigOnly
647 core.sharedRepository
648 core.compression core.looseCompression
649 core.bigFileThreshold core.fsyncObjectFiles)) {
650 my $v = $t_local_git_cfg->{$copy};
652 runcmd qw(git config), $copy, $_ foreach @$v;
654 # this is confusing: we have
655 # . playtree, not a worktree, has .git/, our cwd
656 # $maindir might be a worktree so
657 # $maindir_gitdir contains our main working "dgit", HEAD, etc.
658 # $maindir_gitcommon the shared stuff, including .objects
659 rmtree('.git/objects');
660 symlink "$maindir_gitcommon/objects",'.git/objects' or die $!;
661 ensuredir '.git/info';
662 open GA, "> .git/info/attributes" or die $!;
663 print GA "* $negate_harmful_gitattrs\n" or die $!;