chiark / gitweb /
dgit: remove dead $need_split_build_invocation code path
[dgit.git] / Debian / Dgit.pm
1 # -*- perl -*-
2 # dgit
3 # Debian::Dgit: functions common to dgit and its helpers and servers
4 #
5 # Copyright (C) 2015-2016  Ian Jackson
6 #
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.
11 #
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.
16 #
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/>.
19
20 package Debian::Dgit;
21
22 use strict;
23 use warnings;
24
25 use Carp;
26 use POSIX;
27 use IO::Handle;
28 use Config;
29 use Digest::SHA;
30 use Data::Dumper;
31 use IPC::Open2;
32 use File::Path;
33 use File::Basename;
34 use Dpkg::Control::Hash;
35
36 BEGIN {
37     use Exporter   ();
38     our ($VERSION, @ISA, @EXPORT, @EXPORT_OK, %EXPORT_TAGS);
39
40     $VERSION     = 1.00;
41     @ISA         = qw(Exporter);
42     @EXPORT      = qw(setup_sigwarn forkcheck_setup forkcheck_mainprocess
43                       dep14_version_mangle
44                       debiantags debiantag_old debiantag_new
45                       debiantag_maintview
46                       server_branch server_ref
47                       stat_exists link_ltarget
48                       hashfile
49                       fail failmsg ensuredir must_getcwd executable_on_path
50                       waitstatusmsg failedcmd_waitstatus
51                       failedcmd_report_cmd failedcmd
52                       runcmd shell_cmd cmdoutput cmdoutput_errok
53                       git_rev_parse git_cat_file
54                       git_get_ref git_get_symref git_for_each_ref
55                       git_for_each_tag_referring is_fast_fwd
56                       git_check_unmodified
57                       git_reflog_action_msg  git_update_ref_cmd
58                       $package_re $component_re $deliberately_re
59                       $distro_re $versiontag_re $series_filename_re
60                       $extra_orig_namepart_re
61                       $git_null_obj
62                       $branchprefix
63                       $ffq_refprefix $gdrlast_refprefix
64                       initdebug enabledebug enabledebuglevel
65                       printdebug debugcmd
66                       $debugprefix *debuglevel *DEBUG
67                       shellquote printcmd messagequote
68                       $negate_harmful_gitattrs
69                       changedir git_slurp_config_src
70                       gdr_ffq_prev_branchinfo
71                       parsecontrolfh parsecontrol parsechangelog
72                       getfield parsechangelog_loop
73                       playtree_setup);
74     # implicitly uses $main::us
75     %EXPORT_TAGS = ( policyflags => [qw(NOFFCHECK FRESHREPO NOCOMMITCHECK)],
76                      playground => [qw(record_maindir $maindir $local_git_cfg
77                                        $maindir_gitdir $maindir_gitcommon
78                                        fresh_playground
79                                        ensure_a_playground)]);
80     @EXPORT_OK   = ( @{ $EXPORT_TAGS{policyflags} },
81                      @{ $EXPORT_TAGS{playground} } );
82 }
83
84 our @EXPORT_OK;
85
86 our $package_re = '[0-9a-z][-+.0-9a-z]*';
87 our $component_re = '[0-9a-zA-Z][-+.0-9a-zA-Z]*';
88 our $deliberately_re = "(?:TEST-)?$package_re";
89 our $distro_re = $component_re;
90 our $versiontag_re = qr{[-+.\%_0-9a-zA-Z/]+};
91 our $branchprefix = 'dgit';
92 our $series_filename_re = qr{(?:^|\.)series(?!\n)$}s;
93 our $extra_orig_namepart_re = qr{[-0-9a-z]+};
94 our $git_null_obj = '0' x 40;
95 our $ffq_refprefix = 'ffq-prev';
96 our $gdrlast_refprefix = 'debrebase-last';
97
98 # policy hook exit status bits
99 # see dgit-repos-server head comment for documentation
100 # 1 is reserved in case something fails with `exit 1' and to spot
101 # dynamic loader, runtime, etc., failures, which report 127 or 255
102 sub NOFFCHECK () { return 0x2; }
103 sub FRESHREPO () { return 0x4; }
104 sub NOCOMMITCHECK () { return 0x8; }
105
106 our $debugprefix;
107 our $debuglevel = 0;
108
109 our $negate_harmful_gitattrs =
110     "-text -eol -crlf -ident -filter -working-tree-encoding";
111     # ^ when updating this, alter the regexp in dgit:is_gitattrs_setup
112
113 our $forkcheck_mainprocess;
114
115 sub forkcheck_setup () {
116     $forkcheck_mainprocess = $$;
117 }
118
119 sub forkcheck_mainprocess () {
120     # You must have called forkcheck_setup or setup_sigwarn already
121     getppid != $forkcheck_mainprocess;
122 }
123
124 sub setup_sigwarn () {
125     forkcheck_setup();
126     $SIG{__WARN__} = sub { 
127         confess $_[0] if forkcheck_mainprocess;
128     };
129 }
130
131 sub initdebug ($) { 
132     ($debugprefix) = @_;
133     open DEBUG, ">/dev/null" or die $!;
134 }
135
136 sub enabledebug () {
137     open DEBUG, ">&STDERR" or die $!;
138     DEBUG->autoflush(1);
139     $debuglevel ||= 1;
140 }
141     
142 sub enabledebuglevel ($) {
143     my ($newlevel) = @_; # may be undef (eg from env var)
144     die if $debuglevel;
145     $newlevel //= 0;
146     $newlevel += 0;
147     return unless $newlevel;
148     $debuglevel = $newlevel;
149     enabledebug();
150 }
151     
152 sub printdebug {
153     print DEBUG $debugprefix, @_ or die $! if $debuglevel>0;
154 }
155
156 sub messagequote ($) {
157     local ($_) = @_;
158     s{\\}{\\\\}g;
159     s{\n}{\\n}g;
160     s{\x08}{\\b}g;
161     s{\t}{\\t}g;
162     s{[\000-\037\177]}{ sprintf "\\x%02x", ord $& }ge;
163     $_;
164 }
165
166 sub shellquote {
167     my @out;
168     local $_;
169     defined or confess 'internal error' foreach @_;
170     foreach my $a (@_) {
171         $_ = $a;
172         if (!length || m{[^-=_./:0-9a-z]}i) {
173             s{['\\]}{'\\$&'}g;
174             push @out, "'$_'";
175         } else {
176             push @out, $_;
177         }
178     }
179     return join ' ', @out;
180 }
181
182 sub printcmd {
183     my $fh = shift @_;
184     my $intro = shift @_;
185     print $fh $intro," " or die $!;
186     print $fh shellquote @_ or die $!;
187     print $fh "\n" or die $!;
188 }
189
190 sub debugcmd {
191     my $extraprefix = shift @_;
192     printcmd(\*DEBUG,$debugprefix.$extraprefix,@_) if $debuglevel>0;
193 }
194
195 sub dep14_version_mangle ($) {
196     my ($v) = @_;
197     # DEP-14 patch proposed 2016-11-09  "Version Mangling"
198     $v =~ y/~:/_%/;
199     $v =~ s/\.(?=\.|$|lock$)/.#/g;
200     return $v;
201 }
202
203 sub debiantag_old ($$) { 
204     my ($v,$distro) = @_;
205     return "$distro/". dep14_version_mangle $v;
206 }
207
208 sub debiantag_new ($$) { 
209     my ($v,$distro) = @_;
210     return "archive/$distro/".dep14_version_mangle $v;
211 }
212
213 sub debiantag_maintview ($$) { 
214     my ($v,$distro) = @_;
215     return "$distro/".dep14_version_mangle $v;
216 }
217
218 sub debiantags ($$) {
219     my ($version,$distro) = @_;
220     map { $_->($version, $distro) } (\&debiantag_new, \&debiantag_old);
221 }
222
223 sub server_branch ($) { return "$branchprefix/$_[0]"; }
224 sub server_ref ($) { return "refs/".server_branch($_[0]); }
225
226 sub stat_exists ($) {
227     my ($f) = @_;
228     return 1 if stat $f;
229     return 0 if $!==&ENOENT;
230     die "stat $f: $!";
231 }
232
233 sub _us () {
234     $::us // ($0 =~ m#[^/]*$#, $&);
235 }
236
237 sub failmsg {
238     my $s = "error: @_\n";
239     $s =~ s/\n\n$/\n/;
240     my $prefix = _us().": ";
241     $s =~ s/^/$prefix/gm;
242     return "\n".$s;
243 }
244
245 sub fail {
246     die failmsg @_;
247 }
248
249 sub ensuredir ($) {
250     my ($dir) = @_; # does not create parents
251     return if mkdir $dir;
252     return if $! == EEXIST;
253     die "mkdir $dir: $!";
254 }
255
256 sub must_getcwd () {
257     my $d = getcwd();
258     defined $d or fail "getcwd failed: $!";
259     return $d;
260 }
261
262 sub executable_on_path ($) {
263     my ($program) = @_;
264     return 1 if $program =~ m{/};
265     my @path = split /:/, ($ENV{PATH} // "/usr/local/bin:/bin:/usr/bin");
266     foreach my $pe (@path) {
267         my $here = "$pe/$program";
268         return $here if stat_exists $here && -x _;
269     }
270     return undef;
271 }
272
273 our @signames = split / /, $Config{sig_name};
274
275 sub waitstatusmsg () {
276     if (!$?) {
277         return "terminated, reporting successful completion";
278     } elsif (!($? & 255)) {
279         return "failed with error exit status ".WEXITSTATUS($?);
280     } elsif (WIFSIGNALED($?)) {
281         my $signum=WTERMSIG($?);
282         return "died due to fatal signal ".
283             ($signames[$signum] // "number $signum").
284             ($? & 128 ? " (core dumped)" : ""); # POSIX(3pm) has no WCOREDUMP
285     } else {
286         return "failed with unknown wait status ".$?;
287     }
288 }
289
290 sub failedcmd_report_cmd {
291     my $intro = shift @_;
292     $intro //= "failed command";
293     { local ($!); printcmd \*STDERR, _us().": $intro:", @_ or die $!; };
294 }
295
296 sub failedcmd_waitstatus {
297     if ($? < 0) {
298         return "failed to fork/exec: $!";
299     } elsif ($?) {
300         return "subprocess ".waitstatusmsg();
301     } else {
302         return "subprocess produced invalid output";
303     }
304 }
305
306 sub failedcmd {
307     # Expects $!,$? as set by close - see below.
308     # To use with system(), set $?=-1 first.
309     #
310     # Actual behaviour of perl operations:
311     #   success              $!==0       $?==0       close of piped open
312     #   program failed       $!==0       $? >0       close of piped open
313     #   syscall failure      $! >0       $?=-1       close of piped open
314     #   failure              $! >0       unchanged   close of something else
315     #   success              trashed     $?==0       system
316     #   program failed       trashed     $? >0       system
317     #   syscall failure      $! >0       unchanged   system
318     failedcmd_report_cmd undef, @_;
319     fail failedcmd_waitstatus();
320 }
321
322 sub runcmd {
323     debugcmd "+",@_;
324     $!=0; $?=-1;
325     failedcmd @_ if system @_;
326 }
327
328 sub shell_cmd {
329     my ($first_shell, @cmd) = @_;
330     return qw(sh -ec), $first_shell.'; exec "$@"', 'x', @cmd;
331 }
332
333 sub cmdoutput_errok {
334     confess Dumper(\@_)." ?" if grep { !defined } @_;
335     debugcmd "|",@_;
336     open P, "-|", @_ or die "$_[0] $!";
337     my $d;
338     $!=0; $?=0;
339     { local $/ = undef; $d = <P>; }
340     die $! if P->error;
341     if (!close P) { printdebug "=>!$?\n"; return undef; }
342     chomp $d;
343     if ($debuglevel > 0) {
344         $d =~ m/^.*/;
345         my $dd = $&;
346         my $more = (length $' ? '...' : ''); #');
347         $dd =~ s{[^\n -~]|\\}{ sprintf "\\x%02x", ord $& }ge;
348         printdebug "=> \`$dd'",$more,"\n";
349     }
350     return $d;
351 }
352
353 sub cmdoutput {
354     my $d = cmdoutput_errok @_;
355     defined $d or failedcmd @_;
356     return $d;
357 }
358
359 sub link_ltarget ($$) {
360     my ($old,$new) = @_;
361     lstat $old or return undef;
362     if (-l _) {
363         $old = cmdoutput qw(realpath  --), $old;
364     }
365     my $r = link $old, $new;
366     $r = symlink $old, $new if !$r && $!==EXDEV;
367     $r or die "(sym)link $old $new: $!";
368 }
369
370 sub hashfile ($) {
371     my ($fn) = @_;
372     my $h = Digest::SHA->new(256);
373     $h->addfile($fn);
374     return $h->hexdigest();
375 }
376
377 sub git_rev_parse ($) {
378     return cmdoutput qw(git rev-parse), "$_[0]~0";
379 }
380
381 sub git_cat_file ($;$) {
382     my ($objname, $etype) = @_;
383     # => ($type, $data) or ('missing', undef)
384     # in scalar context, just the data
385     # if $etype defined, dies unless type is $etype or in @$etype
386     our ($gcf_pid, $gcf_i, $gcf_o);
387     my $chk = sub {
388         my ($gtype, $data) = @_;
389         if ($etype) {
390             $etype = [$etype] unless ref $etype;
391             confess "$objname expected @$etype but is $gtype"
392                 unless grep { $gtype eq $_ } @$etype;
393         }
394         return ($gtype, $data);
395     };
396     if (!$gcf_pid) {
397         my @cmd = qw(git cat-file --batch);
398         debugcmd "GCF|", @cmd;
399         $gcf_pid = open2 $gcf_o, $gcf_i, @cmd or die $!;
400     }
401     printdebug "GCF>| ", $objname, "\n";
402     print $gcf_i $objname, "\n" or die $!;
403     my $x = <$gcf_o>;
404     printdebug "GCF<| ", $x;
405     if ($x =~ m/ (missing)$/) { return $chk->($1, undef); }
406     my ($type, $size) = $x =~ m/^.* (\w+) (\d+)\n/ or die "$objname ?";
407     my $data;
408     (read $gcf_o, $data, $size) == $size or die "$objname $!";
409     $x = <$gcf_o>;
410     $x eq "\n" or die "$objname ($_) $!";
411     return $chk->($type, $data);
412 }
413
414 sub git_get_symref (;$) {
415     my ($symref) = @_;  $symref //= 'HEAD';
416     # => undef if not a symref, otherwise refs/...
417     my @cmd = (qw(git symbolic-ref -q HEAD));
418     my $branch = cmdoutput_errok @cmd;
419     if (!defined $branch) {
420         $?==256 or failedcmd @cmd;
421     } else {
422         chomp $branch;
423     }
424     return $branch;
425 }
426
427 sub git_for_each_ref ($$;$) {
428     my ($pattern,$func,$gitdir) = @_;
429     # calls $func->($objid,$objtype,$fullrefname,$reftail);
430     # $reftail is RHS of ref after refs/[^/]+/
431     # breaks if $pattern matches any ref `refs/blah' where blah has no `/'
432     # $pattern may be an array ref to mean multiple patterns
433     $pattern = [ $pattern ] unless ref $pattern;
434     my @cmd = (qw(git for-each-ref), @$pattern);
435     if (defined $gitdir) {
436         @cmd = ('sh','-ec','cd "$1"; shift; exec "$@"','x', $gitdir, @cmd);
437     }
438     open GFER, "-|", @cmd or die $!;
439     debugcmd "|", @cmd;
440     while (<GFER>) {
441         chomp or die "$_ ?";
442         printdebug "|> ", $_, "\n";
443         m#^(\w+)\s+(\w+)\s+(refs/[^/]+/(\S+))$# or die "$_ ?";
444         $func->($1,$2,$3,$4);
445     }
446     $!=0; $?=0; close GFER or die "$pattern $? $!";
447 }
448
449 sub git_get_ref ($) {
450     # => '' if no such ref
451     my ($refname) = @_;
452     local $_ = $refname;
453     s{^refs/}{[r]efs/} or die "$refname $_ ?";
454     return cmdoutput qw(git for-each-ref --format=%(objectname)), $_;
455 }
456
457 sub git_for_each_tag_referring ($$) {
458     my ($objreferring, $func) = @_;
459     # calls $func->($tagobjid,$refobjid,$fullrefname,$tagname);
460     printdebug "git_for_each_tag_referring ",
461         ($objreferring // 'UNDEF'),"\n";
462     git_for_each_ref('refs/tags', sub {
463         my ($tagobjid,$objtype,$fullrefname,$tagname) = @_;
464         return unless $objtype eq 'tag';
465         my $refobjid = git_rev_parse $tagobjid;
466         return unless
467             !defined $objreferring # caller wants them all
468             or $tagobjid eq $objreferring
469             or $refobjid eq $objreferring;
470         $func->($tagobjid,$refobjid,$fullrefname,$tagname);
471     });
472 }
473
474 sub git_check_unmodified () {
475     foreach my $cached (qw(0 1)) {
476         my @cmd = qw(git diff --quiet);
477         push @cmd, qw(--cached) if $cached;
478         push @cmd, qw(HEAD);
479         debugcmd "+",@cmd;
480         $!=0; $?=-1; system @cmd;
481         return if !$?;
482         if ($?==256) {
483             fail
484                 $cached
485                 ? "git index contains changes (does not match HEAD)"
486                 : "working tree is dirty (does not match HEAD)";
487         } else {
488             failedcmd @cmd;
489         }
490     }
491 }
492
493 sub is_fast_fwd ($$) {
494     my ($ancestor,$child) = @_;
495     my @cmd = (qw(git merge-base), $ancestor, $child);
496     my $mb = cmdoutput_errok @cmd;
497     if (defined $mb) {
498         return git_rev_parse($mb) eq git_rev_parse($ancestor);
499     } else {
500         $?==256 or failedcmd @cmd;
501         return 0;
502     }
503 }
504
505 sub git_reflog_action_msg ($) {
506     my ($msg) = @_;
507     my $rla = $ENV{GIT_REFLOG_ACTION};
508     $msg = "$rla: $msg" if length $rla;
509     return $msg;
510 }
511
512 sub git_update_ref_cmd {
513     # returns  qw(git update-ref), qw(-m), @_
514     # except that message may be modified to honour GIT_REFLOG_ACTION
515     my $msg = shift @_;
516     $msg = git_reflog_action_msg $msg;
517     return qw(git update-ref -m), $msg, @_;
518 }
519
520 sub changedir ($) {
521     my ($newdir) = @_;
522     printdebug "CD $newdir\n";
523     chdir $newdir or confess "chdir: $newdir: $!";
524 }
525
526 sub git_slurp_config_src ($) {
527     my ($src) = @_;
528     # returns $r such that $r->{KEY}[] = VALUE
529     my @cmd = (qw(git config -z --get-regexp), "--$src", qw(.*));
530     debugcmd "|",@cmd;
531
532     local ($debuglevel) = $debuglevel-2;
533     local $/="\0";
534
535     my $r = { };
536     open GITS, "-|", @cmd or die $!;
537     while (<GITS>) {
538         chomp or die;
539         printdebug "=> ", (messagequote $_), "\n";
540         m/\n/ or die "$_ ?";
541         push @{ $r->{$`} }, $'; #';
542     }
543     $!=0; $?=0;
544     close GITS
545         or ($!==0 && $?==256)
546         or failedcmd @cmd;
547     return $r;
548 }
549
550 sub gdr_ffq_prev_branchinfo ($) {
551     my ($symref) = @_;
552     # => ('status', "message", [$symref, $ffq_prev, $gdrlast])
553     # 'status' may be
554     #    branch         message is undef
555     #    weird-symref   } no $symref,
556     #    notbranch      }  no $ffq_prev
557     return ('detached', 'detached HEAD') unless defined $symref;
558     return ('weird-symref', 'HEAD symref is not to refs/')
559         unless $symref =~ m{^refs/};
560     my $ffq_prev = "refs/$ffq_refprefix/$'";
561     my $gdrlast = "refs/$gdrlast_refprefix/$'";
562     printdebug "ffq_prev_branchinfo branch current $symref\n";
563     return ('branch', undef, $symref, $ffq_prev, $gdrlast);
564 }
565
566 sub parsecontrolfh ($$;$) {
567     my ($fh, $desc, $allowsigned) = @_;
568     our $dpkgcontrolhash_noissigned;
569     my $c;
570     for (;;) {
571         my %opts = ('name' => $desc);
572         $opts{allow_pgp}= $allowsigned || !$dpkgcontrolhash_noissigned;
573         $c = Dpkg::Control::Hash->new(%opts);
574         $c->parse($fh,$desc) or die "parsing of $desc failed";
575         last if $allowsigned;
576         last if $dpkgcontrolhash_noissigned;
577         my $issigned= $c->get_option('is_pgp_signed');
578         if (!defined $issigned) {
579             $dpkgcontrolhash_noissigned= 1;
580             seek $fh, 0,0 or die "seek $desc: $!";
581         } elsif ($issigned) {
582             fail "control file $desc is (already) PGP-signed. ".
583                 " Note that dgit push needs to modify the .dsc and then".
584                 " do the signature itself";
585         } else {
586             last;
587         }
588     }
589     return $c;
590 }
591
592 sub parsecontrol {
593     my ($file, $desc, $allowsigned) = @_;
594     my $fh = new IO::Handle;
595     open $fh, '<', $file or die "$file: $!";
596     my $c = parsecontrolfh($fh,$desc,$allowsigned);
597     $fh->error and die $!;
598     close $fh;
599     return $c;
600 }
601
602 sub parsechangelog {
603     my $c = Dpkg::Control::Hash->new(name => 'parsed changelog');
604     my $p = new IO::Handle;
605     my @cmd = (qw(dpkg-parsechangelog), @_);
606     open $p, '-|', @cmd or die $!;
607     $c->parse($p);
608     $?=0; $!=0; close $p or failedcmd @cmd;
609     return $c;
610 }
611
612 sub getfield ($$) {
613     my ($dctrl,$field) = @_;
614     my $v = $dctrl->{$field};
615     return $v if defined $v;
616     fail "missing field $field in ".$dctrl->get_option('name');
617 }
618
619 sub parsechangelog_loop ($$$) {
620     my ($clogcmd, $descbase, $fn) = @_;
621     # @$clogcmd is qw(dpkg-parsechangelog ...some...options...)
622     # calls $fn->($thisstanza, $desc);
623     debugcmd "|",@$clogcmd;
624     open CLOGS, "-|", @$clogcmd or die $!;
625     for (;;) {
626         my $stanzatext = do { local $/=""; <CLOGS>; };
627         printdebug "clogp stanza ".Dumper($stanzatext) if $debuglevel>1;
628         last if !defined $stanzatext;
629
630         my $desc = "$descbase, entry no.$.";
631         open my $stanzafh, "<", \$stanzatext or die;
632         my $thisstanza = parsecontrolfh $stanzafh, $desc, 1;
633
634         $fn->($thisstanza, $desc);
635     }
636     die $! if CLOGS->error;
637     close CLOGS or $?==SIGPIPE or failedcmd @$clogcmd;
638 }       
639
640 # ========== playground handling ==========
641
642 # terminology:
643 #
644 #   $maindir      user's git working tree
645 #   playground    area in .git/ where we can make files, unpack, etc. etc.
646 #   playtree      git working tree sharing object store with the user's
647 #                 inside playground, or identical to it
648 #
649 # other globals
650 #
651 #   $local_git_cfg    hash of arrays of values: git config from $maindir
652 #
653 # expected calling pattern
654 #
655 #  firstly
656 #
657 #    [record_maindir]
658 #      must be run in directory containing .git
659 #      assigns to $maindir if not already set
660 #      also calls git_slurp_config_src to record git config
661 #        in $local_git_cfg, unless it's already set
662 #
663 #    fresh_playground SUBDIR_PATH_COMPONENTS
664 #      e.g fresh_playground 'dgit/unpack' ('.git/' is implied)
665 #      default SUBDIR_PATH_COMPONENTS is playground_subdir
666 #      calls record_maindir
667 #      sets up a new playground (destroying any old one)
668 #      returns playground pathname
669 #      caller may call multiple times with different subdir paths
670 #       createing different playgrounds
671 #
672 #    ensure_a_playground SUBDIR_PATH_COMPONENTS
673 #      like fresh_playground except:
674 #      merely ensures the directory exists; does not delete an existing one
675 #
676 #  then can use
677 #
678 #    changedir playground
679 #    changedir $maindir
680 #
681 #    playtree_setup $local_git_cfg
682 #            # ^ call in some (perhaps trivial) subdir of playground
683 #
684 #    rmtree playground
685
686 # ----- maindir -----
687
688 # these three all go together
689 our $maindir;
690 our $maindir_gitdir;
691 our $maindir_gitcommon;
692
693 our $local_git_cfg;
694
695 sub record_maindir () {
696     if (!defined $maindir) {
697         $maindir = must_getcwd();
698         if (!stat "$maindir/.git") {
699             fail "cannot stat $maindir/.git: $!";
700         }
701         if (-d _) {
702             # we fall back to this in case we have a pre-worktree
703             # git, which may not know git rev-parse --git-common-dir
704             $maindir_gitdir    = "$maindir/.git";
705             $maindir_gitcommon = "$maindir/.git";
706         } else {
707             $maindir_gitdir    = cmdoutput qw(git rev-parse --git-dir);
708             $maindir_gitcommon = cmdoutput qw(git rev-parse --git-common-dir);
709         }
710     }
711     $local_git_cfg //= git_slurp_config_src 'local';
712 }
713
714 # ----- playgrounds -----
715
716 sub ensure_a_playground_parent ($) {
717     my ($spc) = @_;
718     record_maindir();
719     $spc = "$maindir_gitdir/$spc";
720     my $parent = dirname $spc;
721     mkdir $parent or $!==EEXIST
722         or fail "failed to mkdir playground parent $parent: $!";
723     return $spc;
724 }    
725
726 sub ensure_a_playground ($) {
727     my ($spc) = @_;
728     $spc = ensure_a_playground_parent $spc;
729     mkdir $spc or $!==EEXIST or fail "failed to mkdir a playground $spc: $!";
730     return $spc;
731 }    
732
733 sub fresh_playground ($) {
734     my ($spc) = @_;
735     $spc = ensure_a_playground_parent $spc;
736     rmtree $spc;
737     mkdir $spc or fail "failed to mkdir the playground $spc: $!";
738     return $spc;
739 }
740
741 # ----- playtrees -----
742
743 sub playtree_setup (;$) {
744     my ($t_local_git_cfg) = @_;
745     $t_local_git_cfg //= $local_git_cfg;
746     # for use in the playtree
747     # $maindir must be set, eg by calling record_maindir or fresh_playground
748     runcmd qw(git init -q);
749     runcmd qw(git config gc.auto 0);
750     foreach my $copy (qw(user.email user.name user.useConfigOnly
751                          core.sharedRepository
752                          core.compression core.looseCompression
753                          core.bigFileThreshold core.fsyncObjectFiles)) {
754         my $v = $t_local_git_cfg->{$copy};
755         next unless $v;
756         runcmd qw(git config), $copy, $_ foreach @$v;
757     }
758     # this is confusing: we have
759     #   .                   playtree, not a worktree, has .git/, our cwd
760     #   $maindir            might be a worktree so
761     #   $maindir_gitdir     contains our main working "dgit", HEAD, etc.
762     #   $maindir_gitcommon  the shared stuff, including .objects
763     rmtree('.git/objects');
764     symlink "$maindir_gitcommon/objects",'.git/objects' or die $!;
765     ensuredir '.git/info';
766     open GA, "> .git/info/attributes" or die $!;
767     print GA "* $negate_harmful_gitattrs\n" or die $!;
768     close GA or die $!;
769 }
770
771 1;