chiark / gitweb /
aec5a23980ed0bb72450834df43840dd31aaf7d6
[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 use File::Basename;
34
35 BEGIN {
36     use Exporter   ();
37     our ($VERSION, @ISA, @EXPORT, @EXPORT_OK, %EXPORT_TAGS);
38
39     $VERSION     = 1.00;
40     @ISA         = qw(Exporter);
41     @EXPORT      = qw(setup_sigwarn forkcheck_setup forkcheck_mainprocess
42                       dep14_version_mangle
43                       debiantags debiantag_old debiantag_new
44                       server_branch server_ref
45                       stat_exists link_ltarget
46                       hashfile
47                       fail failmsg ensuredir must_getcwd executable_on_path
48                       waitstatusmsg failedcmd_waitstatus
49                       failedcmd_report_cmd failedcmd
50                       runcmd cmdoutput cmdoutput_errok
51                       git_rev_parse git_cat_file
52                       git_get_ref git_get_symref git_for_each_ref
53                       git_for_each_tag_referring is_fast_fwd
54                       git_check_unmodified
55                       $package_re $component_re $deliberately_re
56                       $distro_re $versiontag_re $series_filename_re
57                       $extra_orig_namepart_re
58                       $git_null_obj
59                       $branchprefix
60                       $ffq_refprefix $gdrlast_refprefix
61                       initdebug enabledebug enabledebuglevel
62                       printdebug debugcmd
63                       $debugprefix *debuglevel *DEBUG
64                       shellquote printcmd messagequote
65                       $negate_harmful_gitattrs
66                       changedir git_slurp_config_src
67                       gdr_ffq_prev_branchinfo
68                       playtree_setup);
69     # implicitly uses $main::us
70     %EXPORT_TAGS = ( policyflags => [qw(NOFFCHECK FRESHREPO NOCOMMITCHECK)],
71                      playground => [qw(record_maindir $maindir $local_git_cfg
72                                        $maindir_gitdir $maindir_gitcommon
73                                        fresh_playground
74                                        ensure_a_playground)]);
75     @EXPORT_OK   = ( @{ $EXPORT_TAGS{policyflags} },
76                      @{ $EXPORT_TAGS{playground} } );
77 }
78
79 our @EXPORT_OK;
80
81 our $package_re = '[0-9a-z][-+.0-9a-z]*';
82 our $component_re = '[0-9a-zA-Z][-+.0-9a-zA-Z]*';
83 our $deliberately_re = "(?:TEST-)?$package_re";
84 our $distro_re = $component_re;
85 our $versiontag_re = qr{[-+.\%_0-9a-zA-Z/]+};
86 our $branchprefix = 'dgit';
87 our $series_filename_re = qr{(?:^|\.)series(?!\n)$}s;
88 our $extra_orig_namepart_re = qr{[-0-9a-z]+};
89 our $git_null_obj = '0' x 40;
90 our $ffq_refprefix = 'ffq-prev';
91 our $gdrlast_refprefix = 'debrebase-last';
92
93 # policy hook exit status bits
94 # see dgit-repos-server head comment for documentation
95 # 1 is reserved in case something fails with `exit 1' and to spot
96 # dynamic loader, runtime, etc., failures, which report 127 or 255
97 sub NOFFCHECK () { return 0x2; }
98 sub FRESHREPO () { return 0x4; }
99 sub NOCOMMITCHECK () { return 0x8; }
100
101 our $debugprefix;
102 our $debuglevel = 0;
103
104 our $negate_harmful_gitattrs =
105     "-text -eol -crlf -ident -filter -working-tree-encoding";
106     # ^ when updating this, alter the regexp in dgit:is_gitattrs_setup
107
108 our $forkcheck_mainprocess;
109
110 sub forkcheck_setup () {
111     $forkcheck_mainprocess = $$;
112 }
113
114 sub forkcheck_mainprocess () {
115     # You must have called forkcheck_setup or setup_sigwarn already
116     getppid != $forkcheck_mainprocess;
117 }
118
119 sub setup_sigwarn () {
120     forkcheck_setup();
121     $SIG{__WARN__} = sub { 
122         confess $_[0] if forkcheck_mainprocess;
123     };
124 }
125
126 sub initdebug ($) { 
127     ($debugprefix) = @_;
128     open DEBUG, ">/dev/null" or die $!;
129 }
130
131 sub enabledebug () {
132     open DEBUG, ">&STDERR" or die $!;
133     DEBUG->autoflush(1);
134     $debuglevel ||= 1;
135 }
136     
137 sub enabledebuglevel ($) {
138     my ($newlevel) = @_; # may be undef (eg from env var)
139     die if $debuglevel;
140     $newlevel //= 0;
141     $newlevel += 0;
142     return unless $newlevel;
143     $debuglevel = $newlevel;
144     enabledebug();
145 }
146     
147 sub printdebug {
148     print DEBUG $debugprefix, @_ or die $! if $debuglevel>0;
149 }
150
151 sub messagequote ($) {
152     local ($_) = @_;
153     s{\\}{\\\\}g;
154     s{\n}{\\n}g;
155     s{\x08}{\\b}g;
156     s{\t}{\\t}g;
157     s{[\000-\037\177]}{ sprintf "\\x%02x", ord $& }ge;
158     $_;
159 }
160
161 sub shellquote {
162     my @out;
163     local $_;
164     defined or confess 'internal error' foreach @_;
165     foreach my $a (@_) {
166         $_ = $a;
167         if (!length || m{[^-=_./:0-9a-z]}i) {
168             s{['\\]}{'\\$&'}g;
169             push @out, "'$_'";
170         } else {
171             push @out, $_;
172         }
173     }
174     return join ' ', @out;
175 }
176
177 sub printcmd {
178     my $fh = shift @_;
179     my $intro = shift @_;
180     print $fh $intro," " or die $!;
181     print $fh shellquote @_ or die $!;
182     print $fh "\n" or die $!;
183 }
184
185 sub debugcmd {
186     my $extraprefix = shift @_;
187     printcmd(\*DEBUG,$debugprefix.$extraprefix,@_) if $debuglevel>0;
188 }
189
190 sub dep14_version_mangle ($) {
191     my ($v) = @_;
192     # DEP-14 patch proposed 2016-11-09  "Version Mangling"
193     $v =~ y/~:/_%/;
194     $v =~ s/\.(?=\.|$|lock$)/.#/g;
195     return $v;
196 }
197
198 sub debiantag_old ($$) { 
199     my ($v,$distro) = @_;
200     return "$distro/". dep14_version_mangle $v;
201 }
202
203 sub debiantag_new ($$) { 
204     my ($v,$distro) = @_;
205     return "archive/$distro/".dep14_version_mangle $v;
206 }
207
208 sub debiantags ($$) {
209     my ($version,$distro) = @_;
210     map { $_->($version, $distro) } (\&debiantag_new, \&debiantag_old);
211 }
212
213 sub server_branch ($) { return "$branchprefix/$_[0]"; }
214 sub server_ref ($) { return "refs/".server_branch($_[0]); }
215
216 sub stat_exists ($) {
217     my ($f) = @_;
218     return 1 if stat $f;
219     return 0 if $!==&ENOENT;
220     die "stat $f: $!";
221 }
222
223 sub _us () {
224     $::us // ($0 =~ m#[^/]*$#, $&);
225 }
226
227 sub failmsg {
228     my $s = "@_\n";
229     $s =~ s/\n\n$/\n/;
230     my $prefix = _us().": ";
231     $s =~ s/^/$prefix/gm;
232     return $s;
233 }
234
235 sub fail {
236     die failmsg @_;
237 }
238
239 sub ensuredir ($) {
240     my ($dir) = @_; # does not create parents
241     return if mkdir $dir;
242     return if $! == EEXIST;
243     die "mkdir $dir: $!";
244 }
245
246 sub must_getcwd () {
247     my $d = getcwd();
248     defined $d or fail "getcwd failed: $!";
249     return $d;
250 }
251
252 sub executable_on_path ($) {
253     my ($program) = @_;
254     return 1 if $program =~ m{/};
255     my @path = split /:/, ($ENV{PATH} // "/usr/local/bin:/bin:/usr/bin");
256     foreach my $pe (@path) {
257         my $here = "$pe/$program";
258         return $here if stat_exists $here && -x _;
259     }
260     return undef;
261 }
262
263 our @signames = split / /, $Config{sig_name};
264
265 sub waitstatusmsg () {
266     if (!$?) {
267         return "terminated, reporting successful completion";
268     } elsif (!($? & 255)) {
269         return "failed with error exit status ".WEXITSTATUS($?);
270     } elsif (WIFSIGNALED($?)) {
271         my $signum=WTERMSIG($?);
272         return "died due to fatal signal ".
273             ($signames[$signum] // "number $signum").
274             ($? & 128 ? " (core dumped)" : ""); # POSIX(3pm) has no WCOREDUMP
275     } else {
276         return "failed with unknown wait status ".$?;
277     }
278 }
279
280 sub failedcmd_report_cmd {
281     my $intro = shift @_;
282     $intro //= "failed command";
283     { local ($!); printcmd \*STDERR, _us().": $intro:", @_ or die $!; };
284 }
285
286 sub failedcmd_waitstatus {
287     if ($? < 0) {
288         return "failed to fork/exec: $!";
289     } elsif ($?) {
290         return "subprocess ".waitstatusmsg();
291     } else {
292         return "subprocess produced invalid output";
293     }
294 }
295
296 sub failedcmd {
297     # Expects $!,$? as set by close - see below.
298     # To use with system(), set $?=-1 first.
299     #
300     # Actual behaviour of perl operations:
301     #   success              $!==0       $?==0       close of piped open
302     #   program failed       $!==0       $? >0       close of piped open
303     #   syscall failure      $! >0       $?=-1       close of piped open
304     #   failure              $! >0       unchanged   close of something else
305     #   success              trashed     $?==0       system
306     #   program failed       trashed     $? >0       system
307     #   syscall failure      $! >0       unchanged   system
308     failedcmd_report_cmd undef, @_;
309     fail failedcmd_waitstatus();
310 }
311
312 sub runcmd {
313     debugcmd "+",@_;
314     $!=0; $?=-1;
315     failedcmd @_ if system @_;
316 }
317
318 sub cmdoutput_errok {
319     confess Dumper(\@_)." ?" if grep { !defined } @_;
320     debugcmd "|",@_;
321     open P, "-|", @_ or die "$_[0] $!";
322     my $d;
323     $!=0; $?=0;
324     { local $/ = undef; $d = <P>; }
325     die $! if P->error;
326     if (!close P) { printdebug "=>!$?\n"; return undef; }
327     chomp $d;
328     if ($debuglevel > 0) {
329         $d =~ m/^.*/;
330         my $dd = $&;
331         my $more = (length $' ? '...' : ''); #');
332         $dd =~ s{[^\n -~]|\\}{ sprintf "\\x%02x", ord $& }ge;
333         printdebug "=> \`$dd'",$more,"\n";
334     }
335     return $d;
336 }
337
338 sub cmdoutput {
339     my $d = cmdoutput_errok @_;
340     defined $d or failedcmd @_;
341     return $d;
342 }
343
344 sub link_ltarget ($$) {
345     my ($old,$new) = @_;
346     lstat $old or return undef;
347     if (-l _) {
348         $old = cmdoutput qw(realpath  --), $old;
349     }
350     my $r = link $old, $new;
351     $r = symlink $old, $new if !$r && $!==EXDEV;
352     $r or die "(sym)link $old $new: $!";
353 }
354
355 sub hashfile ($) {
356     my ($fn) = @_;
357     my $h = Digest::SHA->new(256);
358     $h->addfile($fn);
359     return $h->hexdigest();
360 }
361
362 sub git_rev_parse ($) {
363     return cmdoutput qw(git rev-parse), "$_[0]~0";
364 }
365
366 sub git_cat_file ($;$) {
367     my ($objname, $etype) = @_;
368     # => ($type, $data) or ('missing', undef)
369     # in scalar context, just the data
370     # if $etype defined, dies unless type is $etype or in @$etype
371     our ($gcf_pid, $gcf_i, $gcf_o);
372     my $chk = sub {
373         my ($gtype, $data) = @_;
374         if ($etype) {
375             $etype = [$etype] unless ref $etype;
376             confess "$objname expected @$etype but is $gtype"
377                 unless grep { $gtype eq $_ } @$etype;
378         }
379         return ($gtype, $data);
380     };
381     if (!$gcf_pid) {
382         my @cmd = qw(git cat-file --batch);
383         debugcmd "GCF|", @cmd;
384         $gcf_pid = open2 $gcf_o, $gcf_i, @cmd or die $!;
385     }
386     printdebug "GCF>| ", $objname, "\n";
387     print $gcf_i $objname, "\n" or die $!;
388     my $x = <$gcf_o>;
389     printdebug "GCF<| ", $x;
390     if ($x =~ m/ (missing)$/) { return $chk->($1, undef); }
391     my ($type, $size) = $x =~ m/^.* (\w+) (\d+)\n/ or die "$objname ?";
392     my $data;
393     (read $gcf_o, $data, $size) == $size or die "$objname $!";
394     $x = <$gcf_o>;
395     $x eq "\n" or die "$objname ($_) $!";
396     return $chk->($type, $data);
397 }
398
399 sub git_get_symref (;$) {
400     my ($symref) = @_;  $symref //= 'HEAD';
401     # => undef if not a symref, otherwise refs/...
402     my @cmd = (qw(git symbolic-ref -q HEAD));
403     my $branch = cmdoutput_errok @cmd;
404     if (!defined $branch) {
405         $?==256 or failedcmd @cmd;
406     } else {
407         chomp $branch;
408     }
409     return $branch;
410 }
411
412 sub git_for_each_ref ($$;$) {
413     my ($pattern,$func,$gitdir) = @_;
414     # calls $func->($objid,$objtype,$fullrefname,$reftail);
415     # $reftail is RHS of ref after refs/[^/]+/
416     # breaks if $pattern matches any ref `refs/blah' where blah has no `/'
417     # $pattern may be an array ref to mean multiple patterns
418     $pattern = [ $pattern ] unless ref $pattern;
419     my @cmd = (qw(git for-each-ref), @$pattern);
420     if (defined $gitdir) {
421         @cmd = ('sh','-ec','cd "$1"; shift; exec "$@"','x', $gitdir, @cmd);
422     }
423     open GFER, "-|", @cmd or die $!;
424     debugcmd "|", @cmd;
425     while (<GFER>) {
426         chomp or die "$_ ?";
427         printdebug "|> ", $_, "\n";
428         m#^(\w+)\s+(\w+)\s+(refs/[^/]+/(\S+))$# or die "$_ ?";
429         $func->($1,$2,$3,$4);
430     }
431     $!=0; $?=0; close GFER or die "$pattern $? $!";
432 }
433
434 sub git_get_ref ($) {
435     # => '' if no such ref
436     my ($refname) = @_;
437     local $_ = $refname;
438     s{^refs/}{[r]efs/} or die "$refname $_ ?";
439     return cmdoutput qw(git for-each-ref --format=%(objectname)), $_;
440 }
441
442 sub git_for_each_tag_referring ($$) {
443     my ($objreferring, $func) = @_;
444     # calls $func->($tagobjid,$refobjid,$fullrefname,$tagname);
445     printdebug "git_for_each_tag_referring ",
446         ($objreferring // 'UNDEF'),"\n";
447     git_for_each_ref('refs/tags', sub {
448         my ($tagobjid,$objtype,$fullrefname,$tagname) = @_;
449         return unless $objtype eq 'tag';
450         my $refobjid = git_rev_parse $tagobjid;
451         return unless
452             !defined $objreferring # caller wants them all
453             or $tagobjid eq $objreferring
454             or $refobjid eq $objreferring;
455         $func->($tagobjid,$refobjid,$fullrefname,$tagname);
456     });
457 }
458
459 sub git_check_unmodified () {
460     foreach my $cached (qw(0 1)) {
461         my @cmd = qw(git diff --quiet);
462         push @cmd, qw(--cached) if $cached;
463         push @cmd, qw(HEAD);
464         debugcmd "+",@cmd;
465         $!=0; $?=-1; system @cmd;
466         return if !$?;
467         if ($?==256) {
468             fail
469                 $cached
470                 ? "git index contains changes (does not match HEAD)"
471                 : "working tree is dirty (does not match HEAD)";
472         } else {
473             failedcmd @cmd;
474         }
475     }
476 }
477
478 sub is_fast_fwd ($$) {
479     my ($ancestor,$child) = @_;
480     my @cmd = (qw(git merge-base), $ancestor, $child);
481     my $mb = cmdoutput_errok @cmd;
482     if (defined $mb) {
483         return git_rev_parse($mb) eq git_rev_parse($ancestor);
484     } else {
485         $?==256 or failedcmd @cmd;
486         return 0;
487     }
488 }
489
490 sub changedir ($) {
491     my ($newdir) = @_;
492     printdebug "CD $newdir\n";
493     chdir $newdir or confess "chdir: $newdir: $!";
494 }
495
496 sub git_slurp_config_src ($) {
497     my ($src) = @_;
498     # returns $r such that $r->{KEY}[] = VALUE
499     my @cmd = (qw(git config -z --get-regexp), "--$src", qw(.*));
500     debugcmd "|",@cmd;
501
502     local ($debuglevel) = $debuglevel-2;
503     local $/="\0";
504
505     my $r = { };
506     open GITS, "-|", @cmd or die $!;
507     while (<GITS>) {
508         chomp or die;
509         printdebug "=> ", (messagequote $_), "\n";
510         m/\n/ or die "$_ ?";
511         push @{ $r->{$`} }, $'; #';
512     }
513     $!=0; $?=0;
514     close GITS
515         or ($!==0 && $?==256)
516         or failedcmd @cmd;
517     return $r;
518 }
519
520 sub gdr_ffq_prev_branchinfo ($) {
521     my ($symref) = @_;
522     # => ('status', "message", [$symref, $ffq_prev, $gdrlast])
523     # 'status' may be
524     #    branch         message is undef
525     #    weird-symref   } no $symref,
526     #    notbranch      }  no $ffq_prev
527     return ('detached', 'detached HEAD') unless defined $symref;
528     return ('weird-symref', 'HEAD symref is not to refs/')
529         unless $symref =~ m{^refs/};
530     my $ffq_prev = "refs/$ffq_refprefix/$'";
531     my $gdrlast = "refs/$gdrlast_refprefix/$'";
532     printdebug "ffq_prev_branchinfo branch current $symref\n";
533     return ('branch', undef, $symref, $ffq_prev, $gdrlast);
534 }
535
536 # ========== playground handling ==========
537
538 # terminology:
539 #
540 #   $maindir      user's git working tree
541 #   playground    area in .git/ where we can make files, unpack, etc. etc.
542 #   playtree      git working tree sharing object store with the user's
543 #                 inside playground, or identical to it
544 #
545 # other globals
546 #
547 #   $local_git_cfg    hash of arrays of values: git config from $maindir
548 #
549 # expected calling pattern
550 #
551 #  firstly
552 #
553 #    [record_maindir]
554 #      must be run in directory containing .git
555 #      assigns to $maindir if not already set
556 #      also calls git_slurp_config_src to record git config
557 #        in $local_git_cfg, unless it's already set
558 #
559 #    fresh_playground SUBDIR_PATH_COMPONENTS
560 #      e.g fresh_playground 'dgit/unpack' ('.git/' is implied)
561 #      default SUBDIR_PATH_COMPONENTS is playground_subdir
562 #      calls record_maindir
563 #      sets up a new playground (destroying any old one)
564 #      returns playground pathname
565 #      caller may call multiple times with different subdir paths
566 #       createing different playgrounds
567 #
568 #    ensure_a_playground SUBDIR_PATH_COMPONENTS
569 #      like fresh_playground except:
570 #      merely ensures the directory exists; does not delete an existing one
571 #
572 #  then can use
573 #
574 #    changedir playground
575 #    changedir $maindir
576 #
577 #    playtree_setup $local_git_cfg
578 #            # ^ call in some (perhaps trivial) subdir of playground
579 #
580 #    rmtree playground
581
582 # ----- maindir -----
583
584 # these three all go together
585 our $maindir;
586 our $maindir_gitdir;
587 our $maindir_gitcommon;
588
589 our $local_git_cfg;
590
591 sub record_maindir () {
592     if (!defined $maindir) {
593         $maindir = must_getcwd();
594         if (!stat "$maindir/.git") {
595             fail "cannot stat $maindir/.git: $!";
596         }
597         if (-d _) {
598             # we fall back to this in case we have a pre-worktree
599             # git, which may not know git rev-parse --git-common-dir
600             $maindir_gitdir    = "$maindir/.git";
601             $maindir_gitcommon = "$maindir/.git";
602         } else {
603             $maindir_gitdir    = cmdoutput qw(git rev-parse --git-dir);
604             $maindir_gitcommon = cmdoutput qw(git rev-parse --git-common-dir);
605         }
606     }
607     $local_git_cfg //= git_slurp_config_src 'local';
608 }
609
610 # ----- playgrounds -----
611
612 sub ensure_a_playground_parent ($) {
613     my ($spc) = @_;
614     record_maindir();
615     $spc = "$maindir_gitdir/$spc";
616     my $parent = dirname $spc;
617     mkdir $parent or $!==EEXIST
618         or fail "failed to mkdir playground parent $parent: $!";
619     return $spc;
620 }    
621
622 sub ensure_a_playground ($) {
623     my ($spc) = @_;
624     $spc = ensure_a_playground_parent $spc;
625     mkdir $spc or $!==EEXIST or fail "failed to mkdir a playground $spc: $!";
626     return $spc;
627 }    
628
629 sub fresh_playground ($) {
630     my ($spc) = @_;
631     $spc = ensure_a_playground_parent $spc;
632     rmtree $spc;
633     mkdir $spc or fail "failed to mkdir the playground $spc: $!";
634     return $spc;
635 }
636
637 # ----- playtrees -----
638
639 sub playtree_setup (;$) {
640     my ($t_local_git_cfg) = @_;
641     $t_local_git_cfg //= $local_git_cfg;
642     # for use in the playtree
643     # $maindir must be set, eg by calling record_maindir or fresh_playground
644     runcmd qw(git init -q);
645     runcmd qw(git config gc.auto 0);
646     foreach my $copy (qw(user.email user.name user.useConfigOnly
647                          core.sharedRepository
648                          core.compression core.looseCompression
649                          core.bigFileThreshold core.fsyncObjectFiles)) {
650         my $v = $t_local_git_cfg->{$copy};
651         next unless $v;
652         runcmd qw(git config), $copy, $_ foreach @$v;
653     }
654     # this is confusing: we have
655     #   .                   playtree, not a worktree, has .git/, our cwd
656     #   $maindir            might be a worktree so
657     #   $maindir_gitdir     contains our main working "dgit", HEAD, etc.
658     #   $maindir_gitcommon  the shared stuff, including .objects
659     rmtree('.git/objects');
660     symlink "$maindir_gitcommon/objects",'.git/objects' or die $!;
661     ensuredir '.git/info';
662     open GA, "> .git/info/attributes" or die $!;
663     print GA "* $negate_harmful_gitattrs\n" or die $!;
664     close GA or die $!;
665 }
666
667 1;