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