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