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