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_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
68 fresh_playground $playground
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 ($) {
353 # => ($type, $data) or ('missing', undef)
354 # in scalar context, just the data
355 our ($gcf_pid, $gcf_i, $gcf_o);
357 my @cmd = qw(git cat-file --batch);
358 debugcmd "GCF|", @cmd;
359 $gcf_pid = open2 $gcf_o, $gcf_i, @cmd or die $!;
361 printdebug "GCF>| ", $objname, "\n";
362 print $gcf_i $objname, "\n" or die $!;
364 printdebug "GCF<| ", $x;
365 if ($x =~ m/ (missing)$/) { return ($1, undef); }
366 my ($type, $size) = $x =~ m/^.* (\w+) (\d+)\n/ or die "$objname ?";
368 (read $gcf_o, $data, $size) == $size or die "$objname $!";
370 $x eq "\n" or die "$objname ($_) $!";
371 return ($type, $data);
374 sub git_for_each_ref ($$;$) {
375 my ($pattern,$func,$gitdir) = @_;
376 # calls $func->($objid,$objtype,$fullrefname,$reftail);
377 # $reftail is RHS of ref after refs/[^/]+/
378 # breaks if $pattern matches any ref `refs/blah' where blah has no `/'
379 # $pattern may be an array ref to mean multiple patterns
380 $pattern = [ $pattern ] unless ref $pattern;
381 my @cmd = (qw(git for-each-ref), @$pattern);
382 if (defined $gitdir) {
383 @cmd = ('sh','-ec','cd "$1"; shift; exec "$@"','x', $gitdir, @cmd);
385 open GFER, "-|", @cmd or die $!;
389 printdebug "|> ", $_, "\n";
390 m#^(\w+)\s+(\w+)\s+(refs/[^/]+/(\S+))$# or die "$_ ?";
391 $func->($1,$2,$3,$4);
393 $!=0; $?=0; close GFER or die "$pattern $? $!";
396 sub git_get_ref ($) {
397 # => '' if no such ref
400 s{^refs/}{[r]efs/} or die "$refname $_ ?";
401 return cmdoutput qw(git for-each-ref --format=%(objectname)), $_;
404 sub git_for_each_tag_referring ($$) {
405 my ($objreferring, $func) = @_;
406 # calls $func->($tagobjid,$refobjid,$fullrefname,$tagname);
407 printdebug "git_for_each_tag_referring ",
408 ($objreferring // 'UNDEF'),"\n";
409 git_for_each_ref('refs/tags', sub {
410 my ($tagobjid,$objtype,$fullrefname,$tagname) = @_;
411 return unless $objtype eq 'tag';
412 my $refobjid = git_rev_parse $tagobjid;
414 !defined $objreferring # caller wants them all
415 or $tagobjid eq $objreferring
416 or $refobjid eq $objreferring;
417 $func->($tagobjid,$refobjid,$fullrefname,$tagname);
421 sub is_fast_fwd ($$) {
422 my ($ancestor,$child) = @_;
423 my @cmd = (qw(git merge-base), $ancestor, $child);
424 my $mb = cmdoutput_errok @cmd;
426 return git_rev_parse($mb) eq git_rev_parse($ancestor);
428 $?==256 or failedcmd @cmd;
435 printdebug "CD $newdir\n";
436 chdir $newdir or confess "chdir: $newdir: $!";
439 sub git_slurp_config_src ($) {
441 # returns $r such that $r->{KEY}[] = VALUE
442 my @cmd = (qw(git config -z --get-regexp), "--$src", qw(.*));
445 local ($debuglevel) = $debuglevel-2;
449 open GITS, "-|", @cmd or die $!;
452 printdebug "=> ", (messagequote $_), "\n";
454 push @{ $r->{$`} }, $'; #';
458 or ($!==0 && $?==256)
463 # ========== playground handling ==========
467 # $maindir user's git working tree
468 # $playground area in .git/ where we can make files, unpack, etc. etc.
469 # playtree git working tree sharing object store with the user's
470 # inside playground, or identical to it
474 # $local_git_cfg hash of arrays of values: git config from $maindir
476 # expected calling pattern
481 # must be run in directory containing .git
482 # assigns to $maindir if not already set
483 # also calls git_slurp_config_src to record git config
484 # in $local_git_cfg, unless it's already set
486 # fresh_playground SUBDIR_PATH_COMPONENTS
487 # e.g fresh_playground 'dgit/unpack' ('.git/' is implied)
488 # default SUBDIR_PATH_COMPONENTS is $playground_subdir
489 # calls record_maindir
490 # sets up a new playground (destroying any old one)
491 # assigns to $playground and returns the same pathname
492 # caller may call multiple times with different subdir paths
493 # createing different playgrounds; but $playground global can
494 # refer only to one, obv.
496 # ensure_a_playground SUBDIR_PATH_COMPONENTS
497 # like fresh_playground except:
498 # merely ensures the directory exists; does not delete an existing one
499 # never sets global $playground
503 # changedir $playground
506 # playtree_setup $local_git_cfg
507 # # ^ call in some (perhaps trivial) subdir of $playground
511 # ----- maindir -----
513 # these three all go together
516 our $maindir_gitcommon;
520 sub record_maindir () {
521 if (!defined $maindir) {
522 $maindir = must_getcwd();
523 if (!stat "$maindir/.git") {
524 fail "cannot stat $maindir/.git: $!";
527 # we fall back to this in case we have a pre-worktree
528 # git, which may not know git rev-parse --git-common-dir
529 $maindir_gitdir = "$maindir/.git";
530 $maindir_gitcommon = "$maindir/.git";
532 $maindir_gitdir = cmdoutput qw(git rev-parse --git-dir);
533 $maindir_gitcommon = cmdoutput qw(git rev-parse --git-common-dir);
536 $local_git_cfg //= git_slurp_config_src 'local';
539 # ----- playgrounds -----
543 sub ensure_a_playground_parent ($) {
546 $spc = "$maindir_gitdir/$spc";
547 my $parent = dirname $spc;
548 mkdir $parent or $!==EEXIST
549 or fail "failed to mkdir playground parent $parent: $!";
553 sub ensure_a_playground ($) {
555 $spc = ensure_a_playground_parent $spc;
556 mkdir $spc or $!==EEXIST or fail "failed to mkdir a playground $spc: $!";
560 sub fresh_playground ($) {
562 $spc = ensure_a_playground_parent $spc;
564 mkdir $spc or fail "failed to mkdir the playground $spc: $!";
565 return $playground = $spc;
568 # ----- playtrees -----
570 sub playtree_setup (;$) {
571 my ($t_local_git_cfg) = @_;
572 $t_local_git_cfg //= $local_git_cfg;
573 # for use in the playtree
574 # $maindir must be set, eg by calling record_maindir or fresh_playground
575 runcmd qw(git init -q);
576 runcmd qw(git config gc.auto 0);
577 foreach my $copy (qw(user.email user.name user.useConfigOnly
578 core.sharedRepository
579 core.compression core.looseCompression
580 core.bigFileThreshold core.fsyncObjectFiles)) {
581 my $v = $t_local_git_cfg->{$copy};
583 runcmd qw(git config), $copy, $_ foreach @$v;
585 # this is confusing: we have
586 # . playtree, not a worktree, has .git/, our cwd
587 # $maindir might be a worktree so
588 # $maindir_gitdir contains our main working "dgit", HEAD, etc.
589 # $maindir_gitcommon the shared stuff, including .objects
590 rmtree('.git/objects');
591 symlink "$maindir_gitcommon/objects",'.git/objects' or die $!;
592 ensuredir '.git/info';
593 open GA, "> .git/info/attributes" or die $!;
594 print GA "* $negate_harmful_gitattrs\n" or die $!;