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
54 $package_re $component_re $deliberately_re
55 $distro_re $versiontag_re $series_filename_re
56 $extra_orig_namepart_re
58 initdebug enabledebug enabledebuglevel
60 $debugprefix *debuglevel *DEBUG
61 shellquote printcmd messagequote
62 $negate_harmful_gitattrs
63 changedir git_slurp_config_src
65 # implicitly uses $main::us
66 %EXPORT_TAGS = ( policyflags => [qw(NOFFCHECK FRESHREPO NOCOMMITCHECK)],
67 playground => [qw(record_maindir $maindir $local_git_cfg
68 $maindir_gitdir $maindir_gitcommon
70 ensure_a_playground)]);
71 @EXPORT_OK = ( @{ $EXPORT_TAGS{policyflags} },
72 @{ $EXPORT_TAGS{playground} } );
77 our $package_re = '[0-9a-z][-+.0-9a-z]*';
78 our $component_re = '[0-9a-zA-Z][-+.0-9a-zA-Z]*';
79 our $deliberately_re = "(?:TEST-)?$package_re";
80 our $distro_re = $component_re;
81 our $versiontag_re = qr{[-+.\%_0-9a-zA-Z/]+};
82 our $branchprefix = 'dgit';
83 our $series_filename_re = qr{(?:^|\.)series(?!\n)$}s;
84 our $extra_orig_namepart_re = qr{[-0-9a-z]+};
86 # policy hook exit status bits
87 # see dgit-repos-server head comment for documentation
88 # 1 is reserved in case something fails with `exit 1' and to spot
89 # dynamic loader, runtime, etc., failures, which report 127 or 255
90 sub NOFFCHECK () { return 0x2; }
91 sub FRESHREPO () { return 0x4; }
92 sub NOCOMMITCHECK () { return 0x8; }
97 our $negate_harmful_gitattrs = "-text -eol -crlf -ident -filter";
99 our $forkcheck_mainprocess;
101 sub forkcheck_setup () {
102 $forkcheck_mainprocess = $$;
105 sub forkcheck_mainprocess () {
106 # You must have called forkcheck_setup or setup_sigwarn already
107 getppid != $forkcheck_mainprocess;
110 sub setup_sigwarn () {
112 $SIG{__WARN__} = sub {
113 confess $_[0] if forkcheck_mainprocess;
119 open DEBUG, ">/dev/null" or die $!;
123 open DEBUG, ">&STDERR" or die $!;
128 sub enabledebuglevel ($) {
129 my ($newlevel) = @_; # may be undef (eg from env var)
133 return unless $newlevel;
134 $debuglevel = $newlevel;
139 print DEBUG $debugprefix, @_ or die $! if $debuglevel>0;
142 sub messagequote ($) {
148 s{[\000-\037\177]}{ sprintf "\\x%02x", ord $& }ge;
155 defined or confess 'internal error' foreach @_;
158 if (!length || m{[^-=_./:0-9a-z]}i) {
165 return join ' ', @out;
170 my $intro = shift @_;
171 print $fh $intro," " or die $!;
172 print $fh shellquote @_ or die $!;
173 print $fh "\n" or die $!;
177 my $extraprefix = shift @_;
178 printcmd(\*DEBUG,$debugprefix.$extraprefix,@_) if $debuglevel>0;
181 sub dep14_version_mangle ($) {
183 # DEP-14 patch proposed 2016-11-09 "Version Mangling"
185 $v =~ s/\.(?=\.|$|lock$)/.#/g;
189 sub debiantag_old ($$) {
190 my ($v,$distro) = @_;
191 return "$distro/". dep14_version_mangle $v;
194 sub debiantag_new ($$) {
195 my ($v,$distro) = @_;
196 return "archive/$distro/".dep14_version_mangle $v;
199 sub debiantags ($$) {
200 my ($version,$distro) = @_;
201 map { $_->($version, $distro) } (\&debiantag_new, \&debiantag_old);
204 sub server_branch ($) { return "$branchprefix/$_[0]"; }
205 sub server_ref ($) { return "refs/".server_branch($_[0]); }
207 sub stat_exists ($) {
210 return 0 if $!==&ENOENT;
215 $::us // ($0 =~ m#[^/]*$#, $&);
221 my $prefix = _us().": ";
222 $s =~ s/^/$prefix/gm;
227 my ($dir) = @_; # does not create parents
228 return if mkdir $dir;
229 return if $! == EEXIST;
230 die "mkdir $dir: $!";
235 defined $d or fail "getcwd failed: $!";
239 sub executable_on_path ($) {
241 return 1 if $program =~ m{/};
242 my @path = split /:/, ($ENV{PATH} // "/usr/local/bin:/bin:/usr/bin");
243 foreach my $pe (@path) {
244 my $here = "$pe/$program";
245 return $here if stat_exists $here && -x _;
250 our @signames = split / /, $Config{sig_name};
252 sub waitstatusmsg () {
254 return "terminated, reporting successful completion";
255 } elsif (!($? & 255)) {
256 return "failed with error exit status ".WEXITSTATUS($?);
257 } elsif (WIFSIGNALED($?)) {
258 my $signum=WTERMSIG($?);
259 return "died due to fatal signal ".
260 ($signames[$signum] // "number $signum").
261 ($? & 128 ? " (core dumped)" : ""); # POSIX(3pm) has no WCOREDUMP
263 return "failed with unknown wait status ".$?;
267 sub failedcmd_report_cmd {
268 my $intro = shift @_;
269 $intro //= "failed command";
270 { local ($!); printcmd \*STDERR, _us().": $intro:", @_ or die $!; };
273 sub failedcmd_waitstatus {
275 return "failed to fork/exec: $!";
277 return "subprocess ".waitstatusmsg();
279 return "subprocess produced invalid output";
284 # Expects $!,$? as set by close - see below.
285 # To use with system(), set $?=-1 first.
287 # Actual behaviour of perl operations:
288 # success $!==0 $?==0 close of piped open
289 # program failed $!==0 $? >0 close of piped open
290 # syscall failure $! >0 $?=-1 close of piped open
291 # failure $! >0 unchanged close of something else
292 # success trashed $?==0 system
293 # program failed trashed $? >0 system
294 # syscall failure $! >0 unchanged system
295 failedcmd_report_cmd undef, @_;
296 fail failedcmd_waitstatus();
302 failedcmd @_ if system @_;
305 sub cmdoutput_errok {
306 confess Dumper(\@_)." ?" if grep { !defined } @_;
308 open P, "-|", @_ or die "$_[0] $!";
311 { local $/ = undef; $d = <P>; }
313 if (!close P) { printdebug "=>!$?\n"; return undef; }
315 if ($debuglevel > 0) {
318 my $more = (length $' ? '...' : ''); #');
319 $dd =~ s{[^\n -~]|\\}{ sprintf "\\x%02x", ord $& }ge;
320 printdebug "=> \`$dd'",$more,"\n";
326 my $d = cmdoutput_errok @_;
327 defined $d or failedcmd @_;
331 sub link_ltarget ($$) {
333 lstat $old or return undef;
335 $old = cmdoutput qw(realpath --), $old;
337 my $r = link $old, $new;
338 $r = symlink $old, $new if !$r && $!==EXDEV;
339 $r or die "(sym)link $old $new: $!";
344 my $h = Digest::SHA->new(256);
346 return $h->hexdigest();
349 sub git_rev_parse ($) {
350 return cmdoutput qw(git rev-parse), "$_[0]~0";
353 sub git_cat_file ($;$) {
354 my ($objname, $etype) = @_;
355 # => ($type, $data) or ('missing', undef)
356 # in scalar context, just the data
357 # if $etype defined, dies unless type is $etype or in @$etype
358 our ($gcf_pid, $gcf_i, $gcf_o);
360 my ($gtype, $data) = @_;
362 $etype = [$etype] unless ref $etype;
363 confess "$objname expected @$etype but is $gtype"
364 unless grep { $gtype eq $_ } @$etype;
366 return ($gtype, $data);
369 my @cmd = qw(git cat-file --batch);
370 debugcmd "GCF|", @cmd;
371 $gcf_pid = open2 $gcf_o, $gcf_i, @cmd or die $!;
373 printdebug "GCF>| ", $objname, "\n";
374 print $gcf_i $objname, "\n" or die $!;
376 printdebug "GCF<| ", $x;
377 if ($x =~ m/ (missing)$/) { return $chk->($1, undef); }
378 my ($type, $size) = $x =~ m/^.* (\w+) (\d+)\n/ or die "$objname ?";
380 (read $gcf_o, $data, $size) == $size or die "$objname $!";
382 $x eq "\n" or die "$objname ($_) $!";
383 return $chk->($type, $data);
386 sub git_get_symref (;$) {
387 my ($symref) = @_; $symref //= 'HEAD';
388 # => undef if not a symref, otherwise refs/...
389 my @cmd = (qw(git symbolic-ref -q HEAD));
390 my $branch = cmdoutput_errok @cmd;
391 if (!defined $branch) {
392 $?==256 or failedcmd @cmd;
399 sub git_for_each_ref ($$;$) {
400 my ($pattern,$func,$gitdir) = @_;
401 # calls $func->($objid,$objtype,$fullrefname,$reftail);
402 # $reftail is RHS of ref after refs/[^/]+/
403 # breaks if $pattern matches any ref `refs/blah' where blah has no `/'
404 # $pattern may be an array ref to mean multiple patterns
405 $pattern = [ $pattern ] unless ref $pattern;
406 my @cmd = (qw(git for-each-ref), @$pattern);
407 if (defined $gitdir) {
408 @cmd = ('sh','-ec','cd "$1"; shift; exec "$@"','x', $gitdir, @cmd);
410 open GFER, "-|", @cmd or die $!;
414 printdebug "|> ", $_, "\n";
415 m#^(\w+)\s+(\w+)\s+(refs/[^/]+/(\S+))$# or die "$_ ?";
416 $func->($1,$2,$3,$4);
418 $!=0; $?=0; close GFER or die "$pattern $? $!";
421 sub git_get_ref ($) {
422 # => '' if no such ref
425 s{^refs/}{[r]efs/} or die "$refname $_ ?";
426 return cmdoutput qw(git for-each-ref --format=%(objectname)), $_;
429 sub git_for_each_tag_referring ($$) {
430 my ($objreferring, $func) = @_;
431 # calls $func->($tagobjid,$refobjid,$fullrefname,$tagname);
432 printdebug "git_for_each_tag_referring ",
433 ($objreferring // 'UNDEF'),"\n";
434 git_for_each_ref('refs/tags', sub {
435 my ($tagobjid,$objtype,$fullrefname,$tagname) = @_;
436 return unless $objtype eq 'tag';
437 my $refobjid = git_rev_parse $tagobjid;
439 !defined $objreferring # caller wants them all
440 or $tagobjid eq $objreferring
441 or $refobjid eq $objreferring;
442 $func->($tagobjid,$refobjid,$fullrefname,$tagname);
446 sub is_fast_fwd ($$) {
447 my ($ancestor,$child) = @_;
448 my @cmd = (qw(git merge-base), $ancestor, $child);
449 my $mb = cmdoutput_errok @cmd;
451 return git_rev_parse($mb) eq git_rev_parse($ancestor);
453 $?==256 or failedcmd @cmd;
460 printdebug "CD $newdir\n";
461 chdir $newdir or confess "chdir: $newdir: $!";
464 sub git_slurp_config_src ($) {
466 # returns $r such that $r->{KEY}[] = VALUE
467 my @cmd = (qw(git config -z --get-regexp), "--$src", qw(.*));
470 local ($debuglevel) = $debuglevel-2;
474 open GITS, "-|", @cmd or die $!;
477 printdebug "=> ", (messagequote $_), "\n";
479 push @{ $r->{$`} }, $'; #';
483 or ($!==0 && $?==256)
488 # ========== playground handling ==========
492 # $maindir user's git working tree
493 # playground area in .git/ where we can make files, unpack, etc. etc.
494 # playtree git working tree sharing object store with the user's
495 # inside playground, or identical to it
499 # $local_git_cfg hash of arrays of values: git config from $maindir
501 # expected calling pattern
506 # must be run in directory containing .git
507 # assigns to $maindir if not already set
508 # also calls git_slurp_config_src to record git config
509 # in $local_git_cfg, unless it's already set
511 # fresh_playground SUBDIR_PATH_COMPONENTS
512 # e.g fresh_playground 'dgit/unpack' ('.git/' is implied)
513 # default SUBDIR_PATH_COMPONENTS is playground_subdir
514 # calls record_maindir
515 # sets up a new playground (destroying any old one)
516 # returns playground pathname
517 # caller may call multiple times with different subdir paths
518 # createing different playgrounds
520 # ensure_a_playground SUBDIR_PATH_COMPONENTS
521 # like fresh_playground except:
522 # merely ensures the directory exists; does not delete an existing one
526 # changedir playground
529 # playtree_setup $local_git_cfg
530 # # ^ call in some (perhaps trivial) subdir of playground
534 # ----- maindir -----
536 # these three all go together
539 our $maindir_gitcommon;
543 sub record_maindir () {
544 if (!defined $maindir) {
545 $maindir = must_getcwd();
546 if (!stat "$maindir/.git") {
547 fail "cannot stat $maindir/.git: $!";
550 # we fall back to this in case we have a pre-worktree
551 # git, which may not know git rev-parse --git-common-dir
552 $maindir_gitdir = "$maindir/.git";
553 $maindir_gitcommon = "$maindir/.git";
555 $maindir_gitdir = cmdoutput qw(git rev-parse --git-dir);
556 $maindir_gitcommon = cmdoutput qw(git rev-parse --git-common-dir);
559 $local_git_cfg //= git_slurp_config_src 'local';
562 # ----- playgrounds -----
564 sub ensure_a_playground_parent ($) {
567 $spc = "$maindir_gitdir/$spc";
568 my $parent = dirname $spc;
569 mkdir $parent or $!==EEXIST
570 or fail "failed to mkdir playground parent $parent: $!";
574 sub ensure_a_playground ($) {
576 $spc = ensure_a_playground_parent $spc;
577 mkdir $spc or $!==EEXIST or fail "failed to mkdir a playground $spc: $!";
581 sub fresh_playground ($) {
583 $spc = ensure_a_playground_parent $spc;
585 mkdir $spc or fail "failed to mkdir the playground $spc: $!";
589 # ----- playtrees -----
591 sub playtree_setup (;$) {
592 my ($t_local_git_cfg) = @_;
593 $t_local_git_cfg //= $local_git_cfg;
594 # for use in the playtree
595 # $maindir must be set, eg by calling record_maindir or fresh_playground
596 runcmd qw(git init -q);
597 runcmd qw(git config gc.auto 0);
598 foreach my $copy (qw(user.email user.name user.useConfigOnly
599 core.sharedRepository
600 core.compression core.looseCompression
601 core.bigFileThreshold core.fsyncObjectFiles)) {
602 my $v = $t_local_git_cfg->{$copy};
604 runcmd qw(git config), $copy, $_ foreach @$v;
606 # this is confusing: we have
607 # . playtree, not a worktree, has .git/, our cwd
608 # $maindir might be a worktree so
609 # $maindir_gitdir contains our main working "dgit", HEAD, etc.
610 # $maindir_gitcommon the shared stuff, including .objects
611 rmtree('.git/objects');
612 symlink "$maindir_gitcommon/objects",'.git/objects' or die $!;
613 ensuredir '.git/info';
614 open GA, "> .git/info/attributes" or die $!;
615 print GA "* $negate_harmful_gitattrs\n" or die $!;