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 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
59 initdebug enabledebug enabledebuglevel
61 $debugprefix *debuglevel *DEBUG
62 shellquote printcmd messagequote
63 $negate_harmful_gitattrs
64 changedir git_slurp_config_src
66 # implicitly uses $main::us
67 %EXPORT_TAGS = ( policyflags => [qw(NOFFCHECK FRESHREPO NOCOMMITCHECK)],
68 playground => [qw(record_maindir $maindir $local_git_cfg
69 $maindir_gitdir $maindir_gitcommon
71 ensure_a_playground)]);
72 @EXPORT_OK = ( @{ $EXPORT_TAGS{policyflags} },
73 @{ $EXPORT_TAGS{playground} } );
78 our $package_re = '[0-9a-z][-+.0-9a-z]*';
79 our $component_re = '[0-9a-zA-Z][-+.0-9a-zA-Z]*';
80 our $deliberately_re = "(?:TEST-)?$package_re";
81 our $distro_re = $component_re;
82 our $versiontag_re = qr{[-+.\%_0-9a-zA-Z/]+};
83 our $branchprefix = 'dgit';
84 our $series_filename_re = qr{(?:^|\.)series(?!\n)$}s;
85 our $extra_orig_namepart_re = qr{[-0-9a-z]+};
87 # policy hook exit status bits
88 # see dgit-repos-server head comment for documentation
89 # 1 is reserved in case something fails with `exit 1' and to spot
90 # dynamic loader, runtime, etc., failures, which report 127 or 255
91 sub NOFFCHECK () { return 0x2; }
92 sub FRESHREPO () { return 0x4; }
93 sub NOCOMMITCHECK () { return 0x8; }
98 our $negate_harmful_gitattrs = "-text -eol -crlf -ident -filter";
100 our $forkcheck_mainprocess;
102 sub forkcheck_setup () {
103 $forkcheck_mainprocess = $$;
106 sub forkcheck_mainprocess () {
107 # You must have called forkcheck_setup or setup_sigwarn already
108 getppid != $forkcheck_mainprocess;
111 sub setup_sigwarn () {
113 $SIG{__WARN__} = sub {
114 confess $_[0] if forkcheck_mainprocess;
120 open DEBUG, ">/dev/null" or die $!;
124 open DEBUG, ">&STDERR" or die $!;
129 sub enabledebuglevel ($) {
130 my ($newlevel) = @_; # may be undef (eg from env var)
134 return unless $newlevel;
135 $debuglevel = $newlevel;
140 print DEBUG $debugprefix, @_ or die $! if $debuglevel>0;
143 sub messagequote ($) {
149 s{[\000-\037\177]}{ sprintf "\\x%02x", ord $& }ge;
156 defined or confess 'internal error' foreach @_;
159 if (!length || m{[^-=_./:0-9a-z]}i) {
166 return join ' ', @out;
171 my $intro = shift @_;
172 print $fh $intro," " or die $!;
173 print $fh shellquote @_ or die $!;
174 print $fh "\n" or die $!;
178 my $extraprefix = shift @_;
179 printcmd(\*DEBUG,$debugprefix.$extraprefix,@_) if $debuglevel>0;
182 sub dep14_version_mangle ($) {
184 # DEP-14 patch proposed 2016-11-09 "Version Mangling"
186 $v =~ s/\.(?=\.|$|lock$)/.#/g;
190 sub debiantag_old ($$) {
191 my ($v,$distro) = @_;
192 return "$distro/". dep14_version_mangle $v;
195 sub debiantag_new ($$) {
196 my ($v,$distro) = @_;
197 return "archive/$distro/".dep14_version_mangle $v;
200 sub debiantags ($$) {
201 my ($version,$distro) = @_;
202 map { $_->($version, $distro) } (\&debiantag_new, \&debiantag_old);
205 sub server_branch ($) { return "$branchprefix/$_[0]"; }
206 sub server_ref ($) { return "refs/".server_branch($_[0]); }
208 sub stat_exists ($) {
211 return 0 if $!==&ENOENT;
216 $::us // ($0 =~ m#[^/]*$#, $&);
222 my $prefix = _us().": ";
223 $s =~ s/^/$prefix/gm;
228 my ($dir) = @_; # does not create parents
229 return if mkdir $dir;
230 return if $! == EEXIST;
231 die "mkdir $dir: $!";
236 defined $d or fail "getcwd failed: $!";
240 sub executable_on_path ($) {
242 return 1 if $program =~ m{/};
243 my @path = split /:/, ($ENV{PATH} // "/usr/local/bin:/bin:/usr/bin");
244 foreach my $pe (@path) {
245 my $here = "$pe/$program";
246 return $here if stat_exists $here && -x _;
251 our @signames = split / /, $Config{sig_name};
253 sub waitstatusmsg () {
255 return "terminated, reporting successful completion";
256 } elsif (!($? & 255)) {
257 return "failed with error exit status ".WEXITSTATUS($?);
258 } elsif (WIFSIGNALED($?)) {
259 my $signum=WTERMSIG($?);
260 return "died due to fatal signal ".
261 ($signames[$signum] // "number $signum").
262 ($? & 128 ? " (core dumped)" : ""); # POSIX(3pm) has no WCOREDUMP
264 return "failed with unknown wait status ".$?;
268 sub failedcmd_report_cmd {
269 my $intro = shift @_;
270 $intro //= "failed command";
271 { local ($!); printcmd \*STDERR, _us().": $intro:", @_ or die $!; };
274 sub failedcmd_waitstatus {
276 return "failed to fork/exec: $!";
278 return "subprocess ".waitstatusmsg();
280 return "subprocess produced invalid output";
285 # Expects $!,$? as set by close - see below.
286 # To use with system(), set $?=-1 first.
288 # Actual behaviour of perl operations:
289 # success $!==0 $?==0 close of piped open
290 # program failed $!==0 $? >0 close of piped open
291 # syscall failure $! >0 $?=-1 close of piped open
292 # failure $! >0 unchanged close of something else
293 # success trashed $?==0 system
294 # program failed trashed $? >0 system
295 # syscall failure $! >0 unchanged system
296 failedcmd_report_cmd undef, @_;
297 fail failedcmd_waitstatus();
303 failedcmd @_ if system @_;
306 sub cmdoutput_errok {
307 confess Dumper(\@_)." ?" if grep { !defined } @_;
309 open P, "-|", @_ or die "$_[0] $!";
312 { local $/ = undef; $d = <P>; }
314 if (!close P) { printdebug "=>!$?\n"; return undef; }
316 if ($debuglevel > 0) {
319 my $more = (length $' ? '...' : ''); #');
320 $dd =~ s{[^\n -~]|\\}{ sprintf "\\x%02x", ord $& }ge;
321 printdebug "=> \`$dd'",$more,"\n";
327 my $d = cmdoutput_errok @_;
328 defined $d or failedcmd @_;
332 sub link_ltarget ($$) {
334 lstat $old or return undef;
336 $old = cmdoutput qw(realpath --), $old;
338 my $r = link $old, $new;
339 $r = symlink $old, $new if !$r && $!==EXDEV;
340 $r or die "(sym)link $old $new: $!";
345 my $h = Digest::SHA->new(256);
347 return $h->hexdigest();
350 sub git_rev_parse ($) {
351 return cmdoutput qw(git rev-parse), "$_[0]~0";
354 sub git_cat_file ($;$) {
355 my ($objname, $etype) = @_;
356 # => ($type, $data) or ('missing', undef)
357 # in scalar context, just the data
358 # if $etype defined, dies unless type is $etype or in @$etype
359 our ($gcf_pid, $gcf_i, $gcf_o);
361 my ($gtype, $data) = @_;
363 $etype = [$etype] unless ref $etype;
364 confess "$objname expected @$etype but is $gtype"
365 unless grep { $gtype eq $_ } @$etype;
367 return ($gtype, $data);
370 my @cmd = qw(git cat-file --batch);
371 debugcmd "GCF|", @cmd;
372 $gcf_pid = open2 $gcf_o, $gcf_i, @cmd or die $!;
374 printdebug "GCF>| ", $objname, "\n";
375 print $gcf_i $objname, "\n" or die $!;
377 printdebug "GCF<| ", $x;
378 if ($x =~ m/ (missing)$/) { return $chk->($1, undef); }
379 my ($type, $size) = $x =~ m/^.* (\w+) (\d+)\n/ or die "$objname ?";
381 (read $gcf_o, $data, $size) == $size or die "$objname $!";
383 $x eq "\n" or die "$objname ($_) $!";
384 return $chk->($type, $data);
387 sub git_get_symref (;$) {
388 my ($symref) = @_; $symref //= 'HEAD';
389 # => undef if not a symref, otherwise refs/...
390 my @cmd = (qw(git symbolic-ref -q HEAD));
391 my $branch = cmdoutput_errok @cmd;
392 if (!defined $branch) {
393 $?==256 or failedcmd @cmd;
400 sub git_for_each_ref ($$;$) {
401 my ($pattern,$func,$gitdir) = @_;
402 # calls $func->($objid,$objtype,$fullrefname,$reftail);
403 # $reftail is RHS of ref after refs/[^/]+/
404 # breaks if $pattern matches any ref `refs/blah' where blah has no `/'
405 # $pattern may be an array ref to mean multiple patterns
406 $pattern = [ $pattern ] unless ref $pattern;
407 my @cmd = (qw(git for-each-ref), @$pattern);
408 if (defined $gitdir) {
409 @cmd = ('sh','-ec','cd "$1"; shift; exec "$@"','x', $gitdir, @cmd);
411 open GFER, "-|", @cmd or die $!;
415 printdebug "|> ", $_, "\n";
416 m#^(\w+)\s+(\w+)\s+(refs/[^/]+/(\S+))$# or die "$_ ?";
417 $func->($1,$2,$3,$4);
419 $!=0; $?=0; close GFER or die "$pattern $? $!";
422 sub git_get_ref ($) {
423 # => '' if no such ref
426 s{^refs/}{[r]efs/} or die "$refname $_ ?";
427 return cmdoutput qw(git for-each-ref --format=%(objectname)), $_;
430 sub git_for_each_tag_referring ($$) {
431 my ($objreferring, $func) = @_;
432 # calls $func->($tagobjid,$refobjid,$fullrefname,$tagname);
433 printdebug "git_for_each_tag_referring ",
434 ($objreferring // 'UNDEF'),"\n";
435 git_for_each_ref('refs/tags', sub {
436 my ($tagobjid,$objtype,$fullrefname,$tagname) = @_;
437 return unless $objtype eq 'tag';
438 my $refobjid = git_rev_parse $tagobjid;
440 !defined $objreferring # caller wants them all
441 or $tagobjid eq $objreferring
442 or $refobjid eq $objreferring;
443 $func->($tagobjid,$refobjid,$fullrefname,$tagname);
447 sub git_check_unmodified () {
448 my @cmd = qw(git diff --quiet HEAD);
450 $!=0; $?=-1; system @cmd;
453 fail "working tree is dirty (does not match HEAD)";
459 sub is_fast_fwd ($$) {
460 my ($ancestor,$child) = @_;
461 my @cmd = (qw(git merge-base), $ancestor, $child);
462 my $mb = cmdoutput_errok @cmd;
464 return git_rev_parse($mb) eq git_rev_parse($ancestor);
466 $?==256 or failedcmd @cmd;
473 printdebug "CD $newdir\n";
474 chdir $newdir or confess "chdir: $newdir: $!";
477 sub git_slurp_config_src ($) {
479 # returns $r such that $r->{KEY}[] = VALUE
480 my @cmd = (qw(git config -z --get-regexp), "--$src", qw(.*));
483 local ($debuglevel) = $debuglevel-2;
487 open GITS, "-|", @cmd or die $!;
490 printdebug "=> ", (messagequote $_), "\n";
492 push @{ $r->{$`} }, $'; #';
496 or ($!==0 && $?==256)
501 # ========== playground handling ==========
505 # $maindir user's git working tree
506 # playground area in .git/ where we can make files, unpack, etc. etc.
507 # playtree git working tree sharing object store with the user's
508 # inside playground, or identical to it
512 # $local_git_cfg hash of arrays of values: git config from $maindir
514 # expected calling pattern
519 # must be run in directory containing .git
520 # assigns to $maindir if not already set
521 # also calls git_slurp_config_src to record git config
522 # in $local_git_cfg, unless it's already set
524 # fresh_playground SUBDIR_PATH_COMPONENTS
525 # e.g fresh_playground 'dgit/unpack' ('.git/' is implied)
526 # default SUBDIR_PATH_COMPONENTS is playground_subdir
527 # calls record_maindir
528 # sets up a new playground (destroying any old one)
529 # returns playground pathname
530 # caller may call multiple times with different subdir paths
531 # createing different playgrounds
533 # ensure_a_playground SUBDIR_PATH_COMPONENTS
534 # like fresh_playground except:
535 # merely ensures the directory exists; does not delete an existing one
539 # changedir playground
542 # playtree_setup $local_git_cfg
543 # # ^ call in some (perhaps trivial) subdir of playground
547 # ----- maindir -----
549 # these three all go together
552 our $maindir_gitcommon;
556 sub record_maindir () {
557 if (!defined $maindir) {
558 $maindir = must_getcwd();
559 if (!stat "$maindir/.git") {
560 fail "cannot stat $maindir/.git: $!";
563 # we fall back to this in case we have a pre-worktree
564 # git, which may not know git rev-parse --git-common-dir
565 $maindir_gitdir = "$maindir/.git";
566 $maindir_gitcommon = "$maindir/.git";
568 $maindir_gitdir = cmdoutput qw(git rev-parse --git-dir);
569 $maindir_gitcommon = cmdoutput qw(git rev-parse --git-common-dir);
572 $local_git_cfg //= git_slurp_config_src 'local';
575 # ----- playgrounds -----
577 sub ensure_a_playground_parent ($) {
580 $spc = "$maindir_gitdir/$spc";
581 my $parent = dirname $spc;
582 mkdir $parent or $!==EEXIST
583 or fail "failed to mkdir playground parent $parent: $!";
587 sub ensure_a_playground ($) {
589 $spc = ensure_a_playground_parent $spc;
590 mkdir $spc or $!==EEXIST or fail "failed to mkdir a playground $spc: $!";
594 sub fresh_playground ($) {
596 $spc = ensure_a_playground_parent $spc;
598 mkdir $spc or fail "failed to mkdir the playground $spc: $!";
602 # ----- playtrees -----
604 sub playtree_setup (;$) {
605 my ($t_local_git_cfg) = @_;
606 $t_local_git_cfg //= $local_git_cfg;
607 # for use in the playtree
608 # $maindir must be set, eg by calling record_maindir or fresh_playground
609 runcmd qw(git init -q);
610 runcmd qw(git config gc.auto 0);
611 foreach my $copy (qw(user.email user.name user.useConfigOnly
612 core.sharedRepository
613 core.compression core.looseCompression
614 core.bigFileThreshold core.fsyncObjectFiles)) {
615 my $v = $t_local_git_cfg->{$copy};
617 runcmd qw(git config), $copy, $_ foreach @$v;
619 # this is confusing: we have
620 # . playtree, not a worktree, has .git/, our cwd
621 # $maindir might be a worktree so
622 # $maindir_gitdir contains our main working "dgit", HEAD, etc.
623 # $maindir_gitcommon the shared stuff, including .objects
624 rmtree('.git/objects');
625 symlink "$maindir_gitcommon/objects",'.git/objects' or die $!;
626 ensuredir '.git/info';
627 open GA, "> .git/info/attributes" or die $!;
628 print GA "* $negate_harmful_gitattrs\n" or die $!;