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