В началоEbuild HOWTO (Англ.) → Ebuild scripts
Gentoo-doc HOME Пред.: Ebuild HOWTO (Англ.)В началоУровень выше: Ebuild HOWTO (Англ.)След.: File system Locations

2. Ebuild scripts

2.1. 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.

2.2. Naming ebuild files

Ebuild file names consist of four logical subsections:

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

Примечание

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.

Важно

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 Gentoo Linux 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 suppose that we actually have a fifth section of the ebuild name as well – the .ebuild extension itself.

2.3. 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.

2.3.1. 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:

Листинг 2. Valid Header

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


2.3.2. Variables

The first part of every ebuild file is made up of a number of variables. They fall under 3 categories (and are marked below):

  1. READ: variables you can utilize but never set

  2. MUST: variables you must always set

  3. OPT: variables that you should set

Variable Usage Description
P READ The name and version of the package.
PN READ The name of the package.
PV READ The version of the package.
PR READ Contains the revision number or r0 if no revision number exists.
PVR READ Contains the version number with the revision.
PF READ Contains the full package name ${PN}-${PVR}.
A READ Space delimited list of the filenames in SRC_URI. This does not contain the URL paths, just the filename.
DISTDIR READ Contains the path to the distfiles directory where all the files fetched for a package are stored. Typically, this is /usr/portage/distfiles.
FILESDIR READ Contains the path to the files sub folder in the package specific location in the portage tree. Do not modify this variable.
WORKDIR READ Base of the build root for the ebuild. Nothing should be built outside of this directory.
S OPT The source directory for your package; commonly ${WORKDIR}/${P}. Portage will default to this value so you may not have to set it!
T READ The temporary directory for your package. It is used as a virtual /tmp directory while processing the ebuild.
D READ The root directory that the package is installed to, treat it as the virtual /.
SLOT MUST Portage handles different versions of the same installed programs. If you would want, say GCC 2.95 and GCC 3.2 installed at the same time, you would specify the SLOT in each ebuild. Here we would set the SLOT of GCC 2.95 to 2 while we would set the SLOT of GCC 3.2 to 3. Note: Using 0 as the SLOT value signifies that this package only has 1 SLOT setting (in other words, this package is not SLOTable).
LICENSE MUST This variable specifies what license the program is covered under, i.e. GPL-2, BSD, etc... This field must be set to a valid license (which is any license found in /usr/portage/license/). If the license does not already exist there, it must be added before the ebuild can be added to the portage tree. If the license does not allow redistribution, make sure you place RESTRICT="nomirror" in the ebuild.
KEYWORDS MUST This variable now supports a couple of different functions. First of all, this variable specifies what architecture the ebuild is meant for. Some example keywords include: x86, ppc, sparc, mips, alpha, arm, hppa, amd64 and ia64. See the profiles/arch.list file in the Portage tree for more details. Obviously, you would set this to reflect the architecture of the target machine. Portage will not allow an x86 machine to build anything but x86, as specified by the KEYWORDS variable. Packages that do not support the native architecture are automatically masked by Portage. If the KEYWORDS flag has a preceding ~, then that indicates that the particular ebuild works, but needs to be tested in several environments before being moved to the stable profile with the given keyword. If the KEYWORDS flag has a preceding -, then the package does not work with the given keyword. If there is nothing leading KEYWORDS, then the package is considered stable. You can allow installation of these different types of packages through the ACCEPT_KEYWORDS variable in make.conf.
DESCRIPTION MUST A short, one line description of your package.
SRC_URI MUST The URLs for every source file in your package, separated by whitespace. You should try not to include version numbers in the SRC_URI and S. Always try to use ${PV} or ${P}, and if a version number is not consistent with the name of the source package, make a ${MY_P} variable and use that instead.
HOMEPAGE MUST The homepage of the package. If you are unable to locate an official one, try to provide a link from freshmeat.net or a similar package tracking site. Never refer to a variable name in the string; include only raw text.
IUSE MUST This is set to whatever USE variables your package utilizes. Remember that KEYWORDS should not be listed in here!
DEPEND OPT The package's build dependencies are listed here. See the section Package Dependencies for more details on proper syntax.
RDEPEND OPT The package's runtime dependencies are listed here. Once again, see Package Dependencies for more details.

2.3.3. 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}.

2.3.4. 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 The same as use_with, but returns "--enable-foobar" or "--disable-foobar" accordingly.
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 Issues make install with the necessary path-changes (prefix, datadir, mandir, infodir, datadir, sysconfdir, localstatedir). Again, you can pass extra arguments to the make command by specifying them when you call einstall. Please note that the preferred way to install a package is via the emake install DESTDIR="${D}" command and not via einstall. This command is only a fall back to override broken make files.
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.

2.3.5. 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.

Function Purpose
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 (R).
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.

2.3.6. 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.

Function

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. Replace a given mtune/mcpu/mtune value with the new one (maybe like this: replace-cpu-flags 'i686' 'i586' will replace -mtune/-march/-mcpu=i686 with -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 variable.
filter-ldflags Removes the specified flags from LDFLAGS, only complete flags are matched.
fstack-flags Appends -fno-stack-protector which suppresses -fstack-protector and -fstack-protector-all.

2.3.7. 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 to specify compilers and binutils.

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.

Function

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/object inspection tool
tc-getRANLIB Returns the name of the archiver 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 simple 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 Returns the Minor version
gcc-micro-version Returns the Micro version

2.4. 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:

Листинг 3. Wrapping lines in ebuilds

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


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

If you use Vim for ebuild/eclass editing, the default Gentoo vimrc file, /etc/vim/vimrc, already ensures that correct indentation and filetype settings are used for ebuild and eclass files. For better results, including special syntax highlighting for ebuild keywords, emerge app-vim/gentoo-syntax.

On non-Gentoo systems, you can obtain similar results by using the following lines in your vimrc, or better yet by installing the gentoo-syntax scripts which can be downloaded from Gentoo mirrors.

Листинг 4. Configuring vimrc for ebuild-editing

au BufRead,BufNewFile *.e{build,class} let is_bash=1|setfiletype sh
au BufRead,BufNewFile *.e{build,class} set ts=4 sw=4 noexpandtab


If you're using Emacs, you should emerge app-emacs/gentoo-syntax (for GNU Emacs) or app-xemacs/gentoo-syntax (for XEmacs). These packages provide Emacs major modes for automatic indentation and syntax highlighting of ebuilds and other Gentoo specific file types.

If you're using nano, then you're in luck! Just edit /etc/nanorc and uncomment the section referring to ebuild's.

2.5. USE Variables

The purpose of USE variables is to allow you to configure Portage to globally and automatically enable or disable certain optional build-time features. Here's an example. Let's say you're a GNOME fan, and you'd like any ebuild that has the option of compiling-in optional GNOME support to do so. In this case, you'd add gnome to the USE variable in /etc/make.conf, and then Portage will automatically add optional GNOME functionality to packages if it is available. Likewise, if you don't want optional GNOME features to be added to your ebuilds if they are available, simply edit /etc/make.conf and make sure that gnome is not set in the USE variable. Gentoo Linux has an almost overwhelming number of USE options, allowing you to have your system configured exactly the way you want it.

Примечание

Note: If you unset a USE variable (for example, removing gnome from USE), this will only instruct Portage to disable optional build-time support for GNOME. However, if you emerge an ebuild that requires GNOME, the package will obviously have GNOME support enabled, as you would expect. This also means that GNOME will be automatically installed (as a dependency) if it hasn't been already. That's why it's always a good idea to do an emerge --pretend before doing the "real" emerge; that way, you'll always know exactly what you're going to get!

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:

Листинг 5. Finding out if a USE-flag is set

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:

Листинг 6. Conditionals based on USE-settings

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!"
}


This approach has a very nice result. We don't have to worry about what the default setting is for mysql or X (enable/disabled), we explicitly tell econf what we want it to do based upon the USE variable. Not to mention it's quite clean in terms of readability :).

Occasionally, ebuilds will have conflicting optional features. Checking for these conflicts and returning an error is not a viable solution. Instead, you must favor one of the features over the others. As to which, consult upstream (what they use as typical default), or consider which option provides more common functionality, or just flip a coin. One example comes from the msmtp ebuilds. The package can use either SSL with GnuTLS, SSL with OpenSSL, or no SSL at all. Because GnuTLS has a lot more features compared to OpenSSL, it is favoured:

Листинг 7. Handling conflicting features

src_compile() {
    local myconf

    if use gnutls ; then
        myconf="${myconf} --enable-ssl --with-ssl=gnutls"
    elif use ssl ; then
        myconf="${myconf} --enable-ssl --with-ssl=openssl"
    else
        myconf="${myconf} --disable-ssl"
    fi

    econf \
        # Other stuff
        ${myconf} \
        || die "configure failed"

    emake || die "make failed"
}


To view a continuously updated table of USE variables, please go here.

Пред.: Ebuild HOWTO (Англ.)В началоУровень выше: Ebuild HOWTO (Англ.)След.: File system Locations
В началоEbuild HOWTO (Англ.) → Ebuild scripts