3 # Library functions for debhelper programs, perl version.
5 # Joey Hess, GPL copyright 1997-2000.
7 package Debian::Debhelper::Dh_Lib;
11 use vars qw(@ISA @EXPORT %dh);
13 @EXPORT=qw(&init &doit &complex_doit &verbose_print &error &warning &tmpdir
14 &pkgfile &pkgext &isnative &autoscript &filearray &filedoublearray
15 &GetPackages &basename &dirname &xargs %dh &compat &addsubstvar
16 &delsubstvar &excludefile);
21 # If DH_OPTIONS is set, prepend it @ARGV.
22 if (defined($ENV{DH_OPTIONS})) {
23 # Ignore leading/trailing whitespace.
24 $ENV{DH_OPTIONS}=~s/^\s+//;
25 $ENV{DH_OPTIONS}=~s/\s+$//;
26 unshift @ARGV,split(/\s+/,$ENV{DH_OPTIONS});
29 # Check to see if an argument on the command line starts with a dash.
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.
34 foreach $arg (@ARGV) {
41 eval "use Debian::Debhelper::Dh_Getopt";
43 %dh=Debian::Debhelper::Dh_Getopt::parseopts();
46 # Another way to set excludes.
47 if (exists $ENV{DH_ALWAYS_EXCLUDE} && length $ENV{DH_ALWAYS_EXCLUDE}) {
48 push @{$dh{EXCLUDE}}, $ENV{DH_ALWAYS_EXCLUDE};
51 # Generate EXCLUDE_FIND.
54 foreach (@{$dh{EXCLUDE}}) {
58 $dh{EXCLUDE_FIND}.="-regex .*$x.* -or ";
60 $dh{EXCLUDE_FIND}=~s/ -or $//;
63 # Check to see if DH_VERBOSE environment variable was set, if so,
64 # make sure verbose is on.
65 if (defined $ENV{DH_VERBOSE} && $ENV{DH_VERBOSE} ne "") {
69 # Check to see if DH_NO_ACT environment variable was set, if so,
70 # make sure no act mode is on.
71 if (defined $ENV{DH_NO_ACT} && $ENV{DH_NO_ACT} ne "") {
75 my @allpackages=GetPackages();
76 # Get the name of the main binary package (first one listed in
77 # debian/control). Only if the main package was not set on the
79 if (! exists $dh{MAINPACKAGE} || ! defined $dh{MAINPACKAGE}) {
80 $dh{MAINPACKAGE}=$allpackages[0];
83 # Check if packages to build have been specified, if not, fall back to
84 # the default, doing them all.
85 if (! defined $dh{DOPACKAGES} || ! @{$dh{DOPACKAGES}}) {
86 if ($dh{DOINDEP} || $dh{DOARCH} || $dh{DOSAME}) {
87 error("You asked that all arch in(dep) packages be built, but there are none of that type.");
89 push @{$dh{DOPACKAGES}},@allpackages;
92 # Check to see if -P was specified. If so, we can only act on a single
94 if ($dh{TMPDIR} && $#{$dh{DOPACKAGES}} > 0) {
95 error("-P was specified, but multiple packages would be acted on (".join(",",@{$dh{DOPACKAGES}}).").");
98 # Figure out which package is the first one we were instructed to build.
99 # This package gets special treatement: files and directories specified on
100 # the command line may affect it.
101 $dh{FIRSTPACKAGE}=${$dh{DOPACKAGES}}[0];
104 # Pass it an array containing the arguments of a shell command like would
105 # be run by exec(). It turns that into a line like you might enter at the
106 # shell, escaping metacharacters and quoting arguments that contain spaces.
111 foreach my $word (@args) {
113 # Escape only a few things since it will be quoted.
114 # Note we use double quotes because you cannot
115 # escape ' in single quotes, while " can be escaped
117 # This does make -V"foo bar" turn into "-Vfoo bar",
118 # but that will be parsed identically by the shell
120 $word=~s/([\n`\$"\\])/\$1/g;
121 push @ret, "\"$word\"";
124 # This list is from _Unix in a Nutshell_. (except '#')
125 $word=~s/([\s!"\$()*+#;<>?@\[\]\\`|~])/\\$1/g;
129 return join(' ', @ret);
132 # Run a command, and display the command to stdout if verbose mode is on.
133 # All commands that modifiy files in $TMP should be ran via this
136 # Note that this cannot handle complex commands, especially anything
137 # involving redirection. Use complex_doit instead.
139 verbose_print(escape_shell(@_));
143 $ret == 0 || error("command returned error code $ret");
147 # Run a command and display the command to stdout if verbose mode is on.
148 # Use doit() if you can, instead of this function, because this function
149 # forks a shell. However, this function can handle more complicated stuff
152 verbose_print(join(" ",@_));
155 # The join makes system get a scalar so it forks off a shell.
156 system(join(" ",@_)) == 0
157 || error("command returned error code");
161 # Run a command that may have a huge number of arguments, like xargs does.
162 # Pass in a reference to an array containing the arguments, and then other
163 # parameters that are the command and any parameters that should be passed to
168 # The kernel can accept command lines up to 20k worth of characters.
169 my $command_max=20000; # LINUX SPECIFIC!!
170 # I could use POSIX::ARG_MAX, but that would be slow.
172 # Figure out length of static portion of command.
175 $static_length+=length($_)+1;
179 my $length=$static_length;
181 if (length($_) + 1 + $static_length > $command_max) {
182 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? \"@_ $_\"");
184 $length+=length($_) + 1;
185 if ($length < $command_max) {
189 doit(@_,@collect) if $#collect > -1;
191 $length=$static_length + length($_) + 1;
194 doit(@_,@collect) if $#collect > -1;
197 # Print something if the verbose flag is on.
202 print "\t$message\n";
206 # Output an error message and exit.
218 print STDERR basename($0).": $message\n";
221 # Returns the basename of the argument passed to it.
225 $fn=~s/\/$//g; # ignore trailing slashes
226 $fn=~s:^.*/(.*?)$:$1:;
230 # Returns the directory name of the argument passed to it.
234 $fn=~s/\/$//g; # ignore trailing slashes
235 $fn=~s:^(.*)/.*?$:$1:;
239 # Pass in a number, will return true iff the current compatibility level
240 # is less than or equal to that number.
245 if (defined $ENV{DH_COMPAT}) {
248 elsif (-e 'debian/compat') {
250 open (COMPAT_IN, "debian/compat") || die "debian/compat: $!";
255 if ($c > $max_compat) {
256 error("Sorry, but $max_compat is the highest compatibility level of debhelper currently supported.");
262 # Pass it a name of a binary package, it returns the name of the tmp dir to
263 # use, for that package.
270 elsif (compat(1) && $package eq $dh{MAINPACKAGE}) {
271 # This is for back-compatibility with the debian/tmp tradition.
275 return "debian/$package";
279 # Pass this the name of a binary package, and the name of the file wanted
280 # for the package, and it will return the actual existing filename to use.
282 # It tries several filenames:
283 # * debian/package.filename.buildarch
284 # * debian/package.filename
285 # * debian/file (if the package is the main package)
290 if (-f "debian/$package.$filename.".buildarch()) {
291 return "debian/$package.$filename.".buildarch();
293 elsif (-f "debian/$package.$filename") {
294 return "debian/$package.$filename";
296 elsif ($package eq $dh{MAINPACKAGE} && -f "debian/$filename") {
297 return "debian/$filename";
304 # Pass it a name of a binary package, it returns the name to prefix to files
305 # in debian for this package.
309 if (compat(1) and $package eq $dh{MAINPACKAGE}) {
315 # Returns 1 if the package is a native debian package, null otherwise.
316 # As a side effect, sets $dh{VERSION} to the version of this package.
318 # Caches return code so it only needs to run dpkg-parsechangelog once.
324 return $isnative_cache{$package} if defined $isnative_cache{$package};
326 # Make sure we look at the correct changelog.
327 my $isnative_changelog=pkgfile($package,"changelog");
328 if (! $isnative_changelog) {
329 $isnative_changelog="debian/changelog";
331 # Get the package version.
332 my $version=`dpkg-parsechangelog -l$isnative_changelog`;
333 ($dh{VERSION})=$version=~m/Version:\s*(.*)/m;
334 # Did the changelog parse fail?
335 if (! defined $dh{VERSION}) {
336 error("changelog parse failure");
339 # Is this a native Debian package?
340 if ($dh{VERSION}=~m/.*-/) {
341 return $isnative_cache{$package}=0;
344 return $isnative_cache{$package}=1;
349 # Automatically add a shell script snippet to a debian script.
350 # Only works if the script has #DEBHELPER# in it.
354 # 2: script to add to
355 # 3: filename of snippet
356 # 4: sed to run on the snippet. Ie, s/#PACKAGE#/$PACKAGE/
363 # This is the file we will append to.
364 my $outfile="debian/".pkgext($package)."$script.debhelper";
366 # Figure out what shell script snippet to use.
368 if (defined($ENV{DH_AUTOSCRIPTDIR}) &&
369 -e "$ENV{DH_AUTOSCRIPTDIR}/$filename") {
370 $infile="$ENV{DH_AUTOSCRIPTDIR}/$filename";
373 if (-e "/usr/share/debhelper/autoscripts/$filename") {
374 $infile="/usr/share/debhelper/autoscripts/$filename";
377 error("/usr/share/debhelper/autoscripts/$filename does not exist");
381 complex_doit("echo \"# Automatically added by ".basename($0)."\">> $outfile");
382 complex_doit("sed \"$sed\" $infile >> $outfile");
383 complex_doit("echo '# End automatically added section' >> $outfile");
386 # Removes a whole substvar line.
391 my $ext=pkgext($package);
392 my $substvarfile="debian/${ext}substvars";
394 if (-e $substvarfile) {
395 complex_doit("grep -v '^${substvar}=' $substvarfile > $substvarfile.new || true");
396 doit("mv", "$substvarfile.new","$substvarfile");
400 # Adds a dependency on some package to the specified
401 # substvar in a package's substvar's file.
405 my $deppackage=shift;
409 my $ext=pkgext($package);
410 my $substvarfile="debian/${ext}substvars";
412 $str.=" ($verinfo)" if defined $verinfo && length $verinfo;
414 # Figure out what the line will look like, based on what's there
415 # now, and what we're to add or remove.
417 if (-e $substvarfile) {
419 open(SUBSTVARS_IN, "$substvarfile") || die "read $substvarfile: $!";
420 while (<SUBSTVARS_IN>) {
422 if (/^\Q$substvar\E=(.*)/) {
423 %items = map { $_ => 1} split(", ", $1);
435 $line=join(", ", keys %items);
442 complex_doit("(grep -v ${substvar} $substvarfile 2>/dev/null; echo '${substvar}=$line') > $substvarfile.new");
443 doit("mv", "$substvarfile.new", $substvarfile);
447 # Reads in the specified file, one line at a time. splits on words,
448 # and returns an array of arrays of the contents.
449 # If a value is passed in as the second parameter, then glob
450 # expansion is done in the directory specified by the parameter ("." is
451 # frequently a good choice).
452 sub filedoublearray {
457 open (DH_FARRAY_IN, $file) || error("cannot read $file: $1");
458 while (<DH_FARRAY_IN>) {
460 # Only do glob expansion in v3 mode.
462 # The tricky bit is that the glob expansion is done
463 # as if we were in the specified directory, so the
464 # filenames that come out are relative to it.
465 if (defined $globdir && ! compat(2)) {
466 for (map { glob "$globdir/$_" } split) {
481 # Reads in the specified file, one word at a time, and returns an array of
482 # the result. Can do globbing as does filedoublearray.
484 return map { @$_ } filedoublearray(@_);
487 # Passed a filename, returns true if -X says that file should be excluded.
489 my $filename = shift;
490 foreach my $f (@{$dh{EXCLUDE}}) {
491 return 1 if $filename =~ /\Q$f\E/;
496 # Returns the build architecture. (Memoized)
501 return $arch if defined $arch;
503 $arch=`dpkg --print-architecture` || error($!);
509 # Returns a list of packages in the control file.
510 # Must pass "arch" or "indep" or "same" to specify arch-dependant or
511 # -independant or same arch packages. If nothing is specified, returns all
516 $type="" if ! defined $type;
518 # Look up the build arch if we need to.
520 if ($type eq 'same') {
521 $buildarch=buildarch();
528 open (CONTROL, 'debian/control') ||
529 error("cannot read debian/control: $!\n");
533 if (/^Package:\s*(.*)/) {
535 # Detect duplicate package names in the same control file.
536 if (! $seen{$package}) {
540 error("debian/control has a duplicate entry for $package");
543 if (/^Architecture:\s*(.*)/) {
547 if (!$_ or eof) { # end of stanza.
549 (($type eq 'indep' && $arch eq 'all') ||
550 ($type eq 'arch' && $arch ne 'all') ||
551 ($type eq 'same' && ($arch eq 'any' || $arch =~ /\b$buildarch\b/)) ||
553 push @list, $package;