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