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