]> git.donarmstrong.com Git - debhelper.git/blob - Debian/Debhelper/Dh_Lib.pm
r509: * dh_perl: don't gripe if there is no substvar file. Closes: #133140
[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-2000.
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 &isnative &autoscript &filearray &GetPackages
15             &basename &dirname &xargs %dh &compat &addsubstvar &delsubstvar);
16
17 my $max_compat=4;
18
19 sub init {
20         # If DH_OPTIONS is set, prepend it @ARGV.
21         if (defined($ENV{DH_OPTIONS})) {
22                 # Ignore leading/trailing whitespace.
23                 $ENV{DH_OPTIONS}=~s/^\s+//;
24                 $ENV{DH_OPTIONS}=~s/\s+$//;
25                 unshift @ARGV,split(/\s+/,$ENV{DH_OPTIONS});
26         }
27
28         # Check to see if an argument on the command line starts with a dash.
29         # if so, we need to pass this off to the resource intensive 
30         # Getopt::Long, which I'd prefer to avoid loading at all if possible.
31         my $parseopt=undef;
32         my $arg;
33         foreach $arg (@ARGV) {
34                 if ($arg=~m/^-/) {
35                         $parseopt=1;
36                         last;
37                 }       
38         }
39         if ($parseopt) {
40                 eval "use Debian::Debhelper::Dh_Getopt";
41                 error($!) if $@;
42                 %dh=Debian::Debhelper::Dh_Getopt::parseopts();
43         }
44
45         # Check to see if DH_VERBOSE environment variable was set, if so,
46         # make sure verbose is on.
47         if (defined $ENV{DH_VERBOSE} && $ENV{DH_VERBOSE} ne "") {
48                 $dh{VERBOSE}=1;
49         }
50
51         # Check to see if DH_NO_ACT environment variable was set, if so, 
52         # make sure no act mode is on.
53         if (defined $ENV{DH_NO_ACT} && $ENV{DH_NO_ACT} ne "") {
54                 $dh{NO_ACT}=1;
55         }
56
57         # Get the name of the main binary package (first one listed in
58         # debian/control).
59         my @allpackages=GetPackages();
60         $dh{MAINPACKAGE}=$allpackages[0];
61
62         # Check if packages to build have been specified, if not, fall back to
63         # the default, doing them all.
64         if (! defined $dh{DOPACKAGES} || ! @{$dh{DOPACKAGES}}) {
65                 if ($dh{DOINDEP} || $dh{DOARCH} || $dh{DOSAME}) {
66                         error("You asked that all arch in(dep) packages be built, but there are none of that type.");
67                 }
68                 push @{$dh{DOPACKAGES}},@allpackages;
69         }
70
71         # Check to see if -P was specified. If so, we can only act on a single
72         # package.
73         if ($dh{TMPDIR} && $#{$dh{DOPACKAGES}} > 0) {
74                 error("-P was specified, but multiple packages would be acted on (".join(",",@{$dh{DOPACKAGES}}).").");
75         }
76
77         # Figure out which package is the first one we were instructed to build.
78         # This package gets special treatement: files and directories specified on
79         # the command line may affect it.
80         $dh{FIRSTPACKAGE}=${$dh{DOPACKAGES}}[0];
81 }
82
83 # Pass it an array containing the arguments of a shell command like would
84 # be run by exec(). It turns that into a line like you might enter at the
85 # shell, escaping metacharacters and quoting qrguments that contain spaces.
86 sub escape_shell {
87         my @args=@_;
88         my $line="";
89         my @ret;
90         foreach my $word (@args) {
91                 if ($word=~/\s/) {
92                         # Escape only a few things since it will be quoted.
93                         # Note we use double quotes because you cannot
94                         # escape ' in qingle quotes, while " can be escaped
95                         # in double.
96                         # This does make -V"foo bar" turn into "-Vfoo bar",
97                         # but that will be parsed identically by the shell
98                         # anyway..
99                         $word=~s/([\n`\$"\\])/\$1/g;
100                         push @ret, "\"$word\"";
101                 }
102                 else {
103                         # This list is from _Unix in a Nutshell_. (except '#')
104                         $word=~s/([\s!"\$()*+#;<>?@\[\]\\`|~])/\\$1/g;
105                         push @ret,$word;
106                 }
107         }
108         return join(' ', @ret);
109 }
110
111 # Run a command, and display the command to stdout if verbose mode is on.
112 # All commands that modifiy files in $TMP should be ran via this 
113 # function.
114 #
115 # Note that this cannot handle complex commands, especially anything
116 # involving redirection. Use complex_doit instead.
117 sub doit {
118         verbose_print(escape_shell(@_));
119
120         if (! $dh{NO_ACT}) {
121                 system(@_) == 0 || error("command returned error code");
122         }
123 }
124
125 # Run a command and display the command to stdout if verbose mode is on.
126 # Use doit() if you can, instead of this function, because this function
127 # forks a shell. However, this function can handle more complicated stuff
128 # like redirection.
129 sub complex_doit {
130         verbose_print(join(" ",@_));
131         
132         if (! $dh{NO_ACT}) {
133                 # The join makes system get a scalar so it forks off a shell.
134                 system(join(" ",@_)) == 0
135                         || error("command returned error code");
136         }                       
137 }
138
139 # Run a command that may have a huge number of arguments, like xargs does.
140 # Pass in a reference to an array containing the arguments, and then other
141 # parameters that are the command and any parameters that should be passed to
142 # it each time.
143 sub xargs {
144         my $args=shift;
145
146         # The kernel can accept command lines up to 20k worth of characters.
147         my $command_max=20000; # LINUX SPECIFIC!!
148                         # I could use POSIX::ARG_MAX, but that would be slow.
149
150         # Figure out length of static portion of command.
151         my $static_length=0;
152         foreach (@_) {
153                 $static_length+=length($_)+1;
154         }
155         
156         my @collect=();
157         my $length=$static_length;
158         foreach (@$args) {
159                 if (length($_) + 1 + $static_length > $command_max) {
160                         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? \"@_ $_\"");
161                 }
162                 $length+=length($_) + 1;
163                 if ($length < $command_max) {
164                         push @collect, $_;
165                 }
166                 else {
167                         doit(@_,@collect) if $#collect > -1;
168                         @collect=($_);
169                         $length=$static_length + length($_) + 1;
170                 }
171         }
172         doit(@_,@collect) if $#collect > -1;
173 }
174
175 # Print something if the verbose flag is on.
176 sub verbose_print {
177         my $message=shift;
178         
179         if ($dh{VERBOSE}) {
180                 print "\t$message\n";
181         }
182 }
183
184 # Output an error message and exit.
185 sub error {
186         my $message=shift;
187
188         warning($message);
189         exit 1;
190 }
191
192 # Output a warning.
193 sub warning {
194         my $message=shift;
195         
196         print STDERR basename($0).": $message\n";
197 }
198
199 # Returns the basename of the argument passed to it.
200 sub basename {
201         my $fn=shift;
202         
203         $fn=~s:^.*/(.*?)$:$1:;
204         return $fn;
205 }
206
207 # Returns the directory name of the argument passed to it.
208 sub dirname {
209         my $fn=shift;
210         
211         $fn=~s:^(.*)/.*?$:$1:;
212         return $fn;
213 }
214
215 # Pass in a number, will return true iff the current compatibility level
216 # is less than or equal to that number.
217 sub compat {
218         my $num=shift;
219         
220         my $c=1;
221         if (defined $ENV{DH_COMPAT}) {
222                 $c=$ENV{DH_COMPAT};
223         }
224         elsif (-e 'debian/compat') {
225                 # Try the file..
226                 open (COMPAT_IN, "debian/compat") || die "debian/compat: $!";
227                 $c=<COMPAT_IN>;
228                 chomp $c;
229         }
230
231         if ($c > $max_compat) {
232                 error("Sorry, but $max_compat is the highest compatibility level of debhelper currently supported.");
233         }
234
235         return ($c <= $num);
236 }
237
238 # Pass it a name of a binary package, it returns the name of the tmp dir to
239 # use, for that package.
240 sub tmpdir {
241         my $package=shift;
242
243         if ($dh{TMPDIR}) {
244                 return $dh{TMPDIR};
245         }
246         elsif (compat(1) && $package eq $dh{MAINPACKAGE}) {
247                 # This is for back-compatibility with the debian/tmp tradition.
248                 return "debian/tmp";
249         }
250         else {
251                 return "debian/$package";
252         }
253 }
254
255 # Pass this the name of a binary package, and the name of the file wanted
256 # for the package, and it will return the actual existing filename to use.
257 #
258 # It tries several filenames:
259 #   * debian/package.filename.buildarch
260 #   * debian/package.filename
261 #   * debian/file (if the package is the main package)
262 sub pkgfile {
263         my $package=shift;
264         my $filename=shift;
265
266         if (-f "debian/$package.$filename.".buildarch()) {
267                 return "debian/$package.$filename.".buildarch();
268         }
269         elsif (-f "debian/$package.$filename") {
270                 return "debian/$package.$filename";
271         }
272         elsif ($package eq $dh{MAINPACKAGE} && -f "debian/$filename") {
273                 return "debian/$filename";
274         }
275         else {
276                 return "";
277         }
278 }
279
280 # Pass it a name of a binary package, it returns the name to prefix to files
281 # in debian for this package.
282 sub pkgext {
283         my $package=shift;
284
285         if (compat(1) and $package eq $dh{MAINPACKAGE}) {
286                 return "";
287         }
288         return "$package.";
289 }
290
291 # Returns 1 if the package is a native debian package, null otherwise.
292 # As a side effect, sets $dh{VERSION} to the version of this package.
293 {
294         # Caches return code so it only needs to run dpkg-parsechangelog once.
295         my %isnative_cache;
296         
297         sub isnative {
298                 my $package=shift;
299
300                 return $isnative_cache{$package} if defined $isnative_cache{$package};
301                 
302                 # Make sure we look at the correct changelog.
303                 my $isnative_changelog=pkgfile($package,"changelog");
304                 if (! $isnative_changelog) {
305                         $isnative_changelog="debian/changelog";
306                 }
307                 # Get the package version.
308                 my $version=`dpkg-parsechangelog -l$isnative_changelog`;
309                 ($dh{VERSION})=$version=~m/Version:\s*(.*)/m;
310                 # Did the changelog parse fail?
311                 if (! defined $dh{VERSION}) {
312                         error("changelog parse failure");
313                 }
314
315                 # Is this a native Debian package?
316                 if ($dh{VERSION}=~m/.*-/) {
317                         return $isnative_cache{$package}=0;
318                 }
319                 else {
320                         return $isnative_cache{$package}=1;
321                 }
322         }
323 }
324
325 # Automatically add a shell script snippet to a debian script.
326 # Only works if the script has #DEBHELPER# in it.
327 #
328 # Parameters:
329 # 1: package
330 # 2: script to add to
331 # 3: filename of snippet
332 # 4: sed to run on the snippet. Ie, s/#PACKAGE#/$PACKAGE/
333 sub autoscript {
334         my $package=shift;
335         my $script=shift;
336         my $filename=shift;
337         my $sed=shift || "";
338
339         # This is the file we will append to.
340         my $outfile="debian/".pkgext($package)."$script.debhelper";
341
342         # Figure out what shell script snippet to use.
343         my $infile;
344         if (defined($ENV{DH_AUTOSCRIPTDIR}) && 
345             -e "$ENV{DH_AUTOSCRIPTDIR}/$filename") {
346                 $infile="$ENV{DH_AUTOSCRIPTDIR}/$filename";
347         }
348         else {
349                 if (-e "/usr/share/debhelper/autoscripts/$filename") {
350                         $infile="/usr/share/debhelper/autoscripts/$filename";
351                 }
352                 else {
353                         error("/usr/share/debhelper/autoscripts/$filename does not exist");
354                 }
355         }
356
357         complex_doit("echo \"# Automatically added by ".basename($0)."\">> $outfile");
358         complex_doit("sed \"$sed\" $infile >> $outfile");
359         complex_doit("echo '# End automatically added section' >> $outfile");
360 }
361
362 # Removes a whole substvar line.
363 sub delsubstvar {
364         my $package=shift;
365         my $substvar=shift;
366
367         my $ext=pkgext($package);
368         my $substvarfile="debian/${ext}substvars";
369
370         if (-e $substvarfile) {
371                 complex_doit("grep -v '^${substvar}=' $substvarfile > $substvarfile.new || true");
372                 doit("mv", "$substvarfile.new","$substvarfile");
373         }
374 }
375                                 
376 # Adds a dependency on some package to the specified
377 # substvar in a package's substvar's file.
378 sub addsubstvar {
379         my $package=shift;
380         my $substvar=shift;
381         my $deppackage=shift;
382         my $verinfo=shift;
383         my $remove=shift;
384
385         my $ext=pkgext($package);
386         my $substvarfile="debian/${ext}substvars";
387         my $str=$deppackage;
388         $str.=" ($verinfo)" if length $verinfo;
389
390         # Figure out what the line will look like, based on what's there
391         # now, and what we're to add or remove.
392         my $line="";
393         if (-e $substvarfile) {
394                 my %items;
395                 open(SUBSTVARS_IN, "$substvarfile") || die "read $substvarfile: $!";
396                 while (<SUBSTVARS_IN>) {
397                         chomp;
398                         if (/^\Q$substvar\E=(.*)/) {
399                                 %items = map { $_ => 1} split(", ", $1);
400                                 
401                                 last;
402                         }
403                 }
404                 close SUBSTVARS_IN;
405                 if (! $remove) {
406                         $items{$str}=1;
407                 }
408                 else {
409                         delete $items{$str};
410                 }
411                 $line=join(", ", keys %items);
412         }
413         elsif (! $remove) {
414                 $line=$str;
415         }
416
417         if (length $line) {
418                  complex_doit("echo '${substvar}=$line' >> $substvarfile");
419         }
420 }
421
422 # Reads in the specified file, one word at a time, and returns an array of
423 # the result. If a value is passed in as the second parameter, then glob
424 # expansion is done in the directory specified by the parameter ("." is
425 # frequently a good choice).
426 sub filearray {
427         my $file=shift;
428         my $globdir=shift;
429
430         my @ret;
431         open (DH_FARRAY_IN, $file) || error("cannot read $file: $1");
432         while (<DH_FARRAY_IN>) {
433                 # Only do glob expansion in v3 mode.
434                 #
435                 # The tricky bit is that the glob expansion is done
436                 # as if we were in the specified directory, so the
437                 # filenames that come out are relative to it.
438                 if (defined $globdir && ! compat(2)) {
439                         for (map { glob "$globdir/$_" } split) {
440                                 s#^$globdir/##;
441                                 push @ret, $_;
442                         }
443                 }
444                 else {
445                         push @ret, split;
446                 }
447         }
448         close DH_FARRAY_IN;
449         
450         return @ret;
451 }
452
453 # Returns the build architecture. (Memoized)
454 {
455         my $arch;
456         
457         sub buildarch {
458                 return $arch if defined $arch;
459
460                 $arch=`dpkg --print-architecture` || error($!);
461                 chomp $arch;
462                 return $arch;
463         }
464 }
465
466 # Returns a list of packages in the control file.
467 # Must pass "arch" or "indep" or "same" to specify arch-dependant or
468 # -independant or same arch packages. If nothing is specified, returns all
469 # packages.
470 sub GetPackages {
471         my $type=shift;
472         
473         $type="" if ! defined $type;
474         
475         # Look up the build arch if we need to.
476         my $buildarch='';
477         if ($type eq 'same') {
478                 $buildarch=buildarch();
479         }
480
481         my $package="";
482         my $arch="";
483         my @list=();
484         my %seen;
485         open (CONTROL, 'debian/control') ||
486                 error("cannot read debian/control: $!\n");
487         while (<CONTROL>) {
488                 chomp;
489                 s/\s+$//;
490                 if (/^Package:\s*(.*)/) {
491                         $package=$1;
492                         # Detect duplicate package names in the same control file.
493                         if (! $seen{$package}) {
494                                 $seen{$package}=1;
495                         }
496                         else {
497                                 error("debian/control has a duplicate entry for $package");
498                         }
499                 }
500                 if (/^Architecture:\s*(.*)/) {
501                         $arch=$1;
502                 }
503                 
504                 if (!$_ or eof) { # end of stanza.
505                         if ($package &&
506                             (($type eq 'indep' && $arch eq 'all') ||
507                              ($type eq 'arch' && $arch ne 'all') ||
508                              ($type eq 'same' && ($arch eq 'any' || $arch =~ /\b$buildarch\b/)) ||
509                              ! $type)) {
510                                 push @list, $package;
511                                 $package="";
512                                 $arch="";
513                         }
514                 }
515         }
516         close CONTROL;
517
518         return @list;
519 }
520
521 1