]> git.donarmstrong.com Git - debhelper.git/blob - Debian/Debhelper/Dh_Lib.pm
Make it possible to pass perl code to autoscript.
[debhelper.git] / Debian / Debhelper / Dh_Lib.pm
1 #!/usr/bin/perl -w
2 #
3 # Library functions for debhelper programs, perl version.
4 #
5 # Joey Hess, GPL copyright 1997-2008.
6
7 package Debian::Debhelper::Dh_Lib;
8 use strict;
9
10 use Exporter;
11 use vars qw(@ISA @EXPORT %dh);
12 @ISA=qw(Exporter);
13 @EXPORT=qw(&init &doit &complex_doit &verbose_print &error &warning &tmpdir
14             &pkgfile &pkgext &pkgfilename &isnative &autoscript &filearray
15             &filedoublearray &getpackages &basename &dirname &xargs %dh
16             &compat &addsubstvar &delsubstvar &excludefile &package_arch
17             &is_udeb &udeb_filename &debhelper_script_subst &escape_shell
18             &inhibit_log &load_log &write_log &commit_override_log
19             &dpkg_architecture_value &sourcepackage
20             &is_make_jobserver_unavailable &clean_jobserver_makeflags
21             &cross_command &set_buildflags &get_buildoption);
22
23 my $max_compat=10;
24
25 sub init {
26         my %params=@_;
27
28         # Check to see if an option line starts with a dash,
29         # or DH_OPTIONS is set.
30         # If so, we need to pass this off to the resource intensive 
31         # Getopt::Long, which I'd prefer to avoid loading at all if possible.
32         if ((defined $ENV{DH_OPTIONS} && length $ENV{DH_OPTIONS}) ||
33             (defined $ENV{DH_INTERNAL_OPTIONS} && length $ENV{DH_INTERNAL_OPTIONS}) ||
34             grep /^-/, @ARGV) {
35                 eval "use Debian::Debhelper::Dh_Getopt";
36                 error($@) if $@;
37                 Debian::Debhelper::Dh_Getopt::parseopts(%params);
38         }
39
40         # Another way to set excludes.
41         if (exists $ENV{DH_ALWAYS_EXCLUDE} && length $ENV{DH_ALWAYS_EXCLUDE}) {
42                 push @{$dh{EXCLUDE}}, split(":", $ENV{DH_ALWAYS_EXCLUDE});
43         }
44         
45         # Generate EXCLUDE_FIND.
46         if ($dh{EXCLUDE}) {
47                 $dh{EXCLUDE_FIND}='';
48                 foreach (@{$dh{EXCLUDE}}) {
49                         my $x=$_;
50                         $x=escape_shell($x);
51                         $x=~s/\./\\\\./g;
52                         $dh{EXCLUDE_FIND}.="-regex .\\*$x.\\* -or ";
53                 }
54                 $dh{EXCLUDE_FIND}=~s/ -or $//;
55         }
56         
57         # Check to see if DH_VERBOSE environment variable was set, if so,
58         # make sure verbose is on.
59         if (defined $ENV{DH_VERBOSE} && $ENV{DH_VERBOSE} ne "") {
60                 $dh{VERBOSE}=1;
61         }
62
63         # Check to see if DH_NO_ACT environment variable was set, if so, 
64         # make sure no act mode is on.
65         if (defined $ENV{DH_NO_ACT} && $ENV{DH_NO_ACT} ne "") {
66                 $dh{NO_ACT}=1;
67         }
68
69         # Get the name of the main binary package (first one listed in
70         # debian/control). Only if the main package was not set on the
71         # command line.
72         if (! exists $dh{MAINPACKAGE} || ! defined $dh{MAINPACKAGE}) {
73                 my @allpackages=getpackages();
74                 $dh{MAINPACKAGE}=$allpackages[0];
75         }
76
77         # Check if packages to build have been specified, if not, fall back to
78         # the default, building all relevant packages.
79         if (! defined $dh{DOPACKAGES} || ! @{$dh{DOPACKAGES}}) {
80                 push @{$dh{DOPACKAGES}}, getpackages('both');
81         }
82
83         # Check to see if -P was specified. If so, we can only act on a single
84         # package.
85         if ($dh{TMPDIR} && $#{$dh{DOPACKAGES}} > 0) {
86                 error("-P was specified, but multiple packages would be acted on (".join(",",@{$dh{DOPACKAGES}}).").");
87         }
88
89         # Figure out which package is the first one we were instructed to build.
90         # This package gets special treatement: files and directories specified on
91         # the command line may affect it.
92         $dh{FIRSTPACKAGE}=${$dh{DOPACKAGES}}[0];
93
94         # If no error handling function was specified, just propigate
95         # errors out.
96         if (! exists $dh{ERROR_HANDLER} || ! defined $dh{ERROR_HANDLER}) {
97                 $dh{ERROR_HANDLER}='exit \$?';
98         }
99 }
100
101 # Run at exit. Add the command to the log files for the packages it acted
102 # on, if it's exiting successfully.
103 my $write_log=1;
104 sub END {
105         if ($? == 0 && $write_log) {
106                 write_log(basename($0), @{$dh{DOPACKAGES}});
107         }
108 }
109
110 sub logfile {
111         my $package=shift;
112         my $ext=pkgext($package);
113         return "debian/${ext}debhelper.log"
114 }
115
116 sub add_override {
117         my $line=shift;
118         $line="override_$ENV{DH_INTERNAL_OVERRIDE} $line"
119                 if defined $ENV{DH_INTERNAL_OVERRIDE};
120         return $line;
121 }
122
123 sub remove_override {
124         my $line=shift;
125         $line=~s/^\Qoverride_$ENV{DH_INTERNAL_OVERRIDE}\E\s+//
126                 if defined $ENV{DH_INTERNAL_OVERRIDE};
127         return $line;
128 }
129
130 sub load_log {
131         my ($package, $db)=@_;
132
133         my @log;
134         open(LOG, "<", logfile($package)) || return;
135         while (<LOG>) {
136                 chomp;
137                 my $command=remove_override($_);
138                 push @log, $command;
139                 $db->{$package}{$command}=1 if defined $db;
140         }
141         close LOG;
142         return @log;
143 }
144
145 sub write_log {
146         my $cmd=shift;
147         my @packages=@_;
148
149         return if $dh{NO_ACT};
150
151         foreach my $package (@packages) {
152                 my $log=logfile($package);
153                 open(LOG, ">>", $log) || error("failed to write to ${log}: $!");
154                 print LOG add_override($cmd)."\n";
155                 close LOG;
156         }
157 }
158
159 sub commit_override_log {
160         my @packages=@_;
161
162         return if $dh{NO_ACT};
163
164         foreach my $package (@packages) {
165                 my @log=map { remove_override($_) } load_log($package);
166                 my $log=logfile($package);
167                 open(LOG, ">", $log) || error("failed to write to ${log}: $!");
168                 print LOG $_."\n" foreach @log;
169                 close LOG;
170         }
171 }
172
173 sub inhibit_log {
174         $write_log=0;
175 }
176
177 # Pass it an array containing the arguments of a shell command like would
178 # be run by exec(). It turns that into a line like you might enter at the
179 # shell, escaping metacharacters and quoting arguments that contain spaces.
180 sub escape_shell {
181         my @args=@_;
182         my $line="";
183         my @ret;
184         foreach my $word (@args) {
185                 if ($word=~/\s/) {
186                         # Escape only a few things since it will be quoted.
187                         # Note we use double quotes because you cannot
188                         # escape ' in single quotes, while " can be escaped
189                         # in double.
190                         # This does make -V"foo bar" turn into "-Vfoo bar",
191                         # but that will be parsed identically by the shell
192                         # anyway..
193                         $word=~s/([\n`\$"\\])/\\$1/g;
194                         push @ret, "\"$word\"";
195                 }
196                 else {
197                         # This list is from _Unix in a Nutshell_. (except '#')
198                         $word=~s/([\s!"\$()*+#;<>?@\[\]\\`|~])/\\$1/g;
199                         push @ret,$word;
200                 }
201         }
202         return join(' ', @ret);
203 }
204
205 # Run a command, and display the command to stdout if verbose mode is on.
206 # All commands that modifiy files in $TMP should be ran via this 
207 # function.
208 #
209 # Note that this cannot handle complex commands, especially anything
210 # involving redirection. Use complex_doit instead.
211 sub doit {
212         verbose_print(escape_shell(@_));
213
214         if (! $dh{NO_ACT}) {
215                 system(@_) == 0 || _error_exitcode(join(" ", @_));
216         }
217 }
218
219 # Run a command and display the command to stdout if verbose mode is on.
220 # Use doit() if you can, instead of this function, because this function
221 # forks a shell. However, this function can handle more complicated stuff
222 # like redirection.
223 sub complex_doit {
224         verbose_print(join(" ",@_));
225         
226         if (! $dh{NO_ACT}) {
227                 # The join makes system get a scalar so it forks off a shell.
228                 system(join(" ", @_)) == 0 || _error_exitcode(join(" ", @_))
229         }                       
230 }
231
232 sub _error_exitcode {
233         my $command=shift;
234         if ($? == -1) {
235                 error("$command failed to to execute: $!");
236         }
237         elsif ($? & 127) {
238                 error("$command died with signal ".($? & 127));
239         }
240         else {
241                 error("$command returned exit code ".($? >> 8));
242         }
243 }
244
245 # Run a command that may have a huge number of arguments, like xargs does.
246 # Pass in a reference to an array containing the arguments, and then other
247 # parameters that are the command and any parameters that should be passed to
248 # it each time.
249 sub xargs {
250         my $args=shift;
251
252         # The kernel can accept command lines up to 20k worth of characters.
253         my $command_max=20000; # LINUX SPECIFIC!!
254                         # (And obsolete; it's bigger now.)
255                         # I could use POSIX::ARG_MAX, but that would be slow.
256
257         # Figure out length of static portion of command.
258         my $static_length=0;
259         foreach (@_) {
260                 $static_length+=length($_)+1;
261         }
262         
263         my @collect=();
264         my $length=$static_length;
265         foreach (@$args) {
266                 if (length($_) + 1 + $static_length > $command_max) {
267                         error("This command is greater than the maximum command size allowed by the kernel, and cannot be split up further. What on earth are you doing? \"@_ $_\"");
268                 }
269                 $length+=length($_) + 1;
270                 if ($length < $command_max) {
271                         push @collect, $_;
272                 }
273                 else {
274                         doit(@_,@collect) if $#collect > -1;
275                         @collect=($_);
276                         $length=$static_length + length($_) + 1;
277                 }
278         }
279         doit(@_,@collect) if $#collect > -1;
280 }
281
282 # Print something if the verbose flag is on.
283 sub verbose_print {
284         my $message=shift;
285         
286         if ($dh{VERBOSE}) {
287                 print "\t$message\n";
288         }
289 }
290
291 # Output an error message and die (can be caught).
292 sub error {
293         my $message=shift;
294
295         die basename($0).": $message\n";
296 }
297
298 # Output a warning.
299 sub warning {
300         my $message=shift;
301         
302         print STDERR basename($0).": $message\n";
303 }
304
305 # Returns the basename of the argument passed to it.
306 sub basename {
307         my $fn=shift;
308
309         $fn=~s/\/$//g; # ignore trailing slashes
310         $fn=~s:^.*/(.*?)$:$1:;
311         return $fn;
312 }
313
314 # Returns the directory name of the argument passed to it.
315 sub dirname {
316         my $fn=shift;
317         
318         $fn=~s/\/$//g; # ignore trailing slashes
319         $fn=~s:^(.*)/.*?$:$1:;
320         return $fn;
321 }
322
323 # Pass in a number, will return true iff the current compatibility level
324 # is less than or equal to that number.
325 {
326         my $warned_compat=0;
327         my $c;
328
329         sub compat {
330                 my $num=shift;
331                 my $nowarn=shift;
332         
333                 if (! defined $c) {
334                         $c=1;
335                         if (-e 'debian/compat') {
336                                 open (COMPAT_IN, "debian/compat") || error "debian/compat: $!";
337                                 my $l=<COMPAT_IN>;
338                                 close COMPAT_IN;
339                                 if (! defined $l || ! length $l) {
340                                         warning("debian/compat is empty, assuming level $c")
341                                                 unless defined $ENV{DH_COMPAT};
342                                 }
343                                 else {
344                                         chomp $l;
345                                         $c=$l;
346                                 }
347                         }
348                         else {
349                                 warning("No compatibility level specified in debian/compat");
350                                 warning("This package will soon FTBFS; time to fix it!");
351                         }
352
353                         if (defined $ENV{DH_COMPAT}) {
354                                 $c=$ENV{DH_COMPAT};
355                         }
356                 }
357
358                 if ($c <= 4 && ! $warned_compat && ! $nowarn) {
359                         warning("Compatibility levels before 5 are deprecated (level $c in use)");
360                         $warned_compat=1;
361                 }
362         
363                 if ($c > $max_compat) {
364                         error("Sorry, but $max_compat is the highest compatibility level supported by this debhelper.");
365                 }
366
367                 return ($c <= $num);
368         }
369 }
370
371 # Pass it a name of a binary package, it returns the name of the tmp dir to
372 # use, for that package.
373 sub tmpdir {
374         my $package=shift;
375
376         if ($dh{TMPDIR}) {
377                 return $dh{TMPDIR};
378         }
379         elsif (compat(1) && $package eq $dh{MAINPACKAGE}) {
380                 # This is for back-compatibility with the debian/tmp tradition.
381                 return "debian/tmp";
382         }
383         else {
384                 return "debian/$package";
385         }
386 }
387
388 # Pass this the name of a binary package, and the name of the file wanted
389 # for the package, and it will return the actual existing filename to use.
390 #
391 # It tries several filenames:
392 #   * debian/package.filename.buildarch
393 #   * debian/package.filename.buildos
394 #   * debian/package.filename
395 #   * debian/filename (if the package is the main package)
396 # If --name was specified then the files
397 # must have the name after the package name:
398 #   * debian/package.name.filename.buildarch
399 #   * debian/package.name.filename.buildos
400 #   * debian/package.name.filename
401 #   * debian/name.filename (if the package is the main package)
402 sub pkgfile {
403         my $package=shift;
404         my $filename=shift;
405
406         if (defined $dh{NAME}) {
407                 $filename="$dh{NAME}.$filename";
408         }
409         
410         # First, check for files ending in buildarch and buildos.
411         my $match;
412         foreach my $file (glob("debian/$package.$filename.*")) {
413                 next if ! -f $file;
414                 next if $dh{IGNORE} && exists $dh{IGNORE}->{$file};
415                 if ($file eq "debian/$package.$filename.".buildarch()) {
416                         $match=$file;
417                         # buildarch files are used in preference to buildos files.
418                         last;
419                 }
420                 elsif ($file eq "debian/$package.$filename.".buildos()) {
421                         $match=$file;
422                 }
423         }
424         return $match if defined $match;
425
426         my @try=("debian/$package.$filename");
427         if ($package eq $dh{MAINPACKAGE}) {
428                 push @try, "debian/$filename";
429         }
430         
431         foreach my $file (@try) {
432                 if (-f $file &&
433                     (! $dh{IGNORE} || ! exists $dh{IGNORE}->{$file})) {
434                         return $file;
435                 }
436
437         }
438
439         return "";
440
441 }
442
443 # Pass it a name of a binary package, it returns the name to prefix to files
444 # in debian/ for this package.
445 sub pkgext {
446         my $package=shift;
447
448         if (compat(1) and $package eq $dh{MAINPACKAGE}) {
449                 return "";
450         }
451         return "$package.";
452 }
453
454 # Pass it the name of a binary package, it returns the name to install
455 # files by in eg, etc. Normally this is the same, but --name can override
456 # it.
457 sub pkgfilename {
458         my $package=shift;
459
460         if (defined $dh{NAME}) {
461                 return $dh{NAME};
462         }
463         return $package;
464 }
465
466 # Returns 1 if the package is a native debian package, null otherwise.
467 # As a side effect, sets $dh{VERSION} to the version of this package.
468 {
469         # Caches return code so it only needs to run dpkg-parsechangelog once.
470         my %isnative_cache;
471         
472         sub isnative {
473                 my $package=shift;
474
475                 return $isnative_cache{$package} if defined $isnative_cache{$package};
476                 
477                 # Make sure we look at the correct changelog.
478                 my $isnative_changelog=pkgfile($package,"changelog");
479                 if (! $isnative_changelog) {
480                         $isnative_changelog="debian/changelog";
481                 }
482                 # Get the package version.
483                 my $version=`dpkg-parsechangelog -l$isnative_changelog`;
484                 ($dh{VERSION})=$version=~m/Version:\s*(.*)/m;
485                 # Did the changelog parse fail?
486                 if (! defined $dh{VERSION}) {
487                         error("changelog parse failure");
488                 }
489
490                 # Is this a native Debian package?
491                 if ($dh{VERSION}=~m/.*-/) {
492                         return $isnative_cache{$package}=0;
493                 }
494                 else {
495                         return $isnative_cache{$package}=1;
496                 }
497         }
498 }
499
500 # Automatically add a shell script snippet to a debian script.
501 # Only works if the script has #DEBHELPER# in it.
502 #
503 # Parameters:
504 # 1: package
505 # 2: script to add to
506 # 3: filename of snippet
507 # 4: either text: shell-quoted sed to run on the snippet. Ie, 's/#PACKAGE#/$PACKAGE/'
508 #    or a sub to run on each line of the snippet. Ie sub { s/#PACKAGE#/$PACKAGE/ }
509 sub autoscript {
510         my $package=shift;
511         my $script=shift;
512         my $filename=shift;
513         my $sed=shift || "";
514
515         # This is the file we will modify.
516         my $outfile="debian/".pkgext($package)."$script.debhelper";
517
518         # Figure out what shell script snippet to use.
519         my $infile;
520         if (defined($ENV{DH_AUTOSCRIPTDIR}) && 
521             -e "$ENV{DH_AUTOSCRIPTDIR}/$filename") {
522                 $infile="$ENV{DH_AUTOSCRIPTDIR}/$filename";
523         }
524         else {
525                 if (-e "/usr/share/debhelper/autoscripts/$filename") {
526                         $infile="/usr/share/debhelper/autoscripts/$filename";
527                 }
528                 else {
529                         error("/usr/share/debhelper/autoscripts/$filename does not exist");
530                 }
531         }
532
533         if (-e $outfile && ($script eq 'postrm' || $script eq 'prerm')
534            && !compat(5)) {
535                 # Add fragments to top so they run in reverse order when removing.
536                 complex_doit("echo \"# Automatically added by ".basename($0)."\"> $outfile.new");
537                 autoscript_sed($sed, $infile, "$outfile.new");
538                 complex_doit("echo '# End automatically added section' >> $outfile.new");
539                 complex_doit("cat $outfile >> $outfile.new");
540                 complex_doit("mv $outfile.new $outfile");
541         }
542         else {
543                 complex_doit("echo \"# Automatically added by ".basename($0)."\">> $outfile");
544                 autoscript_sed($sed, $infile, $outfile);
545                 complex_doit("echo '# End automatically added section' >> $outfile");
546         }
547 }
548
549 sub autoscript_sed {
550         my $sed = shift;
551         my $infile = shift;
552         my $outfile = shift;
553         if (ref($sed) eq 'CODE') {
554                 open(IN, $infile) or die "$infile: $!";
555                 open(OUT, ">>$outfile") or die "$outfile: $!";
556                 while (<IN>) { $sed->(); print OUT }
557                 close(OUT) or die "$outfile: $!";
558                 close(IN) or die "$infile: $!";
559         }
560         else {
561                 complex_doit("sed \"$sed\" $infile >> $outfile");
562         }
563 }
564
565 # Removes a whole substvar line.
566 sub delsubstvar {
567         my $package=shift;
568         my $substvar=shift;
569
570         my $ext=pkgext($package);
571         my $substvarfile="debian/${ext}substvars";
572
573         if (-e $substvarfile) {
574                 complex_doit("grep -s -v '^${substvar}=' $substvarfile > $substvarfile.new || true");
575                 doit("mv", "$substvarfile.new","$substvarfile");
576         }
577 }
578                                 
579 # Adds a dependency on some package to the specified
580 # substvar in a package's substvar's file.
581 sub addsubstvar {
582         my $package=shift;
583         my $substvar=shift;
584         my $deppackage=shift;
585         my $verinfo=shift;
586         my $remove=shift;
587
588         my $ext=pkgext($package);
589         my $substvarfile="debian/${ext}substvars";
590         my $str=$deppackage;
591         $str.=" ($verinfo)" if defined $verinfo && length $verinfo;
592
593         # Figure out what the line will look like, based on what's there
594         # now, and what we're to add or remove.
595         my $line="";
596         if (-e $substvarfile) {
597                 my %items;
598                 open(SUBSTVARS_IN, "$substvarfile") || error "read $substvarfile: $!";
599                 while (<SUBSTVARS_IN>) {
600                         chomp;
601                         if (/^\Q$substvar\E=(.*)/) {
602                                 %items = map { $_ => 1} split(", ", $1);
603                                 
604                                 last;
605                         }
606                 }
607                 close SUBSTVARS_IN;
608                 if (! $remove) {
609                         $items{$str}=1;
610                 }
611                 else {
612                         delete $items{$str};
613                 }
614                 $line=join(", ", sort keys %items);
615         }
616         elsif (! $remove) {
617                 $line=$str;
618         }
619
620         if (length $line) {
621                  complex_doit("(grep -s -v ${substvar} $substvarfile; echo ".escape_shell("${substvar}=$line").") > $substvarfile.new");
622                  doit("mv", "$substvarfile.new", $substvarfile);
623         }
624         else {
625                 delsubstvar($package,$substvar);
626         }
627 }
628
629 # Reads in the specified file, one line at a time. splits on words, 
630 # and returns an array of arrays of the contents.
631 # If a value is passed in as the second parameter, then glob
632 # expansion is done in the directory specified by the parameter ("." is
633 # frequently a good choice).
634 sub filedoublearray {
635         my $file=shift;
636         my $globdir=shift;
637
638         # executable config files are a v9 thing.
639         my $x=! compat(8) && -x $file;
640         if ($x) {
641                 require Cwd;
642                 my $cmd=Cwd::abs_path($file);
643                 open (DH_FARRAY_IN, "$cmd |") || error("cannot run $file: $!");
644         }
645         else {
646                 open (DH_FARRAY_IN, $file) || error("cannot read $file: $!");
647         }
648
649         my @ret;
650         while (<DH_FARRAY_IN>) {
651                 chomp;
652                 # Only ignore comments and empty lines in v5 mode.
653                 if (! compat(4) && ! $x)  {
654                         next if /^#/ || /^$/;
655                 }
656                 my @line;
657                 # Only do glob expansion in v3 mode.
658                 #
659                 # The tricky bit is that the glob expansion is done
660                 # as if we were in the specified directory, so the
661                 # filenames that come out are relative to it.
662                 if (defined $globdir && ! compat(2) && ! $x) {
663                         foreach (map { glob "$globdir/$_" } split) {
664                                 s#^$globdir/##;
665                                 push @line, $_;
666                         }
667                 }
668                 else {
669                         @line = split;
670                 }
671                 push @ret, [@line];
672         }
673
674         close DH_FARRAY_IN || error("problem reading $file: $!");
675         
676         return @ret;
677 }
678
679 # Reads in the specified file, one word at a time, and returns an array of
680 # the result. Can do globbing as does filedoublearray.
681 sub filearray {
682         return map { @$_ } filedoublearray(@_);
683 }
684
685 # Passed a filename, returns true if -X says that file should be excluded.
686 sub excludefile {
687         my $filename = shift;
688         foreach my $f (@{$dh{EXCLUDE}}) {
689                 return 1 if $filename =~ /\Q$f\E/;
690         }
691         return 0;
692 }
693
694 {
695         my %dpkg_arch_output;
696         sub dpkg_architecture_value {
697                 my $var = shift;
698                 if (! exists($dpkg_arch_output{$var})) {
699                         local $_;
700                         open(PIPE, '-|', 'dpkg-architecture')
701                                 or error("dpkg-architecture failed");
702                         while (<PIPE>) {
703                                 chomp;
704                                 my ($k, $v) = split(/=/, $_, 2);
705                                 $dpkg_arch_output{$k} = $v;
706                         }
707                         close(PIPE);
708                 }
709                 return $dpkg_arch_output{$var};
710         }
711 }
712
713 # Returns the build architecture.
714 sub buildarch {
715         dpkg_architecture_value('DEB_HOST_ARCH');
716 }
717
718 # Returns the build OS.
719 sub buildos {
720         dpkg_architecture_value("DEB_HOST_ARCH_OS");
721 }
722
723 # Passed an arch and a list of arches to match against, returns true if matched
724 {
725         my %knownsame;
726
727         sub samearch {
728                 my $arch=shift;
729                 my @archlist=split(/\s+/,shift);
730         
731                 foreach my $a (@archlist) {
732                         # Avoid expensive dpkg-architecture call to compare
733                         # with a simple architecture name. "linux-any" and
734                         # other architecture wildcards are (currently)
735                         # always hypenated.
736                         if ($a !~ /-/) {
737                                 return 1 if $arch eq $a;
738                         }
739                         elsif (exists $knownsame{$arch}{$a}) {
740                                 return 1 if $knownsame{$arch}{$a};
741                         }
742                         elsif (system("dpkg-architecture", "-a$arch", "-i$a") == 0) {
743                                 return $knownsame{$arch}{$a}=1;
744                         }
745                         else {
746                                 $knownsame{$arch}{$a}=0;
747                         }
748                 }
749         
750                 return 0;
751         }
752 }
753
754 # Returns source package name
755 sub sourcepackage {
756         open (CONTROL, 'debian/control') ||
757             error("cannot read debian/control: $!\n");
758         while (<CONTROL>) {
759                 chomp;
760                 s/\s+$//;
761                 if (/^Source:\s*(.*)/) {
762                         close CONTROL;
763                         return $1;
764                 }
765         }
766
767         close CONTROL;
768         error("could not find Source: line in control file.");
769 }
770
771 # Returns a list of packages in the control file.
772 # Pass "arch" or "indep" to specify arch-dependant (that will be built
773 # for the system's arch) or independant. If nothing is specified,
774 # returns all packages. Also, "both" returns the union of "arch" and "indep"
775 # packages.
776 # As a side effect, populates %package_arches and %package_types with the
777 # types of all packages (not only those returned).
778 my (%package_types, %package_arches);
779 sub getpackages {
780         my $type=shift;
781
782         %package_types=();
783         %package_arches=();
784         
785         $type="" if ! defined $type;
786
787         my $package="";
788         my $arch="";
789         my $package_type;
790         my @list=();
791         my %seen;
792         open (CONTROL, 'debian/control') ||
793                 error("cannot read debian/control: $!\n");
794         while (<CONTROL>) {
795                 chomp;
796                 s/\s+$//;
797                 if (/^Package:\s*(.*)/) {
798                         $package=$1;
799                         # Detect duplicate package names in the same control file.
800                         if (! $seen{$package}) {
801                                 $seen{$package}=1;
802                         }
803                         else {
804                                 error("debian/control has a duplicate entry for $package");
805                         }
806                         $package_type="deb";
807                 }
808                 if (/^Architecture:\s*(.*)/) {
809                         $arch=$1;
810                 }
811                 if (/^(?:X[BC]*-)?Package-Type:\s*(.*)/) {
812                         $package_type=$1;
813                 }
814                 
815                 if (!$_ or eof) { # end of stanza.
816                         if ($package) {
817                                 $package_types{$package}=$package_type;
818                                 $package_arches{$package}=$arch;
819                         }
820
821                         if ($package &&
822                             ((($type eq 'indep' || $type eq 'both') && $arch eq 'all') ||
823                              (($type eq 'arch'  || $type eq 'both') && ($arch eq 'any' ||
824                                              ($arch ne 'all' &&
825                                               samearch(buildarch(), $arch)))) ||
826                              ! $type)) {
827                                 push @list, $package;
828                                 $package="";
829                                 $arch="";
830                         }
831                 }
832         }
833         close CONTROL;
834
835         return @list;
836 }
837
838 # Returns the arch a package will build for.
839 sub package_arch {
840         my $package=shift;
841         
842         if (! exists $package_arches{$package}) {
843                 warning "package $package is not in control info";
844                 return buildarch();
845         }
846         return $package_arches{$package} eq 'all' ? "all" : buildarch();
847 }
848
849 # Return true if a given package is really a udeb.
850 sub is_udeb {
851         my $package=shift;
852         
853         if (! exists $package_types{$package}) {
854                 warning "package $package is not in control info";
855                 return 0;
856         }
857         return $package_types{$package} eq 'udeb';
858 }
859
860 # Generates the filename that is used for a udeb package.
861 sub udeb_filename {
862         my $package=shift;
863         
864         my $filearch=package_arch($package);
865         isnative($package); # side effect
866         my $version=$dh{VERSION};
867         $version=~s/^[0-9]+://; # strip any epoch
868         return "${package}_${version}_$filearch.udeb";
869 }
870
871 # Handles #DEBHELPER# substitution in a script; also can generate a new
872 # script from scratch if none exists but there is a .debhelper file for it.
873 sub debhelper_script_subst {
874         my $package=shift;
875         my $script=shift;
876         
877         my $tmp=tmpdir($package);
878         my $ext=pkgext($package);
879         my $file=pkgfile($package,$script);
880
881         if ($file ne '') {
882                 if (-f "debian/$ext$script.debhelper") {
883                         # Add this into the script, where it has #DEBHELPER#
884                         complex_doit("perl -pe 's~#DEBHELPER#~qx{cat debian/$ext$script.debhelper}~eg' < $file > $tmp/DEBIAN/$script");
885                 }
886                 else {
887                         # Just get rid of any #DEBHELPER# in the script.
888                         complex_doit("sed s/#DEBHELPER#// < $file > $tmp/DEBIAN/$script");
889                 }
890                 doit("chown","0:0","$tmp/DEBIAN/$script");
891                 doit("chmod",755,"$tmp/DEBIAN/$script");
892         }
893         elsif ( -f "debian/$ext$script.debhelper" ) {
894                 complex_doit("printf '#!/bin/sh\nset -e\n' > $tmp/DEBIAN/$script");
895                 complex_doit("cat debian/$ext$script.debhelper >> $tmp/DEBIAN/$script");
896                 doit("chown","0:0","$tmp/DEBIAN/$script");
897                 doit("chmod",755,"$tmp/DEBIAN/$script");
898         }
899 }
900
901 # Checks if make's jobserver is enabled via MAKEFLAGS, but
902 # the FD used to communicate with it is actually not available.
903 sub is_make_jobserver_unavailable {
904         if (exists $ENV{MAKEFLAGS} && 
905             $ENV{MAKEFLAGS} =~ /(?:^|\s)--jobserver-fds=(\d+)/) {
906                 if (!open(my $in, "<&$1")) {
907                         return 1; # unavailable
908                 }
909                 else {
910                         close $in;
911                         return 0; # available
912                 }
913         }
914
915         return; # no jobserver specified
916 }
917
918 # Cleans out jobserver options from MAKEFLAGS.
919 sub clean_jobserver_makeflags {
920         if (exists $ENV{MAKEFLAGS}) {
921                 if ($ENV{MAKEFLAGS} =~ /(?:^|\s)--jobserver-fds=(\d+)/) {
922                         $ENV{MAKEFLAGS} =~ s/(?:^|\s)--jobserver-fds=\S+//g;
923                         $ENV{MAKEFLAGS} =~ s/(?:^|\s)-j\b//g;
924                 }
925                 delete $ENV{MAKEFLAGS} if $ENV{MAKEFLAGS} =~ /^\s*$/;
926         }
927 }
928
929 # If cross-compiling, returns appropriate cross version of command.
930 sub cross_command {
931         my $command=shift;
932         if (dpkg_architecture_value("DEB_BUILD_GNU_TYPE")
933             ne dpkg_architecture_value("DEB_HOST_GNU_TYPE")) {
934                 return dpkg_architecture_value("DEB_HOST_GNU_TYPE")."-$command";
935         }
936         else {
937                 return $command;
938         }
939 }
940
941 # Sets environment variables from dpkg-buildflags. Avoids changing
942 # any existing environment variables.
943 sub set_buildflags {
944         return if $ENV{DH_INTERNAL_BUILDFLAGS} || compat(8);
945         $ENV{DH_INTERNAL_BUILDFLAGS}=1;
946
947         eval "use Dpkg::BuildFlags";
948         if ($@) {
949                 warning "unable to load build flags: $@";
950                 return;
951         }
952
953         my $buildflags = Dpkg::BuildFlags->new();
954         $buildflags->load_config();
955         foreach my $flag ($buildflags->list()) {
956                 next unless $flag =~ /^[A-Z]/; # Skip flags starting with lowercase
957                 if (! exists $ENV{$flag}) {
958                         $ENV{$flag} = $buildflags->get($flag);
959                 }
960         }
961 }
962
963 # Gets a DEB_BUILD_OPTIONS option, if set.
964 sub get_buildoption {
965         my $wanted=shift;
966
967         return undef unless exists $ENV{DEB_BUILD_OPTIONS};
968
969         foreach my $opt (split(/\s+/, $ENV{DEB_BUILD_OPTIONS})) {
970                 # currently parallel= is the only one with a parameter
971                 if ($opt =~ /^parallel=(-?\d+)$/ && $wanted eq 'parallel') {
972                         return $1;
973                 }
974                 elsif ($opt eq $wanted) {
975                         return 1;
976                 }
977         }
978 }
979
980 1