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