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