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