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." ".(join '', shellquote @_)."\n" or confess "$!";
226 my $extraprefix = shift @_;
227 printcmd(\*DEBUG,$debugprefix.$extraprefix,@_)
228 if $debuglevel >= $debugcmd_when_debuglevel;
231 sub dep14_version_mangle ($) {
233 # DEP-14 patch proposed 2016-11-09 "Version Mangling"
235 $v =~ s/\.(?=\.|$|lock$)/.#/g;
239 sub debiantag_new ($$) {
240 my ($v,$distro) = @_;
241 return "archive/$distro/".dep14_version_mangle $v;
244 sub debiantag_maintview ($$) {
245 my ($v,$distro) = @_;
246 return "$distro/".dep14_version_mangle $v;
249 sub debiantags ($$) {
250 my ($version,$distro) = @_;
251 map { $_->($version, $distro) } (\&debiantag_new, \&debiantag_maintview);
260 sub upstreamversion ($) {
266 sub source_file_leafname ($$$) {
267 my ($package,$vsn,$sfx) = @_;
268 return "${package}_".(stripepoch $vsn).$sfx
271 sub is_orig_file_of_p_v ($$$) {
272 my ($f, $package, $upstreamvsn) = @_;
273 my $base = source_file_leafname $package, $upstreamvsn, '';
274 return 0 unless $f =~ m/^\Q$base\E\.$orig_f_tail_re$/;
278 sub server_branch ($) { return "$branchprefix/$_[0]"; }
279 sub server_ref ($) { return "refs/".server_branch($_[0]); }
281 sub stat_exists ($) {
284 return 0 if $!==&ENOENT;
285 confess "stat $f: $!";
289 $::us // ($0 =~ m#[^/]*$#, $&);
293 my $s = f_ "error: %s\n", "@_";
295 my $prefix = _us().": ";
296 $s =~ s/^/$prefix/gm;
305 my ($dir) = @_; # does not create parents
306 return if mkdir $dir;
307 return if $! == EEXIST;
308 confess "mkdir $dir: $!";
311 sub ensurepath ($$) {
312 my ($firsttocreate, $subdir) = @_; # creates necessary bits of $subidr
313 ensuredir $firsttocreate;
314 make_path "$firsttocreate/$subdir";
319 defined $d or fail f_ "getcwd failed: %s\n", $!;
323 sub executable_on_path ($) {
325 return 1 if $program =~ m{/};
326 my @path = split /:/, ($ENV{PATH} // "/usr/local/bin:/bin:/usr/bin");
327 foreach my $pe (@path) {
328 my $here = "$pe/$program";
329 return $here if stat_exists $here && -x _;
334 our @signames = split / /, $Config{sig_name};
336 sub waitstatusmsg () {
338 return __ "terminated, reporting successful completion";
339 } elsif (!($? & 255)) {
340 return f_ "failed with error exit status %s", WEXITSTATUS($?);
341 } elsif (WIFSIGNALED($?)) {
342 my $signum=WTERMSIG($?);
343 return f_ "died due to fatal signal %s",
344 ($signames[$signum] // "number $signum").
345 ($? & 128 ? " (core dumped)" : ""); # POSIX(3pm) has no WCOREDUMP
347 return f_ "failed with unknown wait status %s", $?;
351 sub failedcmd_report_cmd {
352 my $intro = shift @_;
353 $intro //= __ "failed command";
354 { local ($!); printcmd \*STDERR, _us().": $intro:", @_ or confess "$!"; };
357 sub failedcmd_waitstatus {
359 return f_ "failed to fork/exec: %s", $!;
361 return f_ "subprocess %s", waitstatusmsg();
363 return __ "subprocess produced invalid output";
368 # Expects $!,$? as set by close - see below.
369 # To use with system(), set $?=-1 first.
371 # Actual behaviour of perl operations:
372 # success $!==0 $?==0 close of piped open
373 # program failed $!==0 $? >0 close of piped open
374 # syscall failure $! >0 $?=-1 close of piped open
375 # failure $! >0 unchanged close of something else
376 # success trashed $?==0 system
377 # program failed trashed $? >0 system
378 # syscall failure $! >0 unchanged system
379 failedcmd_report_cmd undef, @_;
380 fail failedcmd_waitstatus();
386 failedcmd @_ if system @_;
390 my ($first_shell, @cmd) = @_;
391 return qw(sh -ec), $first_shell.'; exec "$@"', 'x', @cmd;
394 sub cmdoutput_errok {
395 confess Dumper(\@_)." ?" if grep { !defined } @_;
396 local $printdebug_when_debuglevel = $debugcmd_when_debuglevel;
398 open P, "-|", @_ or confess "$_[0] $!";
401 { local $/ = undef; $d = <P>; }
402 confess "$!" if P->error;
403 if (!close P) { printdebug "=>!$?\n"; return undef; }
405 if ($debuglevel > 0) {
408 my $more = (length $' ? '...' : ''); #');
409 $dd =~ s{[^\n -~]|\\}{ sprintf "\\x%02x", ord $& }ge;
410 printdebug "=> \`$dd'",$more,"\n";
416 my $d = cmdoutput_errok @_;
417 defined $d or failedcmd @_;
421 sub link_ltarget ($$) {
423 lstat $old or return undef;
425 $old = cmdoutput qw(realpath --), $old;
427 my $r = link $old, $new;
428 $r = symlink $old, $new if !$r && $!==EXDEV;
429 $r or fail "(sym)link $old $new: $!\n";
432 sub rename_link_xf ($$$) {
433 # renames/moves or links/copies $src to $dst,
434 # even if $dst is on a different fs
435 # (May use the filename "$dst.tmp".);
436 # On success, returns true.
437 # On failure, returns false and sets
438 # $@ to a reason message
439 # $! to an errno value, or -1 if not known
440 # having possibly printed something about mv to stderr.
441 # Not safe to use without $keeporig if $dst might be a symlink
442 # to $src, as it might delete $src leaving $dst invalid.
443 my ($keeporig,$src,$dst) = @_;
446 : rename $src, $dst) {
454 $@ = f_ "stat source file: %S", $!;
457 my @src_stat = (stat _)[0..1];
461 @dst_stat = (stat _)[0..1];
462 } elsif ($! == ENOENT) {
464 $@ = f_ "stat destination file: %S", $!;
468 if ("@src_stat" eq "@dst_stat") {
469 # (Symlinks to) the same file. No need for a copy but
470 # we may need to delete the original.
471 printdebug "rename_link_xf $keeporig $src $dst EXDEV but same\n";
474 my @cmd = (qw(cp --), $src, "$dst.tmp");
477 failedcmd_report_cmd undef, @cmd;
478 $@ = failedcmd_waitstatus();
482 if (!rename "$dst.tmp", $dst) {
483 $@ = f_ "finally install file after cp: %S", $!;
489 $@ = f_ "delete old file after cp: %S", $!;
498 my $h = Digest::SHA->new(256);
500 return $h->hexdigest();
503 sub git_rev_parse ($) {
504 return cmdoutput qw(git rev-parse), "$_[0]~0";
507 sub changedir_git_toplevel () {
508 my $toplevel = cmdoutput qw(git rev-parse --show-toplevel);
509 length $toplevel or fail __ <<END;
510 not in a git working tree?
511 (git rev-parse --show-toplevel produced no output)
513 chdir $toplevel or fail f_ "chdir toplevel %s: %s\n", $toplevel, $!;
516 sub git_cat_file ($;$) {
517 my ($objname, $etype) = @_;
518 # => ($type, $data) or ('missing', undef)
519 # in scalar context, just the data
520 # if $etype defined, dies unless type is $etype or in @$etype
521 our ($gcf_pid, $gcf_i, $gcf_o);
522 local $printdebug_when_debuglevel = $debugcmd_when_debuglevel;
524 my ($gtype, $data) = @_;
526 $etype = [$etype] unless ref $etype;
527 confess "$objname expected @$etype but is $gtype"
528 unless grep { $gtype eq $_ } @$etype;
530 return ($gtype, $data);
533 my @cmd = qw(git cat-file --batch);
534 debugcmd "GCF|", @cmd;
535 $gcf_pid = open2 $gcf_o, $gcf_i, @cmd or confess "$!";
537 printdebug "GCF>| $objname\n";
538 print $gcf_i $objname, "\n" or confess "$!";
540 printdebug "GCF<| ", $x;
541 if ($x =~ m/ (missing)$/) { return $chk->($1, undef); }
542 my ($type, $size) = $x =~ m/^.* (\w+) (\d+)\n/ or confess "$objname ?";
544 (read $gcf_o, $data, $size) == $size or confess "$objname $!";
546 $x eq "\n" or confess "$objname ($_) $!";
547 return $chk->($type, $data);
550 sub git_get_symref (;$) {
551 my ($symref) = @_; $symref //= 'HEAD';
552 # => undef if not a symref, otherwise refs/...
553 my @cmd = (qw(git symbolic-ref -q HEAD));
554 my $branch = cmdoutput_errok @cmd;
555 if (!defined $branch) {
556 $?==256 or failedcmd @cmd;
563 sub git_for_each_ref ($$;$) {
564 my ($pattern,$func,$gitdir) = @_;
565 # calls $func->($objid,$objtype,$fullrefname,$reftail);
566 # $reftail is RHS of ref after refs/[^/]+/
567 # breaks if $pattern matches any ref `refs/blah' where blah has no `/'
568 # $pattern may be an array ref to mean multiple patterns
569 $pattern = [ $pattern ] unless ref $pattern;
570 my @cmd = (qw(git for-each-ref), @$pattern);
571 if (defined $gitdir) {
572 @cmd = ('sh','-ec','cd "$1"; shift; exec "$@"','x', $gitdir, @cmd);
574 open GFER, "-|", @cmd or confess "$!";
577 chomp or confess "$_ ?";
578 printdebug "|> ", $_, "\n";
579 m#^(\w+)\s+(\w+)\s+(refs/[^/]+/(\S+))$# or confess "$_ ?";
580 $func->($1,$2,$3,$4);
582 $!=0; $?=0; close GFER or confess "$pattern $? $!";
585 sub git_get_ref ($) {
586 # => '' if no such ref
589 s{^refs/}{[r]efs/} or confess "$refname $_ ?";
590 return cmdoutput qw(git for-each-ref --format=%(objectname)), $_;
593 sub git_for_each_tag_referring ($$) {
594 my ($objreferring, $func) = @_;
595 # calls $func->($tagobjid,$refobjid,$fullrefname,$tagname);
596 printdebug "git_for_each_tag_referring ",
597 ($objreferring // 'UNDEF'),"\n";
598 git_for_each_ref('refs/tags', sub {
599 my ($tagobjid,$objtype,$fullrefname,$tagname) = @_;
600 return unless $objtype eq 'tag';
601 my $refobjid = git_rev_parse $tagobjid;
603 !defined $objreferring # caller wants them all
604 or $tagobjid eq $objreferring
605 or $refobjid eq $objreferring;
606 $func->($tagobjid,$refobjid,$fullrefname,$tagname);
610 sub git_check_unmodified () {
611 foreach my $cached (qw(0 1)) {
612 my @cmd = qw(git diff --quiet);
613 push @cmd, qw(--cached) if $cached;
616 $!=0; $?=-1; system @cmd;
621 ? __ "git index contains changes (does not match HEAD)"
622 : __ "working tree is dirty (does not match HEAD)";
629 sub upstream_commitish_search ($$) {
630 my ($upstream_version, $tried) = @_;
631 # todo: at some point maybe use git-deborig to do this
632 foreach my $tagpfx ('', 'v', 'upstream/') {
633 my $tag = $tagpfx.(dep14_version_mangle $upstream_version);
634 my $new_upstream = git_get_ref "refs/tags/$tag";
636 return $new_upstream if length $new_upstream;
640 sub resolve_upstream_version ($$) {
641 my ($new_upstream, $upstream_version) = @_;
643 my $used = $new_upstream;
644 my $message = __ 'using specified upstream commitish';
645 if (!defined $new_upstream) {
647 $new_upstream = upstream_commitish_search $upstream_version, \@tried;
648 if (!length $new_upstream) {
650 "Could not determine appropriate upstream commitish.\n".
651 " (Tried these tags: %s)\n".
652 " Check version, and specify upstream commitish explicitly.",
656 $message = f_ 'using upstream from git tag %s', $used;
657 } elsif ($new_upstream =~ m{^refs/tags/($versiontag_re)$}s) {
658 $message = f_ 'using upstream from git tag %s', $1;
661 $new_upstream = git_rev_parse $new_upstream;
663 return ($new_upstream, $used, $message);
664 # used is a human-readable idea of what we found
667 sub is_fast_fwd ($$) {
668 my ($ancestor,$child) = @_;
669 my @cmd = (qw(git merge-base), $ancestor, $child);
670 my $mb = cmdoutput_errok @cmd;
672 return git_rev_parse($mb) eq git_rev_parse($ancestor);
674 $?==256 or failedcmd @cmd;
679 sub git_reflog_action_msg ($) {
681 my $rla = $ENV{GIT_REFLOG_ACTION};
682 $msg = "$rla: $msg" if length $rla;
686 sub git_update_ref_cmd {
687 # returns qw(git update-ref), qw(-m), @_
688 # except that message may be modified to honour GIT_REFLOG_ACTION
690 $msg = git_reflog_action_msg $msg;
691 return qw(git update-ref -m), $msg, @_;
694 sub rm_subdir_cached ($) {
696 runcmd qw(git rm --quiet -rf --cached --ignore-unmatch), $subdir;
699 sub read_tree_subdir ($$) {
700 my ($subdir, $new_tree_object) = @_;
701 # If $new_tree_object is '', the subtree is deleted.
702 confess unless defined $new_tree_object;
703 rm_subdir_cached $subdir;
704 runcmd qw(git read-tree), "--prefix=$subdir/", $new_tree_object
705 if length $new_tree_object;
708 sub read_tree_debian ($) {
710 read_tree_subdir 'debian', "$treeish:debian";
711 rm_subdir_cached 'debian/patches';
714 sub read_tree_upstream ($;$$) {
715 my ($treeish, $keep_patches, $tree_with_debian) = @_;
716 # if $tree_with_debian is supplied, will use that for debian/
717 # otherwise will save and restore it. If $tree_with_debian
718 # is '' then debian/ is deleted.
720 defined $tree_with_debian ? "$tree_with_debian:debian"
721 : cmdoutput qw(git write-tree --prefix=debian/);
722 runcmd qw(git read-tree), $treeish;
723 read_tree_subdir 'debian', $debian;
724 rm_subdir_cached 'debian/patches' unless $keep_patches;
729 printdebug "CD $newdir\n";
730 chdir $newdir or confess "chdir: $newdir: $!";
733 sub git_slurp_config_src ($) {
735 # returns $r such that $r->{KEY}[] = VALUE
736 my @cmd = (qw(git config -z --get-regexp), "--$src", qw(.*));
739 local ($debuglevel) = $debuglevel-2;
743 open GITS, "-|", @cmd or confess "$!";
746 printdebug "=> ", (messagequote $_), "\n";
747 m/\n/ or confess "$_ ?";
748 push @{ $r->{$`} }, $'; #';
752 or ($!==0 && $?==256)
757 sub gdr_ffq_prev_branchinfo ($) {
759 # => ('status', "message", [$symref, $ffq_prev, $gdrlast])
761 # branch message is undef
762 # weird-symref } no $symref,
763 # notbranch } no $ffq_prev
764 return ('detached', __ 'detached HEAD') unless defined $symref;
765 return ('weird-symref', __ 'HEAD symref is not to refs/')
766 unless $symref =~ m{^refs/};
767 my $ffq_prev = "refs/$ffq_refprefix/$'";
768 my $gdrlast = "refs/$gdrlast_refprefix/$'";
769 printdebug "ffq_prev_branchinfo branch current $symref\n";
770 return ('branch', undef, $symref, $ffq_prev, $gdrlast);
773 sub parsecontrolfh ($$;$) {
774 my ($fh, $desc, $allowsigned) = @_;
775 our $dpkgcontrolhash_noissigned;
778 my %opts = ('name' => $desc);
779 $opts{allow_pgp}= $allowsigned || !$dpkgcontrolhash_noissigned;
780 $c = Dpkg::Control::Hash->new(%opts);
781 $c->parse($fh,$desc) or fail f_ "parsing of %s failed", $desc;
782 last if $allowsigned;
783 last if $dpkgcontrolhash_noissigned;
784 my $issigned= $c->get_option('is_pgp_signed');
785 if (!defined $issigned) {
786 $dpkgcontrolhash_noissigned= 1;
787 seek $fh, 0,0 or confess "seek $desc: $!";
788 } elsif ($issigned) {
790 "control file %s is (already) PGP-signed. ".
791 " Note that dgit push needs to modify the .dsc and then".
792 " do the signature itself",
802 my ($file, $desc, $allowsigned) = @_;
803 my $fh = new IO::Handle;
804 open $fh, '<', $file or fail f_ "open %s (%s): %s", $file, $desc, $!;
805 my $c = parsecontrolfh($fh,$desc,$allowsigned);
806 $fh->error and confess "$!";
812 my $c = Dpkg::Control::Hash->new(name => 'parsed changelog');
813 my $p = new IO::Handle;
814 my @cmd = (qw(dpkg-parsechangelog), @_);
815 open $p, '-|', @cmd or confess "$!";
817 $?=0; $!=0; close $p or failedcmd @cmd;
822 my ($dctrl,$field) = @_;
823 my $v = $dctrl->{$field};
824 return $v if defined $v;
825 fail f_ "missing field %s in %s", $field, $dctrl->get_option('name');
828 sub parsechangelog_loop ($$$) {
829 my ($clogcmd, $descbase, $fn) = @_;
830 # @$clogcmd is qw(dpkg-parsechangelog ...some...options...)
831 # calls $fn->($thisstanza, $desc);
832 debugcmd "|",@$clogcmd;
833 open CLOGS, "-|", @$clogcmd or confess "$!";
835 my $stanzatext = do { local $/=""; <CLOGS>; };
836 printdebug "clogp stanza ".Dumper($stanzatext) if $debuglevel>1;
837 last if !defined $stanzatext;
839 my $desc = "$descbase, entry no.$.";
840 open my $stanzafh, "<", \$stanzatext or confess;
841 my $thisstanza = parsecontrolfh $stanzafh, $desc, 1;
843 $fn->($thisstanza, $desc);
845 confess "$!" if CLOGS->error;
846 close CLOGS or $?==SIGPIPE or failedcmd @$clogcmd;
849 sub make_commit ($$) {
850 my ($parents, $message_paras) = @_;
851 my $tree = cmdoutput qw(git write-tree);
852 my @cmd = (qw(git commit-tree), $tree);
853 push @cmd, qw(-p), $_ foreach @$parents;
854 push @cmd, qw(-m), $_ foreach @$message_paras;
855 return cmdoutput @cmd;
858 sub hash_commit ($) {
860 return cmdoutput qw(git hash-object -w -t commit), $file;
863 sub hash_commit_text ($) {
866 my @cmd = (qw(git hash-object -w -t commit --stdin));
868 print Dumper($text) if $debuglevel > 1;
869 my $child = open2($out, $in, @cmd) or confess "$!";
872 print $in $text or confess "$!";
873 close $in or confess "$!";
875 $h =~ m/^\w+$/ or confess;
877 printdebug "=> $h\n";
880 waitpid $child, 0 == $child or confess "$child $!";
881 $? and failedcmd @cmd;
885 sub reflog_cache_insert ($$$) {
886 my ($ref, $cachekey, $value) = @_;
887 # you must call this in $maindir
888 # you must have called record_maindir
890 # When we no longer need to support squeeze, use --create-reflog
892 my $parent = $ref; $parent =~ s{/[^/]+$}{};
893 ensurepath "$maindir_gitcommon/logs", "$parent";
894 my $makelogfh = new IO::File "$maindir_gitcommon/logs/$ref", '>>'
897 my $oldcache = git_get_ref $ref;
899 if ($oldcache eq $value) {
900 my $tree = cmdoutput qw(git rev-parse), "$value:";
901 # git update-ref doesn't always update, in this case. *sigh*
902 my $authline = (ucfirst _us()).
903 ' <'._us().'@example.com> 1000000000 +0000';
904 my $dummy = hash_commit_text <<ENDU.(__ <<END);
911 Dummy commit - do not use
913 runcmd qw(git update-ref -m), _us()." - dummy", $ref, $dummy;
915 runcmd qw(git update-ref -m), $cachekey, $ref, $value;
918 sub reflog_cache_lookup ($$) {
919 my ($ref, $cachekey) = @_;
920 # you may call this in $maindir or in a playtree
921 # you must have called record_maindir
922 my @cmd = (qw(git log -g), '--pretty=format:%H %gs', $ref);
923 debugcmd "|(probably)",@cmd;
924 my $child = open GC, "-|"; defined $child or confess "$!";
926 chdir $maindir or confess "$!";
927 if (!stat "$maindir_gitcommon/logs/$ref") {
928 $! == ENOENT or confess "$!";
929 printdebug ">(no reflog)\n";
932 exec @cmd; die f_ "exec %s: %s\n", $cmd[0], $!;
936 printdebug ">| ", $_, "\n" if $debuglevel > 1;
937 next unless m/^(\w+) (\S.*\S)$/ && $2 eq $cachekey;
941 confess "$!" if GC->error;
942 failedcmd unless close GC;
946 # ========== playground handling ==========
950 # $maindir user's git working tree
951 # playground area in .git/ where we can make files, unpack, etc. etc.
952 # playtree git working tree sharing object store with the user's
953 # inside playground, or identical to it
957 # $local_git_cfg hash of arrays of values: git config from $maindir
959 # expected calling pattern
964 # must be run in directory containing .git
965 # assigns to $maindir if not already set
966 # also calls git_slurp_config_src to record git config
967 # in $local_git_cfg, unless it's already set
969 # fresh_playground SUBDIR_PATH_COMPONENTS
970 # e.g fresh_playground 'dgit/unpack' ('.git/' is implied)
971 # default SUBDIR_PATH_COMPONENTS is playground_subdir
972 # calls record_maindir
973 # sets up a new playground (destroying any old one)
974 # returns playground pathname
975 # caller may call multiple times with different subdir paths
976 # createing different playgrounds
978 # ensure_a_playground SUBDIR_PATH_COMPONENTS
979 # like fresh_playground except:
980 # merely ensures the directory exists; does not delete an existing one
984 # changedir playground
987 # playtree_setup $local_git_cfg
988 # # ^ call in some (perhaps trivial) subdir of playground
992 # ----- maindir -----
996 sub record_maindir () {
997 if (!defined $maindir) {
998 $maindir = must_getcwd();
999 if (!stat "$maindir/.git") {
1000 fail f_ "cannot stat %s/.git: %s", $maindir, $!;
1003 # we fall back to this in case we have a pre-worktree
1004 # git, which may not know git rev-parse --git-common-dir
1005 $maindir_gitdir = "$maindir/.git";
1006 $maindir_gitcommon = "$maindir/.git";
1008 $maindir_gitdir = cmdoutput qw(git rev-parse --git-dir);
1009 $maindir_gitcommon = cmdoutput qw(git rev-parse --git-common-dir);
1012 $local_git_cfg //= git_slurp_config_src 'local';
1015 # ----- playgrounds -----
1017 sub ensure_a_playground_parent ($) {
1020 $spc = "$maindir_gitdir/$spc";
1021 my $parent = dirname $spc;
1022 mkdir $parent or $!==EEXIST or fail f_
1023 "failed to mkdir playground parent %s: %s", $parent, $!;
1027 sub ensure_a_playground ($) {
1029 $spc = ensure_a_playground_parent $spc;
1030 mkdir $spc or $!==EEXIST or fail f_
1031 "failed to mkdir a playground %s: %s", $spc, $!;
1035 sub fresh_playground ($) {
1037 $spc = ensure_a_playground_parent $spc;
1039 mkdir $spc or fail f_
1040 "failed to mkdir the playground %s: %s", $spc, $!;
1044 # ----- playtrees -----
1046 sub playtree_setup (;$) {
1047 my ($t_local_git_cfg) = @_;
1048 $t_local_git_cfg //= $local_git_cfg;
1049 # for use in the playtree
1050 # $maindir must be set, eg by calling record_maindir or fresh_playground
1051 runcmd qw(git init -q);
1052 runcmd qw(git config gc.auto 0);
1053 foreach my $copy (qw(user.email user.name user.useConfigOnly
1054 core.sharedRepository
1055 core.compression core.looseCompression
1056 core.bigFileThreshold core.fsyncObjectFiles)) {
1057 my $v = $t_local_git_cfg->{$copy};
1059 runcmd qw(git config), $copy, $_ foreach @$v;
1061 # this is confusing: we have
1062 # . playtree, not a worktree, has .git/, our cwd
1063 # $maindir might be a worktree so
1064 # $maindir_gitdir contains our main working "dgit", HEAD, etc.
1065 # $maindir_gitcommon the shared stuff, including .objects
1066 rmtree('.git/objects');
1067 symlink "$maindir_gitcommon/objects",'.git/objects' or confess "$!";
1068 ensuredir '.git/info';
1069 open GA, "> .git/info/attributes" or confess "$!";
1070 print GA "* $negate_harmful_gitattrs\n" or confess "$!";
1071 close GA or confess "$!";