chiark / gitweb /
2004fe1e835c847e9521de3a45cfbc5ab16557d1
[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     }
660     $new_upstream = git_rev_parse $new_upstream;
661
662     return ($new_upstream, $used, $message);
663     # used is a human-readable idea of what we found
664 }
665
666 sub is_fast_fwd ($$) {
667     my ($ancestor,$child) = @_;
668     my @cmd = (qw(git merge-base), $ancestor, $child);
669     my $mb = cmdoutput_errok @cmd;
670     if (defined $mb) {
671         return git_rev_parse($mb) eq git_rev_parse($ancestor);
672     } else {
673         $?==256 or failedcmd @cmd;
674         return 0;
675     }
676 }
677
678 sub git_reflog_action_msg ($) {
679     my ($msg) = @_;
680     my $rla = $ENV{GIT_REFLOG_ACTION};
681     $msg = "$rla: $msg" if length $rla;
682     return $msg;
683 }
684
685 sub git_update_ref_cmd {
686     # returns  qw(git update-ref), qw(-m), @_
687     # except that message may be modified to honour GIT_REFLOG_ACTION
688     my $msg = shift @_;
689     $msg = git_reflog_action_msg $msg;
690     return qw(git update-ref -m), $msg, @_;
691 }
692
693 sub rm_subdir_cached ($) {
694     my ($subdir) = @_;
695     runcmd qw(git rm --quiet -rf --cached --ignore-unmatch), $subdir;
696 }
697
698 sub read_tree_subdir ($$) {
699     my ($subdir, $new_tree_object) = @_;
700     # If $new_tree_object is '', the subtree is deleted.
701     confess unless defined $new_tree_object;
702     rm_subdir_cached $subdir;
703     runcmd qw(git read-tree), "--prefix=$subdir/", $new_tree_object
704         if length $new_tree_object;
705 }
706
707 sub read_tree_debian ($) {
708     my ($treeish) = @_;
709     read_tree_subdir 'debian', "$treeish:debian";
710     rm_subdir_cached 'debian/patches';
711 }
712
713 sub read_tree_upstream ($;$$) {
714     my ($treeish, $keep_patches, $tree_with_debian) = @_;
715     # if $tree_with_debian is supplied, will use that for debian/
716     # otherwise will save and restore it.  If $tree_with_debian
717     # is '' then debian/ is deleted.
718     my $debian =
719         defined $tree_with_debian ? "$tree_with_debian:debian"
720         : cmdoutput qw(git write-tree --prefix=debian/);
721     runcmd qw(git read-tree), $treeish;
722     read_tree_subdir 'debian', $debian;
723     rm_subdir_cached 'debian/patches' unless $keep_patches;
724 }
725
726 sub changedir ($) {
727     my ($newdir) = @_;
728     printdebug "CD $newdir\n";
729     chdir $newdir or confess "chdir: $newdir: $!";
730 }
731
732 sub git_slurp_config_src ($) {
733     my ($src) = @_;
734     # returns $r such that $r->{KEY}[] = VALUE
735     my @cmd = (qw(git config -z --get-regexp), "--$src", qw(.*));
736     debugcmd "|",@cmd;
737
738     local ($debuglevel) = $debuglevel-2;
739     local $/="\0";
740
741     my $r = { };
742     open GITS, "-|", @cmd or confess "$!";
743     while (<GITS>) {
744         chomp or confess;
745         printdebug "=> ", (messagequote $_), "\n";
746         m/\n/ or confess "$_ ?";
747         push @{ $r->{$`} }, $'; #';
748     }
749     $!=0; $?=0;
750     close GITS
751         or ($!==0 && $?==256)
752         or failedcmd @cmd;
753     return $r;
754 }
755
756 sub gdr_ffq_prev_branchinfo ($) {
757     my ($symref) = @_;
758     # => ('status', "message", [$symref, $ffq_prev, $gdrlast])
759     # 'status' may be
760     #    branch         message is undef
761     #    weird-symref   } no $symref,
762     #    notbranch      }  no $ffq_prev
763     return ('detached', __ 'detached HEAD') unless defined $symref;
764     return ('weird-symref', __ 'HEAD symref is not to refs/')
765         unless $symref =~ m{^refs/};
766     my $ffq_prev = "refs/$ffq_refprefix/$'";
767     my $gdrlast = "refs/$gdrlast_refprefix/$'";
768     printdebug "ffq_prev_branchinfo branch current $symref\n";
769     return ('branch', undef, $symref, $ffq_prev, $gdrlast);
770 }
771
772 sub parsecontrolfh ($$;$) {
773     my ($fh, $desc, $allowsigned) = @_;
774     our $dpkgcontrolhash_noissigned;
775     my $c;
776     for (;;) {
777         my %opts = ('name' => $desc);
778         $opts{allow_pgp}= $allowsigned || !$dpkgcontrolhash_noissigned;
779         $c = Dpkg::Control::Hash->new(%opts);
780         $c->parse($fh,$desc) or fail f_ "parsing of %s failed", $desc;
781         last if $allowsigned;
782         last if $dpkgcontrolhash_noissigned;
783         my $issigned= $c->get_option('is_pgp_signed');
784         if (!defined $issigned) {
785             $dpkgcontrolhash_noissigned= 1;
786             seek $fh, 0,0 or confess "seek $desc: $!";
787         } elsif ($issigned) {
788             fail f_
789                 "control file %s is (already) PGP-signed. ".
790                 " Note that dgit push needs to modify the .dsc and then".
791                 " do the signature itself",
792                 $desc;
793         } else {
794             last;
795         }
796     }
797     return $c;
798 }
799
800 sub parsecontrol {
801     my ($file, $desc, $allowsigned) = @_;
802     my $fh = new IO::Handle;
803     open $fh, '<', $file or fail f_ "open %s (%s): %s", $file, $desc, $!;
804     my $c = parsecontrolfh($fh,$desc,$allowsigned);
805     $fh->error and confess "$!";
806     close $fh;
807     return $c;
808 }
809
810 sub parsechangelog {
811     my $c = Dpkg::Control::Hash->new(name => 'parsed changelog');
812     my $p = new IO::Handle;
813     my @cmd = (qw(dpkg-parsechangelog), @_);
814     open $p, '-|', @cmd or confess "$!";
815     $c->parse($p);
816     $?=0; $!=0; close $p or failedcmd @cmd;
817     return $c;
818 }
819
820 sub getfield ($$) {
821     my ($dctrl,$field) = @_;
822     my $v = $dctrl->{$field};
823     return $v if defined $v;
824     fail f_ "missing field %s in %s", $field, $dctrl->get_option('name');
825 }
826
827 sub parsechangelog_loop ($$$) {
828     my ($clogcmd, $descbase, $fn) = @_;
829     # @$clogcmd is qw(dpkg-parsechangelog ...some...options...)
830     # calls $fn->($thisstanza, $desc);
831     debugcmd "|",@$clogcmd;
832     open CLOGS, "-|", @$clogcmd or confess "$!";
833     for (;;) {
834         my $stanzatext = do { local $/=""; <CLOGS>; };
835         printdebug "clogp stanza ".Dumper($stanzatext) if $debuglevel>1;
836         last if !defined $stanzatext;
837
838         my $desc = "$descbase, entry no.$.";
839         open my $stanzafh, "<", \$stanzatext or confess;
840         my $thisstanza = parsecontrolfh $stanzafh, $desc, 1;
841
842         $fn->($thisstanza, $desc);
843     }
844     confess "$!" if CLOGS->error;
845     close CLOGS or $?==SIGPIPE or failedcmd @$clogcmd;
846 }       
847
848 sub make_commit ($$) {
849     my ($parents, $message_paras) = @_;
850     my $tree = cmdoutput qw(git write-tree);
851     my @cmd = (qw(git commit-tree), $tree);
852     push @cmd, qw(-p), $_ foreach @$parents;
853     push @cmd, qw(-m), $_ foreach @$message_paras;
854     return cmdoutput @cmd;
855 }
856
857 sub hash_commit ($) {
858     my ($file) = @_;
859     return cmdoutput qw(git hash-object -w -t commit), $file;
860 }
861
862 sub hash_commit_text ($) {
863     my ($text) = @_;
864     my ($out, $in);
865     my @cmd = (qw(git hash-object -w -t commit --stdin));
866     debugcmd "|",@cmd;
867     print Dumper($text) if $debuglevel > 1;
868     my $child = open2($out, $in, @cmd) or confess "$!";
869     my $h;
870     eval {
871         print $in $text or confess "$!";
872         close $in or confess "$!";
873         $h = <$out>;
874         $h =~ m/^\w+$/ or confess;
875         $h = $&;
876         printdebug "=> $h\n";
877     };
878     close $out;
879     waitpid $child, 0 == $child or confess "$child $!";
880     $? and failedcmd @cmd;
881     return $h;
882 }
883
884 sub reflog_cache_insert ($$$) {
885     my ($ref, $cachekey, $value) = @_;
886     # you must call this in $maindir
887     # you must have called record_maindir
888
889     # When we no longer need to support squeeze, use --create-reflog
890     # instead of this:
891     my $parent = $ref; $parent =~ s{/[^/]+$}{};
892     ensuredir "$maindir_gitcommon/logs/$parent";
893     my $makelogfh = new IO::File "$maindir_gitcommon/logs/$ref", '>>'
894       or confess "$!";
895
896     my $oldcache = git_get_ref $ref;
897
898     if ($oldcache eq $value) {
899         my $tree = cmdoutput qw(git rev-parse), "$value:";
900         # git update-ref doesn't always update, in this case.  *sigh*
901         my $authline = (ucfirst _us()).
902             ' <'._us().'@example.com> 1000000000 +0000';
903         my $dummy = hash_commit_text <<ENDU.(__ <<END);
904 tree $tree
905 parent $value
906 author $authline
907 committer $authline
908
909 ENDU
910 Dummy commit - do not use
911 END
912         runcmd qw(git update-ref -m), _us()." - dummy", $ref, $dummy;
913     }
914     runcmd qw(git update-ref -m), $cachekey, $ref, $value;
915 }
916
917 sub reflog_cache_lookup ($$) {
918     my ($ref, $cachekey) = @_;
919     # you may call this in $maindir or in a playtree
920     # you must have called record_maindir
921     my @cmd = (qw(git log -g), '--pretty=format:%H %gs', $ref);
922     debugcmd "|(probably)",@cmd;
923     my $child = open GC, "-|";  defined $child or confess "$!";
924     if (!$child) {
925         chdir $maindir or confess "$!";
926         if (!stat "$maindir_gitcommon/logs/$ref") {
927             $! == ENOENT or confess "$!";
928             printdebug ">(no reflog)\n";
929             finish 0;
930         }
931         exec @cmd; die f_ "exec %s: %s\n", $cmd[0], $!;
932     }
933     while (<GC>) {
934         chomp;
935         printdebug ">| ", $_, "\n" if $debuglevel > 1;
936         next unless m/^(\w+) (\S.*\S)$/ && $2 eq $cachekey;
937         close GC;
938         return $1;
939     }
940     confess "$!" if GC->error;
941     failedcmd unless close GC;
942     return undef;
943 }
944
945 # ========== playground handling ==========
946
947 # terminology:
948 #
949 #   $maindir      user's git working tree
950 #   playground    area in .git/ where we can make files, unpack, etc. etc.
951 #   playtree      git working tree sharing object store with the user's
952 #                 inside playground, or identical to it
953 #
954 # other globals
955 #
956 #   $local_git_cfg    hash of arrays of values: git config from $maindir
957 #
958 # expected calling pattern
959 #
960 #  firstly
961 #
962 #    [record_maindir]
963 #      must be run in directory containing .git
964 #      assigns to $maindir if not already set
965 #      also calls git_slurp_config_src to record git config
966 #        in $local_git_cfg, unless it's already set
967 #
968 #    fresh_playground SUBDIR_PATH_COMPONENTS
969 #      e.g fresh_playground 'dgit/unpack' ('.git/' is implied)
970 #      default SUBDIR_PATH_COMPONENTS is playground_subdir
971 #      calls record_maindir
972 #      sets up a new playground (destroying any old one)
973 #      returns playground pathname
974 #      caller may call multiple times with different subdir paths
975 #       createing different playgrounds
976 #
977 #    ensure_a_playground SUBDIR_PATH_COMPONENTS
978 #      like fresh_playground except:
979 #      merely ensures the directory exists; does not delete an existing one
980 #
981 #  then can use
982 #
983 #    changedir playground
984 #    changedir $maindir
985 #
986 #    playtree_setup $local_git_cfg
987 #            # ^ call in some (perhaps trivial) subdir of playground
988 #
989 #    rmtree playground
990
991 # ----- maindir -----
992
993 our $local_git_cfg;
994
995 sub record_maindir () {
996     if (!defined $maindir) {
997         $maindir = must_getcwd();
998         if (!stat "$maindir/.git") {
999             fail f_ "cannot stat %s/.git: %s", $maindir, $!;
1000         }
1001         if (-d _) {
1002             # we fall back to this in case we have a pre-worktree
1003             # git, which may not know git rev-parse --git-common-dir
1004             $maindir_gitdir    = "$maindir/.git";
1005             $maindir_gitcommon = "$maindir/.git";
1006         } else {
1007             $maindir_gitdir    = cmdoutput qw(git rev-parse --git-dir);
1008             $maindir_gitcommon = cmdoutput qw(git rev-parse --git-common-dir);
1009         }
1010     }
1011     $local_git_cfg //= git_slurp_config_src 'local';
1012 }
1013
1014 # ----- playgrounds -----
1015
1016 sub ensure_a_playground_parent ($) {
1017     my ($spc) = @_;
1018     record_maindir();
1019     $spc = "$maindir_gitdir/$spc";
1020     my $parent = dirname $spc;
1021     mkdir $parent or $!==EEXIST or fail f_
1022         "failed to mkdir playground parent %s: %s", $parent, $!;
1023     return $spc;
1024 }    
1025
1026 sub ensure_a_playground ($) {
1027     my ($spc) = @_;
1028     $spc = ensure_a_playground_parent $spc;
1029     mkdir $spc or $!==EEXIST or fail f_
1030         "failed to mkdir a playground %s: %s", $spc, $!;
1031     return $spc;
1032 }    
1033
1034 sub fresh_playground ($) {
1035     my ($spc) = @_;
1036     $spc = ensure_a_playground_parent $spc;
1037     rmtree $spc;
1038     mkdir $spc or fail f_
1039         "failed to mkdir the playground %s: %s", $spc, $!;
1040     return $spc;
1041 }
1042
1043 # ----- playtrees -----
1044
1045 sub playtree_setup (;$) {
1046     my ($t_local_git_cfg) = @_;
1047     $t_local_git_cfg //= $local_git_cfg;
1048     # for use in the playtree
1049     # $maindir must be set, eg by calling record_maindir or fresh_playground
1050     runcmd qw(git init -q);
1051     runcmd qw(git config gc.auto 0);
1052     foreach my $copy (qw(user.email user.name user.useConfigOnly
1053                          core.sharedRepository
1054                          core.compression core.looseCompression
1055                          core.bigFileThreshold core.fsyncObjectFiles)) {
1056         my $v = $t_local_git_cfg->{$copy};
1057         next unless $v;
1058         runcmd qw(git config), $copy, $_ foreach @$v;
1059     }
1060     # this is confusing: we have
1061     #   .                   playtree, not a worktree, has .git/, our cwd
1062     #   $maindir            might be a worktree so
1063     #   $maindir_gitdir     contains our main working "dgit", HEAD, etc.
1064     #   $maindir_gitcommon  the shared stuff, including .objects
1065     rmtree('.git/objects');
1066     symlink "$maindir_gitcommon/objects",'.git/objects' or confess "$!";
1067     ensuredir '.git/info';
1068     open GA, "> .git/info/attributes" or confess "$!";
1069     print GA "* $negate_harmful_gitattrs\n" or confess "$!";
1070     close GA or confess "$!";
1071 }
1072
1073 1;