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