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