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/>.
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 must_getcwd executable_on_path
55 waitstatusmsg failedcmd_waitstatus
56 failedcmd_report_cmd failedcmd
57 runcmd shell_cmd cmdoutput cmdoutput_errok
58 git_rev_parse changedir_git_toplevel git_cat_file
59 git_get_ref git_get_symref git_for_each_ref
60 git_for_each_tag_referring is_fast_fwd
62 git_reflog_action_msg git_update_ref_cmd
64 reflog_cache_insert reflog_cache_lookup
65 $package_re $component_re $deliberately_re
66 $distro_re $versiontag_re $series_filename_re
67 $orig_f_comp_re $orig_f_sig_re $orig_f_tail_re
68 $extra_orig_namepart_re
71 $ffq_refprefix $gdrlast_refprefix
72 initdebug enabledebug enabledebuglevel
74 $printdebug_when_debuglevel $debugcmd_when_debuglevel
75 $debugprefix *debuglevel *DEBUG
76 shellquote printcmd messagequote
77 $negate_harmful_gitattrs
78 changedir git_slurp_config_src
79 gdr_ffq_prev_branchinfo
80 parsecontrolfh parsecontrol parsechangelog
81 getfield parsechangelog_loop
83 # implicitly uses $main::us
84 %EXPORT_TAGS = ( policyflags => [qw(NOFFCHECK FRESHREPO NOCOMMITCHECK)],
85 playground => [qw(record_maindir $maindir $local_git_cfg
86 $maindir_gitdir $maindir_gitcommon
88 ensure_a_playground)]);
89 @EXPORT_OK = ( @{ $EXPORT_TAGS{policyflags} },
90 @{ $EXPORT_TAGS{playground} } );
95 our $package_re = '[0-9a-z][-+.0-9a-z]*';
96 our $component_re = '[0-9a-zA-Z][-+.0-9a-zA-Z]*';
97 our $deliberately_re = "(?:TEST-)?$package_re";
98 our $distro_re = $component_re;
99 our $versiontag_re = qr{[-+.\%_0-9a-zA-Z/]+};
100 our $branchprefix = 'dgit';
101 our $series_filename_re = qr{(?:^|\.)series(?!\n)$}s;
102 our $extra_orig_namepart_re = qr{[-0-9a-zA-Z]+};
103 our $orig_f_comp_re = qr{orig(?:-$extra_orig_namepart_re)?};
104 our $orig_f_sig_re = '\\.(?:asc|gpg|pgp)';
105 our $orig_f_tail_re = "$orig_f_comp_re\\.tar(?:\\.\\w+)?(?:$orig_f_sig_re)?";
106 our $git_null_obj = '0' x 40;
107 our $ffq_refprefix = 'ffq-prev';
108 our $gdrlast_refprefix = 'debrebase-last';
109 our $printdebug_when_debuglevel = 1;
110 our $debugcmd_when_debuglevel = 1;
112 # these three all go together, only valid after record_maindir
115 our $maindir_gitcommon;
117 # policy hook exit status bits
118 # see dgit-repos-server head comment for documentation
119 # 1 is reserved in case something fails with `exit 1' and to spot
120 # dynamic loader, runtime, etc., failures, which report 127 or 255
121 sub NOFFCHECK () { return 0x2; }
122 sub FRESHREPO () { return 0x4; }
123 sub NOCOMMITCHECK () { return 0x8; }
128 our $negate_harmful_gitattrs =
129 "-text -eol -crlf -ident -filter -working-tree-encoding";
130 # ^ when updating this, alter the regexp in dgit:is_gitattrs_setup
132 our $forkcheck_mainprocess;
134 sub forkcheck_setup () {
135 $forkcheck_mainprocess = $$;
138 sub forkcheck_mainprocess () {
139 # You must have called forkcheck_setup or setup_sigwarn already
140 getppid != $forkcheck_mainprocess;
143 sub setup_sigwarn () {
145 $SIG{__WARN__} = sub {
146 confess $_[0] if forkcheck_mainprocess;
152 open DEBUG, ">/dev/null" or confess "$!";
156 open DEBUG, ">&STDERR" or confess "$!";
161 sub enabledebuglevel ($) {
162 my ($newlevel) = @_; # may be undef (eg from env var)
163 confess if $debuglevel;
166 return unless $newlevel;
167 $debuglevel = $newlevel;
172 # Prints a prefix, and @_, to DEBUG. @_ should normally contain
175 # With no (or only empty) arguments just prints the prefix and
176 # leaves the caller to do more with DEBUG. The caller should make
177 # sure then to call printdebug with something ending in "\n" to
178 # get the prefix right in subsequent calls.
180 return unless $debuglevel >= $printdebug_when_debuglevel;
181 our $printdebug_noprefix;
182 print DEBUG $debugprefix unless $printdebug_noprefix;
183 pop @_ while @_ and !length $_[-1];
185 print DEBUG @_ or confess "$!";
186 $printdebug_noprefix = $_[-1] !~ m{\n$};
189 sub messagequote ($) {
195 s{[\000-\037\177]}{ sprintf "\\x%02x", ord $& }ge;
202 defined or confess __ 'internal error' foreach @_;
205 if (!length || m{[^-=_./:0-9a-z]}i) {
212 return join ' ', @out;
217 my $intro = shift @_;
218 print $fh $intro," " or confess "$!";
219 print $fh shellquote @_ or confess "$!";
220 print $fh "\n" or confess "$!";
224 my $extraprefix = shift @_;
225 printcmd(\*DEBUG,$debugprefix.$extraprefix,@_)
226 if $debuglevel >= $debugcmd_when_debuglevel;
229 sub dep14_version_mangle ($) {
231 # DEP-14 patch proposed 2016-11-09 "Version Mangling"
233 $v =~ s/\.(?=\.|$|lock$)/.#/g;
237 sub debiantag_new ($$) {
238 my ($v,$distro) = @_;
239 return "archive/$distro/".dep14_version_mangle $v;
242 sub debiantag_maintview ($$) {
243 my ($v,$distro) = @_;
244 return "$distro/".dep14_version_mangle $v;
247 sub debiantags ($$) {
248 my ($version,$distro) = @_;
249 map { $_->($version, $distro) } (\&debiantag_new, \&debiantag_maintview);
258 sub upstreamversion ($) {
264 sub source_file_leafname ($$$) {
265 my ($package,$vsn,$sfx) = @_;
266 return "${package}_".(stripepoch $vsn).$sfx
269 sub is_orig_file_of_p_v ($$$) {
270 my ($f, $package, $upstreamvsn) = @_;
271 my $base = source_file_leafname $package, $upstreamvsn, '';
272 return 0 unless $f =~ m/^\Q$base\E\.$orig_f_tail_re$/;
276 sub server_branch ($) { return "$branchprefix/$_[0]"; }
277 sub server_ref ($) { return "refs/".server_branch($_[0]); }
279 sub stat_exists ($) {
282 return 0 if $!==&ENOENT;
283 confess "stat $f: $!";
287 $::us // ($0 =~ m#[^/]*$#, $&);
291 my $s = f_ "error: %s\n", "@_";
293 my $prefix = _us().": ";
294 $s =~ s/^/$prefix/gm;
303 my ($dir) = @_; # does not create parents
304 return if mkdir $dir;
305 return if $! == EEXIST;
306 confess "mkdir $dir: $!";
311 defined $d or fail f_ "getcwd failed: %s\n", $!;
315 sub executable_on_path ($) {
317 return 1 if $program =~ m{/};
318 my @path = split /:/, ($ENV{PATH} // "/usr/local/bin:/bin:/usr/bin");
319 foreach my $pe (@path) {
320 my $here = "$pe/$program";
321 return $here if stat_exists $here && -x _;
326 our @signames = split / /, $Config{sig_name};
328 sub waitstatusmsg () {
330 return __ "terminated, reporting successful completion";
331 } elsif (!($? & 255)) {
332 return f_ "failed with error exit status %s", WEXITSTATUS($?);
333 } elsif (WIFSIGNALED($?)) {
334 my $signum=WTERMSIG($?);
335 return f_ "died due to fatal signal %s",
336 ($signames[$signum] // "number $signum").
337 ($? & 128 ? " (core dumped)" : ""); # POSIX(3pm) has no WCOREDUMP
339 return f_ "failed with unknown wait status %s", $?;
343 sub failedcmd_report_cmd {
344 my $intro = shift @_;
345 $intro //= __ "failed command";
346 { local ($!); printcmd \*STDERR, _us().": $intro:", @_ or confess "$!"; };
349 sub failedcmd_waitstatus {
351 return f_ "failed to fork/exec: %s", $!;
353 return f_ "subprocess %s", waitstatusmsg();
355 return __ "subprocess produced invalid output";
360 # Expects $!,$? as set by close - see below.
361 # To use with system(), set $?=-1 first.
363 # Actual behaviour of perl operations:
364 # success $!==0 $?==0 close of piped open
365 # program failed $!==0 $? >0 close of piped open
366 # syscall failure $! >0 $?=-1 close of piped open
367 # failure $! >0 unchanged close of something else
368 # success trashed $?==0 system
369 # program failed trashed $? >0 system
370 # syscall failure $! >0 unchanged system
371 failedcmd_report_cmd undef, @_;
372 fail failedcmd_waitstatus();
378 failedcmd @_ if system @_;
382 my ($first_shell, @cmd) = @_;
383 return qw(sh -ec), $first_shell.'; exec "$@"', 'x', @cmd;
386 sub cmdoutput_errok {
387 confess Dumper(\@_)." ?" if grep { !defined } @_;
388 local $printdebug_when_debuglevel = $debugcmd_when_debuglevel;
390 open P, "-|", @_ or confess "$_[0] $!";
393 { local $/ = undef; $d = <P>; }
394 confess "$!" if P->error;
395 if (!close P) { printdebug "=>!$?\n"; return undef; }
397 if ($debuglevel > 0) {
400 my $more = (length $' ? '...' : ''); #');
401 $dd =~ s{[^\n -~]|\\}{ sprintf "\\x%02x", ord $& }ge;
402 printdebug "=> \`$dd'",$more,"\n";
408 my $d = cmdoutput_errok @_;
409 defined $d or failedcmd @_;
413 sub link_ltarget ($$) {
415 lstat $old or return undef;
417 $old = cmdoutput qw(realpath --), $old;
419 my $r = link $old, $new;
420 $r = symlink $old, $new if !$r && $!==EXDEV;
421 $r or fail "(sym)link $old $new: $!\n";
424 sub rename_link_xf ($$$) {
425 # renames/moves or links/copies $src to $dst,
426 # even if $dst is on a different fs
427 # (May use the filename "$dst.tmp".);
428 # On success, returns true.
429 # On failure, returns false and sets
430 # $@ to a reason message
431 # $! to an errno value, or -1 if not known
432 # having possibly printed something about mv to stderr.
433 # Not safe to use without $keeporig if $dst might be a symlink
434 # to $src, as it might delete $src leaving $dst invalid.
435 my ($keeporig,$src,$dst) = @_;
438 : rename $src, $dst) {
446 $@ = f_ "stat source file: %S", $!;
449 my @src_stat = (stat _)[0..1];
453 @dst_stat = (stat _)[0..1];
454 } elsif ($! == ENOENT) {
456 $@ = f_ "stat destination file: %S", $!;
460 if ("@src_stat" eq "@dst_stat") {
461 # (Symlinks to) the same file. No need for a copy but
462 # we may need to delete the original.
463 printdebug "rename_link_xf $keeporig $src $dst EXDEV but same\n";
466 my @cmd = (qw(cp --), $src, "$dst.tmp");
469 failedcmd_report_cmd undef, @cmd;
470 $@ = failedcmd_waitstatus();
474 if (!rename "$dst.tmp", $dst) {
475 $@ = f_ "finally install file after cp: %S", $!;
481 $@ = f_ "delete old file after cp: %S", $!;
490 my $h = Digest::SHA->new(256);
492 return $h->hexdigest();
495 sub git_rev_parse ($) {
496 return cmdoutput qw(git rev-parse), "$_[0]~0";
499 sub changedir_git_toplevel () {
500 my $toplevel = cmdoutput qw(git rev-parse --show-toplevel);
501 length $toplevel or fail __ <<END;
502 not in a git working tree?
503 (git rev-parse --show-toplevel produced no output)
505 chdir $toplevel or fail f_ "chdir toplevel %s: %s\n", $toplevel, $!;
508 sub git_cat_file ($;$) {
509 my ($objname, $etype) = @_;
510 # => ($type, $data) or ('missing', undef)
511 # in scalar context, just the data
512 # if $etype defined, dies unless type is $etype or in @$etype
513 our ($gcf_pid, $gcf_i, $gcf_o);
514 local $printdebug_when_debuglevel = $debugcmd_when_debuglevel;
516 my ($gtype, $data) = @_;
518 $etype = [$etype] unless ref $etype;
519 confess "$objname expected @$etype but is $gtype"
520 unless grep { $gtype eq $_ } @$etype;
522 return ($gtype, $data);
525 my @cmd = qw(git cat-file --batch);
526 debugcmd "GCF|", @cmd;
527 $gcf_pid = open2 $gcf_o, $gcf_i, @cmd or confess "$!";
529 printdebug "GCF>| $objname\n";
530 print $gcf_i $objname, "\n" or confess "$!";
532 printdebug "GCF<| ", $x;
533 if ($x =~ m/ (missing)$/) { return $chk->($1, undef); }
534 my ($type, $size) = $x =~ m/^.* (\w+) (\d+)\n/ or confess "$objname ?";
536 (read $gcf_o, $data, $size) == $size or confess "$objname $!";
538 $x eq "\n" or confess "$objname ($_) $!";
539 return $chk->($type, $data);
542 sub git_get_symref (;$) {
543 my ($symref) = @_; $symref //= 'HEAD';
544 # => undef if not a symref, otherwise refs/...
545 my @cmd = (qw(git symbolic-ref -q HEAD));
546 my $branch = cmdoutput_errok @cmd;
547 if (!defined $branch) {
548 $?==256 or failedcmd @cmd;
555 sub git_for_each_ref ($$;$) {
556 my ($pattern,$func,$gitdir) = @_;
557 # calls $func->($objid,$objtype,$fullrefname,$reftail);
558 # $reftail is RHS of ref after refs/[^/]+/
559 # breaks if $pattern matches any ref `refs/blah' where blah has no `/'
560 # $pattern may be an array ref to mean multiple patterns
561 $pattern = [ $pattern ] unless ref $pattern;
562 my @cmd = (qw(git for-each-ref), @$pattern);
563 if (defined $gitdir) {
564 @cmd = ('sh','-ec','cd "$1"; shift; exec "$@"','x', $gitdir, @cmd);
566 open GFER, "-|", @cmd or confess "$!";
569 chomp or confess "$_ ?";
570 printdebug "|> ", $_, "\n";
571 m#^(\w+)\s+(\w+)\s+(refs/[^/]+/(\S+))$# or confess "$_ ?";
572 $func->($1,$2,$3,$4);
574 $!=0; $?=0; close GFER or confess "$pattern $? $!";
577 sub git_get_ref ($) {
578 # => '' if no such ref
581 s{^refs/}{[r]efs/} or confess "$refname $_ ?";
582 return cmdoutput qw(git for-each-ref --format=%(objectname)), $_;
585 sub git_for_each_tag_referring ($$) {
586 my ($objreferring, $func) = @_;
587 # calls $func->($tagobjid,$refobjid,$fullrefname,$tagname);
588 printdebug "git_for_each_tag_referring ",
589 ($objreferring // 'UNDEF'),"\n";
590 git_for_each_ref('refs/tags', sub {
591 my ($tagobjid,$objtype,$fullrefname,$tagname) = @_;
592 return unless $objtype eq 'tag';
593 my $refobjid = git_rev_parse $tagobjid;
595 !defined $objreferring # caller wants them all
596 or $tagobjid eq $objreferring
597 or $refobjid eq $objreferring;
598 $func->($tagobjid,$refobjid,$fullrefname,$tagname);
602 sub git_check_unmodified () {
603 foreach my $cached (qw(0 1)) {
604 my @cmd = qw(git diff --quiet);
605 push @cmd, qw(--cached) if $cached;
608 $!=0; $?=-1; system @cmd;
613 ? __ "git index contains changes (does not match HEAD)"
614 : __ "working tree is dirty (does not match HEAD)";
621 sub upstream_commitish_search ($$) {
622 my ($upstream_version, $tried) = @_;
623 # todo: at some point maybe use git-deborig to do this
624 foreach my $tagpfx ('', 'v', 'upstream/') {
625 my $tag = $tagpfx.(dep14_version_mangle $upstream_version);
626 my $new_upstream = git_get_ref "refs/tags/$tag";
628 return $new_upstream if length $new_upstream;
632 sub resolve_upstream_version ($$) {
633 my ($new_upstream, $upstream_version) = @_;
635 my $used = $new_upstream;
636 if (!defined $new_upstream) {
638 $new_upstream = upstream_commitish_search $upstream_version, \@tried;
639 if (!length $new_upstream) {
641 "Could not determine appropriate upstream commitish.\n".
642 " (Tried these tags: %s)\n".
643 " Check version, and specify upstream commitish explicitly.",
648 $new_upstream = git_rev_parse $new_upstream;
650 return ($new_upstream, $used);
651 # used is a human-readable idea of what we found
654 sub is_fast_fwd ($$) {
655 my ($ancestor,$child) = @_;
656 my @cmd = (qw(git merge-base), $ancestor, $child);
657 my $mb = cmdoutput_errok @cmd;
659 return git_rev_parse($mb) eq git_rev_parse($ancestor);
661 $?==256 or failedcmd @cmd;
666 sub git_reflog_action_msg ($) {
668 my $rla = $ENV{GIT_REFLOG_ACTION};
669 $msg = "$rla: $msg" if length $rla;
673 sub git_update_ref_cmd {
674 # returns qw(git update-ref), qw(-m), @_
675 # except that message may be modified to honour GIT_REFLOG_ACTION
677 $msg = git_reflog_action_msg $msg;
678 return qw(git update-ref -m), $msg, @_;
683 printdebug "CD $newdir\n";
684 chdir $newdir or confess "chdir: $newdir: $!";
687 sub git_slurp_config_src ($) {
689 # returns $r such that $r->{KEY}[] = VALUE
690 my @cmd = (qw(git config -z --get-regexp), "--$src", qw(.*));
693 local ($debuglevel) = $debuglevel-2;
697 open GITS, "-|", @cmd or confess "$!";
700 printdebug "=> ", (messagequote $_), "\n";
701 m/\n/ or confess "$_ ?";
702 push @{ $r->{$`} }, $'; #';
706 or ($!==0 && $?==256)
711 sub gdr_ffq_prev_branchinfo ($) {
713 # => ('status', "message", [$symref, $ffq_prev, $gdrlast])
715 # branch message is undef
716 # weird-symref } no $symref,
717 # notbranch } no $ffq_prev
718 return ('detached', __ 'detached HEAD') unless defined $symref;
719 return ('weird-symref', __ 'HEAD symref is not to refs/')
720 unless $symref =~ m{^refs/};
721 my $ffq_prev = "refs/$ffq_refprefix/$'";
722 my $gdrlast = "refs/$gdrlast_refprefix/$'";
723 printdebug "ffq_prev_branchinfo branch current $symref\n";
724 return ('branch', undef, $symref, $ffq_prev, $gdrlast);
727 sub parsecontrolfh ($$;$) {
728 my ($fh, $desc, $allowsigned) = @_;
729 our $dpkgcontrolhash_noissigned;
732 my %opts = ('name' => $desc);
733 $opts{allow_pgp}= $allowsigned || !$dpkgcontrolhash_noissigned;
734 $c = Dpkg::Control::Hash->new(%opts);
735 $c->parse($fh,$desc) or fail f_ "parsing of %s failed", $desc;
736 last if $allowsigned;
737 last if $dpkgcontrolhash_noissigned;
738 my $issigned= $c->get_option('is_pgp_signed');
739 if (!defined $issigned) {
740 $dpkgcontrolhash_noissigned= 1;
741 seek $fh, 0,0 or confess "seek $desc: $!";
742 } elsif ($issigned) {
744 "control file %s is (already) PGP-signed. ".
745 " Note that dgit push needs to modify the .dsc and then".
746 " do the signature itself",
756 my ($file, $desc, $allowsigned) = @_;
757 my $fh = new IO::Handle;
758 open $fh, '<', $file or fail f_ "open %s (%s): %s", $file, $desc, $!;
759 my $c = parsecontrolfh($fh,$desc,$allowsigned);
760 $fh->error and confess "$!";
766 my $c = Dpkg::Control::Hash->new(name => 'parsed changelog');
767 my $p = new IO::Handle;
768 my @cmd = (qw(dpkg-parsechangelog), @_);
769 open $p, '-|', @cmd or confess "$!";
771 $?=0; $!=0; close $p or failedcmd @cmd;
776 my ($dctrl,$field) = @_;
777 my $v = $dctrl->{$field};
778 return $v if defined $v;
779 fail f_ "missing field %s in %s", $field, $dctrl->get_option('name');
782 sub parsechangelog_loop ($$$) {
783 my ($clogcmd, $descbase, $fn) = @_;
784 # @$clogcmd is qw(dpkg-parsechangelog ...some...options...)
785 # calls $fn->($thisstanza, $desc);
786 debugcmd "|",@$clogcmd;
787 open CLOGS, "-|", @$clogcmd or confess "$!";
789 my $stanzatext = do { local $/=""; <CLOGS>; };
790 printdebug "clogp stanza ".Dumper($stanzatext) if $debuglevel>1;
791 last if !defined $stanzatext;
793 my $desc = "$descbase, entry no.$.";
794 open my $stanzafh, "<", \$stanzatext or confess;
795 my $thisstanza = parsecontrolfh $stanzafh, $desc, 1;
797 $fn->($thisstanza, $desc);
799 confess "$!" if CLOGS->error;
800 close CLOGS or $?==SIGPIPE or failedcmd @$clogcmd;
803 sub make_commit_text ($) {
806 my @cmd = (qw(git hash-object -w -t commit --stdin));
808 print Dumper($text) if $debuglevel > 1;
809 my $child = open2($out, $in, @cmd) or confess "$!";
812 print $in $text or confess "$!";
813 close $in or confess "$!";
815 $h =~ m/^\w+$/ or confess;
817 printdebug "=> $h\n";
820 waitpid $child, 0 == $child or confess "$child $!";
821 $? and failedcmd @cmd;
825 sub reflog_cache_insert ($$$) {
826 my ($ref, $cachekey, $value) = @_;
827 # you must call this in $maindir
828 # you must have called record_maindir
830 # When we no longer need to support squeeze, use --create-reflog
832 my $parent = $ref; $parent =~ s{/[^/]+$}{};
833 ensuredir "$maindir_gitcommon/logs/$parent";
834 my $makelogfh = new IO::File "$maindir_gitcommon/logs/$ref", '>>'
837 my $oldcache = git_get_ref $ref;
839 if ($oldcache eq $value) {
840 my $tree = cmdoutput qw(git rev-parse), "$value:";
841 # git update-ref doesn't always update, in this case. *sigh*
842 my $authline = (ucfirst _us()).
843 ' <'._us().'@example.com> 1000000000 +0000';
844 my $dummy = make_commit_text <<ENDU.(__ <<END);
851 Dummy commit - do not use
853 runcmd qw(git update-ref -m), _us()." - dummy", $ref, $dummy;
855 runcmd qw(git update-ref -m), $cachekey, $ref, $value;
858 sub reflog_cache_lookup ($$) {
859 my ($ref, $cachekey) = @_;
860 # you may call this in $maindir or in a playtree
861 # you must have called record_maindir
862 my @cmd = (qw(git log -g), '--pretty=format:%H %gs', $ref);
863 debugcmd "|(probably)",@cmd;
864 my $child = open GC, "-|"; defined $child or confess "$!";
866 chdir $maindir or confess "$!";
867 if (!stat "$maindir_gitcommon/logs/$ref") {
868 $! == ENOENT or confess "$!";
869 printdebug ">(no reflog)\n";
872 exec @cmd; die f_ "exec %s: %s\n", $cmd[0], $!;
876 printdebug ">| ", $_, "\n" if $debuglevel > 1;
877 next unless m/^(\w+) (\S.*\S)$/ && $2 eq $cachekey;
881 confess "$!" if GC->error;
882 failedcmd unless close GC;
886 # ========== playground handling ==========
890 # $maindir user's git working tree
891 # playground area in .git/ where we can make files, unpack, etc. etc.
892 # playtree git working tree sharing object store with the user's
893 # inside playground, or identical to it
897 # $local_git_cfg hash of arrays of values: git config from $maindir
899 # expected calling pattern
904 # must be run in directory containing .git
905 # assigns to $maindir if not already set
906 # also calls git_slurp_config_src to record git config
907 # in $local_git_cfg, unless it's already set
909 # fresh_playground SUBDIR_PATH_COMPONENTS
910 # e.g fresh_playground 'dgit/unpack' ('.git/' is implied)
911 # default SUBDIR_PATH_COMPONENTS is playground_subdir
912 # calls record_maindir
913 # sets up a new playground (destroying any old one)
914 # returns playground pathname
915 # caller may call multiple times with different subdir paths
916 # createing different playgrounds
918 # ensure_a_playground SUBDIR_PATH_COMPONENTS
919 # like fresh_playground except:
920 # merely ensures the directory exists; does not delete an existing one
924 # changedir playground
927 # playtree_setup $local_git_cfg
928 # # ^ call in some (perhaps trivial) subdir of playground
932 # ----- maindir -----
936 sub record_maindir () {
937 if (!defined $maindir) {
938 $maindir = must_getcwd();
939 if (!stat "$maindir/.git") {
940 fail f_ "cannot stat %s/.git: %s", $maindir, $!;
943 # we fall back to this in case we have a pre-worktree
944 # git, which may not know git rev-parse --git-common-dir
945 $maindir_gitdir = "$maindir/.git";
946 $maindir_gitcommon = "$maindir/.git";
948 $maindir_gitdir = cmdoutput qw(git rev-parse --git-dir);
949 $maindir_gitcommon = cmdoutput qw(git rev-parse --git-common-dir);
952 $local_git_cfg //= git_slurp_config_src 'local';
955 # ----- playgrounds -----
957 sub ensure_a_playground_parent ($) {
960 $spc = "$maindir_gitdir/$spc";
961 my $parent = dirname $spc;
962 mkdir $parent or $!==EEXIST or fail f_
963 "failed to mkdir playground parent %s: %s", $parent, $!;
967 sub ensure_a_playground ($) {
969 $spc = ensure_a_playground_parent $spc;
970 mkdir $spc or $!==EEXIST or fail f_
971 "failed to mkdir a playground %s: %s", $spc, $!;
975 sub fresh_playground ($) {
977 $spc = ensure_a_playground_parent $spc;
979 mkdir $spc or fail f_
980 "failed to mkdir the playground %s: %s", $spc, $!;
984 # ----- playtrees -----
986 sub playtree_setup (;$) {
987 my ($t_local_git_cfg) = @_;
988 $t_local_git_cfg //= $local_git_cfg;
989 # for use in the playtree
990 # $maindir must be set, eg by calling record_maindir or fresh_playground
991 runcmd qw(git init -q);
992 runcmd qw(git config gc.auto 0);
993 foreach my $copy (qw(user.email user.name user.useConfigOnly
994 core.sharedRepository
995 core.compression core.looseCompression
996 core.bigFileThreshold core.fsyncObjectFiles)) {
997 my $v = $t_local_git_cfg->{$copy};
999 runcmd qw(git config), $copy, $_ foreach @$v;
1001 # this is confusing: we have
1002 # . playtree, not a worktree, has .git/, our cwd
1003 # $maindir might be a worktree so
1004 # $maindir_gitdir contains our main working "dgit", HEAD, etc.
1005 # $maindir_gitcommon the shared stuff, including .objects
1006 rmtree('.git/objects');
1007 symlink "$maindir_gitcommon/objects",'.git/objects' or confess "$!";
1008 ensuredir '.git/info';
1009 open GA, "> .git/info/attributes" or confess "$!";
1010 print GA "* $negate_harmful_gitattrs\n" or confess "$!";
1011 close GA or confess "$!";