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
57 initdebug enabledebug enabledebuglevel
59 $debugprefix *debuglevel *DEBUG
60 shellquote printcmd messagequote
61 $negate_harmful_gitattrs
62 changedir git_slurp_config_src
64 # implicitly uses $main::us
65 %EXPORT_TAGS = ( policyflags => [qw(NOFFCHECK FRESHREPO NOCOMMITCHECK)],
66 playground => [qw(record_maindir $maindir $local_git_cfg
67 $maindir_gitdir $maindir_gitcommon
69 ensure_a_playground)]);
70 @EXPORT_OK = ( @{ $EXPORT_TAGS{policyflags} },
71 @{ $EXPORT_TAGS{playground} } );
76 our $package_re = '[0-9a-z][-+.0-9a-z]*';
77 our $component_re = '[0-9a-zA-Z][-+.0-9a-zA-Z]*';
78 our $deliberately_re = "(?:TEST-)?$package_re";
79 our $distro_re = $component_re;
80 our $versiontag_re = qr{[-+.\%_0-9a-zA-Z/]+};
81 our $branchprefix = 'dgit';
82 our $series_filename_re = qr{(?:^|\.)series(?!\n)$}s;
84 # policy hook exit status bits
85 # see dgit-repos-server head comment for documentation
86 # 1 is reserved in case something fails with `exit 1' and to spot
87 # dynamic loader, runtime, etc., failures, which report 127 or 255
88 sub NOFFCHECK () { return 0x2; }
89 sub FRESHREPO () { return 0x4; }
90 sub NOCOMMITCHECK () { return 0x8; }
95 our $negate_harmful_gitattrs = "-text -eol -crlf -ident -filter";
97 our $forkcheck_mainprocess;
99 sub forkcheck_setup () {
100 $forkcheck_mainprocess = $$;
103 sub forkcheck_mainprocess () {
104 # You must have called forkcheck_setup or setup_sigwarn already
105 getppid != $forkcheck_mainprocess;
108 sub setup_sigwarn () {
110 $SIG{__WARN__} = sub {
111 die $_[0] if forkcheck_mainprocess;
117 open DEBUG, ">/dev/null" or die $!;
121 open DEBUG, ">&STDERR" or die $!;
126 sub enabledebuglevel ($) {
127 my ($newlevel) = @_; # may be undef (eg from env var)
131 return unless $newlevel;
132 $debuglevel = $newlevel;
137 print DEBUG $debugprefix, @_ or die $! if $debuglevel>0;
140 sub messagequote ($) {
146 s{[\000-\037\177]}{ sprintf "\\x%02x", ord $& }ge;
153 defined or confess 'internal error' foreach @_;
156 if (!length || m{[^-=_./:0-9a-z]}i) {
163 return join ' ', @out;
168 my $intro = shift @_;
169 print $fh $intro," " or die $!;
170 print $fh shellquote @_ or die $!;
171 print $fh "\n" or die $!;
175 my $extraprefix = shift @_;
176 printcmd(\*DEBUG,$debugprefix.$extraprefix,@_) if $debuglevel>0;
179 sub dep14_version_mangle ($) {
181 # DEP-14 patch proposed 2016-11-09 "Version Mangling"
183 $v =~ s/\.(?=\.|$|lock$)/.#/g;
187 sub debiantag_old ($$) {
188 my ($v,$distro) = @_;
189 return "$distro/". dep14_version_mangle $v;
192 sub debiantag_new ($$) {
193 my ($v,$distro) = @_;
194 return "archive/$distro/".dep14_version_mangle $v;
197 sub debiantags ($$) {
198 my ($version,$distro) = @_;
199 map { $_->($version, $distro) } (\&debiantag_new, \&debiantag_old);
202 sub server_branch ($) { return "$branchprefix/$_[0]"; }
203 sub server_ref ($) { return "refs/".server_branch($_[0]); }
205 sub stat_exists ($) {
208 return 0 if $!==&ENOENT;
213 $::us // ($0 =~ m#[^/]*$#, $&);
219 my $prefix = _us().": ";
220 $s =~ s/^/$prefix/gm;
225 my ($dir) = @_; # does not create parents
226 return if mkdir $dir;
227 return if $! == EEXIST;
228 die "mkdir $dir: $!";
233 defined $d or fail "getcwd failed: $!";
237 sub executable_on_path ($) {
239 return 1 if $program =~ m{/};
240 my @path = split /:/, ($ENV{PATH} // "/usr/local/bin:/bin:/usr/bin");
241 foreach my $pe (@path) {
242 my $here = "$pe/$program";
243 return $here if stat_exists $here && -x _;
248 our @signames = split / /, $Config{sig_name};
250 sub waitstatusmsg () {
252 return "terminated, reporting successful completion";
253 } elsif (!($? & 255)) {
254 return "failed with error exit status ".WEXITSTATUS($?);
255 } elsif (WIFSIGNALED($?)) {
256 my $signum=WTERMSIG($?);
257 return "died due to fatal signal ".
258 ($signames[$signum] // "number $signum").
259 ($? & 128 ? " (core dumped)" : ""); # POSIX(3pm) has no WCOREDUMP
261 return "failed with unknown wait status ".$?;
265 sub failedcmd_report_cmd {
266 my $intro = shift @_;
267 $intro //= "failed command";
268 { local ($!); printcmd \*STDERR, _us().": $intro:", @_ or die $!; };
271 sub failedcmd_waitstatus {
273 return "failed to fork/exec: $!";
275 return "subprocess ".waitstatusmsg();
277 return "subprocess produced invalid output";
282 # Expects $!,$? as set by close - see below.
283 # To use with system(), set $?=-1 first.
285 # Actual behaviour of perl operations:
286 # success $!==0 $?==0 close of piped open
287 # program failed $!==0 $? >0 close of piped open
288 # syscall failure $! >0 $?=-1 close of piped open
289 # failure $! >0 unchanged close of something else
290 # success trashed $?==0 system
291 # program failed trashed $? >0 system
292 # syscall failure $! >0 unchanged system
293 failedcmd_report_cmd undef, @_;
294 fail failedcmd_waitstatus();
300 failedcmd @_ if system @_;
303 sub cmdoutput_errok {
304 confess Dumper(\@_)." ?" if grep { !defined } @_;
306 open P, "-|", @_ or die "$_[0] $!";
309 { local $/ = undef; $d = <P>; }
311 if (!close P) { printdebug "=>!$?\n"; return undef; }
313 if ($debuglevel > 0) {
316 my $more = (length $' ? '...' : ''); #');
317 $dd =~ s{[^\n -~]|\\}{ sprintf "\\x%02x", ord $& }ge;
318 printdebug "=> \`$dd'",$more,"\n";
324 my $d = cmdoutput_errok @_;
325 defined $d or failedcmd @_;
329 sub link_ltarget ($$) {
331 lstat $old or return undef;
333 $old = cmdoutput qw(realpath --), $old;
335 my $r = link $old, $new;
336 $r = symlink $old, $new if !$r && $!==EXDEV;
337 $r or die "(sym)link $old $new: $!";
342 my $h = Digest::SHA->new(256);
344 return $h->hexdigest();
347 sub git_rev_parse ($) {
348 return cmdoutput qw(git rev-parse), "$_[0]~0";
351 sub git_cat_file ($;$) {
352 my ($objname, $etype) = @_;
353 # => ($type, $data) or ('missing', undef)
354 # in scalar context, just the data
355 # if $etype defined, dies unless type is $etype or in @$etype
356 our ($gcf_pid, $gcf_i, $gcf_o);
358 my ($gtype, $data) = @_;
360 $etype = [$etype] unless ref $etype;
361 confess "$objname expected @$etype but is $gtype"
362 unless grep { $gtype eq $_ } @$etype;
364 return ($gtype, $data);
367 my @cmd = qw(git cat-file --batch);
368 debugcmd "GCF|", @cmd;
369 $gcf_pid = open2 $gcf_o, $gcf_i, @cmd or die $!;
371 printdebug "GCF>| ", $objname, "\n";
372 print $gcf_i $objname, "\n" or die $!;
374 printdebug "GCF<| ", $x;
375 if ($x =~ m/ (missing)$/) { return $chk->($1, undef); }
376 my ($type, $size) = $x =~ m/^.* (\w+) (\d+)\n/ or die "$objname ?";
378 (read $gcf_o, $data, $size) == $size or die "$objname $!";
380 $x eq "\n" or die "$objname ($_) $!";
381 return $chk->($type, $data);
384 sub git_get_symref (;$) {
385 my ($symref) = @_; $symref //= 'HEAD';
386 # => undef if not a symref, otherwise refs/...
387 my @cmd = (qw(git symbolic-ref -q HEAD));
388 my $branch = cmdoutput_errok @cmd;
389 if (!defined $branch) {
390 $?==256 or failedcmd @cmd;
397 sub git_for_each_ref ($$;$) {
398 my ($pattern,$func,$gitdir) = @_;
399 # calls $func->($objid,$objtype,$fullrefname,$reftail);
400 # $reftail is RHS of ref after refs/[^/]+/
401 # breaks if $pattern matches any ref `refs/blah' where blah has no `/'
402 # $pattern may be an array ref to mean multiple patterns
403 $pattern = [ $pattern ] unless ref $pattern;
404 my @cmd = (qw(git for-each-ref), @$pattern);
405 if (defined $gitdir) {
406 @cmd = ('sh','-ec','cd "$1"; shift; exec "$@"','x', $gitdir, @cmd);
408 open GFER, "-|", @cmd or die $!;
412 printdebug "|> ", $_, "\n";
413 m#^(\w+)\s+(\w+)\s+(refs/[^/]+/(\S+))$# or die "$_ ?";
414 $func->($1,$2,$3,$4);
416 $!=0; $?=0; close GFER or die "$pattern $? $!";
419 sub git_get_ref ($) {
420 # => '' if no such ref
423 s{^refs/}{[r]efs/} or die "$refname $_ ?";
424 return cmdoutput qw(git for-each-ref --format=%(objectname)), $_;
427 sub git_for_each_tag_referring ($$) {
428 my ($objreferring, $func) = @_;
429 # calls $func->($tagobjid,$refobjid,$fullrefname,$tagname);
430 printdebug "git_for_each_tag_referring ",
431 ($objreferring // 'UNDEF'),"\n";
432 git_for_each_ref('refs/tags', sub {
433 my ($tagobjid,$objtype,$fullrefname,$tagname) = @_;
434 return unless $objtype eq 'tag';
435 my $refobjid = git_rev_parse $tagobjid;
437 !defined $objreferring # caller wants them all
438 or $tagobjid eq $objreferring
439 or $refobjid eq $objreferring;
440 $func->($tagobjid,$refobjid,$fullrefname,$tagname);
444 sub is_fast_fwd ($$) {
445 my ($ancestor,$child) = @_;
446 my @cmd = (qw(git merge-base), $ancestor, $child);
447 my $mb = cmdoutput_errok @cmd;
449 return git_rev_parse($mb) eq git_rev_parse($ancestor);
451 $?==256 or failedcmd @cmd;
458 printdebug "CD $newdir\n";
459 chdir $newdir or confess "chdir: $newdir: $!";
462 sub git_slurp_config_src ($) {
464 # returns $r such that $r->{KEY}[] = VALUE
465 my @cmd = (qw(git config -z --get-regexp), "--$src", qw(.*));
468 local ($debuglevel) = $debuglevel-2;
472 open GITS, "-|", @cmd or die $!;
475 printdebug "=> ", (messagequote $_), "\n";
477 push @{ $r->{$`} }, $'; #';
481 or ($!==0 && $?==256)
486 # ========== playground handling ==========
490 # $maindir user's git working tree
491 # playground area in .git/ where we can make files, unpack, etc. etc.
492 # playtree git working tree sharing object store with the user's
493 # inside playground, or identical to it
497 # $local_git_cfg hash of arrays of values: git config from $maindir
499 # expected calling pattern
504 # must be run in directory containing .git
505 # assigns to $maindir if not already set
506 # also calls git_slurp_config_src to record git config
507 # in $local_git_cfg, unless it's already set
509 # fresh_playground SUBDIR_PATH_COMPONENTS
510 # e.g fresh_playground 'dgit/unpack' ('.git/' is implied)
511 # default SUBDIR_PATH_COMPONENTS is playground_subdir
512 # calls record_maindir
513 # sets up a new playground (destroying any old one)
514 # returns playground pathname
515 # caller may call multiple times with different subdir paths
516 # createing different playgrounds
518 # ensure_a_playground SUBDIR_PATH_COMPONENTS
519 # like fresh_playground except:
520 # merely ensures the directory exists; does not delete an existing one
524 # changedir playground
527 # playtree_setup $local_git_cfg
528 # # ^ call in some (perhaps trivial) subdir of playground
532 # ----- maindir -----
534 # these three all go together
537 our $maindir_gitcommon;
541 sub record_maindir () {
542 if (!defined $maindir) {
543 $maindir = must_getcwd();
544 if (!stat "$maindir/.git") {
545 fail "cannot stat $maindir/.git: $!";
548 # we fall back to this in case we have a pre-worktree
549 # git, which may not know git rev-parse --git-common-dir
550 $maindir_gitdir = "$maindir/.git";
551 $maindir_gitcommon = "$maindir/.git";
553 $maindir_gitdir = cmdoutput qw(git rev-parse --git-dir);
554 $maindir_gitcommon = cmdoutput qw(git rev-parse --git-common-dir);
557 $local_git_cfg //= git_slurp_config_src 'local';
560 # ----- playgrounds -----
562 sub ensure_a_playground_parent ($) {
565 $spc = "$maindir_gitdir/$spc";
566 my $parent = dirname $spc;
567 mkdir $parent or $!==EEXIST
568 or fail "failed to mkdir playground parent $parent: $!";
572 sub ensure_a_playground ($) {
574 $spc = ensure_a_playground_parent $spc;
575 mkdir $spc or $!==EEXIST or fail "failed to mkdir a playground $spc: $!";
579 sub fresh_playground ($) {
581 $spc = ensure_a_playground_parent $spc;
583 mkdir $spc or fail "failed to mkdir the playground $spc: $!";
587 # ----- playtrees -----
589 sub playtree_setup (;$) {
590 my ($t_local_git_cfg) = @_;
591 $t_local_git_cfg //= $local_git_cfg;
592 # for use in the playtree
593 # $maindir must be set, eg by calling record_maindir or fresh_playground
594 runcmd qw(git init -q);
595 runcmd qw(git config gc.auto 0);
596 foreach my $copy (qw(user.email user.name user.useConfigOnly
597 core.sharedRepository
598 core.compression core.looseCompression
599 core.bigFileThreshold core.fsyncObjectFiles)) {
600 my $v = $t_local_git_cfg->{$copy};
602 runcmd qw(git config), $copy, $_ foreach @$v;
604 # this is confusing: we have
605 # . playtree, not a worktree, has .git/, our cwd
606 # $maindir might be a worktree so
607 # $maindir_gitdir contains our main working "dgit", HEAD, etc.
608 # $maindir_gitcommon the shared stuff, including .objects
609 rmtree('.git/objects');
610 symlink "$maindir_gitcommon/objects",'.git/objects' or die $!;
611 ensuredir '.git/info';
612 open GA, "> .git/info/attributes" or die $!;
613 print GA "* $negate_harmful_gitattrs\n" or die $!;