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
60 initdebug enabledebug enabledebuglevel
62 $debugprefix *debuglevel *DEBUG
63 shellquote printcmd messagequote
64 $negate_harmful_gitattrs
65 changedir git_slurp_config_src
67 # implicitly uses $main::us
68 %EXPORT_TAGS = ( policyflags => [qw(NOFFCHECK FRESHREPO NOCOMMITCHECK)],
69 playground => [qw(record_maindir $maindir $local_git_cfg
70 $maindir_gitdir $maindir_gitcommon
72 ensure_a_playground)]);
73 @EXPORT_OK = ( @{ $EXPORT_TAGS{policyflags} },
74 @{ $EXPORT_TAGS{playground} } );
79 our $package_re = '[0-9a-z][-+.0-9a-z]*';
80 our $component_re = '[0-9a-zA-Z][-+.0-9a-zA-Z]*';
81 our $deliberately_re = "(?:TEST-)?$package_re";
82 our $distro_re = $component_re;
83 our $versiontag_re = qr{[-+.\%_0-9a-zA-Z/]+};
84 our $branchprefix = 'dgit';
85 our $series_filename_re = qr{(?:^|\.)series(?!\n)$}s;
86 our $extra_orig_namepart_re = qr{[-0-9a-z]+};
87 our $git_null_obj = '0' x 40;
89 # policy hook exit status bits
90 # see dgit-repos-server head comment for documentation
91 # 1 is reserved in case something fails with `exit 1' and to spot
92 # dynamic loader, runtime, etc., failures, which report 127 or 255
93 sub NOFFCHECK () { return 0x2; }
94 sub FRESHREPO () { return 0x4; }
95 sub NOCOMMITCHECK () { return 0x8; }
100 our $negate_harmful_gitattrs = "-text -eol -crlf -ident -filter";
102 our $forkcheck_mainprocess;
104 sub forkcheck_setup () {
105 $forkcheck_mainprocess = $$;
108 sub forkcheck_mainprocess () {
109 # You must have called forkcheck_setup or setup_sigwarn already
110 getppid != $forkcheck_mainprocess;
113 sub setup_sigwarn () {
115 $SIG{__WARN__} = sub {
116 confess $_[0] if forkcheck_mainprocess;
122 open DEBUG, ">/dev/null" or die $!;
126 open DEBUG, ">&STDERR" or die $!;
131 sub enabledebuglevel ($) {
132 my ($newlevel) = @_; # may be undef (eg from env var)
136 return unless $newlevel;
137 $debuglevel = $newlevel;
142 print DEBUG $debugprefix, @_ or die $! if $debuglevel>0;
145 sub messagequote ($) {
151 s{[\000-\037\177]}{ sprintf "\\x%02x", ord $& }ge;
158 defined or confess 'internal error' foreach @_;
161 if (!length || m{[^-=_./:0-9a-z]}i) {
168 return join ' ', @out;
173 my $intro = shift @_;
174 print $fh $intro," " or die $!;
175 print $fh shellquote @_ or die $!;
176 print $fh "\n" or die $!;
180 my $extraprefix = shift @_;
181 printcmd(\*DEBUG,$debugprefix.$extraprefix,@_) if $debuglevel>0;
184 sub dep14_version_mangle ($) {
186 # DEP-14 patch proposed 2016-11-09 "Version Mangling"
188 $v =~ s/\.(?=\.|$|lock$)/.#/g;
192 sub debiantag_old ($$) {
193 my ($v,$distro) = @_;
194 return "$distro/". dep14_version_mangle $v;
197 sub debiantag_new ($$) {
198 my ($v,$distro) = @_;
199 return "archive/$distro/".dep14_version_mangle $v;
202 sub debiantags ($$) {
203 my ($version,$distro) = @_;
204 map { $_->($version, $distro) } (\&debiantag_new, \&debiantag_old);
207 sub server_branch ($) { return "$branchprefix/$_[0]"; }
208 sub server_ref ($) { return "refs/".server_branch($_[0]); }
210 sub stat_exists ($) {
213 return 0 if $!==&ENOENT;
218 $::us // ($0 =~ m#[^/]*$#, $&);
224 my $prefix = _us().": ";
225 $s =~ s/^/$prefix/gm;
230 my ($dir) = @_; # does not create parents
231 return if mkdir $dir;
232 return if $! == EEXIST;
233 die "mkdir $dir: $!";
238 defined $d or fail "getcwd failed: $!";
242 sub executable_on_path ($) {
244 return 1 if $program =~ m{/};
245 my @path = split /:/, ($ENV{PATH} // "/usr/local/bin:/bin:/usr/bin");
246 foreach my $pe (@path) {
247 my $here = "$pe/$program";
248 return $here if stat_exists $here && -x _;
253 our @signames = split / /, $Config{sig_name};
255 sub waitstatusmsg () {
257 return "terminated, reporting successful completion";
258 } elsif (!($? & 255)) {
259 return "failed with error exit status ".WEXITSTATUS($?);
260 } elsif (WIFSIGNALED($?)) {
261 my $signum=WTERMSIG($?);
262 return "died due to fatal signal ".
263 ($signames[$signum] // "number $signum").
264 ($? & 128 ? " (core dumped)" : ""); # POSIX(3pm) has no WCOREDUMP
266 return "failed with unknown wait status ".$?;
270 sub failedcmd_report_cmd {
271 my $intro = shift @_;
272 $intro //= "failed command";
273 { local ($!); printcmd \*STDERR, _us().": $intro:", @_ or die $!; };
276 sub failedcmd_waitstatus {
278 return "failed to fork/exec: $!";
280 return "subprocess ".waitstatusmsg();
282 return "subprocess produced invalid output";
287 # Expects $!,$? as set by close - see below.
288 # To use with system(), set $?=-1 first.
290 # Actual behaviour of perl operations:
291 # success $!==0 $?==0 close of piped open
292 # program failed $!==0 $? >0 close of piped open
293 # syscall failure $! >0 $?=-1 close of piped open
294 # failure $! >0 unchanged close of something else
295 # success trashed $?==0 system
296 # program failed trashed $? >0 system
297 # syscall failure $! >0 unchanged system
298 failedcmd_report_cmd undef, @_;
299 fail failedcmd_waitstatus();
305 failedcmd @_ if system @_;
308 sub cmdoutput_errok {
309 confess Dumper(\@_)." ?" if grep { !defined } @_;
311 open P, "-|", @_ or die "$_[0] $!";
314 { local $/ = undef; $d = <P>; }
316 if (!close P) { printdebug "=>!$?\n"; return undef; }
318 if ($debuglevel > 0) {
321 my $more = (length $' ? '...' : ''); #');
322 $dd =~ s{[^\n -~]|\\}{ sprintf "\\x%02x", ord $& }ge;
323 printdebug "=> \`$dd'",$more,"\n";
329 my $d = cmdoutput_errok @_;
330 defined $d or failedcmd @_;
334 sub link_ltarget ($$) {
336 lstat $old or return undef;
338 $old = cmdoutput qw(realpath --), $old;
340 my $r = link $old, $new;
341 $r = symlink $old, $new if !$r && $!==EXDEV;
342 $r or die "(sym)link $old $new: $!";
347 my $h = Digest::SHA->new(256);
349 return $h->hexdigest();
352 sub git_rev_parse ($) {
353 return cmdoutput qw(git rev-parse), "$_[0]~0";
356 sub git_cat_file ($;$) {
357 my ($objname, $etype) = @_;
358 # => ($type, $data) or ('missing', undef)
359 # in scalar context, just the data
360 # if $etype defined, dies unless type is $etype or in @$etype
361 our ($gcf_pid, $gcf_i, $gcf_o);
363 my ($gtype, $data) = @_;
365 $etype = [$etype] unless ref $etype;
366 confess "$objname expected @$etype but is $gtype"
367 unless grep { $gtype eq $_ } @$etype;
369 return ($gtype, $data);
372 my @cmd = qw(git cat-file --batch);
373 debugcmd "GCF|", @cmd;
374 $gcf_pid = open2 $gcf_o, $gcf_i, @cmd or die $!;
376 printdebug "GCF>| ", $objname, "\n";
377 print $gcf_i $objname, "\n" or die $!;
379 printdebug "GCF<| ", $x;
380 if ($x =~ m/ (missing)$/) { return $chk->($1, undef); }
381 my ($type, $size) = $x =~ m/^.* (\w+) (\d+)\n/ or die "$objname ?";
383 (read $gcf_o, $data, $size) == $size or die "$objname $!";
385 $x eq "\n" or die "$objname ($_) $!";
386 return $chk->($type, $data);
389 sub git_get_symref (;$) {
390 my ($symref) = @_; $symref //= 'HEAD';
391 # => undef if not a symref, otherwise refs/...
392 my @cmd = (qw(git symbolic-ref -q HEAD));
393 my $branch = cmdoutput_errok @cmd;
394 if (!defined $branch) {
395 $?==256 or failedcmd @cmd;
402 sub git_for_each_ref ($$;$) {
403 my ($pattern,$func,$gitdir) = @_;
404 # calls $func->($objid,$objtype,$fullrefname,$reftail);
405 # $reftail is RHS of ref after refs/[^/]+/
406 # breaks if $pattern matches any ref `refs/blah' where blah has no `/'
407 # $pattern may be an array ref to mean multiple patterns
408 $pattern = [ $pattern ] unless ref $pattern;
409 my @cmd = (qw(git for-each-ref), @$pattern);
410 if (defined $gitdir) {
411 @cmd = ('sh','-ec','cd "$1"; shift; exec "$@"','x', $gitdir, @cmd);
413 open GFER, "-|", @cmd or die $!;
417 printdebug "|> ", $_, "\n";
418 m#^(\w+)\s+(\w+)\s+(refs/[^/]+/(\S+))$# or die "$_ ?";
419 $func->($1,$2,$3,$4);
421 $!=0; $?=0; close GFER or die "$pattern $? $!";
424 sub git_get_ref ($) {
425 # => '' if no such ref
428 s{^refs/}{[r]efs/} or die "$refname $_ ?";
429 return cmdoutput qw(git for-each-ref --format=%(objectname)), $_;
432 sub git_for_each_tag_referring ($$) {
433 my ($objreferring, $func) = @_;
434 # calls $func->($tagobjid,$refobjid,$fullrefname,$tagname);
435 printdebug "git_for_each_tag_referring ",
436 ($objreferring // 'UNDEF'),"\n";
437 git_for_each_ref('refs/tags', sub {
438 my ($tagobjid,$objtype,$fullrefname,$tagname) = @_;
439 return unless $objtype eq 'tag';
440 my $refobjid = git_rev_parse $tagobjid;
442 !defined $objreferring # caller wants them all
443 or $tagobjid eq $objreferring
444 or $refobjid eq $objreferring;
445 $func->($tagobjid,$refobjid,$fullrefname,$tagname);
449 sub git_check_unmodified () {
450 foreach my $cached (qw(0 1)) {
451 my @cmd = qw(git diff --quiet);
452 push @cmd, qw(--cached) if $cached;
455 $!=0; $?=-1; system @cmd;
460 ? "git index contains changes (does not match HEAD)"
461 : "working tree is dirty (does not match HEAD)";
468 sub is_fast_fwd ($$) {
469 my ($ancestor,$child) = @_;
470 my @cmd = (qw(git merge-base), $ancestor, $child);
471 my $mb = cmdoutput_errok @cmd;
473 return git_rev_parse($mb) eq git_rev_parse($ancestor);
475 $?==256 or failedcmd @cmd;
482 printdebug "CD $newdir\n";
483 chdir $newdir or confess "chdir: $newdir: $!";
486 sub git_slurp_config_src ($) {
488 # returns $r such that $r->{KEY}[] = VALUE
489 my @cmd = (qw(git config -z --get-regexp), "--$src", qw(.*));
492 local ($debuglevel) = $debuglevel-2;
496 open GITS, "-|", @cmd or die $!;
499 printdebug "=> ", (messagequote $_), "\n";
501 push @{ $r->{$`} }, $'; #';
505 or ($!==0 && $?==256)
510 # ========== playground handling ==========
514 # $maindir user's git working tree
515 # playground area in .git/ where we can make files, unpack, etc. etc.
516 # playtree git working tree sharing object store with the user's
517 # inside playground, or identical to it
521 # $local_git_cfg hash of arrays of values: git config from $maindir
523 # expected calling pattern
528 # must be run in directory containing .git
529 # assigns to $maindir if not already set
530 # also calls git_slurp_config_src to record git config
531 # in $local_git_cfg, unless it's already set
533 # fresh_playground SUBDIR_PATH_COMPONENTS
534 # e.g fresh_playground 'dgit/unpack' ('.git/' is implied)
535 # default SUBDIR_PATH_COMPONENTS is playground_subdir
536 # calls record_maindir
537 # sets up a new playground (destroying any old one)
538 # returns playground pathname
539 # caller may call multiple times with different subdir paths
540 # createing different playgrounds
542 # ensure_a_playground SUBDIR_PATH_COMPONENTS
543 # like fresh_playground except:
544 # merely ensures the directory exists; does not delete an existing one
548 # changedir playground
551 # playtree_setup $local_git_cfg
552 # # ^ call in some (perhaps trivial) subdir of playground
556 # ----- maindir -----
558 # these three all go together
561 our $maindir_gitcommon;
565 sub record_maindir () {
566 if (!defined $maindir) {
567 $maindir = must_getcwd();
568 if (!stat "$maindir/.git") {
569 fail "cannot stat $maindir/.git: $!";
572 # we fall back to this in case we have a pre-worktree
573 # git, which may not know git rev-parse --git-common-dir
574 $maindir_gitdir = "$maindir/.git";
575 $maindir_gitcommon = "$maindir/.git";
577 $maindir_gitdir = cmdoutput qw(git rev-parse --git-dir);
578 $maindir_gitcommon = cmdoutput qw(git rev-parse --git-common-dir);
581 $local_git_cfg //= git_slurp_config_src 'local';
584 # ----- playgrounds -----
586 sub ensure_a_playground_parent ($) {
589 $spc = "$maindir_gitdir/$spc";
590 my $parent = dirname $spc;
591 mkdir $parent or $!==EEXIST
592 or fail "failed to mkdir playground parent $parent: $!";
596 sub ensure_a_playground ($) {
598 $spc = ensure_a_playground_parent $spc;
599 mkdir $spc or $!==EEXIST or fail "failed to mkdir a playground $spc: $!";
603 sub fresh_playground ($) {
605 $spc = ensure_a_playground_parent $spc;
607 mkdir $spc or fail "failed to mkdir the playground $spc: $!";
611 # ----- playtrees -----
613 sub playtree_setup (;$) {
614 my ($t_local_git_cfg) = @_;
615 $t_local_git_cfg //= $local_git_cfg;
616 # for use in the playtree
617 # $maindir must be set, eg by calling record_maindir or fresh_playground
618 runcmd qw(git init -q);
619 runcmd qw(git config gc.auto 0);
620 foreach my $copy (qw(user.email user.name user.useConfigOnly
621 core.sharedRepository
622 core.compression core.looseCompression
623 core.bigFileThreshold core.fsyncObjectFiles)) {
624 my $v = $t_local_git_cfg->{$copy};
626 runcmd qw(git config), $copy, $_ foreach @$v;
628 # this is confusing: we have
629 # . playtree, not a worktree, has .git/, our cwd
630 # $maindir might be a worktree so
631 # $maindir_gitdir contains our main working "dgit", HEAD, etc.
632 # $maindir_gitcommon the shared stuff, including .objects
633 rmtree('.git/objects');
634 symlink "$maindir_gitcommon/objects",'.git/objects' or die $!;
635 ensuredir '.git/info';
636 open GA, "> .git/info/attributes" or die $!;
637 print GA "* $negate_harmful_gitattrs\n" or die $!;