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