chiark / gitweb /
892ebf9b1cb021e9ffcdbe52afc1e6c0315dece9
[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_new
47                       debiantag_maintview
48                       upstreamversion upstream_commitish_search
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 changedir_git_toplevel 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-zA-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_new ($$) { 
237     my ($v,$distro) = @_;
238     return "archive/$distro/".dep14_version_mangle $v;
239 }
240
241 sub debiantag_maintview ($$) { 
242     my ($v,$distro) = @_;
243     return "$distro/".dep14_version_mangle $v;
244 }
245
246 sub debiantags ($$) {
247     my ($version,$distro) = @_;
248     map { $_->($version, $distro) } (\&debiantag_new, \&debiantag_maintview);
249 }
250
251 sub stripepoch ($) {
252     my ($vsn) = @_;
253     $vsn =~ s/^\d+\://;
254     return $vsn;
255 }
256
257 sub upstreamversion ($) {
258     my ($vsn) = @_;
259     $vsn =~ s/-[^-]+$//;
260     return $vsn;
261 }
262
263 sub source_file_leafname ($$$) {
264     my ($package,$vsn,$sfx) = @_;
265     return "${package}_".(stripepoch $vsn).$sfx
266 }
267
268 sub is_orig_file_of_p_v ($$$) {
269     my ($f, $package, $upstreamvsn) = @_;
270     my $base = source_file_leafname $package, $upstreamvsn, '';
271     return 0 unless $f =~ m/^\Q$base\E\.$orig_f_tail_re$/;
272     return 1;
273 }
274
275 sub server_branch ($) { return "$branchprefix/$_[0]"; }
276 sub server_ref ($) { return "refs/".server_branch($_[0]); }
277
278 sub stat_exists ($) {
279     my ($f) = @_;
280     return 1 if stat $f;
281     return 0 if $!==&ENOENT;
282     confess "stat $f: $!";
283 }
284
285 sub _us () {
286     $::us // ($0 =~ m#[^/]*$#, $&);
287 }
288
289 sub failmsg {
290     my $s = f_ "error: %s\n", "@_";
291     $s =~ s/\n\n$/\n/g;
292     my $prefix = _us().": ";
293     $s =~ s/^/$prefix/gm;
294     return "\n".$s;
295 }
296
297 sub fail {
298     die failmsg @_;
299 }
300
301 sub ensuredir ($) {
302     my ($dir) = @_; # does not create parents
303     return if mkdir $dir;
304     return if $! == EEXIST;
305     confess "mkdir $dir: $!";
306 }
307
308 sub must_getcwd () {
309     my $d = getcwd();
310     defined $d or fail f_ "getcwd failed: %s\n", $!;
311     return $d;
312 }
313
314 sub executable_on_path ($) {
315     my ($program) = @_;
316     return 1 if $program =~ m{/};
317     my @path = split /:/, ($ENV{PATH} // "/usr/local/bin:/bin:/usr/bin");
318     foreach my $pe (@path) {
319         my $here = "$pe/$program";
320         return $here if stat_exists $here && -x _;
321     }
322     return undef;
323 }
324
325 our @signames = split / /, $Config{sig_name};
326
327 sub waitstatusmsg () {
328     if (!$?) {
329         return __ "terminated, reporting successful completion";
330     } elsif (!($? & 255)) {
331         return f_ "failed with error exit status %s", WEXITSTATUS($?);
332     } elsif (WIFSIGNALED($?)) {
333         my $signum=WTERMSIG($?);
334         return f_ "died due to fatal signal %s",
335             ($signames[$signum] // "number $signum").
336             ($? & 128 ? " (core dumped)" : ""); # POSIX(3pm) has no WCOREDUMP
337     } else {
338         return f_ "failed with unknown wait status %s", $?;
339     }
340 }
341
342 sub failedcmd_report_cmd {
343     my $intro = shift @_;
344     $intro //= __ "failed command";
345     { local ($!); printcmd \*STDERR, _us().": $intro:", @_ or confess "$!"; };
346 }
347
348 sub failedcmd_waitstatus {
349     if ($? < 0) {
350         return f_ "failed to fork/exec: %s", $!;
351     } elsif ($?) {
352         return f_ "subprocess %s", waitstatusmsg();
353     } else {
354         return __ "subprocess produced invalid output";
355     }
356 }
357
358 sub failedcmd {
359     # Expects $!,$? as set by close - see below.
360     # To use with system(), set $?=-1 first.
361     #
362     # Actual behaviour of perl operations:
363     #   success              $!==0       $?==0       close of piped open
364     #   program failed       $!==0       $? >0       close of piped open
365     #   syscall failure      $! >0       $?=-1       close of piped open
366     #   failure              $! >0       unchanged   close of something else
367     #   success              trashed     $?==0       system
368     #   program failed       trashed     $? >0       system
369     #   syscall failure      $! >0       unchanged   system
370     failedcmd_report_cmd undef, @_;
371     fail failedcmd_waitstatus();
372 }
373
374 sub runcmd {
375     debugcmd "+",@_;
376     $!=0; $?=-1;
377     failedcmd @_ if system @_;
378 }
379
380 sub shell_cmd {
381     my ($first_shell, @cmd) = @_;
382     return qw(sh -ec), $first_shell.'; exec "$@"', 'x', @cmd;
383 }
384
385 sub cmdoutput_errok {
386     confess Dumper(\@_)." ?" if grep { !defined } @_;
387     local $printdebug_when_debuglevel = $debugcmd_when_debuglevel;
388     debugcmd "|",@_;
389     open P, "-|", @_ or confess "$_[0] $!";
390     my $d;
391     $!=0; $?=0;
392     { local $/ = undef; $d = <P>; }
393     confess "$!" if P->error;
394     if (!close P) { printdebug "=>!$?\n"; return undef; }
395     chomp $d;
396     if ($debuglevel > 0) {
397         $d =~ m/^.*/;
398         my $dd = $&;
399         my $more = (length $' ? '...' : ''); #');
400         $dd =~ s{[^\n -~]|\\}{ sprintf "\\x%02x", ord $& }ge;
401         printdebug "=> \`$dd'",$more,"\n";
402     }
403     return $d;
404 }
405
406 sub cmdoutput {
407     my $d = cmdoutput_errok @_;
408     defined $d or failedcmd @_;
409     return $d;
410 }
411
412 sub link_ltarget ($$) {
413     my ($old,$new) = @_;
414     lstat $old or return undef;
415     if (-l _) {
416         $old = cmdoutput qw(realpath  --), $old;
417     }
418     my $r = link $old, $new;
419     $r = symlink $old, $new if !$r && $!==EXDEV;
420     $r or fail "(sym)link $old $new: $!\n";
421 }
422
423 sub rename_link_xf ($$$) {
424     # renames/moves or links/copies $src to $dst,
425     # even if $dst is on a different fs
426     # (May use the filename "$dst.tmp".);
427     # On success, returns true.
428     # On failure, returns false and sets
429     #    $@ to a reason message
430     #    $! to an errno value, or -1 if not known
431     # having possibly printed something about mv to stderr.
432     # Not safe to use without $keeporig if $dst might be a symlink
433     # to $src, as it might delete $src leaving $dst invalid.
434     my ($keeporig,$src,$dst) = @_;
435     if ($keeporig
436         ? link   $src, $dst
437         : rename $src, $dst) {
438         return 1;
439     }
440     if ($! != EXDEV) {
441         $@ = "$!";
442         return 0;
443     }
444     if (!stat $src) {
445         $@ = f_ "stat source file: %S", $!;
446         return 0;
447     }
448     my @src_stat = (stat _)[0..1];
449
450     my @dst_stat;
451     if (stat $dst) {
452         @dst_stat = (stat _)[0..1];
453     } elsif ($! == ENOENT) {
454     } else {
455         $@ = f_ "stat destination file: %S", $!;
456         return 0;
457     }
458
459     if ("@src_stat" eq "@dst_stat") {
460         # (Symlinks to) the same file.  No need for a copy but
461         # we may need to delete the original.
462         printdebug "rename_link_xf $keeporig $src $dst EXDEV but same\n";
463     } else {
464         $!=0; $?=0;
465         my @cmd = (qw(cp --), $src, "$dst.tmp");
466         debugcmd '+',@cmd;
467         if (system @cmd) {
468             failedcmd_report_cmd undef, @cmd;
469             $@ = failedcmd_waitstatus();
470             $! = -1;
471             return 0;
472         }
473         if (!rename "$dst.tmp", $dst) {
474             $@ = f_ "finally install file after cp: %S", $!;
475             return 0;
476         }
477     }
478     if (!$keeporig) {
479         if (!unlink $src) {
480             $@ = f_ "delete old file after cp: %S", $!;
481             return 0;
482         }
483     }
484     return 1;
485 }
486
487 sub hashfile ($) {
488     my ($fn) = @_;
489     my $h = Digest::SHA->new(256);
490     $h->addfile($fn);
491     return $h->hexdigest();
492 }
493
494 sub git_rev_parse ($) {
495     return cmdoutput qw(git rev-parse), "$_[0]~0";
496 }
497
498 sub changedir_git_toplevel () {
499     my $toplevel = cmdoutput qw(git rev-parse --show-toplevel);
500     length $toplevel or fail __ <<END;
501 not in a git working tree?
502 (git rev-parse --show-toplevel produced no output)
503 END
504     chdir $toplevel or fail f_ "chdir toplevel %s: %s\n", $toplevel, $!;
505 }
506
507 sub git_cat_file ($;$) {
508     my ($objname, $etype) = @_;
509     # => ($type, $data) or ('missing', undef)
510     # in scalar context, just the data
511     # if $etype defined, dies unless type is $etype or in @$etype
512     our ($gcf_pid, $gcf_i, $gcf_o);
513     local $printdebug_when_debuglevel = $debugcmd_when_debuglevel;
514     my $chk = sub {
515         my ($gtype, $data) = @_;
516         if ($etype) {
517             $etype = [$etype] unless ref $etype;
518             confess "$objname expected @$etype but is $gtype"
519                 unless grep { $gtype eq $_ } @$etype;
520         }
521         return ($gtype, $data);
522     };
523     if (!$gcf_pid) {
524         my @cmd = qw(git cat-file --batch);
525         debugcmd "GCF|", @cmd;
526         $gcf_pid = open2 $gcf_o, $gcf_i, @cmd or confess "$!";
527     }
528     printdebug "GCF>| $objname\n";
529     print $gcf_i $objname, "\n" or confess "$!";
530     my $x = <$gcf_o>;
531     printdebug "GCF<| ", $x;
532     if ($x =~ m/ (missing)$/) { return $chk->($1, undef); }
533     my ($type, $size) = $x =~ m/^.* (\w+) (\d+)\n/ or confess "$objname ?";
534     my $data;
535     (read $gcf_o, $data, $size) == $size or confess "$objname $!";
536     $x = <$gcf_o>;
537     $x eq "\n" or confess "$objname ($_) $!";
538     return $chk->($type, $data);
539 }
540
541 sub git_get_symref (;$) {
542     my ($symref) = @_;  $symref //= 'HEAD';
543     # => undef if not a symref, otherwise refs/...
544     my @cmd = (qw(git symbolic-ref -q HEAD));
545     my $branch = cmdoutput_errok @cmd;
546     if (!defined $branch) {
547         $?==256 or failedcmd @cmd;
548     } else {
549         chomp $branch;
550     }
551     return $branch;
552 }
553
554 sub git_for_each_ref ($$;$) {
555     my ($pattern,$func,$gitdir) = @_;
556     # calls $func->($objid,$objtype,$fullrefname,$reftail);
557     # $reftail is RHS of ref after refs/[^/]+/
558     # breaks if $pattern matches any ref `refs/blah' where blah has no `/'
559     # $pattern may be an array ref to mean multiple patterns
560     $pattern = [ $pattern ] unless ref $pattern;
561     my @cmd = (qw(git for-each-ref), @$pattern);
562     if (defined $gitdir) {
563         @cmd = ('sh','-ec','cd "$1"; shift; exec "$@"','x', $gitdir, @cmd);
564     }
565     open GFER, "-|", @cmd or confess "$!";
566     debugcmd "|", @cmd;
567     while (<GFER>) {
568         chomp or confess "$_ ?";
569         printdebug "|> ", $_, "\n";
570         m#^(\w+)\s+(\w+)\s+(refs/[^/]+/(\S+))$# or confess "$_ ?";
571         $func->($1,$2,$3,$4);
572     }
573     $!=0; $?=0; close GFER or confess "$pattern $? $!";
574 }
575
576 sub git_get_ref ($) {
577     # => '' if no such ref
578     my ($refname) = @_;
579     local $_ = $refname;
580     s{^refs/}{[r]efs/} or confess "$refname $_ ?";
581     return cmdoutput qw(git for-each-ref --format=%(objectname)), $_;
582 }
583
584 sub git_for_each_tag_referring ($$) {
585     my ($objreferring, $func) = @_;
586     # calls $func->($tagobjid,$refobjid,$fullrefname,$tagname);
587     printdebug "git_for_each_tag_referring ",
588         ($objreferring // 'UNDEF'),"\n";
589     git_for_each_ref('refs/tags', sub {
590         my ($tagobjid,$objtype,$fullrefname,$tagname) = @_;
591         return unless $objtype eq 'tag';
592         my $refobjid = git_rev_parse $tagobjid;
593         return unless
594             !defined $objreferring # caller wants them all
595             or $tagobjid eq $objreferring
596             or $refobjid eq $objreferring;
597         $func->($tagobjid,$refobjid,$fullrefname,$tagname);
598     });
599 }
600
601 sub git_check_unmodified () {
602     foreach my $cached (qw(0 1)) {
603         my @cmd = qw(git diff --quiet);
604         push @cmd, qw(--cached) if $cached;
605         push @cmd, qw(HEAD);
606         debugcmd "+",@cmd;
607         $!=0; $?=-1; system @cmd;
608         return if !$?;
609         if ($?==256) {
610             fail
611                 $cached
612                 ? __ "git index contains changes (does not match HEAD)"
613                 : __ "working tree is dirty (does not match HEAD)";
614         } else {
615             failedcmd @cmd;
616         }
617     }
618 }
619
620 sub upstream_commitish_search ($$) {
621     my ($upstream_version, $tried) = @_;
622     # todo: at some point maybe use git-deborig to do this
623     foreach my $tagpfx ('', 'v', 'upstream/') {
624         my $tag = $tagpfx.(dep14_version_mangle $upstream_version);
625         my $new_upstream = git_get_ref "refs/tags/$tag";
626         push @$tried, $tag;
627         return $new_upstream if length $new_upstream;
628     }
629 }
630
631 sub is_fast_fwd ($$) {
632     my ($ancestor,$child) = @_;
633     my @cmd = (qw(git merge-base), $ancestor, $child);
634     my $mb = cmdoutput_errok @cmd;
635     if (defined $mb) {
636         return git_rev_parse($mb) eq git_rev_parse($ancestor);
637     } else {
638         $?==256 or failedcmd @cmd;
639         return 0;
640     }
641 }
642
643 sub git_reflog_action_msg ($) {
644     my ($msg) = @_;
645     my $rla = $ENV{GIT_REFLOG_ACTION};
646     $msg = "$rla: $msg" if length $rla;
647     return $msg;
648 }
649
650 sub git_update_ref_cmd {
651     # returns  qw(git update-ref), qw(-m), @_
652     # except that message may be modified to honour GIT_REFLOG_ACTION
653     my $msg = shift @_;
654     $msg = git_reflog_action_msg $msg;
655     return qw(git update-ref -m), $msg, @_;
656 }
657
658 sub changedir ($) {
659     my ($newdir) = @_;
660     printdebug "CD $newdir\n";
661     chdir $newdir or confess "chdir: $newdir: $!";
662 }
663
664 sub git_slurp_config_src ($) {
665     my ($src) = @_;
666     # returns $r such that $r->{KEY}[] = VALUE
667     my @cmd = (qw(git config -z --get-regexp), "--$src", qw(.*));
668     debugcmd "|",@cmd;
669
670     local ($debuglevel) = $debuglevel-2;
671     local $/="\0";
672
673     my $r = { };
674     open GITS, "-|", @cmd or confess "$!";
675     while (<GITS>) {
676         chomp or confess;
677         printdebug "=> ", (messagequote $_), "\n";
678         m/\n/ or confess "$_ ?";
679         push @{ $r->{$`} }, $'; #';
680     }
681     $!=0; $?=0;
682     close GITS
683         or ($!==0 && $?==256)
684         or failedcmd @cmd;
685     return $r;
686 }
687
688 sub gdr_ffq_prev_branchinfo ($) {
689     my ($symref) = @_;
690     # => ('status', "message", [$symref, $ffq_prev, $gdrlast])
691     # 'status' may be
692     #    branch         message is undef
693     #    weird-symref   } no $symref,
694     #    notbranch      }  no $ffq_prev
695     return ('detached', __ 'detached HEAD') unless defined $symref;
696     return ('weird-symref', __ 'HEAD symref is not to refs/')
697         unless $symref =~ m{^refs/};
698     my $ffq_prev = "refs/$ffq_refprefix/$'";
699     my $gdrlast = "refs/$gdrlast_refprefix/$'";
700     printdebug "ffq_prev_branchinfo branch current $symref\n";
701     return ('branch', undef, $symref, $ffq_prev, $gdrlast);
702 }
703
704 sub parsecontrolfh ($$;$) {
705     my ($fh, $desc, $allowsigned) = @_;
706     our $dpkgcontrolhash_noissigned;
707     my $c;
708     for (;;) {
709         my %opts = ('name' => $desc);
710         $opts{allow_pgp}= $allowsigned || !$dpkgcontrolhash_noissigned;
711         $c = Dpkg::Control::Hash->new(%opts);
712         $c->parse($fh,$desc) or fail f_ "parsing of %s failed", $desc;
713         last if $allowsigned;
714         last if $dpkgcontrolhash_noissigned;
715         my $issigned= $c->get_option('is_pgp_signed');
716         if (!defined $issigned) {
717             $dpkgcontrolhash_noissigned= 1;
718             seek $fh, 0,0 or confess "seek $desc: $!";
719         } elsif ($issigned) {
720             fail f_
721                 "control file %s is (already) PGP-signed. ".
722                 " Note that dgit push needs to modify the .dsc and then".
723                 " do the signature itself",
724                 $desc;
725         } else {
726             last;
727         }
728     }
729     return $c;
730 }
731
732 sub parsecontrol {
733     my ($file, $desc, $allowsigned) = @_;
734     my $fh = new IO::Handle;
735     open $fh, '<', $file or fail f_ "open %s (%s): %s", $file, $desc, $!;
736     my $c = parsecontrolfh($fh,$desc,$allowsigned);
737     $fh->error and confess "$!";
738     close $fh;
739     return $c;
740 }
741
742 sub parsechangelog {
743     my $c = Dpkg::Control::Hash->new(name => 'parsed changelog');
744     my $p = new IO::Handle;
745     my @cmd = (qw(dpkg-parsechangelog), @_);
746     open $p, '-|', @cmd or confess "$!";
747     $c->parse($p);
748     $?=0; $!=0; close $p or failedcmd @cmd;
749     return $c;
750 }
751
752 sub getfield ($$) {
753     my ($dctrl,$field) = @_;
754     my $v = $dctrl->{$field};
755     return $v if defined $v;
756     fail f_ "missing field %s in %s", $field, $dctrl->get_option('name');
757 }
758
759 sub parsechangelog_loop ($$$) {
760     my ($clogcmd, $descbase, $fn) = @_;
761     # @$clogcmd is qw(dpkg-parsechangelog ...some...options...)
762     # calls $fn->($thisstanza, $desc);
763     debugcmd "|",@$clogcmd;
764     open CLOGS, "-|", @$clogcmd or confess "$!";
765     for (;;) {
766         my $stanzatext = do { local $/=""; <CLOGS>; };
767         printdebug "clogp stanza ".Dumper($stanzatext) if $debuglevel>1;
768         last if !defined $stanzatext;
769
770         my $desc = "$descbase, entry no.$.";
771         open my $stanzafh, "<", \$stanzatext or confess;
772         my $thisstanza = parsecontrolfh $stanzafh, $desc, 1;
773
774         $fn->($thisstanza, $desc);
775     }
776     confess "$!" if CLOGS->error;
777     close CLOGS or $?==SIGPIPE or failedcmd @$clogcmd;
778 }       
779
780 sub make_commit_text ($) {
781     my ($text) = @_;
782     my ($out, $in);
783     my @cmd = (qw(git hash-object -w -t commit --stdin));
784     debugcmd "|",@cmd;
785     print Dumper($text) if $debuglevel > 1;
786     my $child = open2($out, $in, @cmd) or confess "$!";
787     my $h;
788     eval {
789         print $in $text or confess "$!";
790         close $in or confess "$!";
791         $h = <$out>;
792         $h =~ m/^\w+$/ or confess;
793         $h = $&;
794         printdebug "=> $h\n";
795     };
796     close $out;
797     waitpid $child, 0 == $child or confess "$child $!";
798     $? and failedcmd @cmd;
799     return $h;
800 }
801
802 sub reflog_cache_insert ($$$) {
803     my ($ref, $cachekey, $value) = @_;
804     # you must call this in $maindir
805     # you must have called record_maindir
806
807     # When we no longer need to support squeeze, use --create-reflog
808     # instead of this:
809     my $parent = $ref; $parent =~ s{/[^/]+$}{};
810     ensuredir "$maindir_gitcommon/logs/$parent";
811     my $makelogfh = new IO::File "$maindir_gitcommon/logs/$ref", '>>'
812       or confess "$!";
813
814     my $oldcache = git_get_ref $ref;
815
816     if ($oldcache eq $value) {
817         my $tree = cmdoutput qw(git rev-parse), "$value:";
818         # git update-ref doesn't always update, in this case.  *sigh*
819         my $authline = (ucfirst _us()).
820             ' <'._us().'@example.com> 1000000000 +0000';
821         my $dummy = make_commit_text <<ENDU.(__ <<END);
822 tree $tree
823 parent $value
824 author $authline
825 committer $authline
826
827 ENDU
828 Dummy commit - do not use
829 END
830         runcmd qw(git update-ref -m), _us()." - dummy", $ref, $dummy;
831     }
832     runcmd qw(git update-ref -m), $cachekey, $ref, $value;
833 }
834
835 sub reflog_cache_lookup ($$) {
836     my ($ref, $cachekey) = @_;
837     # you may call this in $maindir or in a playtree
838     # you must have called record_maindir
839     my @cmd = (qw(git log -g), '--pretty=format:%H %gs', $ref);
840     debugcmd "|(probably)",@cmd;
841     my $child = open GC, "-|";  defined $child or confess "$!";
842     if (!$child) {
843         chdir $maindir or confess "$!";
844         if (!stat "$maindir_gitcommon/logs/$ref") {
845             $! == ENOENT or confess "$!";
846             printdebug ">(no reflog)\n";
847             finish 0;
848         }
849         exec @cmd; die f_ "exec %s: %s\n", $cmd[0], $!;
850     }
851     while (<GC>) {
852         chomp;
853         printdebug ">| ", $_, "\n" if $debuglevel > 1;
854         next unless m/^(\w+) (\S.*\S)$/ && $2 eq $cachekey;
855         close GC;
856         return $1;
857     }
858     confess "$!" if GC->error;
859     failedcmd unless close GC;
860     return undef;
861 }
862
863 # ========== playground handling ==========
864
865 # terminology:
866 #
867 #   $maindir      user's git working tree
868 #   playground    area in .git/ where we can make files, unpack, etc. etc.
869 #   playtree      git working tree sharing object store with the user's
870 #                 inside playground, or identical to it
871 #
872 # other globals
873 #
874 #   $local_git_cfg    hash of arrays of values: git config from $maindir
875 #
876 # expected calling pattern
877 #
878 #  firstly
879 #
880 #    [record_maindir]
881 #      must be run in directory containing .git
882 #      assigns to $maindir if not already set
883 #      also calls git_slurp_config_src to record git config
884 #        in $local_git_cfg, unless it's already set
885 #
886 #    fresh_playground SUBDIR_PATH_COMPONENTS
887 #      e.g fresh_playground 'dgit/unpack' ('.git/' is implied)
888 #      default SUBDIR_PATH_COMPONENTS is playground_subdir
889 #      calls record_maindir
890 #      sets up a new playground (destroying any old one)
891 #      returns playground pathname
892 #      caller may call multiple times with different subdir paths
893 #       createing different playgrounds
894 #
895 #    ensure_a_playground SUBDIR_PATH_COMPONENTS
896 #      like fresh_playground except:
897 #      merely ensures the directory exists; does not delete an existing one
898 #
899 #  then can use
900 #
901 #    changedir playground
902 #    changedir $maindir
903 #
904 #    playtree_setup $local_git_cfg
905 #            # ^ call in some (perhaps trivial) subdir of playground
906 #
907 #    rmtree playground
908
909 # ----- maindir -----
910
911 our $local_git_cfg;
912
913 sub record_maindir () {
914     if (!defined $maindir) {
915         $maindir = must_getcwd();
916         if (!stat "$maindir/.git") {
917             fail f_ "cannot stat %s/.git: %s", $maindir, $!;
918         }
919         if (-d _) {
920             # we fall back to this in case we have a pre-worktree
921             # git, which may not know git rev-parse --git-common-dir
922             $maindir_gitdir    = "$maindir/.git";
923             $maindir_gitcommon = "$maindir/.git";
924         } else {
925             $maindir_gitdir    = cmdoutput qw(git rev-parse --git-dir);
926             $maindir_gitcommon = cmdoutput qw(git rev-parse --git-common-dir);
927         }
928     }
929     $local_git_cfg //= git_slurp_config_src 'local';
930 }
931
932 # ----- playgrounds -----
933
934 sub ensure_a_playground_parent ($) {
935     my ($spc) = @_;
936     record_maindir();
937     $spc = "$maindir_gitdir/$spc";
938     my $parent = dirname $spc;
939     mkdir $parent or $!==EEXIST or fail f_
940         "failed to mkdir playground parent %s: %s", $parent, $!;
941     return $spc;
942 }    
943
944 sub ensure_a_playground ($) {
945     my ($spc) = @_;
946     $spc = ensure_a_playground_parent $spc;
947     mkdir $spc or $!==EEXIST or fail f_
948         "failed to mkdir a playground %s: %s", $spc, $!;
949     return $spc;
950 }    
951
952 sub fresh_playground ($) {
953     my ($spc) = @_;
954     $spc = ensure_a_playground_parent $spc;
955     rmtree $spc;
956     mkdir $spc or fail f_
957         "failed to mkdir the playground %s: %s", $spc, $!;
958     return $spc;
959 }
960
961 # ----- playtrees -----
962
963 sub playtree_setup (;$) {
964     my ($t_local_git_cfg) = @_;
965     $t_local_git_cfg //= $local_git_cfg;
966     # for use in the playtree
967     # $maindir must be set, eg by calling record_maindir or fresh_playground
968     runcmd qw(git init -q);
969     runcmd qw(git config gc.auto 0);
970     foreach my $copy (qw(user.email user.name user.useConfigOnly
971                          core.sharedRepository
972                          core.compression core.looseCompression
973                          core.bigFileThreshold core.fsyncObjectFiles)) {
974         my $v = $t_local_git_cfg->{$copy};
975         next unless $v;
976         runcmd qw(git config), $copy, $_ foreach @$v;
977     }
978     # this is confusing: we have
979     #   .                   playtree, not a worktree, has .git/, our cwd
980     #   $maindir            might be a worktree so
981     #   $maindir_gitdir     contains our main working "dgit", HEAD, etc.
982     #   $maindir_gitcommon  the shared stuff, including .objects
983     rmtree('.git/objects');
984     symlink "$maindir_gitcommon/objects",'.git/objects' or confess "$!";
985     ensuredir '.git/info';
986     open GA, "> .git/info/attributes" or confess "$!";
987     print GA "* $negate_harmful_gitattrs\n" or confess "$!";
988     close GA or confess "$!";
989 }
990
991 1;