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