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