source: trunk/debbuild@ 176

Last change on this file since 176 was 176, checked in by kdeugau, 11 years ago

/trunk

Extend/fix autoreq handling for some new quirks (so it doesn't pick
up -dev dependencies that really aren't required at runtime), possibly
make it a bit more efficient

  • Property svn:executable set to *
  • Property svn:keywords set to Date Rev Author
File size: 69.0 KB
Line 
1#!/usr/bin/perl -w
2# debbuild script
3# Shamelessly steals interface from rpm's "rpmbuild" to create
4# Debian packages. Please note that such packages are highly
5# unlikely to conform to "Debian Policy".
6###
7# SVN revision info
8# $Date: 2012-12-04 22:04:26 +0000 (Tue, 04 Dec 2012) $
9# SVN revision $Rev: 176 $
10# Last update by $Author: kdeugau $
11###
12# Copyright (C) 2005-2012 Kris Deugau <kdeugau@deepnet.cx>
13#
14# This program is free software; you can redistribute it and/or modify
15# it under the terms of the GNU General Public License as published by
16# the Free Software Foundation; either version 2 of the License, or
17# (at your option) any later version.
18#
19# This program is distributed in the hope that it will be useful,
20# but WITHOUT ANY WARRANTY; without even the implied warranty of
21# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
22# GNU General Public License for more details.
23#
24# You should have received a copy of the GNU General Public License
25# along with this program; if not, write to the Free Software
26# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
27
28use strict;
29use warnings;
30use Fcntl; # for sysopen flags
31use Cwd 'abs_path'; # for finding where files really are
32use Config;
33
34my $version = "0.9"; #VERSION#
35
36# regex debugger
37#use re "debug";
38
39# Behavioural compatibility FTW! Yes, rpmbuild does this too.
40die "No .spec file to work with! Exiting.\n" if scalar(@ARGV) == 0;
41
42# Program flow:
43# -> Parse/execute "system" config/macros (if any - should be rare)
44# -> Parse/execute "user" config/macros (if any - *my* requirement is %_topdir)
45# -> Parse command line for options, spec file/tarball/.src.deb (NB - also accept .src.rpm)
46
47sub expandmacros;
48
49# User's prefs for dirs, environment, etc,etc,etc.
50# config file ~/.debmacros
51# Default ordered search paths for config/macros:
52# /usr/lib/rpm/rpmrc /usr/lib/rpm/redhat/rpmrc /etc/rpmrc ~/.rpmrc
53# /usr/lib/rpm/macros /usr/lib/rpm/redhat/macros /etc/rpm/macros ~/.rpmmacros
54# **NOTE: May be possible to (ab)use bits of debhelper
55
56# Build tree
57# default is /usr/src/debian/{BUILD,SOURCES,SPECS,DEBS,SDEBS}
58
59# Globals
60my $finalmessages = ''; # A place to stuff messages that I want printed at the *very* end of any processing.
61my $specfile;
62my $tarball;
63my $srcpkg;
64my $cmdbuildroot;
65my $tarballdir = '%{name}-%{version}'; # We do this in case of a spec file not using %setup...
66my %specglobals; # For %define's in specfile, among other things.
67
68$specglobals{'_vendor'} = 'debbuild';
69$specglobals{'vendor'} = 'debbuild';
70
71# Initialized globals
72my $verbosity = 0;
73my $NoAutoReq = 0;
74my %cmdopts = (type => '',
75 stage => 'a',
76 short => 'n'
77 );
78my $topdir = "/usr/src/debian";
79#my $specglobals{buildroot} = "%{_tmppath}/%{name}-%{version}-%{release}.root".int(rand(99998)+1);
80$specglobals{buildroot} = '%{_topdir}/BUILDROOT/%{name}-%{version}-%{release}';
81
82# "Constants"
83my %targets = ('p' => 'Prep',
84 'c' => 'Compile',
85 'i' => 'Install',
86 'l' => 'Verify %files',
87 'a' => 'Build binary and source',
88 'b' => 'Build binary',
89 's' => 'Build source'
90 );
91# Ah, the joys of multiple architectures. :( Feh.
92# As copied from rpm
93my %optflags = ( 'i386' => '-O2 -g -march=i386 -mcpu=i686',
94 'amd64' => '-O2 -g'
95 );
96my $hostarch; # we set this later...
97my $scriptletbase =
98q(#!/bin/bash
99
100 RPM_SOURCE_DIR="%{_topdir}/SOURCES"
101 RPM_BUILD_DIR="%{_topdir}/BUILD"
102 RPM_OPT_FLAGS="%{optflags}"
103 RPM_ARCH="%{_arch}"
104 RPM_OS="linux"
105 export RPM_SOURCE_DIR RPM_BUILD_DIR RPM_OPT_FLAGS RPM_ARCH RPM_OS
106 RPM_DOC_DIR="/usr/share/doc"
107 export RPM_DOC_DIR
108 RPM_PACKAGE_NAME="%{name}"
109 RPM_PACKAGE_VERSION="%{version}"
110 RPM_PACKAGE_RELEASE="%{release}"
111 export RPM_PACKAGE_NAME RPM_PACKAGE_VERSION RPM_PACKAGE_RELEASE
112 RPM_BUILD_ROOT="%{buildroot}"
113 export RPM_BUILD_ROOT
114);
115foreach (`dpkg-architecture`) {
116 s/=(.+)/="$1"/;
117 $scriptletbase .= " $_";
118 ($hostarch) = (/^DEB_HOST_ARCH="(.+)"$/) if /DEB_HOST_ARCH=/;
119}
120$scriptletbase .=
121q(
122 set -x
123 umask 022
124 cd %{_topdir}/BUILD
125);
126
127# Hackery to try to bring some semblance of sanity to packages built for more
128# than one Debian version at the same time. Whee.
129# /etc/debian-version and/or version of base-files package
130my %distmap = (
131 "3.1.9ubuntu7.1" => "dapper",
132 "4ubuntu2" => "feisty",
133 "3.0" => "woody",
134 "3.1" => "sarge",
135 "4" => "etch",
136 "5" => "lenny",
137 "6.0" => "squeeze",
138 "7.0" => "wheezy",
139 "8.0" => "jessie",
140 "99" => "sid");
141# Enh. There doesn't seem to be any better way to do this... :(
142{
143# could theoretically also do something with this... it's about as stable as "dpkg-query ..." below... :(
144# my $releasever = qx { cat /etc/debian_version };
145# chomp $releasever;
146 my $basever;
147
148 if ( ! -e '/usr/bin/dpkg-query' ) {
149 # call it woody, since sarge and newer have dpkg-query, and we don't much care about obsolete^n releases
150 $basever = "3.0";
151 } else {
152
153# *eyeroll* there *really* has to be a better way to go about this. You
154# can't sanely build packages for multiple distro targets if you can't
155# programmatically figure out which one you're building on.
156
157# note that we care only about major release numbers; tracking minor or point
158# releases would be... exponentially more painful.
159
160 # for the lazy copy-paster: dpkg-query --showformat '${version}\n' -W base-files
161 # avoid shellisms
162 if (open BASEGETTER, "-|", "dpkg-query", "--showformat", '${version}', "-W", "base-files") {
163 $basever = <BASEGETTER>;
164 close BASEGETTER;
165
166 ($basever) = ($basever =~ /^(\d(?:\.\d)?)/);
167 }
168
169 } # got dpkg-query?
170
171 $specglobals{"debdist"} = $distmap{$basever};
172 $specglobals{"debver"} = $basever; # this may have trouble with Ubuntu versions?
173
174} # done trying to set debian dist/version
175
176# Package data
177# This is the form of $pkgdata{pkgname}{meta}
178# meta includes Summary, Name, Version, Release, Group, Copyright,
179# Source, URL, Packager, BuildRoot, Description, BuildRequires,
180# Requires, Provides
181# 10/31/2005 Maybe this should be flatter? -kgd
182my %pkgdata = (main => {source => ''});
183my @pkglist = ('main'); #sigh
184# Files listing. Embedding this in %pkgdata would be, um, messy.
185my %filelist;
186my %doclist;
187my $buildreq = '';
188
189# Scriptlets
190my $prepscript = '';
191my $buildscript = '';
192# %install doesn't need the full treatment from %clean; just an empty place to install to.
193# NB - rpm doesn't do this; is it really necessary?
194my $installscript = '[ "$RPM_BUILD_ROOT" != "/" ] && rm -rf $RPM_BUILD_ROOT'."\n";
195my $cleanscript = '';
196
197# Snag some environment data
198my $tmpdir;
199if (defined $ENV{TMP} && $ENV{TMP} =~ /^(\/var)?\/tmp$/) {
200 $tmpdir = $ENV{TMP};
201} else {
202 $tmpdir = "/var/tmp";
203}
204
205##main
206
207load_userconfig();
208parse_cmd();
209
210if ($cmdopts{install}) {
211 install_sdeb();
212 exit 0;
213}
214
215# output stage of --showpkgs
216if ($cmdopts{type} eq 'd') {
217 parse_spec();
218 foreach my $pkg (@pkglist) {
219 $pkgdata{$pkg}{name} =~ tr/_/-/;
220
221 my $pkgfullname = "$pkgdata{$pkg}{name}_".
222 (defined($pkgdata{main}{epoch}) ? "$pkgdata{main}{epoch}:" : '').
223 "$pkgdata{$pkg}{version}-$pkgdata{main}{release}_$pkgdata{$pkg}{arch}.deb";
224
225 print "$pkgfullname\n" if $filelist{$pkg};
226
227 }
228 # Source package
229 print "$pkgdata{main}{name}-".
230 (defined($pkgdata{main}{epoch}) ? "$pkgdata{main}{epoch}:" : '').
231 "$pkgdata{main}{version}-$pkgdata{main}{release}.sdeb\n";
232 exit 0;
233}
234
235# Stick --rebuild handling in here - basically install_sdeb()
236# followed by tweaking options to run with -ba
237if ($cmdopts{type} eq 's') {
238 if ($srcpkg =~ /\.src\.rpm$/) {
239 my @srclist = qx { rpm -qlp $srcpkg };
240 foreach (@srclist) {
241 chomp;
242 $specfile = "$topdir/SPECS/$_" if /\.spec$/;
243 }
244 qx { rpm -i $srcpkg };
245 } else {
246 install_sdeb();
247 my @srclist = qx { pax < $srcpkg };
248 foreach (@srclist) {
249 chomp;
250 $specfile = "$topdir/$_" if /SPECS/;
251 }
252 }
253 $cmdopts{type} = 'b';
254 $cmdopts{stage} = 'a';
255}
256
257if ($cmdopts{type} eq 'b') {
258 # Need to read the spec file to find the tarball. Note that
259 # this also generates most of the shell script required.
260 parse_spec();
261 die "Can't build $pkgdata{main}{name}: build requirements not met.\n"
262 if !checkbuildreq();
263}
264
265if ($cmdopts{type} eq 't') {
266 # Need to unpack the tarball to find the spec file. Sort of the inverse of -b above.
267 # zcat $tarball |tar -t |grep .spec
268 # collect some info about the tarball
269 $specfile = "$topdir/BUILD/". qx { zcat $tarball |tar -t |grep -e '[\.]spec\$' };
270 chomp $specfile;
271 my ($fileonly, $dirname) = ($tarball =~ /(([a-zA-Z0-9._-]+)\.tar\.(?:gz|bz2|xz))$/);
272
273 $tarball = abs_path($tarball);
274##fixme: use macro expansions for the executables
275 my $unpackcmd = "cd $topdir/BUILD; ".
276 ( $tarball =~ /\.tar\.gz$/ ? "/bin/gzip" : "" ).
277 ( $tarball =~ /\.tar\.bz2$/ ? "/bin/bzip2" : "" ).
278 ( $tarball =~ /\.tar\.(?:gz|Z)$/ ? "/usr/bin/xz" : "" ).
279 " -dc $tarball |/bin/tar -xf -";
280
281 system "$unpackcmd";
282 system "cp $tarball $topdir/SOURCES/$fileonly";
283 system "cp $specfile $topdir/SPECS/";
284 parse_spec();
285 die "Can't build $pkgdata{main}{name}: build requirements not met.\n"
286 if !checkbuildreq();
287}
288
289# -> srcpkg if -.s
290if ($cmdopts{stage} eq 's') {
291 srcpackage();
292 print $finalmessages;
293 exit 0;
294}
295
296# Hokay. Need to:
297# -> prep if -.p OR (-.[cilabs] AND !--short-circuit)
298if ($cmdopts{stage} eq 'p' || ($cmdopts{stage} =~ /[cilabs]/ && $cmdopts{short} ne 'y')) {
299 prep();
300}
301# -> build if -.c OR (-.[ilabs] AND !--short-circuit)
302if ($cmdopts{stage} eq 'c' || ($cmdopts{stage} =~ /[ilabs]/ && $cmdopts{short} ne 'y')) {
303 build();
304}
305# -> install if -.[ilabs]
306#if ($cmdopts{stage} eq 'i' || ($cmdopts{stage} =~ /[labs]/ && $cmdopts{short} ne 'y')) {
307if ($cmdopts{stage} =~ /[ilabs]/) {
308 install();
309#foreach my $pkg (@pkglist) {
310# print "files in $pkg:\n ".$filelist{$pkg}."\n";
311#}
312
313}
314# -> binpkg and srcpkg if -.a
315if ($cmdopts{stage} eq 'a') {
316 binpackage();
317 srcpackage();
318 clean();
319}
320# -> binpkg if -.b
321if ($cmdopts{stage} eq 'b') {
322 binpackage();
323 clean();
324}
325
326# Spit out any closing remarks
327print $finalmessages;
328
329# Just in case.
330exit 0;
331
332
333## load_userconfig()
334# Loads user configuration (if any)
335# Currently only handles .debmacros
336# Needs to handle "other files"
337sub load_userconfig {
338 my $homedir = (getpwuid($<))[7];
339 if (-e "$homedir/.debmacros") {
340 open USERMACROS,"<$homedir/.debmacros";
341 while (<USERMACROS>) {
342 # And we also only handle a few macros at the moment.
343 if (/^\%_topdir/) {
344 my (undef,$tmp) = split /\s+/, $_;
345 $topdir = $tmp;
346 }
347 next if /^\%_/;
348 # Allow arbitrary definitions. Note that we're only doing simple defs here for now.
349 if (/^\%([a-z0-9]+)\s+(.+)$/) {
350 $specglobals{$1} = $2;
351 }
352 }
353 }
354} # end load_userconfig()
355
356
357## parse_cmd()
358# Parses command line into global hash %cmdopts, other globals
359# Options based on rpmbuild's options
360sub parse_cmd {
361 # Don't feel like coding my own option parser...
362 #use Getopt::Long;
363 # ... but I may have to: (OTOH, rpm uses popt, so maybe we can too.)
364 #use Getopt::Popt qw(:all);
365 # Or not. >:( Stupid Debian lack of findable Perl module names in packages.
366
367 # ... also note, single-character options are mostly not flags, so they can't be
368 # sanely combined the way most other programs' single-character flag options can.
369
370 # Stuff it.
371 my $prevopt = '';
372 foreach (@ARGV) {
373 chomp;
374
375 # Is it an option?
376 if (/^-/) {
377
378 # Is it a long option?
379 if (/^--/) {
380 if (/^--short-circuit/) {
381 $cmdopts{short} = 'y';
382 } elsif (/^--rebuild/) {
383 $cmdopts{type} = 's';
384 } elsif (/^--showpkgs/) {
385 $cmdopts{type} = 'd'; # d for 'diagnostic' or 'debug' or 'dump'
386 } elsif (/^--help/) {
387 print "debbuild v$version".q{
388Copyright 2005-2012 Kris Deugau <kdeugau@deepnet.cx>
389
390Build .deb packages from RPM-style .spec files
391debbuild supports most package-building options rpmbuild does.
392
393Build options with [ <specfile> | <tarball> | <source package> ]:
394 -bp build through %prep (unpack sources and apply patches) from <specfile>
395 -bc build through %build (%prep, then compile) from <specfile>
396 -bi build through %install (%prep, %build, then install) from <specfile>
397 -bl verify %files section from <specfile>
398 -ba build source and binary packages from <specfile>
399 -bb build binary package only from <specfile>
400 -bs build source package only from <specfile>
401 -tp build through %prep (unpack sources and apply patches) from <tarball>
402 -tc build through %build (%prep, then compile) from <tarball>
403 -ti build through %install (%prep, %build, then install) from <tarball>
404 -ta build source and binary packages from <tarball>
405 -tb build binary package only from <tarball>
406 -ts build source package only from <tarball>
407 --rebuild build binary package from <source package>
408 --buildroot=DIRECTORY override build root
409 --short-circuit skip straight to specified stage (only for c,i)
410
411Common options:
412 -D, --define='MACRO EXPR' define MACRO with value EXPR
413
414debbuild-specific options:
415 -i Unpack a .sdeb in the %_topdir tree
416 --showpkgs Show package names that would be built. Only works with .spec files.
417
418};
419 exit;
420
421 } elsif (/^--define/) {
422 # nothing to do? Can't see anything needed, we handle the actual definition later.
423##fixme
424# add --self-package here
425# deps build-essential pax fakeroot
426 } else {
427 print "Long option $_ not handled\n";
428 }
429 } else {
430 # Not a long option
431 if (/^-[bt]/) {
432 if ($cmdopts{stage} eq 's') {
433 # Mutually exclusive options.
434 die "Can't use $_ with --rebuild\n";
435 } else {
436 # Capture the type (from "bare" files or tarball) and the stage (prep, build, etc)
437 ($cmdopts{stage}) = (/^-[bt]([pcilabs])/);
438 ($cmdopts{type}) = (/^-([bt])[pcilabs]/);
439 }
440 } elsif (/^-v/) {
441 # bump verbosity. Not sure what I'll actually do here...
442 } elsif (/^-i/) {
443 $cmdopts{install} = 1;
444 $prevopt = '-i';
445 } elsif (/^-D/) {
446 # --define. nothing to do on this round; actual work is done next time.
447 } else {
448 die "Bad option $_\n";
449 }
450 }
451
452 } else { # Not an option argument
453
454 # --buildroot is the only option that takes an argument
455 # Therefore, any *other* bare arguments are the spec file,
456 # tarball, or source package we're operating on - depending
457 # on which one we meet.
458 if ($prevopt eq '--buildroot') {
459 $cmdbuildroot = $_;
460 } elsif ($prevopt eq '--define' || $prevopt eq '-D') {
461 my ($macro,$value) = (/([a-z0-9_.-]+)(?:\s+(.+))?/i);
462 if ($value ne '') {
463 $specglobals{$macro} = $value;
464 } else {
465 warn "WARNING: missing value for macro $macro in --define! Ignoring.\n";
466 }
467 } elsif ($prevopt eq '-i') {
468 $srcpkg = $_;
469 } else {
470 if ($cmdopts{type} eq 's') {
471 # Source package
472 if (!/(sdeb|\.src\.rpm)$/) {
473 die "Can't --rebuild with $_\n";
474 }
475 $srcpkg = $_;
476 } elsif ($cmdopts{type} eq 'b' || $cmdopts{type} eq 'd') {
477 # Spec file
478 $specfile = $_;
479 } else {
480 # Tarball build. Need to extract tarball to find spec file. Whee.
481 $tarball = $_;
482 }
483 }
484 }
485 $prevopt = $_;
486 } # foreach @ARGV
487
488 # Some cross-checks. rpmbuild limits --short-circuit to just
489 # the "compile" and "install" targets - with good reason IMO.
490 # Note that --short-circuit with -.p is not really an error, just redundant.
491 # NB - this is NOT fatal, just ignored!
492 if ($cmdopts{short} eq 'y' && $cmdopts{stage} =~ /[labs]/) {
493 warn "Can't use --short-circuit for $targets{$cmdopts{stage}} stage. Ignoring.\n";
494 $cmdopts{short} = 'n';
495 }
496
497 # Valid options, with example arguments (if any):
498# Build from .spec file; mutually exclusive:
499 # -bp
500 # -bc
501 # -bi
502 # -bl
503 # -ba
504 # -bb
505 # -bs
506# Build from tarball; mutually exclusive:
507 # -tp
508 # -tc
509 # -ti
510 # -ta
511 # -tb
512 # -ts
513# Build from .src.(deb|rpm)
514 # --rebuild
515 # --recompile
516
517# General options
518 # --buildroot=DIRECTORY
519 # --clean
520 # --nobuild
521 # --nodeps
522 # --nodirtokens
523 # --rmsource
524 # --rmspec
525 # --short-circuit
526 # --target=CPU-VENDOR-OS
527
528 #my $popt = new Getopt::Popt(argv => \@ARGV, options => \@optionsTable);
529
530} # end parse_cmd()
531
532
533## parse_spec()
534# Parse the .spec file.
535sub parse_spec {
536 die "No .spec file specified! Exiting.\n" if !$specfile;
537 open SPECFILE,"<$specfile" or die "specfile ($specfile) barfed: $!";
538
539 my $iflevel = 0;
540 my $buildarch = $hostarch;
541 $pkgdata{main}{arch} = $hostarch;
542
543 my $stage = 'preamble';
544 my $subname = 'main';
545 my $scriptlet;
546
547# Basic algorithm:
548# For each line
549# if it's a member of an %if construct, branch and see which segment of the
550# spec file we need to parse and which one gets discarded, then
551# short-circuit back to the top of the loop.
552# if it's a %section, bump the stage. Preparse addons to the %section line
553# (eg subpackage) and stuff them in suitable loop-global variables, then
554# short-circuit back to the top of the loop.
555# Otherwise, parse the line according to which section we're supposedly
556# parsing right now
557
558LINE: while (<SPECFILE>) {
559 next if /^#/ && $stage eq 'preamble'; # Ignore comments...
560 next if /^\s*$/ && $stage eq 'preamble'; # ... and blank lines.
561
562# no sense in continuing if we find something we don't grok
563 # Yes, this is really horribly fugly. But it's a cheap crosscheck against invalid
564 # %-tags which also make rpmbuild barf. In theory.
565# notes: some of these are not *entirely* case-sensitive (%ifxxx), but most are.
566 # Extracted from the Maximum RPM online doc via:
567 # grep -h %[a-z] *|perl -e 'while (<>) { /\%([a-z0-9]+)\b/; print "$1|\n"; }'|sort -u
568 if (/^%[a-z]/ &&
569 $_ !~ /^%(?:attr|build|changelog|check|clean|config|configure|defattr|define|description|
570 dir|doc|docdir|else|endif|files|ghost|if|ifarch|ifn|ifnarch|ifnos|ifnxxx|fos|ifxxx|
571 install|makeinstall|package|patch\d+|post|postun|pre|prep|preun|readme|setup|
572 triggerin|triggerpostun|triggerun|verify|verifyscript)\b/x
573 ) {
574 my ($badtag) = (/^%([a-z]+)/i);
575 die "Unknown tag \%$badtag at line $. of $specfile\n";
576 }
577
578# preprocess %define's
579 if (my ($key, $def) = (/^\%define\s+([^\s]+)\s+(.+)$/) ) {
580 $specglobals{$key} = expandmacros($def,'g');
581 }
582
583 if (/^\%if/) {
584 s/^\%if//;
585 chomp;
586 my $expr = expandmacros($_, 'g');
587 $iflevel++;
588
589 if ($expr !~ /^\s*\d+\s*$/) {
590 # gots a logic statement we want to turn into a 1 or a 0. most likely by eval'ing it.
591
592 $expr =~ s/\s+//g;
593
594# For Great w00tness! New and Improved multilayered logic handling.
595
596 my @bits = split /\b/, $expr;
597 $expr = '';
598 foreach my $bit (@bits) {
599 next if $bit eq '"';
600 $bit =~ s/"//g;
601 $expr .= qq("$bit") if $bit =~ /^\w+$/;
602 $expr .= $bit if $bit !~ /^\w+$/;
603 }
604
605 # Done in this order so we don't cascade incorrectly. Yes, those spaces ARE correct in the replacements!
606 $expr =~ s/==/ eq /g;
607 $expr =~ s/!=/ ne /g;
608 $expr =~ s/<=>/ cmp /g;
609 $expr =~ s/<=/ le /g;
610 $expr =~ s/>=/ ge /g;
611 $expr =~ s/</ lt /g;
612 $expr =~ s/>/ gt /g;
613
614 # Turn it into something that eval's to a number. Maybe not needed? O_o
615 #$expr = "( $expr ? 1 : 0 )";
616
617 $expr = eval $expr;
618 }
619
620 next LINE if $expr != 0; # This appears to be the only case we call false.
621 while (<SPECFILE>) {
622 if (/^\%endif/) {
623 $iflevel--;
624 next LINE;
625 } elsif (/^\%else/) {
626 next LINE;
627 }
628 }
629 }
630 if (/^\%else/) {
631 while (<SPECFILE>) {
632 if (/^\%endif/) {
633 $iflevel--;
634 next LINE;
635 }
636 }
637 }
638 if (/^\%endif/) {
639 $iflevel--;
640 next LINE;
641 } # %if/%else/%endif
642
643 if (/^\%{echo:(.+)}/) {
644 my $output = expandmacros($1, 'gp');
645 print "$output";
646 }
647
648# now we pick out the sections and set "state" to parse that section. Fugly but I can't see a better way. >:(
649
650 if (/^\%description(?:\s+(?:-n\s+)?(.+))?/) {
651 $stage = 'desc';
652 $subname = "main";
653 if ($1) { # Magic to add entries to the right package
654 my $tmp = expandmacros("$1", 'gp');
655 if (/-n/) { $subname = $tmp; } else { $subname = "$pkgdata{main}{name}-$tmp"; }
656 }
657 next LINE;
658 } # %description
659
660 if (/^\%package\s+(?:-n\s+)?(.+)/) {
661 $stage = 'package';
662 if ($1) { # Magic to add entries to the right package
663 my $tmp = expandmacros("$1", 'gp');
664 if (/-n/) { $subname = $tmp; } else { $subname = "$pkgdata{main}{name}-$tmp"; }
665 }
666 push @pkglist, $subname;
667 $pkgdata{$subname}{name} = $subname;
668 $pkgdata{$subname}{version} = $pkgdata{main}{version};
669 # Build "same arch as previous package found" by default. Where rpm just picks the
670 # *very* last one, we want to allow arch<native>+arch-all
671 # (eg, Apache is i386, but apache-manual is all)
672 $pkgdata{$subname}{arch} = $buildarch; # Since it's likely subpackages will NOT have a BuildArch line...
673 next LINE;
674 } # %package
675
676 if (/^\%prep/) {
677 $stage = 'prep';
678 # Replace some core macros
679 $pkgdata{main}{source} = expandmacros($pkgdata{main}{source},'gp');
680 next LINE;
681 } # %prep
682
683 if (/^\%build/) {
684 $stage = 'build';
685 $buildscript .= "cd $tarballdir\n";
686 next LINE;
687 } # %build
688
689 if (/^\%install/) {
690 $stage = 'install';
691 $installscript .= "cd $tarballdir\n";
692 next LINE;
693 } # %install
694
695 if (/^\%clean/) {
696 $stage = 'clean';
697 $cleanscript .= "cd $tarballdir\n";
698 next LINE;
699 } # %clean
700
701 if (/^\%(pre|post|preun|postun)\b(?:\s+(?:-n\s+)?(.+))?/i) {
702 $stage = 'prepost';
703 $scriptlet = lc $1;
704 $subname = 'main';
705 if ($2) { # Magic to add entries to the right package
706 my $tmp = expandmacros("$2", 'g');
707 if (/-n/) { $subname = $tmp; } else { $subname = "$pkgdata{main}{name}-$tmp"; }
708 }
709 next LINE;
710 } # %pre/%post/%preun/%postun
711
712 if (/^\%files(?:\s+(?:-n\s+)?(.+))?/) {
713 $stage = 'files';
714 $subname = 'main';
715 if ($1) { # Magic to add entries to the right list of files
716 my $tmp = expandmacros("$1", 'gp');
717 if (/-n/) { $subname = $tmp; } else { $subname = "$pkgdata{main}{name}-$tmp"; }
718 }
719 next LINE;
720 } # %files
721
722 if (/^\%changelog/) {
723 $stage = 'changelog';
724 $pkgdata{main}{changelog} = '';
725 next LINE;
726 }
727
728# now we handle individual lines from the various sections
729
730 if ($stage eq 'desc') {
731 next LINE if /^\s*#/;
732 $pkgdata{$subname}{desc} .= " $_";
733 } # description
734
735 if ($stage eq 'package') {
736 # gotta expand %defines here. Whee.
737# Note that we look for the Debian-specific Recommends, Suggests, and Replaces,
738# although they will have to be wrapped in '%if %{_vendor} == "debbuild"' for
739# an rpmbuild-compatible .spec file
740# NB: NOT going to support Pre-Depends, since it's a "Don't Use" (mis)feature, and
741# RPM's support for a similar tag (PreReq) has been recently dropped.
742 if (my ($dname,$dvalue) = (/^(Recommends|Suggests|Enhances|Replaces|Summary|Group|Version|Requires|Conflicts|Provides|BuildArch(?:itecture)?):\s+(.+)$/i)) {
743 $dname =~ tr/[A-Z]/[a-z]/;
744 if ($dname =~ /^BuildArch/i) {
745 $dvalue =~ s/^noarch/all/ig;
746 $buildarch = $dvalue; # Emulate rpm's behaviour to a degree
747 $dname = 'arch';
748 }
749 if ($dname =~ /recommends|suggests|enhances|replaces|requires|conflicts|provides/) {
750 $pkgdata{$subname}{$dname} .= ", ".expandmacros($dvalue, 'gp');
751 } else {
752 $pkgdata{$subname}{$dname} = expandmacros($dvalue, 'gp');
753 }
754 }
755 } # package
756
757 if ($stage eq 'prep') {
758 # Actual handling for %prep section. May have %setup macro; may
759 # include %patch tags, may be just a bare shell script.
760 if (/^\%setup/) {
761 # Parse out the %setup macro. Note that we aren't supporting
762 # many of RPM's %setup features.
763 $prepscript .= "cd $topdir/BUILD\n";
764 if ( /\s+-n\s+([^\s]+)\s+/ ) {
765 $tarballdir = $1;
766 }
767 $tarballdir = expandmacros($tarballdir,'gp');
768 $prepscript .= "rm -rf $tarballdir\n";
769 if (/\s+-c\s+/) {
770 $prepscript .= "mkdir $tarballdir\ncd $tarballdir\n";
771 }
772 $prepscript .=
773 ( $pkgdata{main}{source} =~ /\.tar\.gz$/ ? "/bin/gzip" : "" ).
774 ( $pkgdata{main}{source} =~ /\.tar\.bz2$/ ? "/bin/bzip2" : "" ).
775 ( $pkgdata{main}{source} =~ /\.tar\.xz$/ ? "/usr/bin/xz" : "" ).
776 " -dc $topdir/SOURCES/$pkgdata{main}{source} | /bin/tar -".
777 ( /\s+-q\s+/ ? '' : 'vv' )."xf -\n".
778 qq(STATUS=\$?\nif [ \$STATUS -ne 0 ]; then\n exit \$STATUS\nfi\n).
779 "cd $topdir/BUILD/$tarballdir\n".
780 qq([ `/usr/bin/id -u` = '0' ] && /bin/chown -Rhf root .\n).
781 qq([ `/usr/bin/id -u` = '0' ] && /bin/chgrp -Rhf root .\n).
782 qq(/bin/chmod -Rf a+rX,g-w,o-w .\n);
783 } elsif ( my ($patchnum,$patchopts) = (/^\%patch([^\s]+)(\s+.+)?$/) ) {
784 chomp $patchnum;
785 $prepscript .= qq(echo "Patch #$patchnum ($pkgdata{main}{"patch$patchnum"}):"\n);
786 # If there are options passed, use'em.
787 # Otherwise, catch a bare %patch and ASS-U-ME it's '-p0'-able.
788 # Will break on options that don't provide -pnn, but what the hell.
789 # Need to decompress .bz2 and .gz patches on the fly. Not sure why one
790 # would ever have such things, but there they are... and rpmbuild supports 'em
791 # patch originally suggested by Lucian Cristian for .bz2
792 # reworked and expanded to support .Z/.gz/.xz as well
793 if ( $pkgdata{main}{"patch$patchnum"} =~ /\.(?:Z|gz|bz2|xz)$/ ) {
794 my $decompressor;
795 $decompressor = 'gzip' if $pkgdata{main}{"patch$patchnum"} =~ /\.(?:Z|gz)$/;
796 $decompressor = 'bzip2' if $pkgdata{main}{"patch$patchnum"} =~ /\.bz2$/;
797 $decompressor = 'xz' if $pkgdata{main}{"patch$patchnum"} =~ /\.xz$/;
798 $prepscript .= qq(/bin/$decompressor -d < $topdir/SOURCES/$pkgdata{main}{"patch$patchnum"} | patch );
799 $prepscript .= $patchopts if $patchopts;
800 $prepscript .= "-p0" if !$patchopts;
801 $prepscript .= qq( -s\nSTATUS=\$?\nif [ \$STATUS -ne 0 ]; then\n exit \$STATUS\nfi\n);
802 } else {
803 $prepscript .= "patch ";
804 $prepscript .= $patchopts if $patchopts;
805 $prepscript .= "-p0" if !$patchopts;
806 $prepscript .= " -s <$topdir/SOURCES/".$pkgdata{main}{"patch$patchnum"}."\n";
807 }
808 } else {
809 $prepscript .= expandmacros($_,'gp');
810 }
811 next LINE;
812 } # prep
813
814 if ($stage eq 'build') {
815 # %build. This is pretty much just a shell script. There
816 # aren't many local macros to deal with.
817 if (/^\%configure/) {
818 $buildscript .= expandmacros($_,'cgbp');
819 } elsif (/^\%\{__make\}/) {
820 $buildscript .= expandmacros($_,'mgbp');
821 } else {
822 $buildscript .= expandmacros($_,'gp');
823 }
824 next LINE;
825 } # build
826
827 if ($stage eq 'install') {
828 if (/^\%makeinstall/) {
829 $installscript .= expandmacros($_,'igbp');
830 } else {
831 $installscript .= expandmacros($_,'gp');
832 }
833 next LINE;
834 } # install
835
836 if ($stage eq 'clean') {
837 $cleanscript .= expandmacros($_,'gp');
838 next LINE;
839 } # clean
840
841 if ($stage eq 'prepost') {
842 $pkgdata{$subname}{$scriptlet} .= expandmacros($_,'gp');
843 next LINE;
844 } # prepost
845
846 if ($stage eq 'files') {
847 # need to deal with these someday
848 next LINE if /^\%dir/;
849 next LINE if /^\%defattr/;
850 next LINE if /^\%verify/;
851 # dunno what to do with this; not sure if there's space in Debian's package structure for it.
852 next LINE if /^\%ghost/;
853 # Debian dpkg doesn't speak "%docdir". Meh.
854 next LINE if /^\%docdir/;
855# my $singleton = 0; # don't recall what this was for
856 next LINE if /^\s*#/;
857 next LINE if /^\s*$/;
858
859# create and initialize flags
860 my ($perms, $owner, $group, $conf, $filesline);
861 $perms = $owner = $group = $conf = '-';
862
863 $filesline = $_;
864
865 # strip and flag %attr constructs
866 if ($filesline =~ /\%attr\b/) {
867 # Extract %attr...
868 my ($args) = (/(\%attr\s*\(\s*[\d-]+\s*,\s*["a-zA-Z0-9-]+\s*,\s*["a-zA-Z0-9-]+\s*\))/);
869 $args =~ s/\s+//g;
870 $args =~ s/"//g; # don't think quotes are ever necessary, but they're *allowed*
871 # ... and parse it ...
872 ($perms,$owner,$group) = ($args =~ /\(([\d-]+),([a-zA-Z0-9-]+),([a-zA-Z0-9-]+)/);
873 # ... and wipe it when we're done.
874 $filesline =~ s/\%attr\s*\(\s*[\d-]+\s*,\s*["a-zA-Z0-9-]+\s*,\s*["a-zA-Z0-9-]+\s*\)//;
875 }
876
877 # Conffiles. Note that Debian and RH have similar, but not
878 # *quite* identical ideas of what constitutes a conffile. Nrgh.
879 # Note that dpkg will always ask if you want to replace the file - noreplace
880 # is more or less permanently enabled.
881##fixme
882# also need to handle missingok (file that doesn't exist, but should be removed on uninstall)
883# hmm. not sure if such is **POSSIBLE** with Debian... maybe an addition to %post?
884 if ($filesline =~ /\%config\b(?:\s*\(\s*noreplace\s*\)\s*)?/) {
885 $pkgdata{$subname}{conffiles} = 1; # Flag it for later
886 $conf = 'y';
887 $filesline =~ s/\%config\b(?:\s*\(\s*noreplace\s*\)\s*)?//;
888 }
889
890 # %doc needs extra processing, because it can be a space-separated list, and may
891 # include both full and partial pathnames. The partial pathnames must be fiddled
892 # into place in the %install script, because Debian doesn't really have the concept
893 # of "documentation file" that rpm does. (Debian "documentation files" are files
894 # in /usr/share/doc/<packagename>.)
895##fixme: unhandled case: %doc %defattr. Eeep.
896# don't really know what to do with %defattr, generally. :(
897 if ($filesline =~ /\%doc\b/) {
898 $filesline =~ s/\s*\%doc\s+//;
899
900# this could probably go elsewhere.
901 my $pkgname = $pkgdata{$subname}{name};
902 $pkgname =~ tr/_/-/;
903
904 # have to extract the partial pathnames that %doc installs automagically
905 foreach (split /\s+/, $filesline) {
906 if (! (/^\%/ or m|^/|) ) {
907 $doclist{$subname} .= " $_";
908 my ($element) = m|([^/\s]+/?)$|;
909 $filesline =~ s|$_|\%{_docdir}/$pkgname/$element|;
910 }
911 }
912 } # $filesline =~ /\%doc\b/
913
914 $filesline =~ s/^\s*//; # Just In Case. For, uh, neatness.
915
916# due to Debian's total lack of real permissions-processing in its actual package
917# handling component (dpkg-deb), this can't really be done "properly". We'll have
918# to add chown/chmod commands to the postinst instead. Feh.
919 $pkgdata{$subname}{'post'} .= "chown $owner $filesline\n" if $owner ne '-';
920 $pkgdata{$subname}{'post'} .= "chgrp $group $filesline\n" if $group ne '-';
921 $pkgdata{$subname}{'post'} .= "chmod $perms $filesline\n" if $perms ne '-';
922
923##fixme
924# need hackery to assure only one filespec per %config. NB: "*" is one filespec. <g>
925 push @{$pkgdata{$subname}{conflist}}, $filesline if $conf ne '-';
926
927 # now that we've got the specials out of the way, we can add things to the appropriate list of files.
928 # ... and finally everything else
929 $filelist{$subname} .= " $filesline";
930
931 next LINE;
932 } # files
933
934 if ($stage eq 'changelog') {
935 # this is one of the few places we do NOT generally want to replace macros...
936 $pkgdata{main}{changelog} .= $_;
937 }
938
939 if ($stage eq 'preamble') {
940 if (/^summary:\s*(.+)/i) {
941 $pkgdata{main}{summary} = $1;
942 } elsif (/^name:\s*(.+)/i) {
943 $pkgdata{main}{name} = expandmacros($1,'g');
944 } elsif (/^epoch:\s*(.+)/i) {
945 $pkgdata{main}{epoch} = expandmacros($1,'g');
946 } elsif (/^version:\s*(.+)/i) {
947 $pkgdata{main}{version} = expandmacros($1,'g');
948 } elsif (/^release:\s*(.+)/i) {
949 $pkgdata{main}{release} = expandmacros($1,'g');
950 } elsif (/^group:\s*(.+)/i) {
951 $pkgdata{main}{group} = $1;
952 } elsif (/^copyright:\s*(.+)/i) {
953 $pkgdata{main}{copyright} = $1;
954 } elsif (/^url:\s*(.+)/i) {
955 $pkgdata{main}{url} = $1;
956 } elsif (/^packager:\s*(.+)/i) {
957 $pkgdata{main}{packager} = $1;
958 } elsif (/^buildroot:\s*(.+)/i) {
959 $specglobals{buildroot} = $1;
960 } elsif (/^source0?:\s*(.+)/i) {
961 $pkgdata{main}{source} = $1;
962 # Do this here since we don't use any URL forms elsewhere (maybe some other time)
963 $pkgdata{main}{source} =~ s|^.+/([^/]+)$|$1|;
964 # .tar, .tar.gz, .tar.bz2, .tgz, .xz
965 die "Unknown tarball format $1\n" if $1 !~ /\.(?:tar(?:\.(?:gz|bz2|xz))?|tgz)$/;
966 } elsif (my ($srcnum, $src) = (/^source([0-9]+):\s*(.+)/i)) {
967 $pkgdata{sources}{$srcnum} = $src;
968 # Do this here since we don't use any URL forms elsewhere (maybe some other time)
969 $pkgdata{sources}{$srcnum} =~ s|^.+/([^/]+)$|$1|;
970 } elsif (/^patch([^:]+):\s*(.+)$/i) {
971 my $patchname = "patch$1";
972 $pkgdata{main}{$patchname} = $2;
973 if ($pkgdata{main}{$patchname} =~ /\//) {
974 # URL-style patch. Rare but not unheard-of.
975 my @patchbits = split '/', $pkgdata{main}{$patchname};
976 $pkgdata{main}{$patchname} = $patchbits[$#patchbits];
977 }
978 chomp $pkgdata{main}{$patchname};
979 } elsif (/^buildarch(?:itecture)?:\s*(.+)/i) {
980 $pkgdata{main}{arch} = $1;
981 $pkgdata{main}{arch} =~ s/^noarch$/all/;
982 $buildarch = $pkgdata{main}{arch};
983 } elsif (/^buildrequires:\s*(.+)/i) {
984 $buildreq .= ", $1";
985 } elsif (/^requires:\s*(.+)/i) {
986 $pkgdata{main}{requires} .= ", ".expandmacros("$1", 'gp');
987 } elsif (/^provides:\s*(.+)/i) {
988 $pkgdata{main}{provides} .= ", $1";
989 } elsif (/^conflicts:\s*(.+)/i) {
990 $pkgdata{main}{conflicts} .= ", $1";
991 } elsif (/^recommends:\s*(.+)/i) {
992 $pkgdata{main}{recommends} .= ", $1";
993 warn "Warning: Debian-specific 'Recommends:' outside \%if wrapper\n" if $iflevel == 0;
994 } elsif (/^suggests:\s*(.+)/i) {
995 $pkgdata{main}{suggests} .= ", $1";
996 warn "Warning: Debian-specific 'Suggests:' outside \%if wrapper\n" if $iflevel == 0;
997 } elsif (/^enhances:\s*(.+)/i) {
998 $pkgdata{main}{enhances} .= ", $1";
999 warn "Warning: Debian-specific 'Enhances:' outside \%if wrapper\n" if $iflevel == 0;
1000 } elsif (/^replaces:\s*(.+)/i) {
1001 $pkgdata{main}{replaces} .= ", $1";
1002 warn "Warning: Debian-specific 'Replaces:' outside \%if wrapper\n" if $iflevel == 0;
1003 } elsif (/^autoreq(?:prov)?:\s*(.+)/i) {
1004 # we don't handle auto-provides (yet)
1005 $NoAutoReq = 1 if $1 =~ /(?:no|0)/i;
1006 }
1007 next LINE;
1008 } # preamble
1009
1010 } # while <SPEC>
1011
1012 # Parse and replace some more macros. More will be replaced even later.
1013
1014 # Expand macros as necessary.
1015 $scriptletbase = expandmacros($scriptletbase,'gp');
1016
1017 $cleanscript = expandmacros($cleanscript,'gp');
1018
1019 $specglobals{buildroot} = $cmdbuildroot if $cmdbuildroot;
1020 $specglobals{buildroot} = expandmacros($specglobals{buildroot},'gp');
1021
1022 close SPECFILE;
1023} # end parse_spec()
1024
1025
1026## prep()
1027# Writes and executes the %prep script (mostly) built while reading the spec file.
1028sub prep {
1029 # Replace some things here just to make sure.
1030 $prepscript = expandmacros($prepscript,'gp');
1031
1032 # create script filename
1033 my $prepscriptfile = "$tmpdir/deb-tmp.prep.".int(rand(99998)+1);
1034 sysopen(PREPSCRIPT, $prepscriptfile, O_RDWR | O_CREAT | O_EXCL | O_NOFOLLOW)
1035 or die "Can't open/create prep script file $prepscriptfile: $!\n";
1036 print PREPSCRIPT $scriptletbase;
1037 print PREPSCRIPT $prepscript;
1038 close PREPSCRIPT;
1039
1040 # execute
1041 print "Calling \%prep script $prepscriptfile...\n";
1042 system("/bin/sh -e $prepscriptfile") == 0
1043 or die "Can't exec: $!\n";
1044
1045 # and clean up
1046 unlink $prepscriptfile;
1047} # end prep()
1048
1049
1050## build()
1051# Writes and executes the %build script (mostly) built while reading the spec file.
1052sub build {
1053 # Expand the macros
1054 $buildscript = expandmacros($buildscript,'cgbp');
1055
1056 # create script filename
1057 my $buildscriptfile = "$tmpdir/deb-tmp.build.".int(rand(99998)+1);
1058 sysopen(BUILDSCRIPT, $buildscriptfile, O_RDWR | O_CREAT | O_EXCL | O_NOFOLLOW)
1059 or die "Can't open/create build script file $buildscriptfile: $!\n";
1060 print BUILDSCRIPT $scriptletbase;
1061 print BUILDSCRIPT $buildscript;
1062 close BUILDSCRIPT;
1063
1064 # execute
1065 print "Calling \%build script $buildscriptfile...\n";
1066 system("/bin/sh -e $buildscriptfile") == 0
1067 or die "Can't exec: $!\n";
1068
1069 # and clean up
1070 unlink $buildscriptfile;
1071} # end build()
1072
1073
1074## install()
1075# Writes and executes the %install script (mostly) built while reading the spec file.
1076sub install {
1077
1078 # munge %doc entries into place
1079 # rpm handles this with a separate executed %doc script, we're not going to bother.
1080 foreach my $docpkg (keys %doclist) {
1081 my $pkgname = $pkgdata{$docpkg}{name};
1082 $pkgname =~ s/_/-/g;
1083
1084 $installscript .= "DOCDIR=\$RPM_BUILD_ROOT\%{_docdir}/$pkgname\nexport DOCDIR\n";
1085 $installscript .= "mkdir -p \$DOCDIR\n";
1086 $doclist{$docpkg} =~ s/^\s*//;
1087 foreach (split(' ',$doclist{$docpkg})) {
1088 $installscript .= "cp -pr $_ \$DOCDIR/\n";
1089 }
1090 }
1091
1092 # Expand the macros
1093 $installscript = expandmacros($installscript,'igbp');
1094
1095 # create script filename
1096 my $installscriptfile = "$tmpdir/deb-tmp.inst.".int(rand(99998)+1);
1097 sysopen(INSTSCRIPT, $installscriptfile, O_RDWR | O_CREAT | O_EXCL | O_NOFOLLOW)
1098 or die "Can't open/create install script file $installscriptfile: $!\n";
1099 print INSTSCRIPT $scriptletbase;
1100 print INSTSCRIPT $installscript;
1101 close INSTSCRIPT;
1102
1103 # execute
1104 print "Calling \%install script $installscriptfile...\n";
1105 system("/bin/sh -e $installscriptfile") == 0
1106 or die "Can't exec: $!\n";
1107
1108 # and clean up
1109 unlink $installscriptfile;
1110
1111 # final bit: compress manpages if present
1112 # done here cuz I don't grok shell well
1113 # should probably error-check all kinds of things. <g>
1114 if (opendir MANROOT, "$specglobals{buildroot}/usr/share/man") {
1115 my @mansects = readdir MANROOT;
1116 closedir MANROOT;
1117 foreach my $mandir (@mansects) {
1118 next if $mandir !~ /^man/;
1119 opendir MANPAGES, "$specglobals{buildroot}/usr/share/man/$mandir";
1120 my @pagelist = readdir MANPAGES;
1121 closedir MANPAGES; # Slightly safer to to this; no accidental recursion. O_o
1122 foreach my $manpage (@pagelist) {
1123 $manpage = "$specglobals{buildroot}/usr/share/man/$mandir/$manpage";
1124 if ( -f $manpage) {
1125 if ($manpage =~ /^(.+)\.(?:Z|gz|bz2)\n?$/) {
1126 my $newpage = $1;
1127 `gunzip $manpage` if $manpage =~ /\.(?:Z|gz)$/;
1128 `bunzip2 $manpage` if $manpage =~ /\.bz2$/;
1129 $manpage = $newpage;
1130 }
1131 `gzip -9 -n $manpage`;
1132 } elsif ( -l $manpage) {
1133 my $linkdest = readlink $manpage;
1134 $linkdest =~ s/\.(?:Z|gz|bz2)//;
1135 unlink $manpage;
1136 $manpage =~ s/\.(?:Z|gz|bz2)//;
1137 symlink "$linkdest.gz", "$manpage.gz" or print "DEBUG: wibble: symlinking manpage failed: $!\n";
1138 }
1139 }
1140 }
1141 } # if opendir MANROOT
1142} # end install()
1143
1144
1145## binpackage()
1146# Creates the binary .deb package from the installed tree in $specglobals{buildroot}.
1147# Writes and executes a shell script to do so.
1148# Creates miscellaneous files required by dpkg-deb to actually build the package file.
1149# Should handle simple subpackages
1150sub binpackage {
1151
1152 foreach my $pkg (@pkglist) {
1153
1154 $pkgdata{$pkg}{arch} = $hostarch if !$pkgdata{$pkg}{arch}; # Just In Case.
1155
1156 # Make sure we have somewhere to write the .deb file
1157 if (!-e "$topdir/DEBS/$pkgdata{$pkg}{arch}") {
1158 mkdir "$topdir/DEBS/$pkgdata{$pkg}{arch}";
1159 }
1160
1161 # Skip building a package if it doesn't actually have any files. NB: This
1162 # differs slightly from rpm's behaviour where a package *will* be built -
1163 # even without any files - if %files is specified anywhere. I can think
1164 # of odd corner cases where that *may* be desireable.
1165 next if (!$filelist{$pkg} or $filelist{$pkg} =~ /^\s*$/);
1166
1167 # Gotta do this first, otherwise we don't have a place to move files from %files
1168 mkdir "$specglobals{buildroot}/$pkg";
1169
1170 # Eliminate any lingering % macros
1171 $filelist{$pkg} = expandmacros $filelist{$pkg}, 'g';
1172
1173 my @pkgfilelist = split ' ', $filelist{$pkg};
1174 foreach my $pkgfile (@pkgfilelist) {
1175 $pkgfile = expandmacros($pkgfile, 'gp');
1176
1177 # Feh. Manpages don't **NEED** to be gzipped, but rpmbuild does, and so shall we.
1178 # ... and your little info page too!
1179 if ($pkgfile =~ m{/usr/share/(?:man/man|info)}) {
1180 # need to check to see if manpage is gzipped
1181 if (-e "$specglobals{buildroot}$pkgfile") {
1182 # if we've just been pointed to a manpage section with "many" pages,
1183 # we need to gzip them all.
1184 # fortunately, we do NOT need to explicitly track each file for the
1185 # purpose of stuffing them in the package... the original %files
1186 # entry will do just fine.
1187 if ( -d "$specglobals{buildroot}$pkgfile") {
1188 foreach my $globfile (glob("$specglobals{buildroot}$pkgfile/*")) {
1189 gzip $globfile if $globfile !~ m|\.gz$|;
1190 }
1191 } else {
1192 if ($pkgfile !~ m|\.gz$|) {
1193 qx { gzip $specglobals{buildroot}$pkgfile };
1194 $pkgfile .= ".gz";
1195 }
1196 }
1197 } else {
1198 if ($pkgfile !~ m|\.gz$|) {
1199 $pkgfile .= ".gz";
1200 } else {
1201 $pkgfile =~ s/\.gz$//;
1202 qx { gzip $specglobals{buildroot}$pkgfile };
1203 $pkgfile .= ".gz";
1204 }
1205 }
1206 }
1207
1208 my ($fpath,$fname) = ($pkgfile =~ m|(.+?/?)?([^/]+/?)$|); # We don't need $fname now, but we might.
1209 qx { mkdir -p $specglobals{buildroot}/$pkg$fpath }
1210 if $fpath && $fpath ne '';
1211 qx { mv $specglobals{buildroot}$pkgfile $specglobals{buildroot}/$pkg$fpath };
1212 }
1213
1214 # Get the "Depends" (Requires) a la RPM. Ish. We strip the leading
1215 # comma and space here (if needed) in case there were "Requires" specified
1216 # in the spec file - those would precede these.
1217 $pkgdata{$pkg}{requires} .= getreqs("$specglobals{buildroot}/$pkg") if ! $NoAutoReq;
1218
1219 # magic needed to properly version dependencies...
1220 # only provided deps will really be included
1221 $pkgdata{$pkg}{requires} =~ s/^, //; # Still have to do this here.
1222 $pkgdata{$pkg}{requires} =~ s/\s+//g;
1223 my @deps = split /,/, $pkgdata{$pkg}{requires};
1224 my $tmp = '';
1225 foreach my $dep (@deps) {
1226 # Hack up the perl(Class::SubClass) deps into something dpkg can understand.
1227 # May or may not be versioned.
1228 # We do this first so the version rewriter can do its magic next.
1229 if (my ($mod,$ver) = ($dep =~ /^perl\(([A-Za-z0-9\:\-]+)\)([><=]+.+)?/) ) {
1230 $mod =~ s/^perl\(//;
1231 $mod =~ s/\)$//;
1232 $mod =~ s/::/-/g;
1233 $mod =~ tr/A-Z/a-z/;
1234 $mod = "lib$mod-perl";
1235 $mod .= $ver if $ver;
1236 $dep = $mod;
1237 }
1238 if (my ($name,$rel,$value) = ($dep =~ /^([a-zA-Z0-9._-]+)([><=]+)([a-zA-Z0-9._-]+)$/)) {
1239 $tmp .= ", $name ($rel $value)";
1240 } else {
1241 $tmp .= ", $dep";
1242 }
1243 }
1244 ($pkgdata{$pkg}{requires} = $tmp) =~ s/^, //;
1245
1246 # Do this here since we're doing {depends}...
1247 if (defined($pkgdata{$pkg}{provides})) {
1248 $pkgdata{$pkg}{provides} =~ s/^, //;
1249 $pkgdata{$pkg}{provides} = expandmacros($pkgdata{$pkg}{provides},'gp');
1250 }
1251 if (defined($pkgdata{$pkg}{conflicts})) {
1252 $pkgdata{$pkg}{conflicts} =~ s/^, //;
1253 $pkgdata{$pkg}{conflicts} = expandmacros($pkgdata{$pkg}{conflicts},'gp');
1254 }
1255
1256# These are Debian-specific!
1257 if (defined($pkgdata{$pkg}{recommends})) {
1258 $pkgdata{$pkg}{recommends} =~ s/^, //;
1259 $pkgdata{$pkg}{recommends} = expandmacros($pkgdata{$pkg}{recommends},'gp');
1260 }
1261 if (defined($pkgdata{$pkg}{suggests})) {
1262 $pkgdata{$pkg}{suggests} =~ s/^, //;
1263 $pkgdata{$pkg}{suggests} = expandmacros($pkgdata{$pkg}{suggests},'gp');
1264 }
1265 if (defined($pkgdata{$pkg}{enhances})) {
1266 $pkgdata{$pkg}{enhances} =~ s/^, //;
1267 $pkgdata{$pkg}{enhances} = expandmacros($pkgdata{$pkg}{enhances},'gp');
1268 }
1269 if (defined($pkgdata{$pkg}{replaces})) {
1270 $pkgdata{$pkg}{replaces} =~ s/^, //;
1271 $pkgdata{$pkg}{replaces} = expandmacros($pkgdata{$pkg}{replaces},'gp');
1272 }
1273
1274 # Gotta do this next, otherwise the control file has nowhere to go. >:(
1275 mkdir "$specglobals{buildroot}/$pkg/DEBIAN";
1276
1277 # Hack the filename for the package into a Debian-tool-compatible format. GRRRRRR!!!!!
1278 # Have I mentioned I hate Debian Policy?
1279 $pkgdata{$pkg}{name} =~ tr/_/-/;
1280
1281 # create script filename
1282 my $debscriptfile = "$tmpdir/deb-tmp.pkg.".int(rand(99998)+1);
1283 sysopen(DEBSCRIPT, $debscriptfile, O_RDWR | O_CREAT | O_EXCL | O_NOFOLLOW)
1284 or die "Can't open/create package-creation script file $debscriptfile: $!\n";
1285 print DEBSCRIPT $scriptletbase;
1286 print DEBSCRIPT "fakeroot -- dpkg-deb -b $specglobals{buildroot}/$pkg $topdir/DEBS/$pkgdata{$pkg}{arch}/".
1287 "$pkgdata{$pkg}{name}_".
1288 (defined($pkgdata{main}{epoch}) ? "$pkgdata{main}{epoch}:" : '').
1289 "$pkgdata{$pkg}{version}-$pkgdata{main}{release}_$pkgdata{$pkg}{arch}.deb\n";
1290 # %$&$%@#@@#%@@@ Debian and their horrible ugly package names. >:(
1291 close DEBSCRIPT;
1292
1293 my $control = "Package: $pkgdata{$pkg}{name}\n".
1294 "Version: ".
1295 (defined($pkgdata{main}{epoch}) ? "$pkgdata{main}{epoch}:" : '').
1296 "$pkgdata{$pkg}{version}-$pkgdata{main}{release}\n".
1297 "Section: $pkgdata{$pkg}{group}\n".
1298 "Priority: optional\n".
1299 "Architecture: $pkgdata{$pkg}{arch}\n".
1300 "Maintainer: $pkgdata{main}{packager}\n".
1301 ( $pkgdata{$pkg}{requires} ne '' ? "Depends: $pkgdata{$pkg}{requires}\n" : '' ).
1302 ( defined($pkgdata{$pkg}{provides}) ? "Provides: $pkgdata{$pkg}{provides}\n" : '' ).
1303 ( defined($pkgdata{$pkg}{conflicts}) ? "Conflicts: $pkgdata{$pkg}{conflicts}\n" : '' ).
1304 ( defined($pkgdata{$pkg}{recommends}) ? "Recommends: $pkgdata{$pkg}{recommends}\n" : '' ).
1305 ( defined($pkgdata{$pkg}{suggests}) ? "Suggests: $pkgdata{$pkg}{suggests}\n" : '' ).
1306 ( defined($pkgdata{$pkg}{enhances}) ? "Enhances: $pkgdata{$pkg}{enhances}\n" : '' ).
1307 ( defined($pkgdata{$pkg}{replaces}) ? "Replaces: $pkgdata{$pkg}{replaces}\n" : '' ).
1308 "Description: $pkgdata{$pkg}{summary}\n";
1309 # Munge things so that Debian tools don't choke on errant blank lines
1310 $pkgdata{$pkg}{desc} =~ s/\s+$//g; # Trim trailing blanks
1311 $pkgdata{$pkg}{desc} =~ s/^ $/ ./mg; # Replace lines consisting of " \n" with " .\n"
1312 $control .= "$pkgdata{$pkg}{desc}\n";
1313
1314 open CONTROL, ">$specglobals{buildroot}/$pkg/DEBIAN/control";
1315 print CONTROL $control;
1316 close CONTROL;
1317
1318 # Iff there are conffiles (as specified in the %files list(s), add'em
1319 # in so dpkg-deb can tag them.
1320 if ($pkgdata{$pkg}{conffiles}) {
1321 open CONFLIST, ">$specglobals{buildroot}/$pkg/DEBIAN/conffiles";
1322 foreach my $conffile (@{$pkgdata{$pkg}{conflist}}) {
1323 $conffile = expandmacros($conffile, 'g');
1324 my @tmp = glob "$specglobals{buildroot}/$pkg/$conffile";
1325 foreach (@tmp) {
1326 s|$specglobals{buildroot}/$pkg/||g; # nrgl. gotta be a better way to do this...
1327 s/\s+/\n/g; # Not gonna support spaces in filenames. Ewww.
1328 print CONFLIST "$_\n";
1329 }
1330 }
1331 close CONFLIST;
1332 }
1333
1334 # found the point of scripts on subpackages.
1335 if ($pkgdata{$pkg}{'pre'}) {
1336 $pkgdata{$pkg}{'pre'} = expandmacros($pkgdata{$pkg}{'pre'},'gp');
1337 open PREINST, ">$specglobals{buildroot}/$pkg/DEBIAN/preinst";
1338 print PREINST "#!/bin/sh\nset -e\n\n";
1339 print PREINST $pkgdata{$pkg}{'pre'};
1340 close PREINST;
1341 chmod 0755, "$specglobals{buildroot}/$pkg/DEBIAN/preinst";
1342 }
1343 if ($pkgdata{$pkg}{'post'}) {
1344 $pkgdata{$pkg}{'post'} = expandmacros($pkgdata{$pkg}{'post'},'gp');
1345 open POSTINST, ">$specglobals{buildroot}/$pkg/DEBIAN/postinst";
1346 print POSTINST "#!/bin/sh\nset -e\n\n";
1347 print POSTINST $pkgdata{$pkg}{'post'};
1348 close POSTINST;
1349 chmod 0755, "$specglobals{buildroot}/$pkg/DEBIAN/postinst";
1350 }
1351 if ($pkgdata{$pkg}{'preun'}) {
1352 $pkgdata{$pkg}{'pre'} = expandmacros($pkgdata{$pkg}{'preun'},'gp');
1353 open PREUNINST, ">$specglobals{buildroot}/$pkg/DEBIAN/prerm";
1354 print PREUNINST "#!/bin/sh\nset -e\n\n";
1355 print PREUNINST $pkgdata{$pkg}{'preun'};
1356 close PREUNINST;
1357 chmod 0755, "$specglobals{buildroot}/$pkg/DEBIAN/prerm";
1358 }
1359 if ($pkgdata{$pkg}{'postun'}) {
1360 $pkgdata{$pkg}{'postun'} = expandmacros($pkgdata{$pkg}{'postun'},'gp');
1361 open POSTUNINST, ">$specglobals{buildroot}/$pkg/DEBIAN/postrm";
1362 print POSTUNINST "#!/bin/sh\nset -e\n\n";
1363 print POSTUNINST $pkgdata{$pkg}{'postun'};
1364 close POSTUNINST;
1365 chmod 0755, "$specglobals{buildroot}/$pkg/DEBIAN/postrm";
1366 }
1367
1368 # execute
1369 print "Calling package creation script $debscriptfile for $pkgdata{$pkg}{name}...\n";
1370 system("/bin/sh -e $debscriptfile") == 0
1371 or die "Can't exec: $!\n";
1372
1373 $finalmessages .= "Wrote binary package ".
1374 "$pkgdata{$pkg}{name}_".
1375 (defined($pkgdata{main}{epoch}) ? "$pkgdata{main}{epoch}:" : '').
1376 "$pkgdata{$pkg}{version}-$pkgdata{main}{release}_$pkgdata{$pkg}{arch}.deb".
1377 " in $topdir/DEBS/$pkgdata{$pkg}{arch}\n";
1378 # and clean up
1379 unlink $debscriptfile;
1380
1381 } # subpackage loop
1382
1383} # end binpackage()
1384
1385
1386## srcpackage()
1387# Builds a .src.deb source package. Note that Debian's idea of
1388# a "source package" is seriously flawed IMO, because you can't
1389# easily copy it as-is.
1390# Not quite identical to RPM, but Good Enough (TM).
1391sub srcpackage {
1392 # In case we were called with -bs.
1393 $pkgdata{main}{name} =~ tr/_/-/;
1394 my $pkgsrcname = "$pkgdata{main}{name}-".
1395 (defined($pkgdata{main}{epoch}) ? "$pkgdata{main}{epoch}:" : '').
1396 "$pkgdata{main}{version}-$pkgdata{main}{release}.sdeb";
1397
1398 my $paxcmd;
1399
1400 # We'll definitely need this later, and *may* need it sooner.
1401 (my $barespec = $specfile) =~ s|.+/([^/]+)$|$1|;
1402
1403 # Copy the specfile to the build tree, but only if it's not there already.
1404##buglet: need to deal with silly case where silly user has put the spec
1405# file in a subdir of %{_topdir}/SPECS. Ewww. Silly user!
1406 if (abs_path($specfile) !~ /^$topdir\/SPECS/) {
1407 $paxcmd .= "cp $specfile %{_topdir}/SPECS/; \n"
1408 }
1409
1410 # use pax -w [file] [file] ... >outfile.sdeb
1411 $paxcmd = "cd $topdir; pax -w ";
1412
1413 # some packages may not have a "main" source.
1414 $paxcmd .= "SOURCES/$pkgdata{main}{source} " if $pkgdata{main}{source};
1415
1416 # create file list: Source[nn], Patch[nn]
1417 foreach my $specbit (keys %{$pkgdata{main}} ) {
1418 next if $specbit eq 'source';
1419 $paxcmd .= "SOURCES/$pkgdata{main}{$specbit} " if $specbit =~ /^patch/;
1420##buglet: need to deal with case where patches are listed as URLs?
1421# or other extended pathnames? Silly !@$%^&!%%!%!! user!
1422 }
1423
1424 foreach my $source (keys %{$pkgdata{sources}}) {
1425 $paxcmd .= "SOURCES/$pkgdata{sources}{$source} ";
1426 }
1427
1428 # add the spec file, source package destination, and cd back where we came from.
1429 $paxcmd .= "SPECS/$barespec > $topdir/SDEBS/$pkgsrcname; cd -";
1430
1431 # In case of %-macros...
1432 $paxcmd = expandmacros($paxcmd,'gp');
1433
1434 system "$paxcmd";
1435 $finalmessages .= "Wrote source package $pkgsrcname in $topdir/SDEBS.\n";
1436} # end srcpackage()
1437
1438
1439## clean()
1440# Writes and executes the %clean script (mostly) built while reading the spec file.
1441sub clean {
1442 # Replace some things here just to make sure.
1443 $cleanscript = expandmacros($cleanscript,'gp');
1444
1445 # create script filename
1446 my $cleanscriptfile = "$tmpdir/deb-tmp.clean.".int(rand(99998)+1);
1447 sysopen(CLEANSCRIPT, $cleanscriptfile, O_RDWR | O_CREAT | O_EXCL | O_NOFOLLOW)
1448 or die $!;
1449 print CLEANSCRIPT $scriptletbase;
1450 print CLEANSCRIPT $cleanscript;
1451 close CLEANSCRIPT;
1452
1453 # execute
1454 print "Calling \%clean script $cleanscriptfile...\n";
1455 system("/bin/sh -e $cleanscriptfile") == 0
1456 or die "Can't exec: $!\n";
1457
1458 # and clean up
1459 unlink $cleanscriptfile;
1460} # end clean()
1461
1462
1463## checkbuildreq()
1464# Checks the build requirements (if any)
1465# Spits out a rude warning and returns a true-false error if any
1466# requirements are not met.
1467sub checkbuildreq {
1468 return 1 if $buildreq eq ''; # No use doing extra work.
1469
1470 if ( ! -e "/usr/bin/dpkg-query" ) {
1471 print "**WARNING** dpkg-query not found. Can't check build-deps.\n".
1472 " Required for sucessful build:\n".$buildreq."\n".
1473 " Continuing anyway.\n";
1474 return 1;
1475 }
1476
1477 my $reqflag = 1; # unset iff a buildreq is missing
1478
1479 $buildreq =~ s/^, //; # Strip the leading comma and space
1480 my @reqlist = split /,\s+/, $buildreq;
1481
1482 foreach my $req (@reqlist) {
1483 # from rpmbuild error message
1484 # Dependency tokens must begin with alpha-numeric, '_' or '/'
1485##fixme: check for suitable whitespace around $rel
1486 my ($pkg,$rel,$ver);
1487
1488 # We have two classes of requirements - versioned and unversioned.
1489 if ($req =~ /[><=]/) {
1490 # Pick up the details of versioned buildreqs
1491 ($pkg,$rel,$ver) = ($req =~ /([a-z0-9._-]+)\s+([><=]+)\s+([a-z0-9._-]+)/);
1492 } else {
1493 # And the unversioned ones.
1494 $pkg = $req;
1495 $rel = '>=';
1496 $ver = 0;
1497 }
1498
1499 my @pkglist = qx { dpkg-query --showformat '\${status}\t\${version}\n' -W $pkg };
1500 if (!$pkglist[0]) {
1501 print " * Missing build-dependency $pkg!\n";
1502 $reqflag = 0;
1503 } else {
1504# real package, installed
1505#kdeugau:~$ dpkg-query --showformat '${status}\t${version}\n' -W libc-client2007e-dev 2>&1
1506#install ok installed 8:2007f~dfsg-1
1507# virtual package, provided by ???
1508#kdeugau:~$ dpkg-query --showformat '${status}\t${version}\n' -W libc-client-dev 2>&1
1509#unknown ok not-installed
1510# real package or virtual package not installed or provided
1511#kdeugau:~$ dpkg-query --showformat '${status}\t${version}\n' -W libdb4.8-dbg 2>&1
1512#dpkg-query: no packages found matching libdb4.8-dbg
1513
1514 my ($reqstat,undef,undef,$reqver) = split /\s+/, $pkglist[0];
1515 if ($reqstat =~ /^unknown/) {
1516 # this seems to be a virtual package.
1517 print " * Warning: $pkg is probably installed but seems to be a virtual package.\n";
1518 } elsif ($reqstat =~ /^install/) {
1519 my ($resp) = qx { dpkg --compare-versions $reqver '$rel' $ver && echo "ok" };
1520 if ($resp !~ /^ok/) {
1521 $reqflag = 0;
1522 print " * Buildreq $pkg is installed, but wrong version ($reqver): Need $ver\n"
1523 }
1524 } else {
1525 # whatever state it's in, it's not completely installed, therefore it's missing.
1526 print " * Missing build-dependency $pkg!\n";
1527 $reqflag = 0;
1528 } # end not installed/installed check
1529 }
1530 } # end req loop
1531
1532 return $reqflag;
1533} # end checkbuildreq()
1534
1535
1536## getreqs()
1537# Find out which libraries/packages are required for any
1538# executables and libs in a given file tree.
1539# (Debian doesn't have soname-level deps; just package-level)
1540# Returns an empty string if the tree contains no binaries.
1541# Doesn't work well on shell scripts. but those *should* be
1542# fine anyway. (Yeah, right...)
1543sub getreqs() {
1544 my $pkgtree = $_[0];
1545
1546 print "Checking library requirements...\n";
1547 my @binlist = qx { find $pkgtree -type f -perm 755 };
1548
1549 if (scalar(@binlist) == 0) {
1550 return '';
1551 }
1552
1553 my @reqlist;
1554 foreach (@binlist) {
1555 push @reqlist, qx { LANG=C ldd $_ };
1556 }
1557
1558 # Get the list of libs provided by this package. Still doesn't
1559 # handle the case where the lib gets stuffed into a subpackage. :/
1560 my @intprovlist = qx { find $pkgtree -type f -name "*.so*" };
1561 my $provlist = '';
1562 foreach (@intprovlist) {
1563 s/$pkgtree//;
1564 $provlist .= "$_";
1565 }
1566
1567 my %reqs;
1568 my $reqlibs = '';
1569 my %reqliblist;
1570
1571 foreach (@reqlist) {
1572 next if /^$pkgtree/;
1573 next if /not a dynamic executable/;
1574 next if m|/lib(?:64)?/ld-linux|; # Hack! Hack! PTHBTT! (libc suxx0rz)
1575 next if /linux-gate.so/; # Kernel hackery for teh W1n!!1!1eleventy-one!1 (Don't ask. Feh.)
1576 next if /linux-vdso.so/; # More kernel hackery. Whee!
1577
1578 # Whee! more hackery to detect provided-here libs. Some apparently return from ldd as "not found".
1579 my ($a,$b) = split / => /;
1580 $a =~ s/\s*//g;
1581 if ($b =~ /not found/) {
1582 next if qx { find $specglobals{buildroot} -name "*$a" };
1583 }
1584
1585 my ($req) = (m|=\>\s+([a-zA-Z0-9._/+-]+)|); # dig out the actual library (so)name.
1586 # And feh, we need the *path*, since I've discovered a new edge case where
1587 # the same libnnn.1.2.3 *file*name is found across *several* lib dirs. >:(
1588
1589 # Ignore libs provided by this package. Note that we don't match
1590 # on word-boundary at the *end* of the lib we're looking for, as the
1591 # looked-for lib may not have the full soname version. (ie, it may
1592 # "just" point to one of the symlinks that get created somewhere.)
1593 next if $provlist =~ /\b$req/;
1594
1595 $reqlibs .= " $req";
1596 $reqliblist{$req} = 1;
1597 }
1598
1599 if (%reqliblist) {
1600 foreach my $rlib (keys %reqliblist) {
1601 my $libpkg = qx { dpkg -S $rlib };
1602 ($libpkg,undef) = split /:/, $libpkg;
1603 $reqs{$libpkg} = 1;
1604 }
1605 }
1606
1607 my $deplist = '';
1608 foreach (keys %reqs) {
1609 $deplist .= ", $_";
1610 }
1611
1612# For now, we're done. We're not going to meddle with versions yet.
1613# Among other things, it's messier than handling "simple" yes/no "do
1614# we have this lib?" deps. >:(
1615
1616 return $deplist;
1617} # end getreqs()
1618
1619
1620## install_sdeb()
1621# Extracts .sdeb contents to %_topdir as appropriate
1622sub install_sdeb {
1623 $srcpkg = abs_path($srcpkg);
1624
1625 my $paxcmd = "cd $topdir; pax -r <$srcpkg; cd -";
1626
1627 # In case of %-macros...
1628 $paxcmd = expandmacros($paxcmd,'gp');
1629
1630 system "$paxcmd";
1631 print "Extracted source package $srcpkg to $topdir.\n";
1632} # end install_sdeb()
1633
1634
1635## expandmacros()
1636# Expands all %{blah} macros in the passed string
1637# Split up a bit with some sections so we don't spend time trying to
1638# expand macros that are only used in a few specific places.
1639sub expandmacros {
1640 my $macrostring = shift;
1641 my $section = shift;
1642
1643 # To allow the FHS-ish %configure and %makeinstall to work The Right Way.
1644 # (Without clobbering the global $specglobals{buildroot}.)
1645 my $prefix = '';
1646
1647 if ($section =~ /c/) {
1648 # %configure macro
1649# Don't know what it's for, don't have a useful default replacement
1650# --program-prefix=%{_program_prefix} \
1651 $macrostring =~ s'%configure'./configure --host=$DEB_HOST_GNU_TYPE \
1652 --build=$DEB_BUILD_GNU_TYPE \
1653 --prefix=%{_prefix} \
1654 --exec-prefix=%{_exec_prefix} \
1655 --bindir=%{_bindir} \
1656 --sbindir=%{_sbindir} \
1657 --sysconfdir=%{_sysconfdir} \
1658 --datadir=%{_datadir} \
1659 --includedir=%{_includedir} \
1660 --libdir=%{_libdir} \
1661 --libexecdir=%{_libexecdir} \
1662 --localstatedir=%{_localstatedir} \
1663 --sharedstatedir=%{_sharedstatedir} \
1664 --mandir=%{_mandir} \
1665 --infodir=%{_infodir} ';
1666 } # done %configure
1667
1668 if ($section =~ /m/) {
1669 $macrostring =~ s'%{__make}'make ';
1670 } # done make
1671
1672# %makeinstall expands with recursive macros in rpm. whee.
1673 if ($section =~ /i/) {
1674 # This is where we need to mangle $prefix.
1675 $macrostring =~ s'%makeinstall'make \
1676 prefix=%{?buildroot:%{buildroot}}%{_prefix} \
1677 exec_prefix=%{?buildroot:%{buildroot}}%{_exec_prefix} \
1678 bindir=%{?buildroot:%{buildroot}}%{_bindir} \
1679 sbindir=%{?buildroot:%{buildroot}}%{_sbindir} \
1680 sysconfdir=%{?buildroot:%{buildroot}}%{_sysconfdir} \
1681 datadir=%{?buildroot:%{buildroot}}%{_datadir} \
1682 includedir=%{?buildroot:%{buildroot}}%{_includedir} \
1683 libdir=%{?buildroot:%{buildroot}}%{_libdir} \
1684 libexecdir=%{?buildroot:%{buildroot}}%{_libexecdir} \
1685 localstatedir=%{?buildroot:%{buildroot}}%{_localstatedir} \
1686 sharedstatedir=%{?buildroot:%{buildroot}}%{_sharedstatedir} \
1687 mandir=%{?buildroot:%{buildroot}}%{_mandir} \
1688 infodir=%{?buildroot:%{buildroot}}%{_infodir} \
1689 install ';
1690 $prefix = $specglobals{buildroot};
1691 } # done %install and/or %makeinstall
1692
1693 # Build data
1694 # Note that these are processed in reverse order to get the substitution order right
1695 if ($section =~ /b/) {
1696# $macrostring =~ s'%{fhs}'host=$DEB_HOST_GNU_TYPE \
1697# build=$DEB_BUILD_GNU_TYPE \
1698 $macrostring =~ s'%{fhs}'prefix=%{_prefix} \
1699 exec-prefix=%{_exec_prefix} \
1700 bindir=%{_bindir} \
1701 sbindir=%{_sbindir} \
1702 sysconfdir=%{_sysconfdir} \
1703 datadir=%{_datadir} \
1704 includedir=%{_includedir} \
1705 libdir=%{_libdir} \
1706 libexecdir=%{_libexecdir} \
1707 localstatedir=%{_localstatedir} \
1708 sharedstatedir=%{_sharedstatedir} \
1709 mandir=%{_mandir} \
1710 infodir=%{_infodir} \
1711';
1712
1713 # Note that the above regex terminates with the extra space
1714 # "Just In Case" of user additions, which will then get neatly
1715 # tagged on the end where they take precedence (supposedly)
1716 # over the "default" ones.
1717
1718 # Now we cascade the macros introduced above. >_<
1719 # Wot ot to go theah:
1720 $macrostring =~ s|%{_mandir}|%{_datadir}/man|g; #/usr/share/man
1721 $macrostring =~ s|%{_infodir}|%{_datadir}/info|g; #/usr/share/info
1722 $macrostring =~ s|%{_oldincludedir}|/usr/include|g; #/usr/include
1723 $macrostring =~ s|%{_includedir}|%{_prefix}/include|g; #/usr/include
1724 $macrostring =~ s|%{_libdir}|%{_exec_prefix}/%{_lib}|g; #/usr/lib
1725 $macrostring =~ s|%{_lib}|lib|g; #?
1726 $macrostring =~ s|%{_localstatedir}|/var|g; #/var
1727 $macrostring =~ s|%{_sharedstatedir}|%{_prefix}/com|g; #/usr/com WTF?
1728 $macrostring =~ s|%{_sysconfdir}|/etc|g; #/etc
1729 $macrostring =~ s|%{_datadir}|%{_prefix}/share|g; #/usr/share
1730 $macrostring =~ s|%{_libexecdir}|%{_exec_prefix}/libexec|g; #/usr/libexec
1731 $macrostring =~ s|%{_sbindir}|%{_exec_prefix}/sbin|g; #/usr/sbin
1732 $macrostring =~ s|%{_bindir}|%{_exec_prefix}/bin|g; #/usr/bin
1733 $macrostring =~ s|%{_exec_prefix}|%{_prefix}|g; #/usr
1734 $macrostring =~ s|%{_prefix}|/usr|g; #/usr
1735 } # done with config section
1736
1737 # Package data
1738 if ($section =~ /p/) {
1739 $macrostring =~ s/\%\{buildroot\}/$specglobals{buildroot}/gi;
1740 $macrostring =~ s/\%\{source0?}/$topdir\/SOURCES\/$pkgdata{main}{source}/gi;
1741 foreach my $source (keys %{$pkgdata{sources}}) {
1742 $macrostring =~ s/\%\{source$source\}/$topdir\/SOURCES\/$pkgdata{sources}{$source}/gi;
1743 }
1744 $macrostring =~ s/\%\{name\}/$pkgdata{main}{name}/gi;
1745 $macrostring =~ s/\%\{version\}/$pkgdata{main}{version}/gi;
1746 $macrostring =~ s/\%\{release\}/$pkgdata{main}{release}/gi;
1747 }
1748
1749 # Globals, and not-so-globals
1750 if ($section =~ /g/) {
1751
1752 $macrostring =~ s|%{_builddir}|%{_topdir}/BUILD|g;
1753 $macrostring =~ s|%{buildsubdir}|$tarballdir|g;
1754 $macrostring =~ s|%{_topdir}|$topdir|g;
1755 $macrostring =~ s|%{_tmppath}|$tmpdir|g;
1756 $macrostring =~ s'%{_docdir}'%{_datadir}/doc'g;
1757
1758 # Standard FHS locations. More or less.
1759 $macrostring =~ s'%{_bindir}'/usr/bin'g;
1760 $macrostring =~ s'%{_sbindir}'/usr/sbin'g;
1761 $macrostring =~ s'%{_mandir}'%{_datadir}/man'g;
1762 $macrostring =~ s'%{_infodir}'%{_datadir}/info'g;
1763 $macrostring =~ s'%{_includedir}'/usr/include'g;
1764 $macrostring =~ s'%{_libdir}'/usr/lib'g;
1765 $macrostring =~ s'%{_sysconfdir}'/etc'g;
1766 $macrostring =~ s'%{_localstatedir}'/var'g;
1767 $macrostring =~ s'%{_prefix}'/usr'g;
1768
1769 # FHS-ish locations that aren't quite actually FHS-specified.
1770 $macrostring =~ s'%{_datadir}'/usr/share'g;
1771
1772 # special %define's. Handle the general case where we eval anything.
1773 # Even more general: %(...) is a spec-parse-time shell code wrapper.
1774 # Prime example:
1775 #%define perl_vendorlib %(eval "`perl -V:installvendorlib`"; echo $installvendorlib)
1776 if ($macrostring =~ /\%\((.+)\)/) {
1777 my $shellstr = $1;
1778 # Oy vey this gets silly for the perl bits. Executing a shell to
1779 # call Perl to get the vendorlib/sitelib/whatever "core" globals.
1780 # This can do more, but... eww.
1781 $shellstr = qx { /bin/sh -c '$shellstr' }; # Yay! ' characters apparently get properly exscapededed.
1782 $macrostring =~ s/\%\(.+\)/$shellstr/;
1783 }
1784
1785 # support for **some** %if constructs. Note that this breaks somewhat if
1786 # there's no value specified... but so does rpm.
1787
1788 my $tmpcount = 0; # runaway shutdown. Not really sure how else to avoid getting stuck.
1789 while ($macrostring =~ m/\%\{([?!]+)([a-z0-9_.-]+)(?:\:([a-z0-9_.\/\-\\]+)?)?\}/g) { #Whew....
1790 my $qex = $1;
1791 my $macro = $2;
1792 my $value = (defined($3) ? $3 : '');
1793
1794 my $neg = '1' if $qex =~ /\!/;
1795 if ($specglobals{$macro}) {
1796 $value = '' if $neg;
1797 } else {
1798 $value = '' if !$neg;
1799 }
1800 $macrostring =~ s/\%\{[?!]+[a-z0-9_.-]+(?:\:([a-z0-9_.\/\-\\]+)?)?\}/$value/;
1801
1802# not certain about this, but I don't want to run away. It *can* happen if planned carefully. :/
1803$tmpcount++;
1804# %makeinstall has 13 occurrences. D'Oh!
1805die "excessive recursive macro replacement; dying.\n" if $tmpcount > 14;
1806
1807 } # while()
1808
1809 # Misc expansions
1810 $macrostring =~ s|%{_arch}|$hostarch|g;
1811 $macrostring =~ s|%{optflags}|$optflags{$hostarch}|g;
1812 $macrostring =~ s|%{_vendor}|$specglobals{'_vendor'}|g;
1813
1814 # system programs. RPM uses a global config file for these; we'll just
1815 # ASS-U-ME and make life a little simpler.
1816 if ($macrostring =~ /\%\{\_\_([a-z0-9_-]+)\}/) {
1817 $macrostring =~ s|%{__([a-z0-9_-]+)}|$1|g;
1818 }
1819
1820# should probably stick a "no runaway" flag in here... Just In Case...
1821 # %define's
1822# note to self: find out valid chars for %define name/label so we can parse them
1823 while (my ($key) = ($macrostring =~ /%{([a-z0-9_]+)}/i) ) {
1824# hrm. This needs thinking.
1825#die "A horrible death! \%{$key}, '$macrostring'\n" if !$specglobals{$key};
1826 $macrostring =~ s|%{$key}|$specglobals{$key}|g;
1827 # wanna limit this to "... if $specglobals{$key}", but need more magic
1828 }
1829
1830 # Perl @INC/...lib locations, and other related bits.
1831 $macrostring =~ s|%{perl_archlib}|$Config{installarchlib}|g;
1832 $macrostring =~ s|%{perl_sitelib}|$Config{installsitelib}|g;
1833 $macrostring =~ s|%{perl_sitearch}|$Config{installsitearch}|g;
1834 $macrostring =~ s|%{perl_vendorlib}|$Config{installvendorlib}|g;
1835 $macrostring =~ s|%{perl_vendorarch}|$Config{installvendorarch}|g;
1836
1837 } # done with globals section
1838
1839 return $macrostring;
1840} # end expandmacros()
1841
1842
1843
1844__END__
1845
1846
1847
1848=head1 NAME
1849
1850debbuild - Build Debian-compatible .deb packages from RPM .spec files
1851
1852=head1 SYNOPSIS
1853
1854 debbuild {-ba|-bb|-bp|-bc|-bi|-bl|-bs} [build-options] file.spec
1855
1856 debbuild {-ta|-tb|-tp|-tc|-ti|-tl|-ts} [build-options] file.tar.{gz|bz2|xz}
1857
1858 debbuild --rebuild file.{src.rpm|sdeb}
1859
1860 debbuild --showpkgs
1861
1862=head1 DESCRIPTION
1863
1864debbuild attempts to build Debian-friendly semi-native packages from RPM spec files,
1865RPM-friendly tarballs, and RPM source packages (.src.rpm files). It accepts I<most> of the
1866options rpmbuild does, and should be able to interpret most spec files usefully. Perl
1867modules should be handled via CPAN+dh-make-perl instead as it's simpler than even tweaking
1868a .spec template.
1869
1870As far as possible, the command-line options are identical to those from rpmbuild, although
1871several rpmbuild options are not supported:
1872
1873 --recompile
1874 --showrc
1875 --buildroot
1876 --clean
1877 --nobuild
1878 --rmsource
1879 --rmspec
1880 --sign
1881 --target
1882
1883Some of these could probably be trivially added. Feel free to send me a patch. ;)
1884
1885Complex spec files will most likely not work well, if at all. Rewrite them from scratch -
1886you'll have to make heavy modifications anyway.
1887
1888If you see something you don't like, mail me. Send a patch if you feel inspired. I don't
1889promise I'll do anything other than say "Yup, that's broken" or "Got your message".
1890
1891=head1 ASSUMPTIONS
1892
1893As with rpmbuild, debbuild makes some assumptions about your system.
1894
1895=over 4
1896
1897=item *
1898
1899Either you have rights to do as you please under /usr/src/debian, or you have created a file
1900~/.debmacros containing a suitable %_topdir definition.
1901
1902Both rpmbuild and debbuild require the directories %_topdir/{BUILD,SOURCES,SPECS}. However,
1903where rpmbuild requires the %_topdir/{RPMS,SRPMS} directories, debbuild
1904requires %_topdir/{DEBS,SDEBS} instead. Create them in advance;
1905some subdirectories are created automatically as needed, but most are not.
1906
1907=item *
1908
1909/var/tmp must allow script execution - rpmbuild and debbuild both rely on creating and
1910executing shell scripts for much of their functionality. By default, debbuild also creates
1911install trees under /var/tmp - however this is (almost) entirely under the control of the
1912package's .spec file.
1913
1914=item *
1915
1916If you wish to --rebuild a .src.rpm, your %_topdir for both debbuild and rpmbuild must either
1917match, or be suitably symlinked one direction or another so that both programs are effectively
1918working in the same tree. (Or you could just manually wrestle files around your system.)
1919
1920You could symlink ~/.rpmmacros to ~/.debmacros (or vice versa) and save yourself some hassle
1921if you need to rebuild .src.rpm packages on a regular basis. Currently debbuild only uses the
1922%_topdir macro definition, although there are many more things that rpmbuild can use from
1923~/.rpmmacros.
1924
1925=back
1926
1927=head1 ERRATA
1928
1929debbuild deliberately does a few things differently from rpm.
1930
1931=head2 BuildArch or BuildArchitecture
1932
1933rpm takes the last BuildArch entry it finds in the .spec file, whatever it is, and runs with
1934that for all packages. Debian's repository system is fairly heavily designed around the
1935assumption that a single source package may generate small binary (executable) packages
1936for each arch, and large binary arch-all packages containing shared data.
1937
1938debbuild allows this by using the architecture specified by (in order of preference):
1939
1940=over 4
1941
1942=item * Host architecture
1943
1944=item * BuildArch specified in .spec file preamble
1945
1946=item * "Last specified" BuildArch for packages with several subpackages
1947
1948=item * BuildArch specified in the %package section for that subpackage
1949
1950=back
1951
1952=head2 Finding out what packages should be built (--showpkgs)
1953
1954rpmbuild does not include any convenient method I know of to list the packages a spec file
1955will produce. Since I needed this ability for another tool, I added it.
1956
1957It requires the .spec file for the package, and produces a list of full package filenames
1958(without path data) that would be generated by one of --rebuild, -ta, -tb, -ba, or -bb.
1959This includes the .sdeb source package.
1960
1961=head1 AUTHOR
1962
1963debbuild was written by Kris Deugau <kdeugau@deepnet.cx>. A version that approximates
1964current is available at http://www.deepnet.cx/debbuild/.
1965
1966=head1 BUGS
1967
1968Funky Things Happen if you forget a command-line option or two. I've been too lazy to bother
1969fixing this.
1970
1971Many macro expansions are unsupported or incompletely supported.
1972
1973The generated scriptlets don't quite match those from rpmbuild exactly. There are extra
1974environment variables and preprocessing that I haven't needed (yet).
1975
1976Dcumentation, such as it is, will likely remain perpetually out of date.
1977
1978%_topdir and the five "working" directories under %_topdir could arguably be created by
1979debbuild. However, rpmbuild doesn't create these directories either.
1980
1981=head1 SEE ALSO
1982
1983rpm(8), rpmbuild(8), and pretty much any document describing how to write a .spec file.
1984
1985=cut
Note: See TracBrowser for help on using the repository browser.