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