Patching with epatch

The canonical way of applying patches in ebuilds is to use epatch (from eutils.eclass, which you must make sure to inherit!) inside src_prepare. This function automatically handles -p levels, gunzip and so on as necessary. Also note that olds ebuild may still use src_unpack to apply patches. This is because those ebuilds are based in EAPI=1. You are advised to use EAPI=2 and apply your patches in src_prepare function instead.

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

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_unpack() {
    unpack ${A}
    cd "${S}"
    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_unpack() {
    unpack ${A}
    cd "${S}"
    epatch "${WORKDIR}/${P}-suse-update.patch.bz2"
    epatch "${FILESDIR}/${PV}-no-TIOCGDEV.patch"
}

As stated before, if you are using EAPI >=2, you should apply the patches in the src_prepare function

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_unpack() {
    unpack ${A}
    cd "${S}"
    EPATCH_SOURCE="${WORKDIR}/patches" EPATCH_SUFFIX="patch" \
        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.