Patching with epatch and eapply

The canonical way of applying patches in ebuilds is to use epatch (from epatch.eclass, which you must make sure to inherit!) inside src_prepare. This function automatically handles -p levels, gunzip and so on as necessary.

Starting with EAPI=7, this function is banned and eapply must be used.

Beginning with EAPI=6, a new function eapply was added to apply patches without the need for an eclass. This function differs from epatch in several ways:

Note that distributing modified tarballs rather than a vanilla tarball and patches is highly discouraged.

Basic eapply

The default src_prepare function will look for a global PATCHES array to apply a list of patches for you.


Advanced eapply

This example shows how different patch levels can be applied:

src_prepare() {
	eapply -p2 "${WORKDIR}/${P}-suse-update.patch"
	eapply -p0 "${FILESDIR}/${PV}-no-TIOCGDEV.patch"
	eapply "${FILESDIR}/${PV}-gcc-6.patch"

Basic epatch

In its simplest form, epatch takes a single filename and applies that patch. It will automatically die if the apply fails. The following is taken from app-misc/detox:

src_prepare() {
	epatch "${FILESDIR}/${P}-destdir.patch"
	epatch "${FILESDIR}/${P}-parallel_build.patch"

For larger patches, using your devspace rather than ${FILESDIR} is more appropriate. In these situations, it is usually best to compress the patch in question with xz or bzip2 (as opposed to ${FILESDIR} patches, which must not be compressed). For example, from app-admin/showconsole:

src_prepare() {
	epatch "${WORKDIR}/${P}-suse-update.patch.bz2"
	epatch "${FILESDIR}/${PV}-no-TIOCGDEV.patch"

Remember to add the patch to SRC_URI.

Multiple Patches with epatch

epatch can also apply multiple patches (which can be selectively based upon arch) from a single directory. This can be useful if upstream have releases that need more patches.

A simple example:

src_prepare() {
		EPATCH_FORCE="yes" epatch

Here, one of the SRC_URI components is a tarball containing many patches with file extension .patch.

Variables which may be defined include:

Variable Purpose
EPATCH_SOURCE Specifies the directory in which epatch looks for patches.
EPATCH_SUFFIX File extension for patches.
EPATCH_OPTS Default options to patch.
EPATCH_EXCLUDE List of patches to exclude.
EPATCH_FORCE Force epatch to apply patches even if they do not follow the canonical naming form (set to yes).

Bulk patches should be named in the form ??_${ARCH}_foo.${EPATCH_SUFFIX}. If they are not, EPATCH_FORCE="yes" must be set. To apply a patch on all archs, use all for the ${ARCH} part.