Ebuild HOWTO (Англ.)

Ссылка на оригинал: http://www.gentoo.org/proj/en/devrel/handbook/handbook.xml?part=2&chap=1

С версии: 1.4



1.a. The Portage tree

Introduction

The Portage tree is typically found at /usr/portage and is organized in a hierarchical structure consisting of category directories, followed by specific package directories. Here's an example; you can find the util-linux-2.11y.ebuild file in the /usr/portage/sys-apps/util-linux directory. There may be several other versions of util-linux ebuilds alongside util-linux-2.11y.ebuild. This is because all ebuilds for a particular package (regardless of version), share the same mycat/mypkg directory in /usr/portage.



Checking Out the Portage Tree from CVS



If you are unfamiliar with the CVS system, please read the CVS Tutorial for more information.

The Portage tree can be found in the gentoo-x86 module of the Gentoo Linux tree. To check out the module (about 350 megabytes) you would first set up CVS via the above guide, then check out the gentoo-x86 module.



What (not) to put in the Portage tree



Before writing a new ebuild, check bugs.gentoo.org to see if an ebuild has already been written for the package, but has not yet been added to the Portage tree. Go to bugs.gentoo.org, choose query and select Advanced Search; as product select Gentoo Linux, as component select ebuilds. In the search field put the name of the ebuild and as status select NEW, ASSIGNED, REOPENED and RESOLVED (RESOLVED is important), then submit the query. For you lazy people, click here.

In general, the Portage tree should only be used for storing .ebuild files, as well as any relatively small companion files, such as patches or sample configuration files. These types of files should be placed in the /usr/portage/mycat/mypkg/files directory to keep the main mycat/mypkg directory uncluttered. Exceptions to this rule are for larger patch files (we recommend this for patches above 20KB) which should be put onto the Gentoo mirrors so that people do not waste excessive amounts of bandwidth and hard drive space. Also, you should not add binary (non-ASCII) files to the Portage CVS tree. If you need to do this in another CVS tree, for example, if you need to add a small PNG graphic for whatever reason, be sure to add it to CVS by using the -kb option, like so:

Code Listing 1.1: Adding binary files to CVS

# cvs add -kb myphoto.png

The -kb option tells CVS that myphoto.png is a binary file and should be treated specially. For example, merging the differences between two different versions of this file should not be allowed to happen, for obvious reasons. Also, speaking of merging changes, any patches you add to Portage should generally not be compressed. This will allow CVS to merge changes and correctly inform developers of conflicts.

Remember, the packages that you commit must be ready out of the box for end users when committed as stable. Make sure that you have a good set of default settings that will satisfy the majority of systems and users that will use your package. If your package is broken, and you are not sure how to get it to work, check some other distributions that have done their own versions of the package. You can check Mandriva or Debian or Fedora for some examples.

When committing to CVS, all developers should use repoman commit instead of cvs commit to submit their ebuilds. Before committing, please run repoman full to make sure you didn't forget something.

CVS Commit Policy

The files Directory

As noted earlier, under each package subdirectory is a files/ directory. Any patches, configuration files, or other ancillary files your package might require should be added to this directory; any files bigger than 20KB-or-so should go to the mirrors to lower the amount of (unneeded) files our users have to download. You may want to consider naming patches you create yourself just to get your package to build with a version-specific name, such as mypkg-1.0-gentoo.diff, or more simply, 1.0-gentoo.diff. Also note that the gentoo extension informs people that this patch was created by us, the Gentoo Linux developers, rather than having been grabbed from a mailing list or somewhere else. Again, you should not compress these patches because CVS does not play well with binary files.

Consider prefixing or suffixing (such as mypkg-1.0) every file you put into the files/ directory, so that the files used for each individual version on an ebuild are distinguishable from one another, and so that the changes between different revisions are visible. This is generally a really good idea :). You may want to use a different suffix if you wish to convey more meaning with the patch name.

If you have many files that should go into the files/ directory, consider creating subdirectories such as files/1.0/ and putting the relevant files in the appropriate subdirectory. If you use this method, you do not need to add version information to the names of the files, which is often more convenient.

1.b. 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 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.

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:

Code Listing 2.1: Valid Header

# 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. They fall under 3 categories (and are marked below):

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.



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

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.



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.



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.

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

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:

Code Listing 2.2: 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.

Code Listing 2.3: 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.

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:

Code Listing 2.4: 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:

Code Listing 2.5: 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:

Code Listing 2.6: 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.

1.c. File system Locations

Introduction to the FHS

The file system layout standards used in Gentoo Linux closely follow the FHS, short for File system Hierarchy Standard. A simplified description of the standard is given here; for a complete specification go to http://www.pathname.com/fhs/.

Note: The /opt hierarchy is addressed in section 3.12 of the FHS. Section 4.4 deals with the /usr/X11R6 directory. KDE and GNOME are not specifically addressed, and are in fact not even mentioned in the current version of the FHS.



How to fit your packages into the file system

Usually, if the package uses autoconf and automake, the default installation destinations are mostly correct, with a few exceptions:

Important: Some distributions choose to install GNOME and KDE into /opt. There exists no standard for these desktop environments in terms of where to actually install their files. In the interests of simplicity and consistency, we elect to install all KDE and GNOME packages into the /usr hierarchy.

In general, you should have ebuilds install their files into the /usr tree. Some programs can be compiled and linked with or without GNOME, KDE, and X11 libraries, which can cause confusion. Our solution is to install everything into /usr which avoids ambiguity and needless complexity for ebuild authors. The location in which to install a program's files should not depend on the presence or absence of specific USE variables. Therefore, the ebuilds in the portage tree almost always install into the /usr hierarchy exclusively.

Note: The /opt directory is reserved in Gentoo Linux for binary-only packages. Examples include mozilla-bin, acroread, netscape and realplayer. Packages that get installed here will usually require a /etc/env.d/foo stub file. This is so that paths and additional variables can be included into the environment. For more information on /etc/env.d, please visit this document.

1.d. The Portage scripts and utilities

Public scripts

These are scripts used by the system-administrator to install and remove packages, and maintain the package database.

ebuild is the main engine of the Portage system; it performs all major tasks such as unpacking, compiling, installing, merging, and unmerging packages. It is called using the command: ebuild path/to/package.ebuild command. The commands available are:

Command

Description

Related ebuild Function

setup*

Performs any miscellaneous commands required before the ebuild can proceed

pkg_setup

depend

Displays the dependencies required to build the package

N/A

merge*

Unpacks, compiles, installs, and merges the package into your file system

N/A

qmerge*

Merges the package into your file system, assuming that the unpack, compile, and install stages have already been executed

N/A

unpack*

Unpacks the source tarballs into the work directory

src_unpack

compile*

Compiles the package

src_compile

rpm

Creates an RPM from the package

N/A

package

Creates a Gentoo tbz2 package

N/A

prerm*

Executes the pre-removal stage of the package

pkg_prerm

postrm*

Executes the post-removal stage of the package

pkg_postrm

preinst*

Executes the pre-installation stage of the package

pkg_preinst

postinst*

Executes the post-installation stage of the package

pkg_postinst

config

Sets up a default configuration once the package is merged

pkg_config

touch*

Updates the mtimes for each source archive in the package

N/A

clean*

Cleans the work directory for the package

N/A

fetch*

Fetches the package source tarballs

N/A

digest*

Creates a digest file for the package

N/A

test*

Runs the self-test routine for the package

src_test

install*

Installs the package into the image directory

src_install

unmerge

Unmerges the package from your file system

N/A

Note: Commands with an asterisk (*) are normally only used by the developer.

emerge recursively merges a package and all of its dependencies into your file system. This command has many options, try emerge --help for a list of them.

env-update updates the configuration files (including, but not limited to /etc/ld.so.conf and /etc/profile.env) to include changes made by installed packages.

Private Scripts and Commands

These are scripts you can use in your ebuild files to perform common tasks.

For you down and dirty people, look at the scripts themselves in /usr/lib/portage/bin.

Command

Default Value

Description

Example

diropts

-m0755

Sets the options used when running dodir

diropts -m0750

dobin

N/A

Installs the specified binaries into DESTTREE/bin

dobin wmacpi

docinto

""

Sets the relative subdir used by dodoc

docinto examples

dodir

N/A

Creates a directory, handling ${D} transparently

dodir /usr/lib/newpackage

dodoc

N/A

Installs the specified files into the package's documentation directory (/usr/share/doc/${PF}/DOCDESTTREE) (see docinto)

dodoc README *.txt

doexe

N/A

Installs the specified files with mode EXEOPTIONS (see exeopts) into PATH defined by EXEINTO (see exeinto).

doexe ${FILESDIR}/quake3

dohard

N/A

Creates a hard link, handling ${D} transparently

dohard ls /bin/dir

dohtml

N/A

Installs the specified files and directories into /usr/share/doc/${PF}/html

dohtml -r doc/html/*

doinfo

N/A

Installs the specified files into /usr/share/info, then compresses them with gzip

doinfo doc/*.info

doins

N/A

Installs the specified files with mode INSOPTIONS (see insopts) into INSDESTTREE (see insinto)

doins *.png icon.xpm

dolib

N/A

Installs the specified libraries into DESTTREE/lib with mode 0644

dolib *.a *.so

dolib.a

N/A

Installs the specified libraries into DESTTREE/lib with mode 0644

dolib.a *.a

dolib.so

N/A

Installs the specified libraries into DESTTREE/lib with mode 0755

dolib.so *.so

doman

N/A

Installs the specified files into /usr/share/man/manX, according to the suffix of the file (file.1 will go into man1)

doman *.1 *.5

dosbin

N/A

Installs the files into DESTTREE/sbin, making sure they are executable

dosbin ksymoops

dosym

N/A

Creates a symlink, handles ${D} transparently

dosym gzip /bin/zcat

emake

N/A

Runs make with MAKEOPTS. Some packages cannot be made in parallel; use emake -j1 instead. If you need to pass any extra arguments to make, simply append them onto the emake command. Users can set the EXTRA_EMAKE environment variable to pass extra flags to emake.

emake

exeinto

/

Sets the root (EXEDESTTREE) for the doexe command

exeinto /usr/lib/${PN}

exeopts

-m0755

Sets the options used when running doexe

exeopts -m1770

fowners

N/A

Applies the specified ownership to the specified file via the chown command, handles ${D} transparently

fowners root:root /sbin/functions.sh

fperms

N/A

Applies the specified permissions to the specified file via the chmod command, handles ${D} transparently

fperms 700 /var/consoles

insinto

/usr

Sets the root (INSDESTTREE) for the doins command

insinto /usr/include

insopts

-m0644

Sets the options used when running doins

insopts -m0444

into

/usr

Sets the target prefix (DESTTREE) for all the 'do' commands (like dobin, dolib, dolib.a, dolib.so, domo, dosbin)

into /

libopts

-m0644

Sets the options used when running dolib

libopts -m0555

newbin

N/A

Wrapper around dobin which installs the specified binary transparently renaming to the second argument

newbin ${FILESDIR}/vmware.sh vmware

newdoc

N/A

Wrapper around dodoc which installs the specified file transparently renaming to the second argument

newdoc README README.opengl

newexe

N/A

Wrapper around doexe which installs the specified file transparently renaming to the second argument

newexe ${FILESDIR}/xinetd.rc xinetd

newins

N/A

Wrapper around doins which installs the specified file transparently renaming to the second argument

newins ntp.conf.example ntp.conf

newman

N/A

Wrapper around doman which installs the specified file transparently renaming to the second argument

newman xboing.man xboing.6

newsbin

N/A

Wrapper around dosbin which installs the specified file transparently renaming to the second argument

newsbin strings strings-static

prepall

N/A

Runs prepallman, prepallinfo and prepallstrip. Also ensures all libraries in /opt/*/lib, /lib, /usr/lib and /usr/X11R6/lib are executable. also moves any stray aclocal macros into /usr/share/aclocal

prepall

prepalldocs

N/A

Recursively gzips all doc files in /usr/share/doc, transparently fixing up any symlink paths

prepalldocs

prepallinfo

N/A

Recursively gzips all info files in /usr/share/info

prepallinfo

prepallman

N/A

Recursively gzips all man pages in /opt/*/man/*, /usr/share/man/*, /usr/local/man/*, /usr/X11R6/share/man/* and transparently fixes up any symlink paths

prepallman

1.e. Package Dependencies

Why dependencies are important

Portage is more than just a convenience script that gives you a unified way to build any one project (program, library) from source. It will also fetch and install any necessary dependencies if you take care to specify these in your ebuild.

In the official ebuilds, all dependencies have already been specified, so when you issue emerge net-www/mozilla/mozilla-1.0, Portage will insure that all libraries necessary for Mozilla to build and run are properly installed before Mozilla itself is built.

Portage even distinguishes between build-time dependencies and run-time dependencies. (Caveat: Currently, Portage installs all build-time and run-time dependencies and leaves it at that. At a later stage, it will be possible to trim your installation so that only the run-time dependencies are left installed).

How to Specify Dependencies in Your ebuild Files (a.k.a. DEPEND Atoms)

The DEPEND variable inside your foo-x.y.z.ebuild tells Portage about which packages are needed to build foo. The RDEPEND variable specifies which packages are needed for foo to run. RDEPEND should be set explicitly even if it's the same as DEPEND because in the future it defaulting to DEPEND is planned to be removed from Portage.

Code Listing 5.1: Depend example

DEPEND="virtual/opengl
        dev-libs/libxml2"
RDEPEND="${DEPEND}"

This tells Portage that to build foo-x.y.z, the packages virtual/opengl (more on virtuals in a bit) and dev-lib/libxml2 are needed. It does not say anything about which version of opengl or libxml2 that are needed, which means "anything goes".

The "anything goes" is of course a bit scary, and will not work in the general case. But for libraries, which strive very hard to be 100% binary compatible all the time, it actually works. For other libraries, we can of course specify version dependencies.

Code Listing 5.2: Version example

>=sys-apps/bar-1.2
=sys-apps/baz-1.0

>= and = do what you would expect; sys-apps/bar version 1.2 or newer is okay (this means that sys-apps/bar-2.0 is okay), while sys-apps/baz version 1.0 is the only version that is accepted. For more information on the version schema of packages, see the section above on Naming ebuild Files.

Other methods of specifying version dependencies are as follows:

Code Listing 5.3: Specifying version dependencies

~sys-apps/qux-1.0
=sys-apps/foo-1.2*
!sys-libs/gdbm

~sys-apps/qux-1.0 will select the newest portage revision of qux-1.0.

=sys-apps/foo-1.2* will select the newest member of the 1.2 series, but will ignore 1.3 and later/earlier series. That is, foo-1.2.3 and foo-1.2.0 are both valid, while foo-1.3.3, foo-1.3.0, and foo-1.1.0 are not.

!sys-libs/gdbm will prevent this package from being emerged while gdbm is already emerged.

Important Notes

There are many things that go wrong with the DEPEND and RDEPEND variables. Here are some important points to follow when you write the dependencies.

Additionally, it is important to ensure that all the dependencies are complete for your package:

For all the latest details about these DEPEND Atoms, please see the section 5 manpage on ebuilds: man 5 ebuild.

1.f. Testing and deploying

ChangeLog

Whenever you update (or write a new) an ebuild, you must also update its (or create a new) ChangeLog. The skel.ChangeLog contains a sample ChangeLog that you can use as a basis.

The purpose of the ChangeLog is to document what is being done, why it is being done, and by whom. This allows both developers and users to trace the changes made in an easy way.

The ChangeLog is primarily targeted at users, so be sure to keep your writing short, to the point, and avoid getting verbose about the internal technical details.

Storing your own ebuilds locally

In order to be able to test your ebuilds and let Portage know about them, you must place those in a known directory. Portage will use the PORTDIR_OVERLAY variable which you can define in /etc/make.conf. You should set this variable to your directory (e.g. /usr/local/portage).

In that directory, you must use the same structure (and categories) as in /usr/portage.

Using this PORTDIR_OVERLAY, your ebuilds remain on your system, even after an emerge sync, and they are still known to Portage.

Testing the package

Have a think about how you will test whether this package works. Sometimes the developers have already included a make test or make check routine that will test the basic functionality of the package. If so, then running env FEATURES=test ebuild foo-x.y.z.ebuild test will execute it. If it is broken try to fix it so that it works (and submit the patch to the upstream developers).

If this is not the case consider adding a src_test routine to your ebuild. This is executed before the src_install routine and can be very helpful for testing the program works across various architectures. The architecture developers will appreciate if you add a routine here so that they do not require knowledge of the package's functionality.

Please keep in mind the general requirements of an ebuild here. The src_test routine must not be interactive. If the test routine depends on other packages use the test USE flag to specify the optional compile time DEPENDancies. Also, please note that src_test routines are not recommended for graphical X applications as the user running portage often cannot run them successfully.

Useful testing tools

We have a few useful tools to help you with writing and maintaining your ebuilds.

Tool

Package

Description

repoman

sys-apps/portage

Developer-only tool to assist with the CVS check in procedure. It does a lot of common QA and tries to make sure that files added to cvs will not break the portage tree.

ccache

dev-util/ccache

Tool that keeps pre-processed files so that recompilation gets done much faster. Be sure to add ccache to the FEATURES variable in /etc/make.conf!

sandboxshell

app-shells/sandboxshell

Launch a shell that creates a sandbox environment. Useful for entering the same environment that portage builds packages inside of and debugging things by hand.

echangelog

app-portage/gentoolkit-dev

Can create a new ChangeLog or add an entry to an existing one.