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