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