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