3.10 Ebuild scripts

Introduction

Ebuild scripts are the basis for the entire Portage system. They contain all the information required to download, unpack, compile and install a set of sources, as well as how to perform any optional pre/post install/removal or configuration steps. While most of Portage is written in Python, the ebuild scripts themselves are written in bash, since using bash allows us to call commands as we would from the command-line. One of the important design principles behind ebuild scripts is to have the commands therein be analogs of those one would type on the command-line if installing the package manually. For this purpose, using bash syntax is a very good thing.

Ebuild scripts are interpreted by the ebuild and emerge commands. Think of the ebuild command as a low-level building tool. It can build and install a single ebuild, but no more. It will check to see if dependencies are satisfied, but it will not attempt to auto-resolve them. On the other hand emerge is a high level engine for ebuild, and has the ability to auto-merge dependencies if needed, perform pretend merges so that user can see what ebuilds would be merged, and more. Generally, emerge blows ebuild out of the water except in one area. With ebuild, you can incrementally step through the various parts of a package emerge (fetching, unpacking, compiling, installing and merging) one at a time. For developers, this is an invaluable debugging tool, because it allows you to isolate ebuild problems to a specific portion of the ebuild.

Naming ebuild files

Ebuild file names consist of four logical subsections:

pkg-ver{_suf{#}}{-r#}.ebuild

Note: The brackets ({}) delineate optional fields and do not appear in the literal package name. # represents any non-zero positive integer.

The first subsection, pkg, is the package name, which should only contain lowercase letters, the digits 0-9, and any number of single hyphen (-), underscore (_) or plus (+) characters. Examples: util-linux, sysklogd and gtk+. We have some packages in Portage that don't follow these rules, but your packages should.

The second subsection, ver, is the version of the package, which should normally be same as the version on the main source tarball. The version is normally made up of two or three (or more) numbers separated by periods, such as 1.2 or 4.5.2, and may have a single letter immediately following the last digit; e.g., 1.4b or 2.6h. The package version is joined to the package name with a hyphen. For example: foo-1.0, bar-2.4.6.

Important: If you're thinking of using a trailing letter in your version string, note that the trailing letter should not be used to signify alpha or beta status for the package, since alphas and betas are prereleases and letter revisions are newer versions. This is an important distinction because Portage uses an ebuild's version number to determine if it is newer or older than other packages with the same category and name. It's very important that version numbers faithfully represent the version of the package so that Portage properly performs its dependency checking duties.

The third subsection, {_suf{#}}, is optional may contain one of these predefined suffixes, listed in least-recent to most-recent order:

Suffix Meaning
_alpha Alpha release
_beta Beta release
_pre Prerelease
_rc Release candidate
(none) Normal release
_p Patch level (normally accompanied by trailing integer)

Any of these suffixes may be immediately followed by a non-zero positive integer, e.g., linux-2.4.0_pre10. Assuming identical version parts, the suffixes are ordered as follows (lower means older): _alpha < _beta < _pre < _rc < (no suffix) < _p.

When comparing identical suffixes with trailing integers, the one with the larger integer will be considered most recent. Example: foo-1.0_alpha4 is more recent than foo-1.0_alpha3.

The fourth subsection of the package name is the Gentoo Linux-specific revision number, {-r#}. This subsection, like the suffix, is also optional. # is a non-zero positive integer; e.g., package-4.5.3-r3.

This revision number is independent of the version of the source tarball and is used to inform people that a new and improved revision of a particular package is available. Initial releases of ebuilds must have no revision number; e.g., package-4.5.3 and are considered by Portage to have a revision number of zero. This means that counting goes as follows: 1.0 (initial version), 1.0-r1, 1.0-r2, etc.

If you make non-trivial improvements to an existing ebuild file, you should copy the ebuild file to a new file with the revision number incremented by 1. Remember to always make mentions of your changes in the ChangeLog when you bump a revision and in your CVS commit message; not doing so is against policy.

... and I we actually have a fifth section of the ebuild name as well – the .ebuild extension itself.

Contents of an ebuild file

This section is an introduction to ebuilds. For the full listing of everything possible in an ebuild, there is a manpage which talks about the internal format, variables, and functions in an ebuild script: man 5 ebuild.

Headers

When you submit your ebuilds, the header should be exactly the same as the one in /usr/portage/header.txt. Most importantly, do not modify it in anyway and make sure that the $Header: $ line is intact.

The first three lines should look something like this:

# Copyright 1999-2005 Gentoo Foundation
# Distributed under the terms of the GNU General Public License v2
# $Header: $

Variables

The first part of every ebuild file is made up of a number of variables. See the development guide to learn more.

Functions

There are a number of different functions that you can define in ebuild files that control the building and installation process of your package.

Function Purpose
pkg_setup Use this function to perform any miscellaneous prerequisite tasks. This might include checking for an existing configuration file.
pkg_nofetch Inform the user about required actions if for some reason (such as licensing issues) the sources may not be downloaded by Portage automatically. Use this in conjunction with RESTRICT="fetch". You only should display messages in this function, never call die.
src_unpack Use this function to unpack your sources, apply patches, and run auxiliary programs such as the autotools. By default, this function unpacks the packages listed in A. The initial working directory is defined by WORKDIR.
src_compile Use this function to configure and build the package. The initial working directory is S.
src_install Use this function to install the package to an image in D. If your package uses automake, you can do this simply with emake DESTDIR="${D}" install. Make sure your package installs all its files using D as the root! The initial working directory is S.
src_test Executed only when FEATURES="test" is set and RESTRICT="test" is unset, the default of this function executes an available testing function from any Makefiles in the ${S} directory, running either "make test" or "make check" depending on what is provided. It can be overriden to create a custom test setup.
pkg_preinst The commands in this function are run just prior to merging a package image into the file system.
pkg_postinst The commands in this function are run just following merging a package image into the file system.
pkg_prerm The commands in this function are run just prior to unmerging a package image from the file system.
pkg_postrm The commands in this function are run just following unmerging a package image from the file system.
pkg_config You use this function to setup an initial configuration for the package after it's installed. All paths in this function should be prefixed with ROOT which points to user-specified install root which may not happen to be /. This function is only executed if and when the user runs: emerge --config =${PF}.

Helper functions

You can also use the following helper functions in your ebuilds.

Function Purpose
use Check if one or more given USE-flags are defined. If so, the function will return shell true. In either case, nothing is echoed to standard output. For a verbose version, please use usev which will echo the USE flag if it is defined.
has_version Returns 1 if the system has the requested version of a certain package. For instance has_version >=sys-libs/glibc-2.3.0.
best_version Returns category/package-version of the requested category/package. For instance best_version x11-libs/gtk+extra.
use_with This function checks if a USE flag has been defined and returns "--with-foobar" or "--without-foobar" accordingly. If you only use one argument, that argument is both use-flag and with(out)-string. Otherwise the first argument is the use-flag and the second argument the with(out)-string. For instance use_with truetype freetype will echo "--with-freetype" if truetype is in USE.
use_enable
check_KV Checks if Portage knows kernel version. If not, display an error and die. If you need the kernel version in your script, use the KV variable which is automatically defined by Portage. On a system running gentoo-sources-2.4.20-r6, KV would have the value "2.4.20".
keepdir Creates (if necessary) a .keep file in the given directory so that it isn't auto-cleaned. Never create a .keep file yourself. If Portage changes how keepdir works, then creating the file yourself will break the package.
econf Issues ./configure with the necessary path-changes (prefix, host, mandir, infodir, datadir, sysconfdir, localstatedir). You can optionally pass extra arguments to ./configure by specifying them when you call econf, and users can set the environment variable EXTRA_ECONF if they need to. Options passed to configure take precedence in the reverse order that they were given. In other words, the first argument passed will always be overridden by the last.
einstall
die Causes the current process to be aborted. It will notify the user using the given arguments as a reason. Do not neglect to pass a message to die if you have more than one call to it in a single function. It is harder to track down a failure if you're not sure where the package failed.
elog Inform the user about something important. The argument given to elog is the message that the user will see. Do not use elog to display banners such as "*****************". The fact that you're using elog is enough to get the user's attention. The message is also logged using portages ELOG system.
einfo Display informative but non-important messages that don't need to be logged.

Helper functions provided by eutils.eclass

You can use the following helper functions that are provided by the eutils eclass in your ebuilds. You must make sure that inherit eutils is present for these functions to work.

Fonction Objectif
epatch This function acts as a friendlier replacement to the patch command and epatch works with .bz2, .gz, .zip and plain text patches. You do not need to specify a -p option, any options that do need to be explicitly specified should be set in EPATCH_OPTS. The function expects either a file or a directory as an argument – if you specify a directory, all patches in the form of "??_${ARCH}_..." will be applied: for a patch to be applied, it needs to match the running architecture, have "_all_" in the name, or EPATCH_FORCE must be set to "yes".
gen_usr_ldscript This function generates linker scripts in /usr/lib for dynamic libraries in /lib. This fixes linking problems when a .so is in /lib while a .a is in /usr/lib.
edos2unix This function performs the same action as the dos2unix binary.
egetent egetent acts as a wrapper for getent for Linux or nidump for Mac OS X.
enewuser Creates a new user. This function expects a mandatory argument with the username, and several optional arguments can be specified: $2 contains a UID, pass -1 for the next available ID; $3 contains the shell, pass -1 for the default; $4 contains a home directory with /dev/null being the default, $5 contains any groups to which the user should be added, empty by default, and $6 contains any extra options that you may wish to pass to useradd.
enewgroup Adds a new group. This function expects a mandatory argument with the group name – an optional second argument makes the group have a specific GID.
make_desktop_entry Makes a desktop entry: the first argument contains the path to the binary. Optionally, the second contains a name for the icon – the default is ${PN}; the third can contain a path to the icon relative to /usr/share/pixmaps or a full path – the default is ${PN}.png; the fourth can contain an application category, and the fifth argument contains an optional application startup path.
check_license Displays a license for the user to accept, if no arguments are specified then the license specified by ${LICENSE} is used.
unpack_pdv Unpacks a pdv generated archive, the first argument must contain the file to unpack and the second should contain "off_t" which has to be manually generated: strace -elseek ${file} and for something like "lseek(3, -4, SEEK_END)" you would pass the value "4".
unpack_makeself Unpacks a makeself generated archive, requires a file to unpack as the argument.
cdrom_get_cds Attempts to get a CD, present with files specified by the arguments present on the system and mounted at ${CDROM_ROOT}.
cdrom_load_next_cd Loads the next CD once you are done with the first CD. If the function returns, ${CDROM_ROOT} would point to the next CD.
strip-linguas This function makes sure that LINGUAS contains only the languages that a package can support specified by the arguments to the function. If the first argument is -i, then a list of .po files in the specified directories is built and the intersection of the lists is used. If the first argument is -u, then a list of .po files in the specified directories is built and the union of the lists is used.

Helper functions provided by flag-o-matic.eclass

You can use the following helper functions that are provided by the "flag-o-matic" eclass in your ebuilds. You must make sure that inherit flag-o-matic is present for these functions to work. You should never modify any compiler settings directly, instead please use flag-o-matic to perform any actions such as filtering flags that cause trouble.

Fonction Purpose
filter-flags This function removes particular flags from C[XX]FLAGS – only complete flags are matched.
append-flags This function adds extra flags to the existing C[XX]FLAGS variables.
replace-flags This replaces the flag specified by the first argument with the one in the second argument in the current C[XX]FLAGS.
replace-cpu-flags Needs two arguments. Replaces a given mtune/mcpu/mtune value with the new one mtune/march/mcpu (for instance, "replace-cpu-flags 'i686' 'i586'" will replace "-mtune/-march/-mcpu=i686" par "-mtune/-march/-mcpu=i586").
strip-flags Strips all flags, except those specified in ALLOWED_FLAGS.
strip-unsupported-flags Strips C[XX]FLAGS of any flags not supported by the running version of GCC.
get-flag Finds a flag and outputs its value.
is-flag This returns true if the flag is set in the current C[XX]FLAGS; only complete matches are performed.
append-ldflags This function adds extra flags to the existing LDFLAGS function.
filter-ldflags Removes the specified flags from LDFLAGS, only complete flags are matched.
fstack-flags Appends -fno-stack-protector, which suppressed -fstack-protector and -fstack-protector-all.

Helper functions provided by toolchain-funcs.eclass

You can use the following helper functions that are provided by the "toolchain-funcs" eclass in your ebuilds. You must make sure that inherit toolchain-funcs is present for these functions to work. You should never explicitly specify any compiler or binutils settings directly, instead please use toolchain-funcs.

The purpose of using the below functions is to support cross-compiling and the ICC compiler. These should be used whenever a package explicitly uses gcc, g++, ld, ranlib or any of the below tools. In general packages that use autoconfiguration tools detect cross compiling automatically and do not need the following functions.

Fonction Purpose
tc-getAR Returns the name of the archiver.
tc-getAS Returns the name of the assembler.
tc-getCC Returns the name of the C compiler.
tc-getCXX Returns the name of the C++ compiler.
tc-getLD Returns the name of the linker.
tc-getNM Returns the name of the symbol inspection tool.
tc-getRANLIB Returns the name of the archive indexer.
tc-getF77 Returns the name of the Fortran compiler.
tc-getGCJ Returns the name of the Java compiler.
tc-getBUILD_CC Returns the name of the C compiler for build.
tc-is-cross-compiler A way to see if we're using a cross-compiler.
gcc-fullversion Returns the version as by $($CC -dumpversion).
gcc-version Returns the version, but only the <major>.<minor>
gcc-major-version Returns the major version.
gcc-minor-version Returne the minor version.
gcc-micro-version Returns the micro version.

Rules for writing an ebuild file

Since ebuild files are really just shell scripts, you should use your editor's shell-script mode for editing them. You should use proper indentation, using only tab characters – no spaces. Make sure you set up your editor to put tab stops at 4 spaces. Always make sure you use braces around your environment variables; e.g. ${P} instead of just $P.

Long lines are wrapped with "\", thus:

./configure \
--prefix=/usr || die "configure failed" 

For further details, refer to skel.ebuild (usually residing in /usr/portage).

USE variables

In your own ebuilds, you can check whether a USE variable is set by using the use <variable> command. You would normally use this command as follows:

if use X; then
  # Commands specific to X...
fi

USE variables can also be used to set dependencies. For example, you may only want to require a package if a certain USE variable is set. This is done by using the syntax flag? ( mycat/mypackage ) in the DEPEND variable for your ebuild. In this example, mycat/mypackage will only be required if flag is present in USE. It is also possible to specify what dependency should be used if some USE flag is set, and what dependency to use if it is not set: flag? ( mycat/mypackage) and !flag? ( othercat/otherpackage ). In this case, if flag is not set, othercat/otherpackage is used instead of mycat/mypackage. Make sure that your ebuilds use this syntax and not Bash IFS. Bash conditionals interfere with Portage's dependency caching, and the use of them will break your ebuild.

Here's an important tip about how to use USE. Most of the time, a package will have a ./configure script used to perform configuration steps. Generally, if your ebuild uses ./configure, any optional build-time functionality will be enabled or disabled by passing the appropriate arguments to the ./configure command. Here's the best way to handle this:

DEPEND="X?       ( >=x11-base/xfree-4.3 )
       mysql?    ( >=dev-db/mysql-3.23.49 )
       apache2?  ( >=net-www/apache-2 )
       !apache2? ( =net-www/apache-1* )" 

src_compile() {
  econf \
    $(use_enable X x11) \
    $(use_enable mysql) \
    || die "Error: econf failed!" 
  emake || die "Error: emake failed!" 
}
Thank you!