chiark / gitweb /
Declare fast forward from 0.22-experimental2
[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
33 BEGIN {
34     use Exporter   ();
35     our ($VERSION, @ISA, @EXPORT, @EXPORT_OK, %EXPORT_TAGS);
36
37     $VERSION     = 1.00;
38     @ISA         = qw(Exporter);
39     @EXPORT      = qw(setup_sigwarn forkcheck_setup forkcheck_mainprocess
40                       dep14_version_mangle
41                       debiantags debiantag_old debiantag_new
42                       server_branch server_ref
43                       stat_exists link_ltarget
44                       hashfile
45                       fail ensuredir executable_on_path
46                       waitstatusmsg failedcmd_waitstatus
47                       failedcmd_report_cmd failedcmd
48                       cmdoutput cmdoutput_errok
49                       git_rev_parse git_cat_file
50                       git_get_ref git_for_each_ref
51                       git_for_each_tag_referring is_fast_fwd
52                       $package_re $component_re $deliberately_re
53                       $distro_re $versiontag_re
54                       $branchprefix
55                       initdebug enabledebug enabledebuglevel
56                       printdebug debugcmd
57                       $debugprefix *debuglevel *DEBUG
58                       shellquote printcmd messagequote);
59     # implicitly uses $main::us
60     %EXPORT_TAGS = ( policyflags => [qw(NOFFCHECK FRESHREPO NOCOMMITCHECK)] );
61     @EXPORT_OK   = @{ $EXPORT_TAGS{policyflags} };
62 }
63
64 our @EXPORT_OK;
65
66 our $package_re = '[0-9a-z][-+.0-9a-z]*';
67 our $component_re = '[0-9a-zA-Z][-+.0-9a-zA-Z]*';
68 our $deliberately_re = "(?:TEST-)?$package_re";
69 our $distro_re = $component_re;
70 our $versiontag_re = qr{[-+.\%_0-9a-zA-Z/]+};
71 our $branchprefix = 'dgit';
72
73 # policy hook exit status bits
74 # see dgit-repos-server head comment for documentation
75 # 1 is reserved in case something fails with `exit 1' and to spot
76 # dynamic loader, runtime, etc., failures, which report 127 or 255
77 sub NOFFCHECK () { return 0x2; }
78 sub FRESHREPO () { return 0x4; }
79 sub NOCOMMITCHECK () { return 0x8; }
80
81 our $debugprefix;
82 our $debuglevel = 0;
83
84 our $forkcheck_mainprocess;
85
86 sub forkcheck_setup () {
87     $forkcheck_mainprocess = $$;
88 }
89
90 sub forkcheck_mainprocess () {
91     # You must have called forkcheck_setup or setup_sigwarn already
92     getppid != $forkcheck_mainprocess;
93 }
94
95 sub setup_sigwarn () {
96     forkcheck_setup();
97     $SIG{__WARN__} = sub { 
98         die $_[0] if forkcheck_mainprocess;
99     };
100 }
101
102 sub initdebug ($) { 
103     ($debugprefix) = @_;
104     open DEBUG, ">/dev/null" or die $!;
105 }
106
107 sub enabledebug () {
108     open DEBUG, ">&STDERR" or die $!;
109     DEBUG->autoflush(1);
110     $debuglevel ||= 1;
111 }
112     
113 sub enabledebuglevel ($) {
114     my ($newlevel) = @_; # may be undef (eg from env var)
115     die if $debuglevel;
116     $newlevel //= 0;
117     $newlevel += 0;
118     return unless $newlevel;
119     $debuglevel = $newlevel;
120     enabledebug();
121 }
122     
123 sub printdebug {
124     print DEBUG $debugprefix, @_ or die $! if $debuglevel>0;
125 }
126
127 sub messagequote ($) {
128     local ($_) = @_;
129     s{\\}{\\\\}g;
130     s{\n}{\\n}g;
131     s{\x08}{\\b}g;
132     s{\t}{\\t}g;
133     s{[\000-\037\177]}{ sprintf "\\x%02x", ord $& }ge;
134     $_;
135 }
136
137 sub shellquote {
138     my @out;
139     local $_;
140     defined or confess 'internal error' foreach @_;
141     foreach my $a (@_) {
142         $_ = $a;
143         if (!length || m{[^-=_./:0-9a-z]}i) {
144             s{['\\]}{'\\$&'}g;
145             push @out, "'$_'";
146         } else {
147             push @out, $_;
148         }
149     }
150     return join ' ', @out;
151 }
152
153 sub printcmd {
154     my $fh = shift @_;
155     my $intro = shift @_;
156     print $fh $intro," " or die $!;
157     print $fh shellquote @_ or die $!;
158     print $fh "\n" or die $!;
159 }
160
161 sub debugcmd {
162     my $extraprefix = shift @_;
163     printcmd(\*DEBUG,$debugprefix.$extraprefix,@_) if $debuglevel>0;
164 }
165
166 sub dep14_version_mangle ($) {
167     my ($v) = @_;
168     # DEP-14 patch proposed 2016-11-09  "Version Mangling"
169     $v =~ y/~:/_%/;
170     $v =~ s/\.(?=\.|$|lock$)/.#/g;
171     return $v;
172 }
173
174 sub debiantag_old ($$) { 
175     my ($v,$distro) = @_;
176     return "$distro/". dep14_version_mangle $v;
177 }
178
179 sub debiantag_new ($$) { 
180     my ($v,$distro) = @_;
181     return "archive/$distro/".dep14_version_mangle $v;
182 }
183
184 sub debiantags ($$) {
185     my ($version,$distro) = @_;
186     map { $_->($version, $distro) } (\&debiantag_new, \&debiantag_old);
187 }
188
189 sub server_branch ($) { return "$branchprefix/$_[0]"; }
190 sub server_ref ($) { return "refs/".server_branch($_[0]); }
191
192 sub stat_exists ($) {
193     my ($f) = @_;
194     return 1 if stat $f;
195     return 0 if $!==&ENOENT;
196     die "stat $f: $!";
197 }
198
199 sub _us () {
200     $::us // ($0 =~ m#[^/]*$#, $&);
201 }
202
203 sub fail { 
204     my $s = "@_\n";
205     $s =~ s/\n\n$/\n/;
206     my $prefix = _us().": ";
207     $s =~ s/^/$prefix/gm;
208     die $s;
209 }
210
211 sub ensuredir ($) {
212     my ($dir) = @_; # does not create parents
213     return if mkdir $dir;
214     return if $! == EEXIST;
215     die "mkdir $dir: $!";
216 }
217
218 sub executable_on_path ($) {
219     my ($program) = @_;
220     return 1 if $program =~ m{/};
221     my @path = split /:/, ($ENV{PATH} // "/usr/local/bin:/bin:/usr/bin");
222     foreach my $pe (@path) {
223         my $here = "$pe/$program";
224         return $here if stat_exists $here && -x _;
225     }
226     return undef;
227 }
228
229 our @signames = split / /, $Config{sig_name};
230
231 sub waitstatusmsg () {
232     if (!$?) {
233         return "terminated, reporting successful completion";
234     } elsif (!($? & 255)) {
235         return "failed with error exit status ".WEXITSTATUS($?);
236     } elsif (WIFSIGNALED($?)) {
237         my $signum=WTERMSIG($?);
238         return "died due to fatal signal ".
239             ($signames[$signum] // "number $signum").
240             ($? & 128 ? " (core dumped)" : ""); # POSIX(3pm) has no WCOREDUMP
241     } else {
242         return "failed with unknown wait status ".$?;
243     }
244 }
245
246 sub failedcmd_report_cmd {
247     my $intro = shift @_;
248     $intro //= "failed command";
249     { local ($!); printcmd \*STDERR, _us().": $intro:", @_ or die $!; };
250 }
251
252 sub failedcmd_waitstatus {
253     if ($? < 0) {
254         return "failed to fork/exec: $!";
255     } elsif ($?) {
256         return "subprocess ".waitstatusmsg();
257     } else {
258         return "subprocess produced invalid output";
259     }
260 }
261
262 sub failedcmd {
263     # Expects $!,$? as set by close - see below.
264     # To use with system(), set $?=-1 first.
265     #
266     # Actual behaviour of perl operations:
267     #   success              $!==0       $?==0       close of piped open
268     #   program failed       $!==0       $? >0       close of piped open
269     #   syscall failure      $! >0       $?=-1       close of piped open
270     #   failure              $! >0       unchanged   close of something else
271     #   success              trashed     $?==0       system
272     #   program failed       trashed     $? >0       system
273     #   syscall failure      $! >0       unchanged   system
274     failedcmd_report_cmd undef, @_;
275     fail failedcmd_waitstatus();
276 }
277
278 sub cmdoutput_errok {
279     confess Dumper(\@_)." ?" if grep { !defined } @_;
280     debugcmd "|",@_;
281     open P, "-|", @_ or die "$_[0] $!";
282     my $d;
283     $!=0; $?=0;
284     { local $/ = undef; $d = <P>; }
285     die $! if P->error;
286     if (!close P) { printdebug "=>!$?\n"; return undef; }
287     chomp $d;
288     if ($debuglevel > 0) {
289         $d =~ m/^.*/;
290         my $dd = $&;
291         my $more = (length $' ? '...' : ''); #');
292         $dd =~ s{[^\n -~]|\\}{ sprintf "\\x%02x", ord $& }ge;
293         printdebug "=> \`$dd'",$more,"\n";
294     }
295     return $d;
296 }
297
298 sub cmdoutput {
299     my $d = cmdoutput_errok @_;
300     defined $d or failedcmd @_;
301     return $d;
302 }
303
304 sub link_ltarget ($$) {
305     my ($old,$new) = @_;
306     lstat $old or return undef;
307     if (-l _) {
308         $old = cmdoutput qw(realpath  --), $old;
309     }
310     my $r = link $old, $new;
311     $r = symlink $old, $new if !$r && $!==EXDEV;
312     $r or die "(sym)link $old $new: $!";
313 }
314
315 sub hashfile ($) {
316     my ($fn) = @_;
317     my $h = Digest::SHA->new(256);
318     $h->addfile($fn);
319     return $h->hexdigest();
320 }
321
322 sub git_rev_parse ($) {
323     return cmdoutput qw(git rev-parse), "$_[0]~0";
324 }
325
326 sub git_cat_file ($) {
327     my ($objname) = @_;
328     # => ($type, $data) or ('missing', undef)
329     # in scalar context, just the data
330     our ($gcf_pid, $gcf_i, $gcf_o);
331     if (!$gcf_pid) {
332         my @cmd = qw(git cat-file --batch);
333         debugcmd "GCF|", @cmd;
334         $gcf_pid = open2 $gcf_o, $gcf_i, @cmd or die $!;
335     }
336     printdebug "GCF>| ", $objname, "\n";
337     print $gcf_i $objname, "\n" or die $!;
338     my $x = <$gcf_o>;
339     printdebug "GCF<| ", $x;
340     if ($x =~ m/ (missing)$/) { return ($1, undef); }
341     my ($type, $size) = $x =~ m/^.* (\w+) (\d+)\n/ or die "$objname ?";
342     my $data;
343     (read $gcf_o, $data, $size) == $size or die "$objname $!";
344     $x = <$gcf_o>;
345     $x eq "\n" or die "$objname ($_) $!";
346     return ($type, $data);
347 }
348
349 sub git_for_each_ref ($$;$) {
350     my ($pattern,$func,$gitdir) = @_;
351     # calls $func->($objid,$objtype,$fullrefname,$reftail);
352     # $reftail is RHS of ref after refs/[^/]+/
353     # breaks if $pattern matches any ref `refs/blah' where blah has no `/'
354     # $pattern may be an array ref to mean multiple patterns
355     $pattern = [ $pattern ] unless ref $pattern;
356     my @cmd = (qw(git for-each-ref), @$pattern);
357     if (defined $gitdir) {
358         @cmd = ('sh','-ec','cd "$1"; shift; exec "$@"','x', $gitdir, @cmd);
359     }
360     open GFER, "-|", @cmd or die $!;
361     debugcmd "|", @cmd;
362     while (<GFER>) {
363         chomp or die "$_ ?";
364         printdebug "|> ", $_, "\n";
365         m#^(\w+)\s+(\w+)\s+(refs/[^/]+/(\S+))$# or die "$_ ?";
366         $func->($1,$2,$3,$4);
367     }
368     $!=0; $?=0; close GFER or die "$pattern $? $!";
369 }
370
371 sub git_get_ref ($) {
372     # => '' if no such ref
373     my ($refname) = @_;
374     local $_ = $refname;
375     s{^refs/}{[r]efs/} or die "$refname $_ ?";
376     return cmdoutput qw(git for-each-ref --format=%(objectname)), $_;
377 }
378
379 sub git_for_each_tag_referring ($$) {
380     my ($objreferring, $func) = @_;
381     # calls $func->($tagobjid,$refobjid,$fullrefname,$tagname);
382     printdebug "git_for_each_tag_referring ",
383         ($objreferring // 'UNDEF'),"\n";
384     git_for_each_ref('refs/tags', sub {
385         my ($tagobjid,$objtype,$fullrefname,$tagname) = @_;
386         return unless $objtype eq 'tag';
387         my $refobjid = git_rev_parse $tagobjid;
388         return unless
389             !defined $objreferring # caller wants them all
390             or $tagobjid eq $objreferring
391             or $refobjid eq $objreferring;
392         $func->($tagobjid,$refobjid,$fullrefname,$tagname);
393     });
394 }
395
396 sub is_fast_fwd ($$) {
397     my ($ancestor,$child) = @_;
398     my @cmd = (qw(git merge-base), $ancestor, $child);
399     my $mb = cmdoutput_errok @cmd;
400     if (defined $mb) {
401         return git_rev_parse($mb) eq git_rev_parse($ancestor);
402     } else {
403         $?==256 or failedcmd @cmd;
404         return 0;
405     }
406 }
407
408 1;