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