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/>.
32 use File::Path qw(:DEFAULT make_path);
34 use Dpkg::Control::Hash;
35 use Debian::Dgit::ExitStatus;
36 use Debian::Dgit::I18n;
40 our ($VERSION, @ISA, @EXPORT, @EXPORT_OK, %EXPORT_TAGS);
44 @EXPORT = qw(setup_sigwarn forkcheck_setup forkcheck_mainprocess
46 debiantags debiantag_new
49 upstream_commitish_search resolve_upstream_version
50 stripepoch source_file_leafname is_orig_file_of_p_v
51 server_branch server_ref
52 stat_exists link_ltarget rename_link_xf
54 fail failmsg ensuredir ensurepath
55 must_getcwd executable_on_path
56 waitstatusmsg failedcmd_waitstatus
57 failedcmd_report_cmd failedcmd
58 runcmd shell_cmd cmdoutput cmdoutput_errok
59 git_rev_parse changedir_git_toplevel git_cat_file
60 git_get_ref git_get_symref git_for_each_ref
61 git_for_each_tag_referring is_fast_fwd
63 git_reflog_action_msg git_update_ref_cmd
64 rm_subdir_cached read_tree_subdir
65 read_tree_debian read_tree_upstream
66 make_commit hash_commit hash_commit_text
67 reflog_cache_insert reflog_cache_lookup
68 $package_re $component_re $suite_re $deliberately_re
69 $distro_re $versiontag_re $series_filename_re
70 $orig_f_comp_re $orig_f_sig_re $orig_f_tail_re
71 $extra_orig_namepart_re
74 $ffq_refprefix $gdrlast_refprefix
75 initdebug enabledebug enabledebuglevel
77 $printdebug_when_debuglevel $debugcmd_when_debuglevel
78 $debugprefix *debuglevel *DEBUG
79 shellquote printcmd messagequote
80 $negate_harmful_gitattrs
81 changedir git_slurp_config_src
82 gdr_ffq_prev_branchinfo
83 parsecontrolfh parsecontrol parsechangelog
84 getfield parsechangelog_loop
86 # implicitly uses $main::us
87 %EXPORT_TAGS = ( policyflags => [qw(NOFFCHECK FRESHREPO NOCOMMITCHECK)],
88 playground => [qw(record_maindir $maindir $local_git_cfg
89 $maindir_gitdir $maindir_gitcommon
91 ensure_a_playground)]);
92 @EXPORT_OK = ( @{ $EXPORT_TAGS{policyflags} },
93 @{ $EXPORT_TAGS{playground} } );
98 our $package_re = '[0-9a-z][-+.0-9a-z]*';
99 our $component_re = '[0-9a-zA-Z][-+.0-9a-zA-Z]*';
100 our $suite_re = '[-+.0-9a-z]+';
101 our $deliberately_re = "(?:TEST-)?$package_re";
102 our $distro_re = $component_re;
103 our $versiontag_re = qr{[-+.\%_0-9a-zA-Z/]+};
104 our $branchprefix = 'dgit';
105 our $series_filename_re = qr{(?:^|\.)series(?!\n)$}s;
106 our $extra_orig_namepart_re = qr{[-0-9a-zA-Z]+};
107 our $orig_f_comp_re = qr{orig(?:-$extra_orig_namepart_re)?};
108 our $orig_f_sig_re = '\\.(?:asc|gpg|pgp)';
109 our $orig_f_tail_re = "$orig_f_comp_re\\.tar(?:\\.\\w+)?(?:$orig_f_sig_re)?";
110 our $git_null_obj = '0' x 40;
111 our $ffq_refprefix = 'ffq-prev';
112 our $gdrlast_refprefix = 'debrebase-last';
113 our $printdebug_when_debuglevel = 1;
114 our $debugcmd_when_debuglevel = 1;
116 # these three all go together, only valid after record_maindir
119 our $maindir_gitcommon;
121 # policy hook exit status bits
122 # see dgit-repos-server head comment for documentation
123 # 1 is reserved in case something fails with `exit 1' and to spot
124 # dynamic loader, runtime, etc., failures, which report 127 or 255
125 sub NOFFCHECK () { return 0x2; }
126 sub FRESHREPO () { return 0x4; }
127 sub NOCOMMITCHECK () { return 0x8; }
132 our $negate_harmful_gitattrs =
133 "-text -eol -crlf -ident -filter -working-tree-encoding";
134 # ^ when updating this, alter the regexp in dgit:is_gitattrs_setup
136 our $forkcheck_mainprocess;
138 sub forkcheck_setup () {
139 $forkcheck_mainprocess = $$;
142 sub forkcheck_mainprocess () {
143 # You must have called forkcheck_setup or setup_sigwarn already
144 getppid != $forkcheck_mainprocess;
147 sub setup_sigwarn () {
149 $SIG{__WARN__} = sub {
150 confess $_[0] if forkcheck_mainprocess;
156 open DEBUG, ">/dev/null" or confess "$!";
160 open DEBUG, ">&STDERR" or confess "$!";
165 sub enabledebuglevel ($) {
166 my ($newlevel) = @_; # may be undef (eg from env var)
167 confess if $debuglevel;
170 return unless $newlevel;
171 $debuglevel = $newlevel;
176 # Prints a prefix, and @_, to DEBUG. @_ should normally contain
179 # With no (or only empty) arguments just prints the prefix and
180 # leaves the caller to do more with DEBUG. The caller should make
181 # sure then to call printdebug with something ending in "\n" to
182 # get the prefix right in subsequent calls.
184 return unless $debuglevel >= $printdebug_when_debuglevel;
185 our $printdebug_noprefix;
186 print DEBUG $debugprefix unless $printdebug_noprefix;
187 pop @_ while @_ and !length $_[-1];
189 print DEBUG @_ or confess "$!";
190 $printdebug_noprefix = $_[-1] !~ m{\n$};
193 sub messagequote ($) {
199 s{[\000-\037\177]}{ sprintf "\\x%02x", ord $& }ge;
206 defined or confess __ 'internal error' foreach @_;
209 if (!length || m{[^-=_./:0-9a-z]}i) {
216 return join ' ', @out;
221 my $intro = shift @_;
222 print $fh $intro," " or confess "$!";
223 print $fh shellquote @_ or confess "$!";
224 print $fh "\n" or confess "$!";
228 my $extraprefix = shift @_;
229 printcmd(\*DEBUG,$debugprefix.$extraprefix,@_)
230 if $debuglevel >= $debugcmd_when_debuglevel;
233 sub dep14_version_mangle ($) {
235 # DEP-14 patch proposed 2016-11-09 "Version Mangling"
237 $v =~ s/\.(?=\.|$|lock$)/.#/g;
241 sub debiantag_new ($$) {
242 my ($v,$distro) = @_;
243 return "archive/$distro/".dep14_version_mangle $v;
246 sub debiantag_maintview ($$) {
247 my ($v,$distro) = @_;
248 return "$distro/".dep14_version_mangle $v;
251 sub debiantags ($$) {
252 my ($version,$distro) = @_;
253 map { $_->($version, $distro) } (\&debiantag_new, \&debiantag_maintview);
262 sub upstreamversion ($) {
268 sub source_file_leafname ($$$) {
269 my ($package,$vsn,$sfx) = @_;
270 return "${package}_".(stripepoch $vsn).$sfx
273 sub is_orig_file_of_p_v ($$$) {
274 my ($f, $package, $upstreamvsn) = @_;
275 my $base = source_file_leafname $package, $upstreamvsn, '';
276 return 0 unless $f =~ m/^\Q$base\E\.$orig_f_tail_re$/;
280 sub server_branch ($) { return "$branchprefix/$_[0]"; }
281 sub server_ref ($) { return "refs/".server_branch($_[0]); }
283 sub stat_exists ($) {
286 return 0 if $!==&ENOENT;
287 confess "stat $f: $!";
291 $::us // ($0 =~ m#[^/]*$#, $&);
295 my $s = f_ "error: %s\n", "@_";
297 my $prefix = _us().": ";
298 $s =~ s/^/$prefix/gm;
307 my ($dir) = @_; # does not create parents
308 return if mkdir $dir;
309 return if $! == EEXIST;
310 confess "mkdir $dir: $!";
313 sub ensurepath ($$) {
314 my ($firsttocreate, $subdir) = @_; # creates necessary bits of $subidr
315 ensuredir $firsttocreate;
316 make_path "$firsttocreate/$subdir";
321 defined $d or fail f_ "getcwd failed: %s\n", $!;
325 sub executable_on_path ($) {
327 return 1 if $program =~ m{/};
328 my @path = split /:/, ($ENV{PATH} // "/usr/local/bin:/bin:/usr/bin");
329 foreach my $pe (@path) {
330 my $here = "$pe/$program";
331 return $here if stat_exists $here && -x _;
336 our @signames = split / /, $Config{sig_name};
338 sub waitstatusmsg () {
340 return __ "terminated, reporting successful completion";
341 } elsif (!($? & 255)) {
342 return f_ "failed with error exit status %s", WEXITSTATUS($?);
343 } elsif (WIFSIGNALED($?)) {
344 my $signum=WTERMSIG($?);
345 return f_ "died due to fatal signal %s",
346 ($signames[$signum] // "number $signum").
347 ($? & 128 ? " (core dumped)" : ""); # POSIX(3pm) has no WCOREDUMP
349 return f_ "failed with unknown wait status %s", $?;
353 sub failedcmd_report_cmd {
354 my $intro = shift @_;
355 $intro //= __ "failed command";
356 { local ($!); printcmd \*STDERR, _us().": $intro:", @_ or confess "$!"; };
359 sub failedcmd_waitstatus {
361 return f_ "failed to fork/exec: %s", $!;
363 return f_ "subprocess %s", waitstatusmsg();
365 return __ "subprocess produced invalid output";
370 # Expects $!,$? as set by close - see below.
371 # To use with system(), set $?=-1 first.
373 # Actual behaviour of perl operations:
374 # success $!==0 $?==0 close of piped open
375 # program failed $!==0 $? >0 close of piped open
376 # syscall failure $! >0 $?=-1 close of piped open
377 # failure $! >0 unchanged close of something else
378 # success trashed $?==0 system
379 # program failed trashed $? >0 system
380 # syscall failure $! >0 unchanged system
381 failedcmd_report_cmd undef, @_;
382 fail failedcmd_waitstatus();
388 failedcmd @_ if system @_;
392 my ($first_shell, @cmd) = @_;
393 return qw(sh -ec), $first_shell.'; exec "$@"', 'x', @cmd;
396 sub cmdoutput_errok {
397 confess Dumper(\@_)." ?" if grep { !defined } @_;
398 local $printdebug_when_debuglevel = $debugcmd_when_debuglevel;
400 open P, "-|", @_ or confess "$_[0] $!";
403 { local $/ = undef; $d = <P>; }
404 confess "$!" if P->error;
405 if (!close P) { printdebug "=>!$?\n"; return undef; }
407 if ($debuglevel > 0) {
410 my $more = (length $' ? '...' : ''); #');
411 $dd =~ s{[^\n -~]|\\}{ sprintf "\\x%02x", ord $& }ge;
412 printdebug "=> \`$dd'",$more,"\n";
418 my $d = cmdoutput_errok @_;
419 defined $d or failedcmd @_;
423 sub link_ltarget ($$) {
425 lstat $old or return undef;
427 $old = cmdoutput qw(realpath --), $old;
429 my $r = link $old, $new;
430 $r = symlink $old, $new if !$r && $!==EXDEV;
431 $r or fail "(sym)link $old $new: $!\n";
434 sub rename_link_xf ($$$) {
435 # renames/moves or links/copies $src to $dst,
436 # even if $dst is on a different fs
437 # (May use the filename "$dst.tmp".);
438 # On success, returns true.
439 # On failure, returns false and sets
440 # $@ to a reason message
441 # $! to an errno value, or -1 if not known
442 # having possibly printed something about mv to stderr.
443 # Not safe to use without $keeporig if $dst might be a symlink
444 # to $src, as it might delete $src leaving $dst invalid.
445 my ($keeporig,$src,$dst) = @_;
448 : rename $src, $dst) {
456 $@ = f_ "stat source file: %S", $!;
459 my @src_stat = (stat _)[0..1];
463 @dst_stat = (stat _)[0..1];
464 } elsif ($! == ENOENT) {
466 $@ = f_ "stat destination file: %S", $!;
470 if ("@src_stat" eq "@dst_stat") {
471 # (Symlinks to) the same file. No need for a copy but
472 # we may need to delete the original.
473 printdebug "rename_link_xf $keeporig $src $dst EXDEV but same\n";
476 my @cmd = (qw(cp --), $src, "$dst.tmp");
479 failedcmd_report_cmd undef, @cmd;
480 $@ = failedcmd_waitstatus();
484 if (!rename "$dst.tmp", $dst) {
485 $@ = f_ "finally install file after cp: %S", $!;
491 $@ = f_ "delete old file after cp: %S", $!;
500 my $h = Digest::SHA->new(256);
502 return $h->hexdigest();
505 sub git_rev_parse ($) {
506 return cmdoutput qw(git rev-parse), "$_[0]~0";
509 sub changedir_git_toplevel () {
510 my $toplevel = cmdoutput qw(git rev-parse --show-toplevel);
511 length $toplevel or fail __ <<END;
512 not in a git working tree?
513 (git rev-parse --show-toplevel produced no output)
515 chdir $toplevel or fail f_ "chdir toplevel %s: %s\n", $toplevel, $!;
518 sub git_cat_file ($;$) {
519 my ($objname, $etype) = @_;
520 # => ($type, $data) or ('missing', undef)
521 # in scalar context, just the data
522 # if $etype defined, dies unless type is $etype or in @$etype
523 our ($gcf_pid, $gcf_i, $gcf_o);
524 local $printdebug_when_debuglevel = $debugcmd_when_debuglevel;
526 my ($gtype, $data) = @_;
528 $etype = [$etype] unless ref $etype;
529 confess "$objname expected @$etype but is $gtype"
530 unless grep { $gtype eq $_ } @$etype;
532 return ($gtype, $data);
535 my @cmd = qw(git cat-file --batch);
536 debugcmd "GCF|", @cmd;
537 $gcf_pid = open2 $gcf_o, $gcf_i, @cmd or confess "$!";
539 printdebug "GCF>| $objname\n";
540 print $gcf_i $objname, "\n" or confess "$!";
542 printdebug "GCF<| ", $x;
543 if ($x =~ m/ (missing)$/) { return $chk->($1, undef); }
544 my ($type, $size) = $x =~ m/^.* (\w+) (\d+)\n/ or confess "$objname ?";
546 (read $gcf_o, $data, $size) == $size or confess "$objname $!";
548 $x eq "\n" or confess "$objname ($_) $!";
549 return $chk->($type, $data);
552 sub git_get_symref (;$) {
553 my ($symref) = @_; $symref //= 'HEAD';
554 # => undef if not a symref, otherwise refs/...
555 my @cmd = (qw(git symbolic-ref -q HEAD));
556 my $branch = cmdoutput_errok @cmd;
557 if (!defined $branch) {
558 $?==256 or failedcmd @cmd;
565 sub git_for_each_ref ($$;$) {
566 my ($pattern,$func,$gitdir) = @_;
567 # calls $func->($objid,$objtype,$fullrefname,$reftail);
568 # $reftail is RHS of ref after refs/[^/]+/
569 # breaks if $pattern matches any ref `refs/blah' where blah has no `/'
570 # $pattern may be an array ref to mean multiple patterns
571 $pattern = [ $pattern ] unless ref $pattern;
572 my @cmd = (qw(git for-each-ref), @$pattern);
573 if (defined $gitdir) {
574 @cmd = ('sh','-ec','cd "$1"; shift; exec "$@"','x', $gitdir, @cmd);
576 open GFER, "-|", @cmd or confess "$!";
579 chomp or confess "$_ ?";
580 printdebug "|> ", $_, "\n";
581 m#^(\w+)\s+(\w+)\s+(refs/[^/]+/(\S+))$# or confess "$_ ?";
582 $func->($1,$2,$3,$4);
584 $!=0; $?=0; close GFER or confess "$pattern $? $!";
587 sub git_get_ref ($) {
588 # => '' if no such ref
591 s{^refs/}{[r]efs/} or confess "$refname $_ ?";
592 return cmdoutput qw(git for-each-ref --format=%(objectname)), $_;
595 sub git_for_each_tag_referring ($$) {
596 my ($objreferring, $func) = @_;
597 # calls $func->($tagobjid,$refobjid,$fullrefname,$tagname);
598 printdebug "git_for_each_tag_referring ",
599 ($objreferring // 'UNDEF'),"\n";
600 git_for_each_ref('refs/tags', sub {
601 my ($tagobjid,$objtype,$fullrefname,$tagname) = @_;
602 return unless $objtype eq 'tag';
603 my $refobjid = git_rev_parse $tagobjid;
605 !defined $objreferring # caller wants them all
606 or $tagobjid eq $objreferring
607 or $refobjid eq $objreferring;
608 $func->($tagobjid,$refobjid,$fullrefname,$tagname);
612 sub git_check_unmodified () {
613 foreach my $cached (qw(0 1)) {
614 my @cmd = qw(git diff --quiet);
615 push @cmd, qw(--cached) if $cached;
618 $!=0; $?=-1; system @cmd;
623 ? __ "git index contains changes (does not match HEAD)"
624 : __ "working tree is dirty (does not match HEAD)";
631 sub upstream_commitish_search ($$) {
632 my ($upstream_version, $tried) = @_;
633 # todo: at some point maybe use git-deborig to do this
634 foreach my $tagpfx ('', 'v', 'upstream/') {
635 my $tag = $tagpfx.(dep14_version_mangle $upstream_version);
636 my $new_upstream = git_get_ref "refs/tags/$tag";
638 return $new_upstream if length $new_upstream;
642 sub resolve_upstream_version ($$) {
643 my ($new_upstream, $upstream_version) = @_;
645 my $used = $new_upstream;
646 my $message = __ 'using specified upstream commitish';
647 if (!defined $new_upstream) {
649 $new_upstream = upstream_commitish_search $upstream_version, \@tried;
650 if (!length $new_upstream) {
652 "Could not determine appropriate upstream commitish.\n".
653 " (Tried these tags: %s)\n".
654 " Check version, and specify upstream commitish explicitly.",
658 $message = f_ 'using upstream from git tag %s', $used;
659 } elsif ($new_upstream =~ m{^refs/tags/($versiontag_re)$}s) {
660 $message = f_ 'using upstream from git tag %s', $1;
663 $new_upstream = git_rev_parse $new_upstream;
665 return ($new_upstream, $used, $message);
666 # used is a human-readable idea of what we found
669 sub is_fast_fwd ($$) {
670 my ($ancestor,$child) = @_;
671 my @cmd = (qw(git merge-base), $ancestor, $child);
672 my $mb = cmdoutput_errok @cmd;
674 return git_rev_parse($mb) eq git_rev_parse($ancestor);
676 $?==256 or failedcmd @cmd;
681 sub git_reflog_action_msg ($) {
683 my $rla = $ENV{GIT_REFLOG_ACTION};
684 $msg = "$rla: $msg" if length $rla;
688 sub git_update_ref_cmd {
689 # returns qw(git update-ref), qw(-m), @_
690 # except that message may be modified to honour GIT_REFLOG_ACTION
692 $msg = git_reflog_action_msg $msg;
693 return qw(git update-ref -m), $msg, @_;
696 sub rm_subdir_cached ($) {
698 runcmd qw(git rm --quiet -rf --cached --ignore-unmatch), $subdir;
701 sub read_tree_subdir ($$) {
702 my ($subdir, $new_tree_object) = @_;
703 # If $new_tree_object is '', the subtree is deleted.
704 confess unless defined $new_tree_object;
705 rm_subdir_cached $subdir;
706 runcmd qw(git read-tree), "--prefix=$subdir/", $new_tree_object
707 if length $new_tree_object;
710 sub read_tree_debian ($) {
712 read_tree_subdir 'debian', "$treeish:debian";
713 rm_subdir_cached 'debian/patches';
716 sub read_tree_upstream ($;$$) {
717 my ($treeish, $keep_patches, $tree_with_debian) = @_;
718 # if $tree_with_debian is supplied, will use that for debian/
719 # otherwise will save and restore it. If $tree_with_debian
720 # is '' then debian/ is deleted.
722 defined $tree_with_debian ? "$tree_with_debian:debian"
723 : cmdoutput qw(git write-tree --prefix=debian/);
724 runcmd qw(git read-tree), $treeish;
725 read_tree_subdir 'debian', $debian;
726 rm_subdir_cached 'debian/patches' unless $keep_patches;
731 printdebug "CD $newdir\n";
732 chdir $newdir or confess "chdir: $newdir: $!";
735 sub git_slurp_config_src ($) {
737 # returns $r such that $r->{KEY}[] = VALUE
738 my @cmd = (qw(git config -z --get-regexp), "--$src", qw(.*));
741 local ($debuglevel) = $debuglevel-2;
745 open GITS, "-|", @cmd or confess "$!";
748 printdebug "=> ", (messagequote $_), "\n";
749 m/\n/ or confess "$_ ?";
750 push @{ $r->{$`} }, $'; #';
754 or ($!==0 && $?==256)
759 sub gdr_ffq_prev_branchinfo ($) {
761 # => ('status', "message", [$symref, $ffq_prev, $gdrlast])
763 # branch message is undef
764 # weird-symref } no $symref,
765 # notbranch } no $ffq_prev
766 return ('detached', __ 'detached HEAD') unless defined $symref;
767 return ('weird-symref', __ 'HEAD symref is not to refs/')
768 unless $symref =~ m{^refs/};
769 my $ffq_prev = "refs/$ffq_refprefix/$'";
770 my $gdrlast = "refs/$gdrlast_refprefix/$'";
771 printdebug "ffq_prev_branchinfo branch current $symref\n";
772 return ('branch', undef, $symref, $ffq_prev, $gdrlast);
775 sub parsecontrolfh ($$;$) {
776 my ($fh, $desc, $allowsigned) = @_;
777 our $dpkgcontrolhash_noissigned;
780 my %opts = ('name' => $desc);
781 $opts{allow_pgp}= $allowsigned || !$dpkgcontrolhash_noissigned;
782 $c = Dpkg::Control::Hash->new(%opts);
783 $c->parse($fh,$desc) or fail f_ "parsing of %s failed", $desc;
784 last if $allowsigned;
785 last if $dpkgcontrolhash_noissigned;
786 my $issigned= $c->get_option('is_pgp_signed');
787 if (!defined $issigned) {
788 $dpkgcontrolhash_noissigned= 1;
789 seek $fh, 0,0 or confess "seek $desc: $!";
790 } elsif ($issigned) {
792 "control file %s is (already) PGP-signed. ".
793 " Note that dgit push needs to modify the .dsc and then".
794 " do the signature itself",
804 my ($file, $desc, $allowsigned) = @_;
805 my $fh = new IO::Handle;
806 open $fh, '<', $file or fail f_ "open %s (%s): %s", $file, $desc, $!;
807 my $c = parsecontrolfh($fh,$desc,$allowsigned);
808 $fh->error and confess "$!";
814 my $c = Dpkg::Control::Hash->new(name => 'parsed changelog');
815 my $p = new IO::Handle;
816 my @cmd = (qw(dpkg-parsechangelog), @_);
817 open $p, '-|', @cmd or confess "$!";
819 $?=0; $!=0; close $p or failedcmd @cmd;
824 my ($dctrl,$field) = @_;
825 my $v = $dctrl->{$field};
826 return $v if defined $v;
827 fail f_ "missing field %s in %s", $field, $dctrl->get_option('name');
830 sub parsechangelog_loop ($$$) {
831 my ($clogcmd, $descbase, $fn) = @_;
832 # @$clogcmd is qw(dpkg-parsechangelog ...some...options...)
833 # calls $fn->($thisstanza, $desc);
834 debugcmd "|",@$clogcmd;
835 open CLOGS, "-|", @$clogcmd or confess "$!";
837 my $stanzatext = do { local $/=""; <CLOGS>; };
838 printdebug "clogp stanza ".Dumper($stanzatext) if $debuglevel>1;
839 last if !defined $stanzatext;
841 my $desc = "$descbase, entry no.$.";
842 open my $stanzafh, "<", \$stanzatext or confess;
843 my $thisstanza = parsecontrolfh $stanzafh, $desc, 1;
845 $fn->($thisstanza, $desc);
847 confess "$!" if CLOGS->error;
848 close CLOGS or $?==SIGPIPE or failedcmd @$clogcmd;
851 sub make_commit ($$) {
852 my ($parents, $message_paras) = @_;
853 my $tree = cmdoutput qw(git write-tree);
854 my @cmd = (qw(git commit-tree), $tree);
855 push @cmd, qw(-p), $_ foreach @$parents;
856 push @cmd, qw(-m), $_ foreach @$message_paras;
857 return cmdoutput @cmd;
860 sub hash_commit ($) {
862 return cmdoutput qw(git hash-object -w -t commit), $file;
865 sub hash_commit_text ($) {
868 my @cmd = (qw(git hash-object -w -t commit --stdin));
870 print Dumper($text) if $debuglevel > 1;
871 my $child = open2($out, $in, @cmd) or confess "$!";
874 print $in $text or confess "$!";
875 close $in or confess "$!";
877 $h =~ m/^\w+$/ or confess;
879 printdebug "=> $h\n";
882 waitpid $child, 0 == $child or confess "$child $!";
883 $? and failedcmd @cmd;
887 sub reflog_cache_insert ($$$) {
888 my ($ref, $cachekey, $value) = @_;
889 # you must call this in $maindir
890 # you must have called record_maindir
892 # When we no longer need to support squeeze, use --create-reflog
894 my $parent = $ref; $parent =~ s{/[^/]+$}{};
895 ensurepath "$maindir_gitcommon/logs", "$parent";
896 my $makelogfh = new IO::File "$maindir_gitcommon/logs/$ref", '>>'
899 my $oldcache = git_get_ref $ref;
901 if ($oldcache eq $value) {
902 my $tree = cmdoutput qw(git rev-parse), "$value:";
903 # git update-ref doesn't always update, in this case. *sigh*
904 my $authline = (ucfirst _us()).
905 ' <'._us().'@example.com> 1000000000 +0000';
906 my $dummy = hash_commit_text <<ENDU.(__ <<END);
913 Dummy commit - do not use
915 runcmd qw(git update-ref -m), _us()." - dummy", $ref, $dummy;
917 runcmd qw(git update-ref -m), $cachekey, $ref, $value;
920 sub reflog_cache_lookup ($$) {
921 my ($ref, $cachekey) = @_;
922 # you may call this in $maindir or in a playtree
923 # you must have called record_maindir
924 my @cmd = (qw(git log -g), '--pretty=format:%H %gs', $ref);
925 debugcmd "|(probably)",@cmd;
926 my $child = open GC, "-|"; defined $child or confess "$!";
928 chdir $maindir or confess "$!";
929 if (!stat "$maindir_gitcommon/logs/$ref") {
930 $! == ENOENT or confess "$!";
931 printdebug ">(no reflog)\n";
934 exec @cmd; die f_ "exec %s: %s\n", $cmd[0], $!;
938 printdebug ">| ", $_, "\n" if $debuglevel > 1;
939 next unless m/^(\w+) (\S.*\S)$/ && $2 eq $cachekey;
943 confess "$!" if GC->error;
944 failedcmd unless close GC;
948 # ========== playground handling ==========
952 # $maindir user's git working tree
953 # playground area in .git/ where we can make files, unpack, etc. etc.
954 # playtree git working tree sharing object store with the user's
955 # inside playground, or identical to it
959 # $local_git_cfg hash of arrays of values: git config from $maindir
961 # expected calling pattern
966 # must be run in directory containing .git
967 # assigns to $maindir if not already set
968 # also calls git_slurp_config_src to record git config
969 # in $local_git_cfg, unless it's already set
971 # fresh_playground SUBDIR_PATH_COMPONENTS
972 # e.g fresh_playground 'dgit/unpack' ('.git/' is implied)
973 # default SUBDIR_PATH_COMPONENTS is playground_subdir
974 # calls record_maindir
975 # sets up a new playground (destroying any old one)
976 # returns playground pathname
977 # caller may call multiple times with different subdir paths
978 # createing different playgrounds
980 # ensure_a_playground SUBDIR_PATH_COMPONENTS
981 # like fresh_playground except:
982 # merely ensures the directory exists; does not delete an existing one
986 # changedir playground
989 # playtree_setup $local_git_cfg
990 # # ^ call in some (perhaps trivial) subdir of playground
994 # ----- maindir -----
998 sub record_maindir () {
999 if (!defined $maindir) {
1000 $maindir = must_getcwd();
1001 if (!stat "$maindir/.git") {
1002 fail f_ "cannot stat %s/.git: %s", $maindir, $!;
1005 # we fall back to this in case we have a pre-worktree
1006 # git, which may not know git rev-parse --git-common-dir
1007 $maindir_gitdir = "$maindir/.git";
1008 $maindir_gitcommon = "$maindir/.git";
1010 $maindir_gitdir = cmdoutput qw(git rev-parse --git-dir);
1011 $maindir_gitcommon = cmdoutput qw(git rev-parse --git-common-dir);
1014 $local_git_cfg //= git_slurp_config_src 'local';
1017 # ----- playgrounds -----
1019 sub ensure_a_playground_parent ($) {
1022 $spc = "$maindir_gitdir/$spc";
1023 my $parent = dirname $spc;
1024 mkdir $parent or $!==EEXIST or fail f_
1025 "failed to mkdir playground parent %s: %s", $parent, $!;
1029 sub ensure_a_playground ($) {
1031 $spc = ensure_a_playground_parent $spc;
1032 mkdir $spc or $!==EEXIST or fail f_
1033 "failed to mkdir a playground %s: %s", $spc, $!;
1037 sub fresh_playground ($) {
1039 $spc = ensure_a_playground_parent $spc;
1041 mkdir $spc or fail f_
1042 "failed to mkdir the playground %s: %s", $spc, $!;
1046 # ----- playtrees -----
1048 sub playtree_setup (;$) {
1049 my ($t_local_git_cfg) = @_;
1050 $t_local_git_cfg //= $local_git_cfg;
1051 # for use in the playtree
1052 # $maindir must be set, eg by calling record_maindir or fresh_playground
1053 runcmd qw(git init -q);
1054 runcmd qw(git config gc.auto 0);
1055 foreach my $copy (qw(user.email user.name user.useConfigOnly
1056 core.sharedRepository
1057 core.compression core.looseCompression
1058 core.bigFileThreshold core.fsyncObjectFiles)) {
1059 my $v = $t_local_git_cfg->{$copy};
1061 runcmd qw(git config), $copy, $_ foreach @$v;
1063 # this is confusing: we have
1064 # . playtree, not a worktree, has .git/, our cwd
1065 # $maindir might be a worktree so
1066 # $maindir_gitdir contains our main working "dgit", HEAD, etc.
1067 # $maindir_gitcommon the shared stuff, including .objects
1068 rmtree('.git/objects');
1069 symlink "$maindir_gitcommon/objects",'.git/objects' or confess "$!";
1070 ensuredir '.git/info';
1071 open GA, "> .git/info/attributes" or confess "$!";
1072 print GA "* $negate_harmful_gitattrs\n" or confess "$!";
1073 close GA or confess "$!";