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