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