diff --git a/eclass/acct-group.eclass b/eclass/acct-group.eclass new file mode 100644 index 0000000..11a9f29 --- /dev/null +++ b/eclass/acct-group.eclass @@ -0,0 +1,162 @@ +# Copyright 2019-2020 Gentoo Authors +# Distributed under the terms of the GNU General Public License v2 + +# @ECLASS: acct-group.eclass +# @MAINTAINER: +# Michał Górny +# @AUTHOR: +# Michael Orlitzky +# Michał Górny +# @SUPPORTED_EAPIS: 7 +# @BLURB: Eclass used to create and maintain a single group entry +# @DESCRIPTION: +# This eclass represents and creates a single group entry. The name +# of the group is derived from ${PN}, while (preferred) GID needs to +# be specified via ACCT_GROUP_ID. Packages (and users) needing the group +# in question should depend on the package providing it. +# +# Example: +# If your package needs group 'foo', you create 'acct-group/foo' package +# and add an ebuild with the following contents: +# +# @CODE +# EAPI=7 +# inherit acct-group +# ACCT_GROUP_ID=200 +# @CODE +# +# Then you add appropriate dependency to your package. The dependency +# type(s) should be: +# - DEPEND (+ RDEPEND) if the group is already needed at build time, +# - RDEPEND if it is needed at install time (e.g. you 'fowners' files +# in pkg_preinst) or run time. + +if [[ -z ${_ACCT_GROUP_ECLASS} ]]; then +_ACCT_GROUP_ECLASS=1 + +case ${EAPI:-0} in + 7) ;; + *) die "EAPI=${EAPI:-0} not supported";; +esac + +inherit user + +[[ ${CATEGORY} == acct-group ]] || + die "Ebuild error: this eclass can be used only in acct-group category!" + + +# << Eclass variables >> + +# @ECLASS-VARIABLE: ACCT_GROUP_NAME +# @INTERNAL +# @DESCRIPTION: +# The name of the group. This is forced to ${PN} and the policy +# prohibits it from being changed. +ACCT_GROUP_NAME=${PN} +readonly ACCT_GROUP_NAME + +# @ECLASS-VARIABLE: ACCT_GROUP_ID +# @REQUIRED +# @DESCRIPTION: +# Preferred GID for the new group. This variable is obligatory, and its +# value must be unique across all group packages. This can be overriden +# in make.conf through ACCT_GROUP__ID variable. +# +# Overlays should set this to -1 to dynamically allocate GID. Using -1 +# in ::gentoo is prohibited by policy. + +# @ECLASS-VARIABLE: ACCT_GROUP_ENFORCE_ID +# @DESCRIPTION: +# If set to a non-null value, the eclass will require the group to have +# specified GID. If the group already exists with another GID, or +# the GID is taken by another group, the install will fail. +: ${ACCT_GROUP_ENFORCE_ID:=} + + +# << Boilerplate ebuild variables >> +: ${DESCRIPTION:="System group: ${ACCT_GROUP_NAME}"} +: ${SLOT:=0} +: ${KEYWORDS:=alpha amd64 arm arm64 hppa ia64 m68k ~mips ppc ppc64 ~riscv s390 sparc x86 ~x64-cygwin ~amd64-linux ~x86-linux ~ppc-macos ~x64-macos ~sparc-solaris ~sparc64-solaris ~x64-solaris ~x86-solaris} +S=${WORKDIR} + + +# << Phase functions >> +EXPORT_FUNCTIONS pkg_pretend src_install pkg_preinst + +# @FUNCTION: acct-group_pkg_pretend +# @DESCRIPTION: +# Performs sanity checks for correct eclass usage, and early-checks +# whether requested GID can be enforced. +acct-group_pkg_pretend() { + debug-print-function ${FUNCNAME} "${@}" + + # verify ACCT_GROUP_ID + [[ -n ${ACCT_GROUP_ID} ]] || die "Ebuild error: ACCT_GROUP_ID must be set!" + [[ ${ACCT_GROUP_ID} -ge -1 ]] || die "Ebuild error: ACCT_GROUP_ID=${ACCT_GROUP_ID} invalid!" + local group_id=${ACCT_GROUP_ID} + + # check for the override + local override_name=${ACCT_GROUP_NAME^^} + local override_var=ACCT_GROUP_${override_name//-/_}_ID + if [[ -n ${!override_var} ]]; then + group_id=${!override_var} + [[ ${group_id} -ge -1 ]] || die "${override_var}=${group_id} invalid!" + fi + + # check for ACCT_GROUP_ID collisions early + if [[ ${group_id} -ne -1 && -n ${ACCT_GROUP_ENFORCE_ID} ]]; then + local group_by_id=$(egetgroupname "${group_id}") + local group_by_name=$(egetent group "${ACCT_GROUP_NAME}") + if [[ -n ${group_by_id} ]]; then + if [[ ${group_by_id} != ${ACCT_GROUP_NAME} ]]; then + eerror "The required GID is already taken by another group." + eerror " GID: ${group_id}" + eerror " needed for: ${ACCT_GROUP_NAME}" + eerror " current group: ${group_by_id}" + die "GID ${group_id} taken already" + fi + elif [[ -n ${group_by_name} ]]; then + eerror "The requested group exists already with wrong GID." + eerror " groupname: ${ACCT_GROUP_NAME}" + eerror " requested GID: ${group_id}" + eerror " current entry: ${group_by_name}" + die "Group ${ACCT_GROUP_NAME} exists with wrong GID" + fi + fi +} + +# @FUNCTION: acct-group_src_install +# @DESCRIPTION: +# Installs sysusers.d file for the group. +acct-group_src_install() { + debug-print-function ${FUNCNAME} "${@}" + + # check for the override + local override_name=${ACCT_GROUP_NAME^^} + local override_var=ACCT_GROUP_${override_name//-/_}_ID + if [[ -n ${!override_var} ]]; then + ewarn "${override_var}=${!override_var} override in effect, support will not be provided." + _ACCT_GROUP_ID=${!override_var} + else + _ACCT_GROUP_ID=${ACCT_GROUP_ID} + fi + + insinto /usr/lib/sysusers.d + newins - ${CATEGORY}-${ACCT_GROUP_NAME}.conf < <( + printf "g\t%q\t%q\n" \ + "${ACCT_GROUP_NAME}" \ + "${_ACCT_GROUP_ID/#-*/-}" + ) +} + +# @FUNCTION: acct-group_pkg_preinst +# @DESCRIPTION: +# Creates the group if it does not exist yet. +acct-group_pkg_preinst() { + debug-print-function ${FUNCNAME} "${@}" + + enewgroup ${ACCT_GROUP_ENFORCE_ID:+-F} "${ACCT_GROUP_NAME}" \ + "${_ACCT_GROUP_ID}" +} + +fi diff --git a/eclass/acct-user.eclass b/eclass/acct-user.eclass new file mode 100644 index 0000000..ee4358b --- /dev/null +++ b/eclass/acct-user.eclass @@ -0,0 +1,489 @@ +# Copyright 2019-2020 Gentoo Authors +# Distributed under the terms of the GNU General Public License v2 + +# @ECLASS: acct-user.eclass +# @MAINTAINER: +# Michał Górny +# @AUTHOR: +# Michael Orlitzky +# Michał Górny +# @SUPPORTED_EAPIS: 7 +# @BLURB: Eclass used to create and maintain a single user entry +# @DESCRIPTION: +# This eclass represents and creates a single user entry. The name +# of the user is derived from ${PN}, while (preferred) UID needs to +# be specified via ACCT_USER_ID. Additional variables are provided +# to override the default home directory, shell and add group +# membership. Packages needing the user in question should depend +# on the package providing it. +# +# The ebuild needs to call acct-user_add_deps after specifying +# ACCT_USER_GROUPS. +# +# Example: +# If your package needs user 'foo' belonging to same-named group, you +# create 'acct-user/foo' package and add an ebuild with the following +# contents: +# +# @CODE +# EAPI=7 +# inherit acct-user +# ACCT_USER_ID=200 +# ACCT_USER_GROUPS=( foo ) +# acct-user_add_deps +# @CODE +# +# Then you add appropriate dependency to your package. The dependency +# type(s) should be: +# - DEPEND (+ RDEPEND) if the user is already needed at build time, +# - RDEPEND if it is needed at install time (e.g. you 'fowners' files +# in pkg_preinst) or run time. + +if [[ -z ${_ACCT_USER_ECLASS} ]]; then +_ACCT_USER_ECLASS=1 + +case ${EAPI:-0} in + 7) ;; + *) die "EAPI=${EAPI:-0} not supported";; +esac + +inherit user + +[[ ${CATEGORY} == acct-user ]] || + die "Ebuild error: this eclass can be used only in acct-user category!" + + +# << Eclass variables >> + +# @ECLASS-VARIABLE: ACCT_USER_NAME +# @INTERNAL +# @DESCRIPTION: +# The name of the user. This is forced to ${PN} and the policy prohibits +# it from being changed. +ACCT_USER_NAME=${PN} +readonly ACCT_USER_NAME + +# @ECLASS-VARIABLE: ACCT_USER_ID +# @REQUIRED +# @DESCRIPTION: +# Preferred UID for the new user. This variable is obligatory, and its +# value must be unique across all user packages. This can be overriden +# in make.conf through ACCT_USER__ID variable. +# +# Overlays should set this to -1 to dynamically allocate UID. Using -1 +# in ::gentoo is prohibited by policy. + +# @ECLASS-VARIABLE: _ACCT_USER_ALREADY_EXISTS +# @INTERNAL +# @DESCRIPTION: +# Status variable which indicates if user already exists. + +# @ECLASS-VARIABLE: ACCT_USER_ENFORCE_ID +# @DESCRIPTION: +# If set to a non-null value, the eclass will require the user to have +# specified UID. If the user already exists with another UID, or +# the UID is taken by another user, the install will fail. +: ${ACCT_USER_ENFORCE_ID:=} + +# @ECLASS-VARIABLE: ACCT_USER_NO_MODIFY +# @DEFAULT_UNSET +# @DESCRIPTION: +# If set to a non-null value, the eclass will not make any changes +# to an already existing user. +: ${ACCT_USER_NO_MODIFY:=} + +# @ECLASS-VARIABLE: ACCT_USER_SHELL +# @DESCRIPTION: +# The shell to use for the user. If not specified, a 'nologin' variant +# for the system is used. This can be overriden in make.conf through +# ACCT_USER__SHELL variable. +: ${ACCT_USER_SHELL:=-1} + +# @ECLASS-VARIABLE: ACCT_USER_HOME +# @DESCRIPTION: +# The home directory for the user. If not specified, /dev/null is used. +# The directory will be created with appropriate permissions if it does +# not exist. When updating, existing home directory will not be moved. +# This can be overriden in make.conf through +# ACCT_USER__HOME variable. +: ${ACCT_USER_HOME:=/dev/null} + +# @ECLASS-VARIABLE: ACCT_USER_HOME_OWNER +# @DEFAULT_UNSET +# @DESCRIPTION: +# The ownership to use for the home directory, in chown ([user][:group]) +# syntax. Defaults to the newly created user, and its primary group. +# This can be overriden in make.conf through +# ACCT_USER__HOME_OWNER variable. + +# @ECLASS-VARIABLE: ACCT_USER_HOME_PERMS +# @DESCRIPTION: +# The permissions to use for the home directory, in chmod (octal +# or verbose) form. This can be overriden in make.conf through +# ACCT_USER__HOME_PERMS variable. +: ${ACCT_USER_HOME_PERMS:=0755} + +# @ECLASS-VARIABLE: ACCT_USER_GROUPS +# @REQUIRED +# @DESCRIPTION: +# List of groups the user should belong to. This must be a bash +# array. The first group specified is the user's primary group, while +# the remaining groups (if any) become supplementary groups. +# +# This can be overriden in make.conf through +# ACCT_USER__GROUPS variable, or appended to +# via ACCT_USER__GROUPS_ADD. Please note that +# due to technical limitations, the override variables are not arrays +# but space-separated lists. + + +# << Boilerplate ebuild variables >> +: ${DESCRIPTION:="System user: ${ACCT_USER_NAME}"} +: ${SLOT:=0} +: ${KEYWORDS:=alpha amd64 arm arm64 hppa ia64 m68k ~mips ppc ppc64 ~riscv s390 sparc x86 ~x64-cygwin ~amd64-linux ~x86-linux ~ppc-macos ~x64-macos ~sparc-solaris ~sparc64-solaris ~x64-solaris ~x86-solaris} +S=${WORKDIR} + + +# << API functions >> + +# @FUNCTION: acct-user_add_deps +# @DESCRIPTION: +# Generate appropriate RDEPEND from ACCT_USER_GROUPS. This must be +# called if ACCT_USER_GROUPS are set. +acct-user_add_deps() { + debug-print-function ${FUNCNAME} "${@}" + + # ACCT_USER_GROUPS sanity check + if [[ $(declare -p ACCT_USER_GROUPS) != "declare -a"* ]]; then + die 'ACCT_USER_GROUPS must be an array.' + elif [[ ${#ACCT_USER_GROUPS[@]} -eq 0 ]]; then + die 'ACCT_USER_GROUPS must not be empty.' + fi + + RDEPEND+=${ACCT_USER_GROUPS[*]/#/ acct-group/} + _ACCT_USER_ADD_DEPS_CALLED=1 +} + + +# << Helper functions >> + +# @FUNCTION: eislocked +# @USAGE: +# @INTERNAL +# @DESCRIPTION: +# Check whether the specified user account is currently locked. +# Returns 0 if it is locked, 1 if it is not, 2 if the platform +# does not support determining it. +eislocked() { + [[ $# -eq 1 ]] || die "usage: ${FUNCNAME} " + + if [[ ${EUID} != 0 ]]; then + einfo "Insufficient privileges to execute ${FUNCNAME[0]}" + return 0 + fi + + case ${CHOST} in + *-freebsd*|*-dragonfly*|*-netbsd*) + [[ $(egetent "$1" | cut -d: -f2) == '*LOCKED*'* ]] + ;; + + *-openbsd*) + return 2 + ;; + + *) + # NB: 'no password' and 'locked' are indistinguishable + # but we also expire the account which is more clear + [[ $(getent shadow "$1" | cut -d: -f2) == '!'* ]] && + [[ $(getent shadow "$1" | cut -d: -f8) == 1 ]] + ;; + esac +} + +# @FUNCTION: elockuser +# @USAGE: +# @INTERNAL +# @DESCRIPTION: +# Lock the specified user account, using the available platform-specific +# functions. This should prevent any login to the account. +# +# Established lock can be reverted using eunlockuser. +# +# This function returns 0 if locking succeeded, 2 if it is not supported +# by the platform code or dies if it fails. +elockuser() { + [[ $# -eq 1 ]] || die "usage: ${FUNCNAME} " + + if [[ ${EUID} != 0 ]]; then + einfo "Insufficient privileges to execute ${FUNCNAME[0]}" + return 0 + fi + + eislocked "$1" + [[ $? -eq 0 ]] && return 0 + + case ${CHOST} in + *-freebsd*|*-dragonfly*) + pw lock "$1" || die "Locking account $1 failed" + pw user mod "$1" -e 1 || die "Expiring account $1 failed" + ;; + + *-netbsd*) + usermod -e 1 -C yes "$1" || die "Locking account $1 failed" + ;; + + *-openbsd*) + return 2 + ;; + + *) + usermod -e 1 -L "$1" || die "Locking account $1 failed" + ;; + esac + + elog "User account $1 locked" + return 0 +} + +# @FUNCTION: eunlockuser +# @USAGE: +# @INTERNAL +# @DESCRIPTION: +# Unlock the specified user account, using the available platform- +# specific functions. +# +# This function returns 0 if unlocking succeeded, 1 if it is not +# supported by the platform code or dies if it fails. +eunlockuser() { + [[ $# -eq 1 ]] || die "usage: ${FUNCNAME} " + + if [[ ${EUID} != 0 ]]; then + einfo "Insufficient privileges to execute ${FUNCNAME[0]}" + return 0 + fi + + eislocked "$1" + [[ $? -eq 1 ]] && return 0 + + case ${CHOST} in + *-freebsd*|*-dragonfly*) + pw user mod "$1" -e 0 || die "Unexpiring account $1 failed" + pw unlock "$1" || die "Unlocking account $1 failed" + ;; + + *-netbsd*) + usermod -e 0 -C no "$1" || die "Unlocking account $1 failed" + ;; + + *-openbsd*) + return 1 + ;; + + *) + # silence warning if account does not have a password + usermod -e "" -U "$1" 2>/dev/null || die "Unlocking account $1 failed" + ;; + esac + + ewarn "User account $1 unlocked after reinstating." + return 0 +} + + +# << Phase functions >> +EXPORT_FUNCTIONS pkg_pretend src_install pkg_preinst pkg_postinst \ + pkg_prerm + +# @FUNCTION: acct-user_pkg_pretend +# @DESCRIPTION: +# Performs sanity checks for correct eclass usage, and early-checks +# whether requested UID can be enforced. +acct-user_pkg_pretend() { + debug-print-function ${FUNCNAME} "${@}" + + # verify that acct-user_add_deps() has been called + # (it verifies ACCT_USER_GROUPS itself) + if [[ -z ${_ACCT_USER_ADD_DEPS_CALLED} ]]; then + die "Ebuild error: acct-user_add_deps must have been called in global scope!" + fi + + # verify ACCT_USER_ID + [[ -n ${ACCT_USER_ID} ]] || die "Ebuild error: ACCT_USER_ID must be set!" + [[ ${ACCT_USER_ID} -ge -1 ]] || die "Ebuild error: ACCT_USER_ID=${ACCT_USER_ID} invalid!" + local user_id=${ACCT_USER_ID} + + # check for the override + local override_name=${ACCT_USER_NAME^^} + local override_var=ACCT_USER_${override_name//-/_}_ID + if [[ -n ${!override_var} ]]; then + user_id=${!override_var} + [[ ${user_id} -ge -1 ]] || die "${override_var}=${user_id} invalid!" + fi + + # check for ACCT_USER_ID collisions early + if [[ ${user_id} -ne -1 && -n ${ACCT_USER_ENFORCE_ID} ]]; then + local user_by_id=$(egetusername "${user_id}") + local user_by_name=$(egetent passwd "${ACCT_USER_NAME}") + if [[ -n ${user_by_id} ]]; then + if [[ ${user_by_id} != ${ACCT_USER_NAME} ]]; then + eerror "The required UID is already taken by another user." + eerror " UID: ${user_id}" + eerror " needed for: ${ACCT_USER_NAME}" + eerror " current user: ${user_by_id}" + die "UID ${user_id} taken already" + fi + elif [[ -n ${user_by_name} ]]; then + eerror "The requested user exists already with wrong UID." + eerror " username: ${ACCT_USER_NAME}" + eerror " requested UID: ${user_id}" + eerror " current entry: ${user_by_name}" + die "Username ${ACCT_USER_NAME} exists with wrong UID" + fi + fi +} + +# @FUNCTION: acct-user_src_install +# @DESCRIPTION: +# Installs a keep-file into the user's home directory to ensure it is +# owned by the package, and sysusers.d file. +acct-user_src_install() { + debug-print-function ${FUNCNAME} "${@}" + + # serialize for override support + local ACCT_USER_GROUPS=${ACCT_USER_GROUPS[*]} + + # support make.conf overrides + local override_name=${ACCT_USER_NAME^^} + override_name=${override_name//-/_} + local var + for var in ACCT_USER_{ID,SHELL,HOME{,_OWNER,_PERMS},GROUPS}; do + local var_name=ACCT_USER_${override_name}_${var#ACCT_USER_} + if [[ -n ${!var_name} ]]; then + ewarn "${var_name}=${!var_name} override in effect, support will not be provided." + else + var_name=${var} + fi + declare -g "_${var}=${!var_name}" + done + var_name=ACCT_USER_${override_name}_GROUPS_ADD + if [[ -n ${!var_name} ]]; then + ewarn "${var_name}=${!var_name} override in effect, support will not be provided." + _ACCT_USER_GROUPS+=" ${!var_name}" + fi + + # deserialize into an array + local groups=( ${_ACCT_USER_GROUPS} ) + + if [[ ${_ACCT_USER_HOME} != /dev/null ]]; then + # note: we can't set permissions here since the user isn't + # created yet + keepdir "${_ACCT_USER_HOME}" + fi + + insinto /usr/lib/sysusers.d + newins - ${CATEGORY}-${ACCT_USER_NAME}.conf < <( + printf "u\t%q\t%q\t%q\t%q\t%q\n" \ + "${ACCT_USER_NAME}" \ + "${_ACCT_USER_ID/#-*/-}:${groups[0]}" \ + "${DESCRIPTION//[:,=]/;}" \ + "${_ACCT_USER_HOME}" \ + "${_ACCT_USER_SHELL/#-*/-}" + if [[ ${#groups[@]} -gt 1 ]]; then + printf "m\t${ACCT_USER_NAME}\t%q\n" \ + "${groups[@]:1}" + fi + ) +} + +# @FUNCTION: acct-user_pkg_preinst +# @DESCRIPTION: +# Creates the user if it does not exist yet. Sets permissions +# of the home directory in install image. +acct-user_pkg_preinst() { + debug-print-function ${FUNCNAME} "${@}" + + # check if user already exists + _ACCT_USER_ALREADY_EXISTS= + if [[ -n $(egetent passwd "${ACCT_USER_NAME}") ]]; then + _ACCT_USER_ALREADY_EXISTS=1 + fi + readonly _ACCT_USER_ALREADY_EXISTS + + enewuser ${ACCT_USER_ENFORCE_ID:+-F} -M "${ACCT_USER_NAME}" \ + "${_ACCT_USER_ID}" "${_ACCT_USER_SHELL}" "${_ACCT_USER_HOME}" \ + "${_ACCT_USER_GROUPS// /,}" + + if [[ ${_ACCT_USER_HOME} != /dev/null ]]; then + # default ownership to user:group + if [[ -z ${_ACCT_USER_HOME_OWNER} ]]; then + local group_array=( ${_ACCT_USER_GROUPS} ) + _ACCT_USER_HOME_OWNER=${ACCT_USER_NAME}:${group_array[0]} + fi + # Path might be missing due to INSTALL_MASK, etc. + # https://bugs.gentoo.org/691478 + if [[ ! -e "${ED}/${_ACCT_USER_HOME#/}" ]]; then + eerror "Home directory is missing from the installation image:" + eerror " ${_ACCT_USER_HOME}" + eerror "Check INSTALL_MASK for entries that would cause this." + die "${_ACCT_USER_HOME} does not exist" + fi + fowners "${_ACCT_USER_HOME_OWNER}" "${_ACCT_USER_HOME}" + fperms "${_ACCT_USER_HOME_PERMS}" "${_ACCT_USER_HOME}" + fi +} + +# @FUNCTION: acct-user_pkg_postinst +# @DESCRIPTION: +# Updates user properties if necessary. This needs to be done after +# new home directory is installed. +acct-user_pkg_postinst() { + debug-print-function ${FUNCNAME} "${@}" + + if [[ ${EUID} != 0 ]]; then + einfo "Insufficient privileges to execute ${FUNCNAME[0]}" + return 0 + fi + + if [[ -n ${ACCT_USER_NO_MODIFY} && -n ${_ACCT_USER_ALREADY_EXISTS} ]]; then + eunlockuser "${ACCT_USER_NAME}" + + ewarn "User ${ACCT_USER_NAME} already exists; Not touching existing user" + ewarn "due to set ACCT_USER_NO_MODIFY." + return 0 + fi + + # NB: eset* functions check current value + esethome "${ACCT_USER_NAME}" "${_ACCT_USER_HOME}" + esetshell "${ACCT_USER_NAME}" "${_ACCT_USER_SHELL}" + esetgroups "${ACCT_USER_NAME}" "${_ACCT_USER_GROUPS// /,}" + # comment field can not contain colons + esetcomment "${ACCT_USER_NAME}" "${DESCRIPTION//[:,=]/;}" + eunlockuser "${ACCT_USER_NAME}" +} + +# @FUNCTION: acct-user_pkg_prerm +# @DESCRIPTION: +# Ensures that the user account is locked out when it is removed. +acct-user_pkg_prerm() { + debug-print-function ${FUNCNAME} "${@}" + + if [[ ${EUID} != 0 ]]; then + einfo "Insufficient privileges to execute ${FUNCNAME[0]}" + return 0 + fi + + if [[ -z ${REPLACED_BY_VERSION} ]]; then + if [[ -z $(egetent passwd "${ACCT_USER_NAME}") ]]; then + ewarn "User account not found: ${ACCT_USER_NAME}" + ewarn "Locking process will be skipped." + return + fi + + esetshell "${ACCT_USER_NAME}" -1 + esetcomment "${ACCT_USER_NAME}" \ + "$(egetcomment "${ACCT_USER_NAME}"); user account removed @ $(date +%Y-%m-%d)" + elockuser "${ACCT_USER_NAME}" + fi +} + +fi diff --git a/eclass/ada.eclass b/eclass/ada.eclass new file mode 100644 index 0000000..4b568a8 --- /dev/null +++ b/eclass/ada.eclass @@ -0,0 +1,464 @@ +# Copyright 2019 Gentoo Authors +# Distributed under the terms of the GNU General Public License v2 + +# @ECLASS: ada.eclass +# @MAINTAINER: +# Ada team +# @AUTHOR: +# Tupone Alfredo +# @SUPPORTED_EAPIS: 6 7 +# @BLURB: An eclass for Ada packages +# @DESCRIPTION: +# This eclass set the IUSE and REQUIRED_USE to request the ADA_TARGET +# when the inheriting ebuild can be supported by more than one Ada +# implementation. It also set ADA_USEDEP and ADA_DEPS with a suitable form. +# A common eclass providing helper functions to build and install +# packages supporting Ada implementations. +# +# This eclass sets correct IUSE. Modification of REQUIRED_USE has to +# be done by the author of the ebuild (but ADA_REQUIRED_USE is +# provided for convenience, see below). ada exports ADA_DEPS +# and ADA_USEDEP so you can create correct dependencies for your +# package easily. +# +# Mostly copied from python-single-r1.eclass + +case "${EAPI:-0}" in + 0|1|2|3|4|5) + die "Unsupported EAPI=${EAPI:-0} (too old) for ${ECLASS}" + ;; + 6|7) + # EAPI=5 is required for sane USE_EXPAND dependencies + ;; + *) + die "Unsupported EAPI=${EAPI} (unknown) for ${ECLASS}" + ;; +esac + +EXPORT_FUNCTIONS pkg_setup + +# @ECLASS-VARIABLE: ADA_DEPS +# @OUTPUT_VARIABLE +# @DESCRIPTION: +# This is an eclass-generated Ada dependency string for all +# implementations listed in ADA_COMPAT. +# +# The dependency string is conditional on ADA_TARGET. +# +# Example use: +# @CODE +# RDEPEND="${ADA_DEPS} +# dev-foo/mydep" +# DEPEND="${RDEPEND}" +# @CODE +# + +# @ECLASS-VARIABLE: _ADA_ALL_IMPLS +# @INTERNAL +# @DESCRIPTION: +# All supported Ada implementations, most preferred last. +_ADA_ALL_IMPLS=( + gnat_2016 gnat_2017 gnat_2018 gnat_2019 +) +readonly _ADA_ALL_IMPLS + + +# @FUNCTION: _ada_impl_supported +# @USAGE: +# @INTERNAL +# @DESCRIPTION: +# Check whether the implementation (ADA_COMPAT-form) +# is still supported. +# +# Returns 0 if the implementation is valid and supported. If it is +# unsupported, returns 1 -- and the caller should ignore the entry. +# If it is invalid, dies with an appopriate error messages. +_ada_impl_supported() { + debug-print-function ${FUNCNAME} "${@}" + + [[ ${#} -eq 1 ]] || die "${FUNCNAME}: takes exactly 1 argument (impl)." + + local impl=${1} + + # keep in sync with _ADA_ALL_IMPLS! + # (not using that list because inline patterns shall be faster) + case "${impl}" in + gnat_201[6789]) + return 0 + ;; + *) + [[ ${ADA_COMPAT_NO_STRICT} ]] && return 1 + die "Invalid implementation in ADA_COMPAT: ${impl}" + esac +} + +# @FUNCTION: _ada_set_impls +# @INTERNAL +# @DESCRIPTION: +# Check ADA_COMPAT for well-formedness and validity, then set +# two global variables: +# +# - _ADA_SUPPORTED_IMPLS containing valid implementations supported +# by the ebuild (ADA_COMPAT - dead implementations), +# +# - and _ADA_UNSUPPORTED_IMPLS containing valid implementations that +# are not supported by the ebuild. +# +# Implementations in both variables are ordered using the pre-defined +# eclass implementation ordering. +# +# This function must be called once in global scope by an eclass +# utilizing ADA_COMPAT. +_ada_set_impls() { + local i + + if ! declare -p ADA_COMPAT &>/dev/null; then + die 'ADA_COMPAT not declared.' + fi + if [[ $(declare -p ADA_COMPAT) != "declare -a"* ]]; then + die 'ADA_COMPAT must be an array.' + fi + for i in "${ADA_COMPAT[@]}"; do + # trigger validity checks + _ada_impl_supported "${i}" + done + + local supp=() unsupp=() + + for i in "${_ADA_ALL_IMPLS[@]}"; do + if has "${i}" "${ADA_COMPAT[@]}"; then + supp+=( "${i}" ) + else + unsupp+=( "${i}" ) + fi + done + if [[ ! ${supp[@]} ]]; then + die "No supported implementation in ADA_COMPAT." + fi + + if [[ ${_ADA_SUPPORTED_IMPLS[@]} ]]; then + # set once already, verify integrity + if [[ ${_ADA_SUPPORTED_IMPLS[@]} != ${supp[@]} ]]; then + eerror "Supported impls (ADA_COMPAT) changed between inherits!" + eerror "Before: ${_ADA_SUPPORTED_IMPLS[*]}" + eerror "Now : ${supp[*]}" + die "_ADA_SUPPORTED_IMPLS integrity check failed" + fi + if [[ ${_ADA_UNSUPPORTED_IMPLS[@]} != ${unsupp[@]} ]]; then + eerror "Unsupported impls changed between inherits!" + eerror "Before: ${_ADA_UNSUPPORTED_IMPLS[*]}" + eerror "Now : ${unsupp[*]}" + die "_ADA_UNSUPPORTED_IMPLS integrity check failed" + fi + else + _ADA_SUPPORTED_IMPLS=( "${supp[@]}" ) + _ADA_UNSUPPORTED_IMPLS=( "${unsupp[@]}" ) + readonly _ADA_SUPPORTED_IMPLS _ADA_UNSUPPORTED_IMPLS + fi +} + +# @FUNCTION: ada_export +# @USAGE: [] ... +# @DESCRIPTION: +# Set and export the Ada implementation-relevant variables passed +# as parameters. +# +# The optional first parameter may specify the requested Ada +# implementation (either as ADA_TARGETS value, e.g. ada2_7, +# or an EADA one, e.g. ada2.7). If no implementation passed, +# the current one will be obtained from ${EADA}. +# +# The variables which can be exported are: GCC, EADA, GNATMAKE. +# They are described more completely in the eclass +# variable documentation. +ada_export() { + debug-print-function ${FUNCNAME} "${@}" + + local impl var + + case "${1}" in + gnat_201[6789]) + impl=${1} + shift + ;; + *) + impl=${EADA} + if [[ -z ${impl} ]]; then + die "ada_export called without a ada implementation and EADA is unset" + fi + ;; + esac + debug-print "${FUNCNAME}: implementation: ${impl}" + + local gcc_pv + case "${impl}" in + gnat_2016) + gcc_pv=4.9.4 + ;; + gnat_2017) + gcc_pv=6.3.0 + ;; + gnat_2018) + gcc_pv=7.3.1 + ;; + gnat_2019) + gcc_pv=8.3.1 + ;; + *) + gcc_pv="9.9.9" + ;; + esac + + for var; do + case "${var}" in + EADA) + export EADA=${impl} + debug-print "${FUNCNAME}: EADA = ${EADA}" + ;; + GCC) + export GCC=${EPREFIX}/usr/bin/gcc-${gcc_pv} + debug-print "${FUNCNAME}: GCC = ${GCC}" + ;; + GCC_PV) + export GCC_PV=${gcc_pv} + debug-print "${FUNCNAME}: GCC_PV = ${GCC_PV}" + ;; + GNAT) + export GNAT=${EPREFIX}/usr/bin/gnat-${gcc_pv} + debug-print "${FUNCNAME}: GNAT = ${GNAT}" + ;; + GNATBIND) + export GNATBIND=${EPREFIX}/usr/bin/gnatbind-${gcc_pv} + debug-print "${FUNCNAME}: GNATBIND = ${GNATBIND}" + ;; + GNATMAKE) + export GNATMAKE=${EPREFIX}/usr/bin/gnatmake-${gcc_pv} + debug-print "${FUNCNAME}: GNATMAKE = ${GNATMAKE}" + ;; + GNATLS) + export GNATLS=${EPREFIX}/usr/bin/gnatls-${gcc_pv} + debug-print "${FUNCNAME}: GNATLS = ${GNATLS}" + ;; + GNATPREP) + export GNATPREP=${EPREFIX}/usr/bin/gnatprep-${gcc_pv} + debug-print "${FUNCNAME}: GNATPREP = ${GNATPREP}" + ;; + GNATCHOP) + export GNATCHOP=${EPREFIX}/usr/bin/gnatchop-${gcc_pv} + debug-print "${FUNCNAME}: GNATCHOP = ${GNATCHOP}" + ;; + ADA_PKG_DEP) + ADA_PKG_DEP="dev-lang/gnat-gpl:${gcc_pv}" + + # use-dep + if [[ ${ADA_REQ_USE} ]]; then + ADA_PKG_DEP+=[${ADA_REQ_USE}] + fi + + export ADA_PKG_DEP + debug-print "${FUNCNAME}: ADA_PKG_DEP = ${ADA_PKG_DEP}" + ;; + *) + die "ada_export: unknown variable ${var}" + esac + done +} + +_ada_single_set_globals() { + _ada_set_impls + local i ADA_PKG_DEP + + local flags=( "${_ADA_SUPPORTED_IMPLS[@]/#/ada_target_}" ) + local unflags=( "${_ADA_UNSUPPORTED_IMPLS[@]/#/-ada_target_}" ) + local allflags=( ${flags[@]} ${unflags[@]} ) + + local optflags=${flags[@]/%/(-)?} + + IUSE="${allflags[*]}" + + if [[ ${#_ADA_UNSUPPORTED_IMPLS[@]} -gt 0 ]]; then + optflags+=,${unflags[@]/%/(-)} + fi + + local deps requse usedep + if [[ ${#_ADA_SUPPORTED_IMPLS[@]} -eq 1 ]]; then + # There is only one supported implementation; set IUSE and other + # variables without ADA_SINGLE_TARGET. + requse=${flags[*]} + ada_export "${_ADA_SUPPORTED_IMPLS[0]}" ADA_PKG_DEP + deps="${flags[*]}? ( ${ADA_PKG_DEP} ) " + else + # Multiple supported implementations; honor ADA_TARGET. + requse="^^ ( ${flags[*]} )" + + for i in "${_ADA_SUPPORTED_IMPLS[@]}"; do + ada_export "${i}" ADA_PKG_DEP + deps+="ada_target_${i}? ( ${ADA_PKG_DEP} ) " + done + fi + usedep=${optflags// /,} + if [[ ${ADA_DEPS+1} ]]; then + if [[ ${ADA_DEPS} != "${deps}" ]]; then + eerror "ADA_DEPS have changed between inherits (ADA_REQ_USE?)!" + eerror "Before: ${ADA_DEPS}" + eerror "Now : ${deps}" + die "ADA_DEPS integrity check failed" + fi + + # these two are formality -- they depend on ADA_COMPAT only + if [[ ${ADA_REQUIRED_USE} != ${requse} ]]; then + eerror "ADA_REQUIRED_USE have changed between inherits!" + eerror "Before: ${ADA_REQUIRED_USE}" + eerror "Now : ${requse}" + die "ADA_REQUIRED_USE integrity check failed" + fi + + if [[ ${ADA_USEDEP} != "${usedep}" ]]; then + eerror "ADA_USEDEP have changed between inherits!" + eerror "Before: ${ADA_USEDEP}" + eerror "Now : ${usedep}" + die "ADA_USEDEP integrity check failed" + fi + else + ADA_DEPS=${deps} + ADA_REQUIRED_USE=${requse} + ADA_USEDEP=${usedep} + readonly ADA_DEPS ADA_REQUIRED_USE ADA_USEDEP + fi +} +_ada_single_set_globals +unset -f _ada_single_set_globals + +# @FUNCTION: ada_wrapper_setup +# @USAGE: [ []] +# @DESCRIPTION: +# Create proper 'ada' executable wrappers +# in the directory named by . Set up PATH +# appropriately. defaults to ${T}/${EADA}. +# +# The wrappers will be created for implementation named by , +# or for one named by ${EADA} if no passed. +# +# If the named directory contains a ada symlink already, it will +# be assumed to contain proper wrappers already and only environment +# setup will be done. If wrapper update is requested, the directory +# shall be removed first. +ada_wrapper_setup() { + debug-print-function ${FUNCNAME} "${@}" + + local workdir=${1:-${T}/${EADA}} + local impl=${2:-${EADA}} + + [[ ${workdir} ]] || die "${FUNCNAME}: no workdir specified." + [[ ${impl} ]] || die "${FUNCNAME}: no impl nor EADA specified." + + if [[ ! -x ${workdir}/bin/gnatmake ]]; then + mkdir -p "${workdir}"/bin || die + + local GCC GNATMAKE GNATLS GNATBIND GNATCHOP GNATPREP + ada_export "${impl}" GCC GNAT GNATMAKE GNATLS GNATCHOP GNATBIND GNATPREP + + # Ada compiler + cat > "${workdir}/bin/gcc" <<-_EOF_ || die + #!/bin/sh + exec "${GCC}" "\${@}" + _EOF_ + chmod a+x "${workdir}/bin/gcc" || die + cat > "${workdir}/bin/gnatmake" <<-_EOF_ || die + #!/bin/sh + exec "${GNATMAKE}" "\${@}" + _EOF_ + chmod a+x "${workdir}/bin/gnatmake" || die + cat > "${workdir}/bin/gnatls" <<-_EOF_ || die + #!/bin/sh + exec "${GNATLS}" "\${@}" + _EOF_ + chmod a+x "${workdir}/bin/gnatls" || die + cat > "${workdir}/bin/gnatbind" <<-_EOF_ || die + #!/bin/sh + exec "${GNATBIND}" "\${@}" + _EOF_ + chmod a+x "${workdir}/bin/gnatbind" || die + cat > "${workdir}/bin/gnatchop" <<-_EOF_ || die + #!/bin/sh + exec "${GNATCHOP}" "\${@}" + _EOF_ + chmod a+x "${workdir}/bin/gnatchop" || die + cat > "${workdir}/bin/gnatprep" <<-_EOF_ || die + #!/bin/sh + exec "${GNATPREP}" "\${@}" + _EOF_ + chmod a+x "${workdir}/bin/gnatprep" || die + cat > "${workdir}/bin/gnat" <<-_EOF_ || die + #!/bin/sh + exec "${GNAT}" "\${@}" + _EOF_ + chmod a+x "${workdir}/bin/gnat" || die + fi + + # Now, set the environment. + # But note that ${workdir} may be shared with something else, + # and thus already on top of PATH. + if [[ ${PATH##:*} != ${workdir}/bin ]]; then + PATH=${workdir}/bin${PATH:+:${PATH}} + fi + export PATH +} + +# @FUNCTION: ada_setup +# @DESCRIPTION: +# Determine what the selected Ada implementation is and set +# the Ada build environment up for it. +ada_setup() { + debug-print-function ${FUNCNAME} "${@}" + + unset EADA + + if [[ ${#_ADA_SUPPORTED_IMPLS[@]} -eq 1 ]]; then + if use "ada_target_${_ADA_SUPPORTED_IMPLS[0]}"; then + # Only one supported implementation, enable it explicitly + ada_export "${_ADA_SUPPORTED_IMPLS[0]}" EADA GCC_PV GNAT GNATBIND GNATLS GNATMAKE + ada_wrapper_setup + fi + else + local impl + for impl in "${_ADA_SUPPORTED_IMPLS[@]}"; do + if use "ada_target_${impl}"; then + if [[ ${EADA} ]]; then + eerror "Your ADA_TARGET setting lists more than a single Ada" + eerror "implementation. Please set it to just one value. If you need" + eerror "to override the value for a single package, please use package.env" + eerror "or an equivalent solution (man 5 portage)." + echo + die "More than one implementation in ADA_TARGET." + fi + + ada_export "${impl}" EADA GCC_PV GNAT GNATBIND GNATLS GNATMAKE + ada_wrapper_setup + fi + done + fi + + if [[ ! ${EADA} ]]; then + eerror "No Ada implementation selected for the build. Please set" + if [[ ${#_ADA_SUPPORTED_IMPLS[@]} -eq 1 ]]; then + eerror "the ADA_TARGETS variable in your make.conf to include one" + else + eerror "the ADA_SINGLE_TARGET variable in your make.conf to one" + fi + eerror "of the following values:" + eerror + eerror "${_ADA_SUPPORTED_IMPLS[@]}" + echo + die "No supported Ada implementation in ADA_SINGLE_TARGET/ADA_TARGETS." + fi +} + +# @FUNCTION: ada_pkg_setup +# @DESCRIPTION: +# Runs ada_setup. +ada_pkg_setup() { + debug-print-function ${FUNCNAME} "${@}" + + [[ ${MERGE_TYPE} != binary ]] && ada_setup +} diff --git a/eclass/alternatives.eclass b/eclass/alternatives.eclass new file mode 100644 index 0000000..79f14d8 --- /dev/null +++ b/eclass/alternatives.eclass @@ -0,0 +1,142 @@ +# Copyright 1999-2020 Gentoo Authors +# Distributed under the terms of the GNU General Public License v2 + +# @ECLASS: alternatives.eclass +# @AUTHOR: +# Original author: Alastair Tse (03 Oct 2003) +# @BLURB: Creates symlink to the latest version of multiple slotted packages. +# @DESCRIPTION: +# When a package is SLOT'ed, very often we need to have a symlink to the +# latest version. However, depending on the order the user has merged them, +# more often than not, the symlink maybe clobbered by the older versions. +# +# This eclass provides a convenience function that needs to be given a +# list of alternatives (descending order of recent-ness) and the symlink. +# It will choose the latest version it can find installed and create +# the desired symlink. +# +# There are two ways to use this eclass. First is by declaring two variables +# $SOURCE and $ALTERNATIVES where $SOURCE is the symlink to be created and +# $ALTERNATIVES is a list of alternatives. Second way is the use the function +# alternatives_makesym() like the example below. +# @EXAMPLE: +# pkg_postinst() { +# alternatives_makesym "/usr/bin/python" "/usr/bin/python2.3" "/usr/bin/python2.2" +# } +# +# The above example will create a symlink at /usr/bin/python to either +# /usr/bin/python2.3 or /usr/bin/python2.2. It will choose python2.3 over +# python2.2 if both exist. +# +# Alternatively, you can use this function: +# +# pkg_postinst() { +# alternatives_auto_makesym "/usr/bin/python" "/usr/bin/python[0-9].[0-9]" +# } +# +# This will use bash pathname expansion to fill a list of alternatives it can +# link to. It is probably more robust against version upgrades. You should +# consider using this unless you are want to do something special. + +# @ECLASS-VARIABLE: SOURCE +# @DEFAULT_UNSET +# @DESCRIPTION: +# The symlink to be created + +# @ECLASS-VARIABLE: ALTERNATIVES +# @DEFAULT_UNSET +# @DESCRIPTION: +# The list of alternatives + +# @FUNCTION: alternatives_auto_makesym +# @DESCRIPTION: +# automatic deduction based on a symlink and a regex mask +alternatives_auto_makesym() { + has "${EAPI:-0}" 0 1 2 && ! use prefix && EROOT="${ROOT}" + local SYMLINK REGEX ALT myregex + SYMLINK=$1 + REGEX=$2 + if [ "${REGEX:0:1}" != "/" ] + then + #not an absolute path: + #inherit the root directory of our main link path for our regex search + myregex="${SYMLINK%/*}/${REGEX}" + else + myregex=${REGEX} + fi + + # sort a space delimited string by converting it to a multiline list + # and then run sort -r over it. + # make sure we use ${EROOT} because otherwise stage-building will break + ALT="$(for i in $(echo ${EROOT}${myregex}); do echo ${i#${EROOT}}; done | sort -r)" + alternatives_makesym ${SYMLINK} ${ALT} +} + +alternatives_makesym() { + has "${EAPI:-0}" 0 1 2 && ! use prefix && EPREFIX= + local ALTERNATIVES="" + local SYMLINK="" + local alt pref + + # usage: alternatives_makesym [alternative targets..] + # make sure it is in the prefix, allow it already to be in the prefix + SYMLINK=${EPREFIX}/${1#${EPREFIX}} + # this trick removes the trailing / from ${ROOT} + pref=${ROOT%/} + shift + ALTERNATIVES=$@ + + # step through given alternatives from first to last + # and if one exists, link it and finish. + + for alt in ${ALTERNATIVES}; do + alt=${EPREFIX}/${alt#${EPREFIX}} + if [ -f "${pref}${alt}" ]; then + #are files in same directory? + if [ "${alt%/*}" = "${SYMLINK%/*}" ] + then + #yes; strip leading dirname from alt to create relative symlink + einfo "Linking ${alt} to ${pref}${SYMLINK} (relative)" + ln -sf ${alt##*/} ${pref}${SYMLINK} + else + #no; keep absolute path + einfo "Linking ${alt} to ${pref}${SYMLINK} (absolute)" + ln -sf ${pref}${alt} ${pref}${SYMLINK} + fi + break + fi + done + + # report any errors + if [ ! -L ${pref}${SYMLINK} ]; then + ewarn "Unable to establish ${pref}${SYMLINK} symlink" + else + # we need to check for either the target being in relative path form + # or absolute path form + if [ ! -f "`dirname ${pref}${SYMLINK}`/`readlink ${pref}${SYMLINK}`" -a \ + ! -f "`readlink ${pref}${SYMLINK}`" ]; then + ewarn "Removing dead symlink ${pref}${SYMLINK}" + rm -f ${pref}${SYMLINK} + fi + fi +} + +# @FUNCTION: alernatives-pkg_postinst +# @DESCRIPTION: +# The alternatives pkg_postinst, this function will be exported +alternatives_pkg_postinst() { + if [ -n "${ALTERNATIVES}" -a -n "${SOURCE}" ]; then + alternatives_makesym ${SOURCE} ${ALTERNATIVES} + fi +} + +# @FUNCTION: alternatives_pkg_postrm +# @DESCRIPTION: +# The alternatives pkg_postrm, this function will be exported +alternatives_pkg_postrm() { + if [ -n "${ALTERNATIVES}" -a -n "${SOURCE}" ]; then + alternatives_makesym ${SOURCE} ${ALTERNATIVES} + fi +} + +EXPORT_FUNCTIONS pkg_postinst pkg_postrm diff --git a/eclass/ant-tasks.eclass b/eclass/ant-tasks.eclass new file mode 100644 index 0000000..42f801a --- /dev/null +++ b/eclass/ant-tasks.eclass @@ -0,0 +1,167 @@ +# Copyright 2007-2020 Gentoo Authors +# Distributed under the terms of the GNU General Public License v2 + +# @ECLASS: ant-tasks.eclass +# @MAINTAINER: +# java@gentoo.org +# @AUTHOR: +# Vlastimil Babka +# @SUPPORTED_EAPIS: 6 7 +# @BLURB: Eclass for building dev-java/ant-* packages +# @DESCRIPTION: +# This eclass provides functionality and default ebuild variables for building +# dev-java/ant-* packages easily. + +case "${EAPI:-0}" in + 0|1|2|3|4|5) + die "ant-tasks.eclass: EAPI ${EAPI} is too old." + ;; + 6|7) + ;; + *) + die "ant-tasks.eclass: EAPI ${EAPI} is not supported yet." + ;; +esac + +# we set ant-core dep ourselves, restricted +JAVA_ANT_DISABLE_ANT_CORE_DEP=true +# rewriting build.xml for are the testcases has no reason atm +JAVA_PKG_BSFIX_ALL=no +inherit java-pkg-2 java-ant-2 +[[ ${EAPI:-0} -eq 6 ]] && inherit eapi7-ver + +EXPORT_FUNCTIONS src_unpack src_compile src_install + +# @ECLASS-VARIABLE: ANT_TASK_JDKVER +# @DESCRIPTION: +# Affects the >=virtual/jdk version set in DEPEND string. Defaults to 1.8, can +# be overridden from ebuild BEFORE inheriting this eclass. +ANT_TASK_JDKVER=${ANT_TASK_JDKVER-1.8} + +# @ECLASS-VARIABLE: ANT_TASK_JREVER +# @DESCRIPTION: +# Affects the >=virtual/jre version set in DEPEND string. Defaults to 1.8, can +# be overridden from ebuild BEFORE inheriting this eclass. +ANT_TASK_JREVER=${ANT_TASK_JREVER-1.8} + +# @ECLASS-VARIABLE: ANT_TASK_NAME +# @DESCRIPTION: +# The name of this ant task as recognized by ant's build.xml, derived from $PN +# by removing the ant- prefix. Read-only. +ANT_TASK_NAME="${PN#ant-}" + +# @ECLASS-VARIABLE: ANT_TASK_DEPNAME +# @DESCRIPTION: +# Specifies JAVA_PKG_NAME (PN{-SLOT} used with java-pkg_jar-from) of the package +# that this one depends on. Defaults to the name of ant task, ebuild can +# override it before inheriting this eclass. In case there is more than one +# dependency, the variable can be specified as bash array with multiple strings, +# one for each dependency. +ANT_TASK_DEPNAME=${ANT_TASK_DEPNAME-${ANT_TASK_NAME}} + +# @ECLASS-VARIABLE: ANT_TASK_DISABLE_VM_DEPS +# @DEFAULT_UNSET +# @DESCRIPTION: +# If set, no JDK/JRE deps are added. + +# @VARIABLE: ANT_TASK_PV +# @INTERNAL +# Version of ant-core this task is intended to register and thus load with. +ANT_TASK_PV="${PV}" + +# default for final releases +MY_PV=${PV} + +UPSTREAM_PREFIX="mirror://apache/ant/source" +GENTOO_PREFIX="https://dev.gentoo.org/~fordfrog/distfiles" + +# source/workdir name +MY_P="apache-ant-${MY_PV}" + +# Default values for standard ebuild variables, can be overridden from ebuild. +DESCRIPTION="Apache Ant's optional tasks depending on ${ANT_TASK_DEPNAME}" +HOMEPAGE="http://ant.apache.org/" +SRC_URI="${UPSTREAM_PREFIX}/${MY_P}-src.tar.bz2 + ${GENTOO_PREFIX}/ant-${PV}-gentoo.tar.bz2" +LICENSE="Apache-2.0" +SLOT="0" + +RDEPEND="~dev-java/ant-core-${PV}:0" +DEPEND="${RDEPEND}" + +if [[ -z "${ANT_TASK_DISABLE_VM_DEPS}" ]]; then + RDEPEND+=" >=virtual/jre-${ANT_TASK_JREVER}" + DEPEND+=" >=virtual/jdk-${ANT_TASK_JDKVER}" +fi + +# Would run the full ant test suite for every ant task +RESTRICT="test" + +S="${WORKDIR}/${MY_P}" + +# @FUNCTION: ant-tasks_src_unpack +# @USAGE: [ base ] [ jar-dep ] [ all ] +# @DESCRIPTION: +# The function Is split into two parts, defaults to both of them ('all'). +# +# base: performs the unpack, build.xml replacement and symlinks ant.jar from +# ant-core +# +# jar-dep: symlinks the jar file(s) from dependency package(s) +ant-tasks_src_unpack() { + [[ -z "${1}" ]] && ant-tasks_src_unpack all + + while [[ -n "${1}" ]]; do + case ${1} in + base) + unpack ${A} + cd "${S}" + + # replace build.xml with our modified for split building + if [ -e "${WORKDIR}"/${PV}-build.patch ] ; then + eapply "${WORKDIR}"/${PV}-build.patch + else + mv -f "${WORKDIR}"/build.xml . + fi + + cd lib + # remove bundled xerces + rm -f *.jar + + # ant.jar to build against + java-pkg_jar-from --build-only ant-core ant.jar;; + jar-dep) + # get jar from the dependency package(s) + if [[ -n "${ANT_TASK_DEPNAME}" ]]; then + for depname in "${ANT_TASK_DEPNAME[@]}"; do + java-pkg_jar-from ${depname} + done + fi;; + all) + ant-tasks_src_unpack base jar-dep;; + esac + shift + done + +} + +# @FUNCTION: ant-tasks_src_compile +# @DESCRIPTION: +# Compiles the jar with installed ant-core. +ant-tasks_src_compile() { + ANT_TASKS="none" eant -Dbuild.dep=${ANT_TASK_NAME} jar-dep +} + +# @FUNCTION: ant-tasks_src_install +# @DESCRIPTION: +# Installs the jar and registers its presence for the ant launcher script. +# Version param ensures it won't get loaded (thus break) when ant-core is +# updated to newer version. +ant-tasks_src_install() { + java-pkg_dojar build/lib/${PN}.jar + java-pkg_register-ant-task --version "${ANT_TASK_PV}" + + # create the compatibility symlink + dodir /usr/share/ant/lib + dosym /usr/share/${PN}/lib/${PN}.jar /usr/share/ant/lib/${PN}.jar +} diff --git a/eclass/apache-2.eclass b/eclass/apache-2.eclass new file mode 100644 index 0000000..aac2568 --- /dev/null +++ b/eclass/apache-2.eclass @@ -0,0 +1,714 @@ +# Copyright 1999-2020 Gentoo Authors +# Distributed under the terms of the GNU General Public License v2 + +# @ECLASS: apache-2.eclass +# @MAINTAINER: +# polynomial-c@gentoo.org +# @SUPPORTED_EAPIS: 6 7 +# @BLURB: Provides a common set of functions for apache-2.x ebuilds +# @DESCRIPTION: +# This eclass handles apache-2.x ebuild functions such as LoadModule generation +# and inter-module dependency checking. + +inherit autotools flag-o-matic multilib ssl-cert user toolchain-funcs + +[[ ${CATEGORY}/${PN} != www-servers/apache ]] \ + && die "Do not use this eclass with anything else than www-servers/apache ebuilds!" + +case ${EAPI:-0} in + 0|1|2|3|4|5) + die "This eclass is banned for EAPI<6" + ;; + 6) + inherit eapi7-ver + ;; + *) + LUA_COMPAT=( lua5-{1..4} ) + inherit lua-single + ;; +esac + +# settings which are version specific go in here: +case $(ver_cut 1-2) in + 2.4) + DEFAULT_MPM_THREADED="event" #509922 + ;; + *) + die "Unknown MAJOR.MINOR apache version." + ;; +esac + +# ============================================================================== +# INTERNAL VARIABLES +# ============================================================================== + +# @ECLASS-VARIABLE: GENTOO_PATCHNAME +# @DESCRIPTION: +# This internal variable contains the prefix for the patch tarball. +# Defaults to the full name and version (including revision) of the package. +# If you want to override this in an ebuild, use: +# ORIG_PR="(revision of Gentoo stuff you want)" +# GENTOO_PATCHNAME="gentoo-${PN}-${PV}${ORIG_PR:+-${ORIG_PR}}" +[[ -n "${GENTOO_PATCHNAME}" ]] || GENTOO_PATCHNAME="gentoo-${PF}" + +# @ECLASS-VARIABLE: GENTOO_PATCHDIR +# @DESCRIPTION: +# This internal variable contains the working directory where patches and config +# files are located. +# Defaults to the patchset name appended to the working directory. +[[ -n "${GENTOO_PATCHDIR}" ]] || GENTOO_PATCHDIR="${WORKDIR}/${GENTOO_PATCHNAME}" + +# @VARIABLE: GENTOO_DEVELOPER +# @DESCRIPTION: +# This variable needs to be set in the ebuild and contains the name of the +# gentoo developer who created the patch tarball + +# @VARIABLE: GENTOO_PATCHSTAMP +# @DESCRIPTION: +# This variable needs to be set in the ebuild and contains the date the patch +# tarball was created at in YYYYMMDD format + +# @VARIABLE: GENTOO_PATCH_A +# @DESCRIPTION: +# This variable should contain the entire filename of patch tarball. +# Defaults to the name of the patchset, with a datestamp. +[[ -n "${GENTOO_PATCH_A}" ]] || GENTOO_PATCH_A="${GENTOO_PATCHNAME}-${GENTOO_PATCHSTAMP}.tar.bz2" + +SRC_URI="mirror://apache/httpd/httpd-${PV}.tar.bz2 + https://dev.gentoo.org/~${GENTOO_DEVELOPER}/dist/apache/${GENTOO_PATCH_A}" + +# @VARIABLE: IUSE_MPMS_FORK +# @DESCRIPTION: +# This variable needs to be set in the ebuild and contains a list of forking +# (i.e. non-threaded) MPMs + +# @VARIABLE: IUSE_MPMS_THREAD +# @DESCRIPTION: +# This variable needs to be set in the ebuild and contains a list of threaded +# MPMs + +# @VARIABLE: IUSE_MODULES +# @DESCRIPTION: +# This variable needs to be set in the ebuild and contains a list of available +# built-in modules + +IUSE_MPMS="${IUSE_MPMS_FORK} ${IUSE_MPMS_THREAD}" +IUSE="${IUSE} debug doc gdbm ldap libressl selinux ssl static suexec +suexec-caps suexec-syslog split-usr threads" + +for module in ${IUSE_MODULES} ; do + case ${module} in + # Enable http2 by default (bug #563452) + http2) + IUSE+=" +apache2_modules_${module}" + ;; + *) + IUSE+=" apache2_modules_${module}" + ;; + esac +done + +_apache2_set_mpms() { + local mpm + local ompm + + for mpm in ${IUSE_MPMS} ; do + IUSE="${IUSE} apache2_mpms_${mpm}" + + REQUIRED_USE+=" apache2_mpms_${mpm}? (" + for ompm in ${IUSE_MPMS} ; do + if [[ "${mpm}" != "${ompm}" ]] ; then + REQUIRED_USE+=" !apache2_mpms_${ompm}" + fi + done + + if has ${mpm} ${IUSE_MPMS_FORK} ; then + REQUIRED_USE+=" !threads" + else + REQUIRED_USE+=" threads" + fi + REQUIRED_USE+=" )" + done + + REQUIRED_USE+=" apache2_mpms_prefork? ( !apache2_modules_http2 )" +} +_apache2_set_mpms +unset -f _apache2_set_mpms + +# Dependencies +RDEPEND=" + dev-lang/perl + >=dev-libs/apr-1.5.1:= + =dev-libs/apr-util-1*:=[gdbm=,ldap?] + dev-libs/libpcre + apache2_modules_brotli? ( >=app-arch/brotli-0.6.0:= ) + apache2_modules_deflate? ( sys-libs/zlib ) + apache2_modules_http2? ( + >=net-libs/nghttp2-1.2.1 + kernel_linux? ( sys-apps/util-linux ) + ) + apache2_modules_md? ( >=dev-libs/jansson-2.10 ) + apache2_modules_mime? ( app-misc/mime-types ) + apache2_modules_proxy_http2? ( + >=net-libs/nghttp2-1.2.1 + kernel_linux? ( sys-apps/util-linux ) + ) + apache2_modules_session_crypto? ( + libressl? ( dev-libs/apr-util[libressl] ) + !libressl? ( dev-libs/apr-util[openssl] ) + ) + gdbm? ( sys-libs/gdbm:= ) + ldap? ( =net-nds/openldap-2* ) + selinux? ( sec-policy/selinux-apache ) + ssl? ( + !libressl? ( >=dev-libs/openssl-1.0.2:0= ) + libressl? ( dev-libs/libressl:0= ) + kernel_linux? ( sys-apps/util-linux ) + ) +" + +DEPEND="${RDEPEND}" +BDEPEND=" + virtual/pkgconfig + suexec? ( suexec-caps? ( sys-libs/libcap ) ) +" +if [[ ${EAPI} == 6 ]] ; then + DEPEND+=" ${BDEPEND}" +fi +PDEPEND="~app-admin/apache-tools-${PV}" + +REQUIRED_USE+=" + apache2_modules_http2? ( ssl ) + apache2_modules_md? ( ssl ) +" + +S="${WORKDIR}/httpd-${PV}" + +# @VARIABLE: MODULE_DEPENDS +# @DESCRIPTION: +# This variable needs to be set in the ebuild and contains a space-separated +# list of dependency tokens each with a module and the module it depends on +# separated by a colon + +# now extend REQUIRED_USE to reflect the module dependencies to portage +_apache2_set_module_depends() { + local dep + + for dep in ${MODULE_DEPENDS} ; do + REQUIRED_USE+=" apache2_modules_${dep%:*}? ( apache2_modules_${dep#*:} )" + done +} +_apache2_set_module_depends +unset -f _apache2_set_module_depends + +# ============================================================================== +# INTERNAL FUNCTIONS +# ============================================================================== + +# @ECLASS-VARIABLE: MY_MPM +# @DESCRIPTION: +# This internal variable contains the selected MPM after a call to setup_mpm() + +# @FUNCTION: setup_mpm +# @DESCRIPTION: +# This internal function makes sure that only one of APACHE2_MPMS was selected +# or a default based on USE=threads is selected if APACHE2_MPMS is empty +setup_mpm() { + MY_MPM="" + for x in ${IUSE_MPMS} ; do + if use apache2_mpms_${x} ; then + # there can at most be one MPM selected because of REQUIRED_USE constraints + MY_MPM=${x} + elog + elog "Selected MPM: ${MY_MPM}" + elog + break + fi + done + + if [[ -z "${MY_MPM}" ]] ; then + if use threads ; then + MY_MPM=${DEFAULT_MPM_THREADED} + elog + elog "Selected default threaded MPM: ${MY_MPM}" + elog + else + MY_MPM=prefork + elog + elog "Selected default MPM: ${MY_MPM}" + elog + fi + fi +} + +# @VARIABLE: MODULE_CRITICAL +# @DESCRIPTION: +# This variable needs to be set in the ebuild and contains a space-separated +# list of modules critical for the default apache. A user may still +# disable these modules for custom minimal installation at their own risk. + +# @FUNCTION: check_module_critical +# @DESCRIPTION: +# This internal function warns the user about modules critical for the default +# apache configuration. +check_module_critical() { + local unsupported=0 + + for m in ${MODULE_CRITICAL} ; do + if ! has ${m} ${MY_MODS[@]} ; then + ewarn "Module '${m}' is required in the default apache configuration." + unsupported=1 + fi + done + + if [[ ${unsupported} -ne 0 ]] ; then + ewarn + ewarn "You have disabled one or more required modules" + ewarn "for the default apache configuration." + ewarn "Although this is not an error, please be" + ewarn "aware that this setup is UNSUPPORTED." + ewarn + fi +} + +# @ECLASS-VARIABLE: MY_CONF +# @DESCRIPTION: +# This internal variable contains the econf options for the current module +# selection after a call to setup_modules() + +# @ECLASS-VARIABLE: MY_MODS +# @DESCRIPTION: +# This internal variable contains a sorted, space separated list of currently +# selected modules after a call to setup_modules() + +# @FUNCTION: setup_modules +# @DESCRIPTION: +# This internal function selects all built-in modules based on USE flags and +# APACHE2_MODULES USE_EXPAND flags +setup_modules() { + local mod_type= x= + + if use static ; then + mod_type="static" + else + mod_type="shared" + fi + + MY_CONF=( --enable-so=static ) + MY_MODS=() + + if use ldap ; then + MY_CONF+=( + --enable-authnz_ldap=${mod_type} + --enable-ldap=${mod_type} + ) + MY_MODS+=( ldap authnz_ldap ) + else + MY_CONF+=( --disable-authnz_ldap --disable-ldap ) + fi + + if use ssl ; then + MY_CONF+=( --with-ssl --enable-ssl=${mod_type} ) + MY_MODS+=( ssl ) + else + MY_CONF+=( --without-ssl --disable-ssl ) + fi + + if use suexec ; then + elog "You can manipulate several configure options of suexec" + elog "through the following environment variables:" + elog + elog " SUEXEC_SAFEPATH: Default PATH for suexec (default: '${EPREFIX}/usr/local/bin:${EPREFIX}/usr/bin:${EPREFIX}/bin')" + if ! use suexec-syslog ; then + elog " SUEXEC_LOGFILE: Path to the suexec logfile (default: '${EPREFIX}/var/log/apache2/suexec_log')" + fi + elog " SUEXEC_CALLER: Name of the user Apache is running as (default: apache)" + elog " SUEXEC_DOCROOT: Directory in which suexec will run scripts (default: '${EPREFIX}/var/www')" + elog " SUEXEC_MINUID: Minimum UID, which is allowed to run scripts via suexec (default: 1000)" + elog " SUEXEC_MINGID: Minimum GID, which is allowed to run scripts via suexec (default: 100)" + elog " SUEXEC_USERDIR: User subdirectories (like /home/user/html) (default: public_html)" + elog " SUEXEC_UMASK: Umask for the suexec process (default: 077)" + elog + + MY_CONF+=( --with-suexec-safepath="${SUEXEC_SAFEPATH:-${EPREFIX}/usr/local/bin:${EPREFIX}/usr/bin:${EPREFIX}/bin}" ) + MY_CONF+=( $(use_with !suexec-syslog suexec-logfile "${SUEXEC_LOGFILE:-${EPREFIX}/var/log/apache2/suexec_log}") ) + MY_CONF+=( $(use_with suexec-syslog) ) + if use suexec-syslog && use suexec-caps ; then + MY_CONF+=( --enable-suexec-capabilities ) + fi + MY_CONF+=( --with-suexec-bin="${EPREFIX}/usr/sbin/suexec" ) + MY_CONF+=( --with-suexec-userdir=${SUEXEC_USERDIR:-public_html} ) + MY_CONF+=( --with-suexec-caller=${SUEXEC_CALLER:-apache} ) + MY_CONF+=( --with-suexec-docroot="${SUEXEC_DOCROOT:-${EPREFIX}/var/www}" ) + MY_CONF+=( --with-suexec-uidmin=${SUEXEC_MINUID:-1000} ) + MY_CONF+=( --with-suexec-gidmin=${SUEXEC_MINGID:-100} ) + MY_CONF+=( --with-suexec-umask=${SUEXEC_UMASK:-077} ) + MY_CONF+=( --enable-suexec=${mod_type} ) + MY_MODS+=( suexec ) + else + MY_CONF+=( --disable-suexec ) + fi + + for x in ${IUSE_MODULES} ; do + if use apache2_modules_${x} ; then + MY_CONF+=( --enable-${x}=${mod_type} ) + MY_MODS+=( ${x} ) + else + MY_CONF+=( --disable-${x} ) + fi + done + + # sort and uniquify MY_MODS + MY_MODS=( $(echo ${MY_MODS[@]} | tr ' ' '\n' | sort -u) ) + check_module_critical +} + +# @VARIABLE: MODULE_DEFINES +# @DESCRIPTION: +# This variable needs to be set in the ebuild and contains a space-separated +# list of tokens each mapping a module to a runtime define which can be +# specified in APACHE2_OPTS in /etc/conf.d/apache2 to enable this particular +# module. + +# @FUNCTION: generate_load_module +# @DESCRIPTION: +# This internal function generates the LoadModule lines for httpd.conf based on +# the current module selection and MODULE_DEFINES +generate_load_module() { + local def= endit=0 m= mod_lines= mod_dir="${ED%/}/usr/$(get_libdir)/apache2/modules" + + if use static; then + sed -i -e "/%%LOAD_MODULE%%/d" \ + "${GENTOO_PATCHDIR}"/conf/httpd.conf + return + fi + + for m in ${MY_MODS[@]} ; do + if [[ -e "${mod_dir}/mod_${m}.so" ]] ; then + for def in ${MODULE_DEFINES} ; do + if [[ "${m}" == "${def%:*}" ]] ; then + mod_lines="${mod_lines}\n" + endit=1 + fi + done + + mod_lines="${mod_lines}\nLoadModule ${m}_module modules/mod_${m}.so" + + if [[ ${endit} -ne 0 ]] ; then + mod_lines="${mod_lines}\n" + endit=0 + fi + fi + done + + sed -i -e "s:%%LOAD_MODULE%%:${mod_lines}:" \ + "${GENTOO_PATCHDIR}"/conf/httpd.conf +} + +# @FUNCTION: check_upgrade +# @DESCRIPTION: +# This internal function checks if the previous configuration file for built-in +# modules exists in ROOT and prevents upgrade in this case. Users are supposed +# to convert this file to the new APACHE2_MODULES USE_EXPAND variable and remove +# it afterwards. +check_upgrade() { + if [[ -e "${EROOT}"etc/apache2/apache2-builtin-mods ]]; then + eerror "The previous configuration file for built-in modules" + eerror "(${EROOT}etc/apache2/apache2-builtin-mods) exists on your" + eerror "system." + eerror + eerror "Please read https://wiki.gentoo.org/wiki/Project:Apache/Upgrading" + eerror "for detailed information how to convert this file to the new" + eerror "APACHE2_MODULES USE_EXPAND variable." + eerror + die "upgrade not possible with existing ${ROOT}etc/apache2/apache2-builtin-mods" + fi +} + +# ============================================================================== +# EXPORTED FUNCTIONS +# ============================================================================== + +# @FUNCTION: apache-2_pkg_setup +# @DESCRIPTION: +# This function selects built-in modules, the MPM and other configure options, +# creates the apache user and group and informs about CONFIG_SYSVIPC being +# needed (we don't depend on kernel sources and therefore cannot check). +apache-2_pkg_setup() { + check_upgrade + + # setup apache user and group + enewgroup apache 81 + enewuser apache 81 -1 /var/www apache + + setup_mpm + setup_modules + + if use debug; then + MY_CONF+=( --enable-exception-hook ) + fi + + elog "Please note that you need SysV IPC support in your kernel." + elog "Make sure CONFIG_SYSVIPC=y is set." + elog + + if use userland_BSD; then + elog "On BSD systems you need to add the following line to /boot/loader.conf:" + elog " accf_http_load=\"YES\"" + if use ssl ; then + elog " accf_data_load=\"YES\"" + fi + elog + fi + + if [[ ${EAPI} != 6 ]] && use apache2_modules_lua ; then + lua-single_pkg_setup + fi +} + +# @FUNCTION: apache-2_src_prepare +# @DESCRIPTION: +# This function applies patches, configures a custom file-system layout and +# rebuilds the configure scripts. +apache-2_src_prepare() { + #fix prefix in conf files etc (bug #433736) + use !prefix || sed -e "s@/\(usr\|var\|etc\|run\)/@${EPREFIX}&@g" \ + -i "${GENTOO_PATCHDIR}"/conf/httpd.conf "${GENTOO_PATCHDIR}"/scripts/* \ + "${GENTOO_PATCHDIR}"/docs/*.example "${GENTOO_PATCHDIR}"/patches/*.layout \ + "${GENTOO_PATCHDIR}"/init/* "${GENTOO_PATCHDIR}"/conf/vhosts.d/* \ + "${GENTOO_PATCHDIR}"/conf/modules.d/* || die + + # 03_all_gentoo-apache-tools.patch injects -Wl,-z,now, which is not a good + # idea for everyone + case ${CHOST} in + *-linux-gnu|*-solaris*|*-freebsd*) + # do nothing, these use GNU binutils + : + ;; + *-darwin*) + sed -i -e 's/-Wl,-z,now/-Wl,-bind_at_load/g' \ + "${GENTOO_PATCHDIR}"/patches/03_all_gentoo_apache-tools.patch \ + || die + ;; + *) + # patch it out to be like upstream + sed -i -e 's/-Wl,-z,now//g' \ + "${GENTOO_PATCHDIR}"/patches/03_all_gentoo_apache-tools.patch \ + || die + ;; + esac + + # Use correct multilib libdir in gentoo patches + sed -i -e "s:/usr/lib:/usr/$(get_libdir):g" \ + "${GENTOO_PATCHDIR}"/{conf/httpd.conf,init/*,patches/config.layout} \ + || die "libdir sed failed" + + eapply "${GENTOO_PATCHDIR}"/patches/*.patch + default + + # Don't rename configure.in _before_ any possible user patches! + if [[ -f "configure.in" ]] ; then + elog "Renaming configure.in to configure.ac" + mv configure.{in,ac} || die + fi + + # setup the filesystem layout config + cat "${GENTOO_PATCHDIR}"/patches/config.layout >> "${S}"/config.layout || \ + die "Failed preparing config.layout!" + sed -i -e "s:version:${PF}:g" "${S}"/config.layout || die + + # apache2.8 instead of httpd.8 (bug #194828) + mv docs/man/{httpd,apache2}.8 || die + sed -i -e 's/httpd\.8/apache2.8/g' Makefile.in || die + + # patched-in MPMs need the build environment rebuilt + sed -i -e '/sinclude/d' configure.ac || die + AT_M4DIR=build eautoreconf + + # ${T} must be not group-writable, else grsec TPE will block it + chmod g-w "${T}" || die + + # This package really should upgrade to using pcre's .pc file. + cat <<-\EOF >"${T}"/pcre-config + #!/bin/bash + flags=() + for flag; do + if [[ ${flag} == "--version" ]]; then + flags+=( --modversion ) + else + flags+=( "${flag}" ) + fi + done + exec ${PKG_CONFIG} libpcre "${flags[@]}" + EOF + chmod a+x "${T}"/pcre-config || die +} + +# @FUNCTION: apache-2_src_configure +# @DESCRIPTION: +# This function adds compiler flags and runs econf and emake based on MY_MPM and +# MY_CONF +apache-2_src_configure() { + tc-export PKG_CONFIG + + # Sanity check in case people have bad mounts/TPE settings. #500928 + if ! "${T}"/pcre-config --help >/dev/null ; then + eerror "Could not execute ${T}/pcre-config; do you have bad mount" + eerror "permissions in ${T} or have TPE turned on in your kernel?" + die "check your runtime settings #500928" + fi + + # Instead of filtering --as-needed (bug #128505), append --no-as-needed + # Thanks to Harald van Dijk + append-ldflags $(no-as-needed) + + # peruser MPM debugging with -X is nearly impossible + if has peruser ${IUSE_MPMS} && use apache2_mpms_peruser ; then + use debug && append-flags -DMPM_PERUSER_DEBUG + fi + + # econf overwrites the stuff from config.layout, so we have to put them into + # our myconf line too + MY_CONF+=( + --includedir="${EPREFIX}"/usr/include/apache2 + --libexecdir="${EPREFIX}"/usr/$(get_libdir)/apache2/modules + --datadir="${EPREFIX}"/var/www/localhost + --sysconfdir="${EPREFIX}"/etc/apache2 + --localstatedir="${EPREFIX}"/var + --with-mpm=${MY_MPM} + --with-apr="${SYSROOT}${EPREFIX}"/usr + --with-apr-util="${SYSROOT}${EPREFIX}"/usr + --with-pcre="${T}"/pcre-config + --with-z="${EPREFIX}"/usr + --with-port=80 + --with-program-name=apache2 + --enable-layout=Gentoo + ) + ac_cv_path_PKGCONFIG=${PKG_CONFIG} \ + econf "${MY_CONF[@]}" + + sed -i -e 's:apache2\.conf:httpd.conf:' include/ap_config_auto.h || die +} + +# @FUNCTION: apache-2_src_install +# @DESCRIPTION: +# This function runs `emake install' and generates, installs and adapts the gentoo +# specific configuration files found in the tarball +apache-2_src_install() { + emake DESTDIR="${D}" MKINSTALLDIRS="mkdir -p" install + + # install our configuration files + keepdir /etc/apache2/vhosts.d + keepdir /etc/apache2/modules.d + + generate_load_module + insinto /etc/apache2 + doins -r "${GENTOO_PATCHDIR}"/conf/* + use apache2_modules_mime_magic && doins docs/conf/magic + + insinto /etc/logrotate.d + newins "${GENTOO_PATCHDIR}"/scripts/apache2-logrotate apache2 + + # generate a sane default APACHE2_OPTS + APACHE2_OPTS="-D DEFAULT_VHOST -D INFO" + use doc && APACHE2_OPTS+=" -D MANUAL" + use ssl && APACHE2_OPTS+=" -D SSL -D SSL_DEFAULT_VHOST" + use suexec && APACHE2_OPTS+=" -D SUEXEC" + if has negotiation ${APACHE2_MODULES} && use apache2_modules_negotiation; then + APACHE2_OPTS+=" -D LANGUAGE" + fi + + sed -i -e "s:APACHE2_OPTS=\".*\":APACHE2_OPTS=\"${APACHE2_OPTS}\":" \ + "${GENTOO_PATCHDIR}"/init/apache2.confd || die + + newconfd "${GENTOO_PATCHDIR}"/init/apache2.confd apache2 + newinitd "${GENTOO_PATCHDIR}"/init/apache2.initd apache2 + + # install apache2ctl wrapper for our init script if available + if test -e "${GENTOO_PATCHDIR}"/scripts/apache2ctl; then + exeinto /usr/sbin + doexe "${GENTOO_PATCHDIR}"/scripts/apache2ctl + else + dosym /etc/init.d/apache2 /usr/sbin/apache2ctl + fi + + # provide legacy symlink for apxs, bug 177697 + dosym apxs /usr/sbin/apxs2 + + # install some documentation + dodoc ABOUT_APACHE CHANGES LAYOUT README README.platforms VERSIONING + dodoc "${GENTOO_PATCHDIR}"/docs/* + + # drop in a convenient link to the manual + if use doc ; then + sed -i -e "s:VERSION:${PVR}:" \ + "${ED%/}/etc/apache2/modules.d/00_apache_manual.conf" \ + || die + docompress -x /usr/share/doc/${PF}/manual # 503640 + else + rm -f "${ED%/}/etc/apache2/modules.d/00_apache_manual.conf" \ + || die + rm -Rf "${ED%/}/usr/share/doc/${PF}/manual" || die + fi + + # the default icons and error pages get stored in + # /usr/share/apache2/{error,icons} + dodir /usr/share/apache2 + mv -f "${ED%/}/var/www/localhost/error" \ + "${ED%/}/usr/share/apache2/error" || die + mv -f "${ED%/}/var/www/localhost/icons" \ + "${ED%/}/usr/share/apache2/icons" || die + rm -rf "${ED%/}/var/www/localhost/" || die + eend $? + + # set some sane permissions for suexec + if use suexec ; then + if ! use suexec-syslog || ! use suexec-caps ; then + fowners 0:${SUEXEC_CALLER:-apache} /usr/sbin/suexec + fperms 4710 /usr/sbin/suexec + # provide legacy symlink for suexec, bug 177697 + dosym /usr/sbin/suexec /usr/sbin/suexec2 + fi + fi + + # empty dirs + local i + for i in /var/lib/dav /var/log/apache2 /var/cache/apache2 ; do + keepdir ${i} + fowners apache:apache ${i} + fperms 0750 ${i} + done +} + +# @FUNCTION: apache-2_pkg_postinst +# @DESCRIPTION: +# This function creates test certificates if SSL is enabled and installs the +# default index.html to /var/www/localhost if it does not exist. We do this here +# because the default webroot is a copy of the files that exist elsewhere and we +# don't want them to be managed/removed by portage when apache is upgraded. +apache-2_pkg_postinst() { + if use ssl && [[ ! -e "${EROOT}/etc/ssl/apache2/server.pem" ]]; then + SSL_ORGANIZATION="${SSL_ORGANIZATION:-Apache HTTP Server}" + install_cert /etc/ssl/apache2/server + ewarn + ewarn "The location of SSL certificates has changed. If you are" + ewarn "upgrading from ${CATEGORY}/${PN}-2.2.13 or earlier (or remerged" + ewarn "*any* apache version), you might want to move your old" + ewarn "certificates from /etc/apache2/ssl/ to /etc/ssl/apache2/ and" + ewarn "update your config files." + ewarn + fi + + if [[ ! -e "${EROOT}/var/www/localhost" ]] ; then + mkdir -p "${EROOT}/var/www/localhost/htdocs" + echo "

It works!

" > "${EROOT}/var/www/localhost/htdocs/index.html" + fi + + echo + elog "Attention: cgi and cgid modules are now handled via APACHE2_MODULES flags" + elog "in make.conf. Make sure to enable those in order to compile them." + elog "In general, you should use 'cgid' with threaded MPMs and 'cgi' otherwise." + echo + +} + +EXPORT_FUNCTIONS pkg_setup src_prepare src_configure src_install pkg_postinst diff --git a/eclass/apache-module.eclass b/eclass/apache-module.eclass new file mode 100644 index 0000000..e192a74 --- /dev/null +++ b/eclass/apache-module.eclass @@ -0,0 +1,238 @@ +# Copyright 1999-2020 Gentoo Authors +# Distributed under the terms of the GNU General Public License v2 + +# @ECLASS: apache-module.eclass +# @MAINTAINER: +# apache-devs@gentoo.org +# @BLURB: Provides a common set of functions for apache modules +# @DESCRIPTION: +# This eclass handles apache modules in a sane way. +# +# To make use of this eclass simply call one of the need/want_apache functions +# described in depend.apache.eclass. Make sure you use the need/want_apache call +# after you have defined DEPEND and RDEPEND. Also note that you can not rely on +# the automatic RDEPEND=DEPEND that portage does if you use this eclass. +# +# See Bug 107127 for more information. +# +# @EXAMPLE: +# +# Here is a simple example of an ebuild for mod_foo: +# +# @CODE +# APACHE2_MOD_CONF="42_mod_foo" +# APACHE2_MOD_DEFINE="FOO" +# need_apache2 +# @CODE +# +# A more complicated example for a module with non-standard locations: +# +# @CODE +# APXS2_S="${S}/apache22/src" +# APACHE2_MOD_FILE="${APXS2_S}/${PN}.so" +# APACHE2_MOD_CONF="42_${PN}" +# APACHE2_MOD_DEFINE="FOO" +# DOCFILES="docs/*.html" +# need_apache2_2 +# @CODE +# +# A basic module configuration which just loads the module into apache: +# +# @CODE +# +# LoadModule foo_module modules/mod_foo.so +# +# @CODE + +inherit depend.apache + +# ============================================================================== +# PUBLIC VARIABLES +# ============================================================================== + +# @VARIABLE: APXS2_S +# @DESCRIPTION: +# Path to temporary build directory. (Defaults to `${S}/src' if it exists, +# `${S}' otherwise) + +# @VARIABLE: APXS2_ARGS +# @DESCRIPTION: +# Arguments to pass to the apxs tool. (Defaults to `-c ${PN}.c') + +# @VARIABLE: APACHE2_EXECFILES +# @DESCRIPTION: +# List of files that will be installed into ${APACHE_MODULE_DIR} beside +# ${APACHE2_MOD_FILE}. In addition, this function also sets the executable +# permission on those files. + +# @VARIABLE: APACHE2_MOD_CONF +# @DESCRIPTION: +# Module configuration file installed by src_install (minus the .conf suffix and +# relative to ${FILESDIR}). + +# @VARIABLE: APACHE2_MOD_DEFINE +# @DESCRIPTION: +# Name of define (e.g. FOO) to use in conditional loading of the installed +# module/its config file, multiple defines should be space separated. + +# @VARIABLE: APACHE2_MOD_FILE +# @DESCRIPTION: +# Name of the module that src_install installs minus the .so suffix. (Defaults +# to `${APXS2_S}/.libs/${PN}.so') + +# @VARIABLE: APACHE2_VHOST_CONF +# @DESCRIPTION: +# Virtual host configuration file installed by src_install (minus the .conf +# suffix and relative to ${FILESDIR}). + +# @VARIABLE: DOCFILES +# @DESCRIPTION: +# If the exported src_install() is being used, and ${DOCFILES} is non-zero, some +# sed-fu is applied to split out html documentation (if any) from normal +# documentation, and dodoc'd or dohtml'd. + +# ============================================================================== +# INTERNAL FUNCTIONS +# ============================================================================== + +# Internal function to construct the default ${APXS2_S} path if required. +apache_cd_dir() { + debug-print-function $FUNCNAME $* + + local CD_DIR="${APXS2_S}" + + if [[ -z "${CD_DIR}" ]] ; then + if [[ -d "${S}/src" ]] ; then + CD_DIR="${S}/src" + else + CD_DIR="${S}" + fi + fi + + debug-print $FUNCNAME "CD_DIR=${CD_DIR}" + echo "${CD_DIR}" +} + +# Internal function to construct the default ${APACHE2_MOD_FILE} if required. +apache_mod_file() { + debug-print-function $FUNCNAME $* + + local MOD_FILE="${APACHE2_MOD_FILE:-$(apache_cd_dir)/.libs/${PN}.so}" + + debug-print $FUNCNAME "MOD_FILE=${MOD_FILE}" + echo "${MOD_FILE}" +} + +# Internal function for picking out html files from ${DOCFILES}. It takes an +# optional first argument `html'; if the first argument is equals `html', only +# html files are returned, otherwise normal (non-html) docs are returned. +apache_doc_magic() { + debug-print-function $FUNCNAME $* + + local DOCS= + + if [[ -n "${DOCFILES}" ]] ; then + if [[ "x$1" == "xhtml" ]] ; then + DOCS="`echo ${DOCFILES} | sed -e 's/ /\n/g' | sed -e '/^[^ ]*.html$/ !d'`" + else + DOCS="`echo ${DOCFILES} | sed 's, *[^ ]*\+.html, ,g'`" + fi + fi + + debug-print $FUNCNAME "DOCS=${DOCS}" + echo "${DOCS}" +} + +# ============================================================================== +# EXPORTED FUNCTIONS +# ============================================================================== + +# @FUNCTION: apache-module_src_compile +# @DESCRIPTION: +# The default action is to call ${APXS} with the value of ${APXS2_ARGS}. If a +# module requires a different build setup than this, use ${APXS} in your own +# src_compile routine. +apache-module_src_compile() { + debug-print-function $FUNCNAME $* + + local CD_DIR=$(apache_cd_dir) + cd "${CD_DIR}" || die "cd ${CD_DIR} failed" + + APXS2_ARGS="${APXS2_ARGS:--c ${PN}.c}" + ${APXS} ${APXS2_ARGS} || die "${APXS} ${APXS2_ARGS} failed" +} + +# @FUNCTION: apache-module_src_install +# @DESCRIPTION: +# This installs the files into apache's directories. The module is installed +# from a directory chosen as above (apache_cd_dir). In addition, this function +# can also set the executable permission on files listed in +# ${APACHE2_EXECFILES}. The configuration file name is listed in +# ${APACHE2_MOD_CONF} without the .conf extensions, so if you configuration is +# 55_mod_foo.conf, APACHE2_MOD_CONF would be 55_mod_foo. ${DOCFILES} contains +# the list of files you want filed as documentation. +apache-module_src_install() { + debug-print-function $FUNCNAME $* + + local CD_DIR=$(apache_cd_dir) + pushd "${CD_DIR}" >/dev/null || die "cd ${CD_DIR} failed" + + local MOD_FILE=$(apache_mod_file) + + exeinto "${APACHE_MODULESDIR}" + doexe ${MOD_FILE} || die "internal ebuild error: '${MOD_FILE}' not found" + [[ -n "${APACHE2_EXECFILES}" ]] && doexe ${APACHE2_EXECFILES} + + if [[ -n "${APACHE2_MOD_CONF}" ]] ; then + insinto "${APACHE_MODULES_CONFDIR}" + set -- ${APACHE2_MOD_CONF} + newins "${FILESDIR}/${1}.conf" "$(basename ${2:-$1}).conf" \ + || die "internal ebuild error: '${FILESDIR}/${1}.conf' not found" + fi + + if [[ -n "${APACHE2_VHOST_CONF}" ]] ; then + insinto "${APACHE_VHOSTS_CONFDIR}" + set -- ${APACHE2_VHOST_CONF} + newins "${FILESDIR}/${1}.conf" "$(basename ${2:-$1}).conf " \ + || die "internal ebuild error: '${FILESDIR}/${1}.conf' not found" + fi + + cd "${S}" + + if [[ -n "${DOCFILES}" ]] ; then + local OTHER_DOCS=$(apache_doc_magic) + local HTML_DOCS=$(apache_doc_magic html) + + [[ -n "${OTHER_DOCS}" ]] && dodoc ${OTHER_DOCS} + [[ -n "${HTML_DOCS}" ]] && dohtml ${HTML_DOCS} + fi + + popd >/dev/null +} + +# @FUNCTION: apache-module_pkg_postinst +# @DESCRIPTION: +# This prints out information about the installed module and how to enable it. +apache-module_pkg_postinst() { + debug-print-function $FUNCNAME $* + + if [[ -n "${APACHE2_MOD_DEFINE}" ]] ; then + local my_opts="-D ${APACHE2_MOD_DEFINE// / -D }" + + einfo + einfo "To enable ${PN}, you need to edit your /etc/conf.d/apache2 file and" + einfo "add '${my_opts}' to APACHE2_OPTS." + einfo + fi + + if [[ -n "${APACHE2_MOD_CONF}" ]] ; then + set -- ${APACHE2_MOD_CONF} + einfo + einfo "Configuration file installed as" + einfo " ${APACHE_MODULES_CONFDIR}/$(basename ${2:-$1}).conf" + einfo "You may want to edit it before turning the module on in /etc/conf.d/apache2" + einfo + fi +} + +EXPORT_FUNCTIONS src_compile src_install pkg_postinst diff --git a/eclass/aspell-dict-r1.eclass b/eclass/aspell-dict-r1.eclass new file mode 100644 index 0000000..b07af61 --- /dev/null +++ b/eclass/aspell-dict-r1.eclass @@ -0,0 +1,90 @@ +# Copyright 1999-2020 Gentoo Authors +# Distributed under the terms of the GNU General Public License v2 + +# @ECLASS: aspell-dict-r1.eclass +# @MAINTAINER: +# maintainer-needed@gentoo.org +# @AUTHOR: +# Original author: Seemant Kulleen +# -r1 author: David Seifert +# @SUPPORTED_EAPIS: 6 +# @BLURB: An eclass to streamline the construction of ebuilds for new aspell dicts +# @DESCRIPTION: +# The aspell-dict-r1 eclass is designed to streamline the construction of +# ebuilds for the new aspell dictionaries (from gnu.org) which support +# aspell-0.50. Support for aspell-0.60 has been added by Sergey Ulanov. + +# @ECLASS-VARIABLE: ASPELL_LANG +# @REQUIRED +# @DESCRIPTION: +# Pure cleartext string that is included into DESCRIPTION. This is the name +# of the language, for instance "Hungarian". Needs to be defined before +# inheriting the eclass. + +# @ECLASS-VARIABLE: ASPELL_VERSION +# @DESCRIPTION: +# What major version of aspell is this dictionary for? Valid values are 5, 6 or undefined. +# This value is used to construct SRC_URI and *DEPEND strings. If defined to 6, +# >=app-text/aspell-0.60 will be added to DEPEND and RDEPEND, otherwise, +# >=app-text/aspell-0.50 is added to DEPEND and RDEPEND. If the value is to be overridden, +# it needs to be overridden before inheriting the eclass. + +case ${EAPI:-0} in + [0-5]) + die "aspell-dict-r1.eclass is banned in EAPI ${EAPI:-0}" + ;; + 6) + ;; + *) + die "Unknown EAPI ${EAPI:-0}" + ;; +esac + +EXPORT_FUNCTIONS src_configure src_install + +if [[ ! ${_ASPELL_DICT_R1} ]]; then + +# aspell packages have an idiosyncratic versioning scheme, that is +# the last separating version separator is replaced by a '-'. +_ASPELL_P=aspell${ASPELL_VERSION}-${PN/aspell-/}-${PV%.*}-${PV##*.} + +# @ECLASS-VARIABLE: ASPELL_SPELLANG +# @DESCRIPTION: +# Short (readonly) form of the language code, generated from ${PN} +# For instance, 'aspell-hu' yields the value 'hu'. +readonly ASPELL_SPELLANG=${PN/aspell-/} +S="${WORKDIR}/${_ASPELL_P}" + +DESCRIPTION="${ASPELL_LANG} language dictionary for aspell" +HOMEPAGE="http://aspell.net" +SRC_URI="mirror://gnu/aspell/dict/${ASPELL_SPELLANG}/${_ASPELL_P}.tar.bz2" +unset _ASPELL_P + +IUSE="" +SLOT="0" + +_ASPELL_MAJOR_VERSION=${ASPELL_VERSION:-5} +[[ ${_ASPELL_MAJOR_VERSION} != [56] ]] && die "${ASPELL_VERSION} is not a valid version" + +RDEPEND=">=app-text/aspell-0.${_ASPELL_MAJOR_VERSION}0" +DEPEND="${RDEPEND}" +unset _ASPELL_MAJOR_VERSION + +# @FUNCTION: aspell-dict-r1_src_configure +# @DESCRIPTION: +# The aspell-dict-r1 src_configure function which is exported. +aspell-dict-r1_src_configure() { + # non-autoconf based script, cannot be used with econf + ./configure || die +} + +# @FUNCTION: aspell-dict-r1_src_install +# @DESCRIPTION: +# The aspell-dict-r1 src_install function which is exported. +aspell-dict-r1_src_install() { + default + [[ -s info ]] && dodoc info +} + +_ASPELL_DICT_R1=1 +fi diff --git a/eclass/autotools-multilib.eclass b/eclass/autotools-multilib.eclass new file mode 100644 index 0000000..58bf285 --- /dev/null +++ b/eclass/autotools-multilib.eclass @@ -0,0 +1,92 @@ +# Copyright 1999-2020 Gentoo Authors +# Distributed under the terms of the GNU General Public License v2 + +# @ECLASS: autotools-multilib.eclass +# @MAINTAINER: +# gx86-multilib team +# @AUTHOR: +# Author: Michał Górny +# @SUPPORTED_EAPIS: 4 5 +# @BLURB: autotools-utils wrapper for multilib builds +# @DEPRECATED: multilib-minimal +# @DESCRIPTION: +# The autotools-multilib.eclass provides a glue between +# autotools-utils.eclass(5) and multilib-minimal.eclass(5), aiming +# to provide a convenient way to build packages using autotools +# for multiple ABIs. +# +# Inheriting this eclass sets IUSE and exports default multilib_src_*() +# sub-phases that call autotools-utils phase functions for each ABI +# enabled. The multilib_src_*() functions can be defined in ebuild just +# like in multilib-minimal. + +# EAPI=4 is required for meaningful MULTILIB_USEDEP. +case ${EAPI:-0} in + 6) die "${ECLASS}.eclass is banned in EAPI ${EAPI}";; + 4|5) ;; + *) die "EAPI=${EAPI} is not supported" ;; +esac + +inherit autotools-utils eutils ltprune multilib-build multilib-minimal + +EXPORT_FUNCTIONS src_prepare src_configure src_compile src_test src_install + +# Note: _at_args[@] passing is a backwards compatibility measure. +# Don't use it in new packages. + +autotools-multilib_src_prepare() { + autotools-utils_src_prepare "${@}" + + [[ ${AUTOTOOLS_IN_SOURCE_BUILD} ]] && multilib_copy_sources +} + +multilib_src_configure() { + [[ ${AUTOTOOLS_IN_SOURCE_BUILD} ]] && local ECONF_SOURCE=${BUILD_DIR} + autotools-utils_src_configure "${_at_args[@]}" +} + +autotools-multilib_src_configure() { + local _at_args=( "${@}" ) + + multilib-minimal_src_configure +} + +multilib_src_compile() { + emake "${_at_args[@]}" +} + +autotools-multilib_src_compile() { + local _at_args=( "${@}" ) + + multilib-minimal_src_compile +} + +multilib_src_test() { + autotools-utils_src_test "${_at_args[@]}" +} + +autotools-multilib_src_test() { + local _at_args=( "${@}" ) + + multilib-minimal_src_test +} + +multilib_src_install() { + emake DESTDIR="${D}" "${_at_args[@]}" install +} + +multilib_src_install_all() { + einstalldocs + + # Remove libtool files and unnecessary static libs + local prune_ltfiles=${AUTOTOOLS_PRUNE_LIBTOOL_FILES} + if [[ ${prune_ltfiles} != none ]]; then + prune_libtool_files ${prune_ltfiles:+--${prune_ltfiles}} + fi +} + +autotools-multilib_src_install() { + local _at_args=( "${@}" ) + + multilib-minimal_src_install +} diff --git a/eclass/autotools-utils.eclass b/eclass/autotools-utils.eclass new file mode 100644 index 0000000..3fcaa79 --- /dev/null +++ b/eclass/autotools-utils.eclass @@ -0,0 +1,385 @@ +# Copyright 1999-2020 Gentoo Authors +# Distributed under the terms of the GNU General Public License v2 + +# @ECLASS: autotools-utils.eclass +# @MAINTAINER: +# Maciej Mrozowski +# Michał Górny +# @SUPPORTED_EAPIS: 4 5 +# @BLURB: common ebuild functions for autotools-based packages +# @DEPRECATED: out-of-source +# @DESCRIPTION: +# autotools-utils.eclass is autotools.eclass(5) and base.eclass(5) wrapper +# providing all inherited features along with econf arguments as Bash array, +# out of source build with overridable build dir location, static archives +# handling, libtool files removal. +# +# Please note that autotools-utils does not support mixing of its phase +# functions with regular econf/emake calls. If necessary, please call +# autotools-utils_src_compile instead of the latter. +# +# @EXAMPLE: +# Typical ebuild using autotools-utils.eclass: +# +# @CODE +# EAPI="2" +# +# inherit autotools-utils +# +# DESCRIPTION="Foo bar application" +# HOMEPAGE="http://example.org/foo/" +# SRC_URI="mirror://sourceforge/foo/${P}.tar.bz2" +# +# LICENSE="LGPL-2.1" +# KEYWORDS="" +# SLOT="0" +# IUSE="debug doc examples qt4 static-libs tiff" +# +# CDEPEND=" +# media-libs/libpng:0 +# qt4? ( +# dev-qt/qtcore:4 +# dev-qt/qtgui:4 +# ) +# tiff? ( media-libs/tiff:0 ) +# " +# RDEPEND="${CDEPEND} +# !media-gfx/bar +# " +# DEPEND="${CDEPEND} +# doc? ( app-doc/doxygen ) +# " +# +# # bug 123456 +# AUTOTOOLS_IN_SOURCE_BUILD=1 +# +# DOCS=(AUTHORS ChangeLog README "Read me.txt" TODO) +# +# PATCHES=( +# "${FILESDIR}/${P}-gcc44.patch" # bug 123458 +# "${FILESDIR}/${P}-as-needed.patch" +# "${FILESDIR}/${P}-unbundle_libpng.patch" +# ) +# +# src_configure() { +# local myeconfargs=( +# $(use_enable debug) +# $(use_with qt4) +# $(use_enable threads multithreading) +# $(use_with tiff) +# ) +# autotools-utils_src_configure +# } +# +# src_compile() { +# autotools-utils_src_compile +# use doc && autotools-utils_src_compile docs +# } +# +# src_install() { +# use doc && HTML_DOCS=("${BUILD_DIR}/apidocs/html/") +# autotools-utils_src_install +# if use examples; then +# dobin "${BUILD_DIR}"/foo_example{1,2,3} \\ +# || die 'dobin examples failed' +# fi +# } +# +# @CODE + +# Keep variable names synced with cmake-utils and the other way around! + +case ${EAPI:-0} in + 6) die "${ECLASS}.eclass is banned in EAPI ${EAPI}";; + 4|5) ;; + *) die "EAPI=${EAPI} is not supported" ;; +esac + +# @ECLASS-VARIABLE: AUTOTOOLS_AUTORECONF +# @DEFAULT_UNSET +# @DESCRIPTION: +# Set to a non-empty value before calling inherit to enable running autoreconf +# in src_prepare() and adding autotools dependencies. +# +# This is usually necessary when using live sources or applying patches +# modifying configure.ac or Makefile.am files. Note that in the latter case +# setting this variable is obligatory even though the eclass will work without +# it (to add the necessary dependencies). +# +# The eclass will try to determine the correct autotools to run including a few +# external tools: gettext, glib-gettext, intltool, gtk-doc, gnome-doc-prepare. +# If your tool is not supported, please open a bug and we'll add support for it. +# +# Note that dependencies are added for autoconf, automake and libtool only. +# If your package needs one of the external tools listed above, you need to add +# appropriate packages to DEPEND yourself. +[[ ${AUTOTOOLS_AUTORECONF} ]] || : ${AUTOTOOLS_AUTO_DEPEND:=no} + +# eutils for eqawarn, path_exists +inherit autotools epatch eutils libtool ltprune + +EXPORT_FUNCTIONS src_prepare src_configure src_compile src_install src_test + +# @ECLASS-VARIABLE: BUILD_DIR +# @DEFAULT_UNSET +# @DESCRIPTION: +# Build directory, location where all autotools generated files should be +# placed. For out of source builds it defaults to ${WORKDIR}/${P}_build. +# +# This variable has been called AUTOTOOLS_BUILD_DIR formerly. +# It is set under that name for compatibility. + +# @ECLASS-VARIABLE: AUTOTOOLS_IN_SOURCE_BUILD +# @DEFAULT_UNSET +# @DESCRIPTION: +# Set to enable in-source build. + +# @ECLASS-VARIABLE: ECONF_SOURCE +# @DEFAULT_UNSET +# @DESCRIPTION: +# Specify location of autotools' configure script. By default it uses ${S}. + +# @ECLASS-VARIABLE: DOCS +# @DEFAULT_UNSET +# @DESCRIPTION: +# Array containing documents passed to dodoc command. +# +# In EAPIs 4+, can list directories as well. +# +# Example: +# @CODE +# DOCS=( NEWS README ) +# @CODE + +# @ECLASS-VARIABLE: HTML_DOCS +# @DEFAULT_UNSET +# @DESCRIPTION: +# Array containing documents passed to dohtml command. +# +# Example: +# @CODE +# HTML_DOCS=( doc/html/ ) +# @CODE + +# @ECLASS-VARIABLE: PATCHES +# @DEFAULT_UNSET +# @DESCRIPTION: +# PATCHES array variable containing all various patches to be applied. +# +# Example: +# @CODE +# PATCHES=( "${FILESDIR}"/${P}-mypatch.patch ) +# @CODE + +# @ECLASS-VARIABLE: AUTOTOOLS_PRUNE_LIBTOOL_FILES +# @DEFAULT_UNSET +# @DESCRIPTION: +# Sets the mode of pruning libtool files. The values correspond to +# prune_libtool_files parameters, with leading dashes stripped. +# +# Defaults to pruning the libtool files when static libraries are not +# installed or can be linked properly without them. Libtool files +# for modules (plugins) will be kept in case plugin loader needs them. +# +# If set to 'modules', the .la files for modules will be removed +# as well. This is often the preferred option. +# +# If set to 'all', all .la files will be removed unconditionally. This +# option is discouraged and shall be used only if 'modules' does not +# remove the files. +# +# If set to 'none', no .la files will be pruned ever. Use in corner +# cases only. + +# Determine using IN or OUT source build +_check_build_dir() { + : ${ECONF_SOURCE:=${S}} + # Respect both the old variable and the new one, depending + # on which one was set by the ebuild. + if [[ ! ${BUILD_DIR} && ${AUTOTOOLS_BUILD_DIR} ]]; then + eqawarn "The AUTOTOOLS_BUILD_DIR variable has been renamed to BUILD_DIR." + eqawarn "Please migrate the ebuild to use the new one." + + # In the next call, both variables will be set already + # and we'd have to know which one takes precedence. + _RESPECT_AUTOTOOLS_BUILD_DIR=1 + fi + + if [[ ${_RESPECT_AUTOTOOLS_BUILD_DIR} ]]; then + BUILD_DIR=${AUTOTOOLS_BUILD_DIR:-${WORKDIR}/${P}_build} + else + if [[ -n ${AUTOTOOLS_IN_SOURCE_BUILD} ]]; then + : ${BUILD_DIR:=${ECONF_SOURCE}} + else + : ${BUILD_DIR:=${WORKDIR}/${P}_build} + fi + fi + + # Backwards compatibility for getting the value. + AUTOTOOLS_BUILD_DIR=${BUILD_DIR} + echo ">>> Working in BUILD_DIR: \"${BUILD_DIR}\"" +} + +# @FUNCTION: autotools-utils_src_prepare +# @DESCRIPTION: +# The src_prepare function. +# +# Supporting PATCHES array and user patches. See base.eclass(5) for reference. +autotools-utils_src_prepare() { + debug-print-function ${FUNCNAME} "$@" + + local want_autoreconf=${AUTOTOOLS_AUTORECONF} + + [[ ${PATCHES} ]] && epatch "${PATCHES[@]}" + + at_checksum() { + find '(' -name 'Makefile.am' \ + -o -name 'configure.ac' \ + -o -name 'configure.in' ')' \ + -exec cksum {} + | sort -k2 + } + + [[ ! ${want_autoreconf} ]] && local checksum=$(at_checksum) + epatch_user + if [[ ! ${want_autoreconf} ]]; then + if [[ ${checksum} != $(at_checksum) ]]; then + einfo 'Will autoreconfigure due to user patches applied.' + want_autoreconf=yep + fi + fi + + [[ ${want_autoreconf} ]] && eautoreconf + elibtoolize --patch-only +} + +# @FUNCTION: autotools-utils_src_configure +# @DESCRIPTION: +# The src_configure function. For out of source build it creates build +# directory and runs econf there. Configuration parameters defined +# in myeconfargs are passed here to econf. Additionally following USE +# flags are known: +# +# IUSE="static-libs" passes --enable-shared and either --disable-static/--enable-static +# to econf respectively. + +# @VARIABLE: myeconfargs +# @DEFAULT_UNSET +# @DESCRIPTION: +# Optional econf arguments as Bash array. Should be defined before calling src_configure. +# @CODE +# src_configure() { +# local myeconfargs=( +# --disable-readline +# --with-confdir="/etc/nasty foo confdir/" +# $(use_enable debug cnddebug) +# $(use_enable threads multithreading) +# ) +# autotools-utils_src_configure +# } +# @CODE +autotools-utils_src_configure() { + debug-print-function ${FUNCNAME} "$@" + + [[ -z ${myeconfargs+1} || $(declare -p myeconfargs) == 'declare -a'* ]] \ + || die 'autotools-utils.eclass: myeconfargs has to be an array.' + + # Common args + local econfargs=() + + _check_build_dir + if "${ECONF_SOURCE}"/configure --help 2>&1 | grep -q '^ *--docdir='; then + econfargs+=( + --docdir="${EPREFIX}"/usr/share/doc/${PF} + ) + fi + + # Handle static-libs found in IUSE, disable them by default + if in_iuse static-libs; then + econfargs+=( + --enable-shared + $(use_enable static-libs static) + ) + fi + + # Append user args + econfargs+=("${myeconfargs[@]}") + + mkdir -p "${BUILD_DIR}" || die + pushd "${BUILD_DIR}" > /dev/null || die + econf "${econfargs[@]}" "$@" + popd > /dev/null || die +} + +# @FUNCTION: autotools-utils_src_compile +# @DESCRIPTION: +# The autotools src_compile function, invokes emake in specified BUILD_DIR. +autotools-utils_src_compile() { + debug-print-function ${FUNCNAME} "$@" + + _check_build_dir + pushd "${BUILD_DIR}" > /dev/null || die + emake "$@" || die 'emake failed' + popd > /dev/null || die +} + +# @FUNCTION: autotools-utils_src_install +# @DESCRIPTION: +# The autotools src_install function. Runs emake install, unconditionally +# removes unnecessary static libs (based on shouldnotlink libtool property) +# and removes unnecessary libtool files when static-libs USE flag is defined +# and unset. +# +# DOCS and HTML_DOCS arrays are supported. See base.eclass(5) for reference. +autotools-utils_src_install() { + debug-print-function ${FUNCNAME} "$@" + + _check_build_dir + pushd "${BUILD_DIR}" > /dev/null || die + emake DESTDIR="${D}" "$@" install || die "emake install failed" + popd > /dev/null || die + + # XXX: support installing them from builddir as well? + if declare -p DOCS &>/dev/null; then + # an empty list == don't install anything + if [[ ${DOCS[@]} ]]; then + # dies by itself + dodoc -r "${DOCS[@]}" + fi + else + local f + # same list as in PMS + for f in README* ChangeLog AUTHORS NEWS TODO CHANGES \ + THANKS BUGS FAQ CREDITS CHANGELOG; do + if [[ -s ${f} ]]; then + dodoc "${f}" || die "(default) dodoc ${f} failed" + fi + done + fi + if [[ ${HTML_DOCS} ]]; then + dohtml -r "${HTML_DOCS[@]}" || die "dohtml failed" + fi + + # Remove libtool files and unnecessary static libs + local prune_ltfiles=${AUTOTOOLS_PRUNE_LIBTOOL_FILES} + if [[ ${prune_ltfiles} != none ]]; then + prune_libtool_files ${prune_ltfiles:+--${prune_ltfiles}} + fi +} + +# @FUNCTION: autotools-utils_src_test +# @DESCRIPTION: +# The autotools src_test function. Runs emake check in build directory. +autotools-utils_src_test() { + debug-print-function ${FUNCNAME} "$@" + + _check_build_dir + pushd "${BUILD_DIR}" > /dev/null || die + + if make -ni check "${@}" &>/dev/null; then + emake check "${@}" || die 'emake check failed.' + elif make -ni test "${@}" &>/dev/null; then + emake test "${@}" || die 'emake test failed.' + fi + + popd > /dev/null || die +} diff --git a/eclass/autotools.eclass b/eclass/autotools.eclass new file mode 100644 index 0000000..08c72cd --- /dev/null +++ b/eclass/autotools.eclass @@ -0,0 +1,652 @@ +# Copyright 1999-2021 Gentoo Authors +# Distributed under the terms of the GNU General Public License v2 + +# @ECLASS: autotools.eclass +# @MAINTAINER: +# base-system@gentoo.org +# @SUPPORTED_EAPIS: 0 1 2 3 4 5 6 7 +# @BLURB: Regenerates auto* build scripts +# @DESCRIPTION: +# This eclass is for safely handling autotooled software packages that need to +# regenerate their build scripts. All functions will abort in case of errors. + +# Note: We require GNU m4, as does autoconf. So feel free to use any features +# from the GNU version of m4 without worrying about other variants (i.e. BSD). + +if [[ ${__AUTOTOOLS_AUTO_DEPEND+set} == "set" ]] ; then + # See if we were included already, but someone changed the value + # of AUTOTOOLS_AUTO_DEPEND on us. We could reload the entire + # eclass at that point, but that adds overhead, and it's trivial + # to re-order inherit in eclasses/ebuilds instead. #409611 + if [[ ${__AUTOTOOLS_AUTO_DEPEND} != ${AUTOTOOLS_AUTO_DEPEND} ]] ; then + die "AUTOTOOLS_AUTO_DEPEND changed value between inherits; please inherit autotools.eclass first! ${__AUTOTOOLS_AUTO_DEPEND} -> ${AUTOTOOLS_AUTO_DEPEND}" + fi +fi + +if [[ -z ${_AUTOTOOLS_ECLASS} ]]; then +_AUTOTOOLS_ECLASS=1 + +case ${EAPI:-0} in + 0|1|2|3|4|5|6|7) ;; + *) die "${ECLASS}: EAPI ${EAPI} not supported" ;; +esac + +inherit libtool + +# @ECLASS-VARIABLE: WANT_AUTOCONF +# @DESCRIPTION: +# The major version of autoconf your package needs +: ${WANT_AUTOCONF:=latest} + +# @ECLASS-VARIABLE: WANT_AUTOMAKE +# @DESCRIPTION: +# The major version of automake your package needs +: ${WANT_AUTOMAKE:=latest} + +# @ECLASS-VARIABLE: WANT_LIBTOOL +# @DESCRIPTION: +# Do you want libtool? Valid values here are "latest" and "none". +: ${WANT_LIBTOOL:=latest} + +# @ECLASS-VARIABLE: _LATEST_AUTOMAKE +# @INTERNAL +# @DESCRIPTION: +# CONSTANT! +# The latest major unstable and stable version/slot of automake available +# on each arch. +# Only add unstable version if it is in a different slot than latest stable +# version. +# List latest unstable version first to boost testing adoption rate because +# most package manager dependency resolver will pick the first suitable +# version. +# If a newer slot is stable on any arch, and is NOT reflected in this list, +# then circular dependencies may arise during emerge @system bootstraps. +# +# See bug 312315 and 465732 for further information and context. +# +# Do NOT change this variable in your ebuilds! +# If you want to force a newer minor version, you can specify the correct +# WANT value by using a colon: : +_LATEST_AUTOMAKE=( 1.16.2-r1:1.16 ) + +_automake_atom="sys-devel/automake" +_autoconf_atom="sys-devel/autoconf" +if [[ -n ${WANT_AUTOMAKE} ]]; then + case ${WANT_AUTOMAKE} in + # Even if the package doesn't use automake, we still need to depend + # on it because we run aclocal to process m4 macros. This matches + # the autoreconf tool, so this requirement is correct. #401605 + none) ;; + latest) + # Use SLOT deps if we can. For EAPI=0, we get pretty close. + if [[ ${EAPI:-0} != 0 ]] ; then + _automake_atom="|| ( `printf '>=sys-devel/automake-%s:%s ' ${_LATEST_AUTOMAKE[@]/:/ }` )" + else + _automake_atom="|| ( `printf '>=sys-devel/automake-%s ' ${_LATEST_AUTOMAKE[@]/%:*}` )" + fi + ;; + *) _automake_atom="=sys-devel/automake-${WANT_AUTOMAKE}*" ;; + esac + export WANT_AUTOMAKE +fi + +if [[ -n ${WANT_AUTOCONF} ]] ; then + case ${WANT_AUTOCONF} in + none) _autoconf_atom="" ;; # some packages don't require autoconf at all + 2.1) _autoconf_atom="~sys-devel/autoconf-2.13" ;; + # if you change the "latest" version here, change also autotools_env_setup + latest|2.5) _autoconf_atom=">=sys-devel/autoconf-2.69" ;; + *) die "Invalid WANT_AUTOCONF value '${WANT_AUTOCONF}'" ;; + esac + export WANT_AUTOCONF +fi + +_libtool_atom=">=sys-devel/libtool-2.4" +if [[ -n ${WANT_LIBTOOL} ]] ; then + case ${WANT_LIBTOOL} in + none) _libtool_atom="" ;; + latest) ;; + *) die "Invalid WANT_LIBTOOL value '${WANT_LIBTOOL}'" ;; + esac + export WANT_LIBTOOL +fi + +AUTOTOOLS_DEPEND="${_automake_atom} + ${_autoconf_atom} + ${_libtool_atom}" +RDEPEND="" + +# @ECLASS-VARIABLE: AUTOTOOLS_AUTO_DEPEND +# @DESCRIPTION: +# Set to 'no' to disable automatically adding to DEPEND. This lets +# ebuilds form conditional depends by using ${AUTOTOOLS_DEPEND} in +# their own DEPEND string. +: ${AUTOTOOLS_AUTO_DEPEND:=yes} +if [[ ${AUTOTOOLS_AUTO_DEPEND} != "no" ]] ; then + case ${EAPI:-0} in + 0|1|2|3|4|5|6) DEPEND=${AUTOTOOLS_DEPEND} ;; + 7) BDEPEND=${AUTOTOOLS_DEPEND} ;; + esac +fi +__AUTOTOOLS_AUTO_DEPEND=${AUTOTOOLS_AUTO_DEPEND} # See top of eclass + +unset _automake_atom _autoconf_atom + +# @ECLASS-VARIABLE: AM_OPTS +# @DEFAULT_UNSET +# @DESCRIPTION: +# Additional options to pass to automake during +# eautoreconf call. + +# @ECLASS-VARIABLE: AT_NOEAUTOHEADER +# @DEFAULT_UNSET +# @DESCRIPTION: +# Don't run eautoheader command if set to 'yes'; only used to work around +# packages that don't want their headers being modified. + +# @ECLASS-VARIABLE: AT_NOEAUTOMAKE +# @DEFAULT_UNSET +# @DESCRIPTION: +# Don't run eautomake command if set to 'yes'; only used to workaround +# broken packages. Generally you should, instead, fix the package to +# not call AM_INIT_AUTOMAKE if it doesn't actually use automake. + +# @ECLASS-VARIABLE: AT_NOELIBTOOLIZE +# @DEFAULT_UNSET +# @DESCRIPTION: +# Don't run elibtoolize command if set to 'yes', +# useful when elibtoolize needs to be ran with +# particular options + +# @ECLASS-VARIABLE: AT_M4DIR +# @DESCRIPTION: +# Additional director(y|ies) aclocal should search +: ${AT_M4DIR:=} + +# @ECLASS-VARIABLE: AT_SYS_M4DIR +# @INTERNAL +# @DESCRIPTION: +# For system integrators, a list of additional aclocal search paths. +# This variable gets eval-ed, so you can use variables in the definition +# that may not be valid until eautoreconf & friends are run. +: ${AT_SYS_M4DIR:=} + +# @FUNCTION: eautoreconf +# @DESCRIPTION: +# This function mimes the behavior of autoreconf, but uses the different +# eauto* functions to run the tools. It doesn't accept parameters, but +# the directory with include files can be specified with AT_M4DIR variable. +# +# Should do a full autoreconf - normally what most people will be interested in. +# Also should handle additional directories specified by AC_CONFIG_SUBDIRS. +eautoreconf() { + local x g + + # Subdirs often share a common build dir #529404. If so, we can't safely + # run in parallel because many tools clobber the content in there. Libtool + # and automake both `rm && cp` while aclocal reads the output. We might be + # able to handle this if we split the steps and grab locks on the dirs the + # tools actually write to. Then we'd run all the common tools that use + # those inputs. Doing this in bash does not scale easily. + # If we do re-enable parallel support, make sure #426512 is handled. + if [[ -z ${AT_NO_RECURSIVE} ]] ; then + # Take care of subdirs + for x in $(autotools_check_macro_val AC_CONFIG_SUBDIRS) ; do + if [[ -d ${x} ]] ; then + pushd "${x}" >/dev/null + # Avoid unsafe nested multijob_finish_one for bug #426512. + AT_NOELIBTOOLIZE="yes" eautoreconf || die + popd >/dev/null + fi + done + fi + + einfo "Running eautoreconf in '${PWD}' ..." + + local m4dirs=$(autotools_check_macro_val AC_CONFIG_{AUX,MACRO}_DIR) + [[ -n ${m4dirs} ]] && mkdir -p ${m4dirs} + + # Run all the tools before aclocal so we can gather the .m4 files. + local i tools=( + # + glibgettext false "autotools_run_tool glib-gettextize --copy --force" + gettext false "autotools_run_tool --at-missing autopoint --force" + # intltool must come after autopoint. + intltool false "autotools_run_tool intltoolize --automake --copy --force" + gtkdoc false "autotools_run_tool --at-missing gtkdocize --copy" + gnomedoc false "autotools_run_tool --at-missing gnome-doc-prepare --copy --force" + libtool false "_elibtoolize --auto-ltdl --install --copy --force" + ) + for (( i = 0; i < ${#tools[@]}; i += 3 )) ; do + if _at_uses_${tools[i]} ; then + tools[i+1]=true + ${tools[i+2]} + fi + done + + # Generate aclocal.m4 with our up-to-date m4 files. + local rerun_aclocal=false + eaclocal + + # Check to see if we had macros expanded by other macros or in other + # m4 files that we couldn't detect early. This is uncommon, but some + # packages do this, so we have to handle it correctly. + for (( i = 0; i < ${#tools[@]}; i += 3 )) ; do + if ! ${tools[i+1]} && _at_uses_${tools[i]} ; then + ${tools[i+2]} + rerun_aclocal=true + fi + done + ${rerun_aclocal} && eaclocal + + if [[ ${WANT_AUTOCONF} = 2.1 ]] ; then + eautoconf + else + eautoconf --force + fi + [[ ${AT_NOEAUTOHEADER} != "yes" ]] && eautoheader + [[ ${AT_NOEAUTOMAKE} != "yes" ]] && FROM_EAUTORECONF="yes" eautomake ${AM_OPTS} + + if [[ ${AT_NOELIBTOOLIZE} != "yes" ]] ; then + # Call it here to prevent failures due to elibtoolize called _before_ + # eautoreconf. + elibtoolize --force "${PWD}" + fi + + return 0 +} + +# @FUNCTION: _at_uses_pkg +# @USAGE: +# @INTERNAL +# See if the specified macros are enabled. +_at_uses_pkg() { + if [[ -n $(autotools_check_macro "$@") ]] ; then + return 0 + else + # If the trace didn't find it (perhaps because aclocal.m4 hasn't + # been generated yet), cheat, but be conservative. + local macro args=() + for macro ; do + args+=( -e "^[[:space:]]*${macro}\>" ) + done + egrep -q "${args[@]}" configure.?? + fi +} +_at_uses_autoheader() { _at_uses_pkg A{C,M}_CONFIG_HEADER{S,}; } +_at_uses_automake() { _at_uses_pkg AM_INIT_AUTOMAKE; } +_at_uses_gettext() { _at_uses_pkg AM_GNU_GETTEXT_{,REQUIRE_}VERSION; } +_at_uses_glibgettext() { _at_uses_pkg AM_GLIB_GNU_GETTEXT; } +_at_uses_intltool() { _at_uses_pkg {AC,IT}_PROG_INTLTOOL; } +_at_uses_gtkdoc() { _at_uses_pkg GTK_DOC_CHECK; } +_at_uses_gnomedoc() { _at_uses_pkg GNOME_DOC_INIT; } +_at_uses_libtool() { _at_uses_pkg A{C,M}_PROG_LIBTOOL LT_INIT; } +_at_uses_libltdl() { _at_uses_pkg LT_CONFIG_LTDL_DIR; } + +# @FUNCTION: eaclocal_amflags +# @DESCRIPTION: +# Extract the ACLOCAL_AMFLAGS value from the Makefile.am and try to handle +# (most) of the crazy crap that people throw at us. +eaclocal_amflags() { + local aclocal_opts amflags_file + + for amflags_file in GNUmakefile.am Makefile.am GNUmakefile.in Makefile.in ; do + [[ -e ${amflags_file} ]] || continue + # setup the env in case the pkg does something crazy + # in their ACLOCAL_AMFLAGS. like run a shell script + # which turns around and runs autotools. #365401 + # or split across multiple lines. #383525 + autotools_env_setup + aclocal_opts=$(sed -n \ + "/^ACLOCAL_AMFLAGS[[:space:]]*=/{ \ + # match the first line + s:[^=]*=::p; \ + # then gobble up all escaped lines + : nextline /\\\\$/{ n; p; b nextline; } \ + }" ${amflags_file}) + eval aclocal_opts=\""${aclocal_opts}"\" + break + done + + echo ${aclocal_opts} +} + +# @FUNCTION: eaclocal +# @DESCRIPTION: +# These functions runs the autotools using autotools_run_tool with the +# specified parametes. The name of the tool run is the same of the function +# without e prefix. +# They also force installing the support files for safety. +# Respects AT_M4DIR for additional directories to search for macro's. +eaclocal() { + [[ ! -f aclocal.m4 || -n $(grep -e 'generated.*by aclocal' aclocal.m4) ]] && \ + autotools_run_tool --at-m4flags aclocal "$@" $(eaclocal_amflags) +} + +# @FUNCTION: _elibtoolize +# @DESCRIPTION: +# Runs libtoolize. +# +# Note the '_' prefix: avoid collision with elibtoolize() from libtool.eclass. +_elibtoolize() { + local LIBTOOLIZE=${LIBTOOLIZE:-$(type -P glibtoolize > /dev/null && echo glibtoolize || echo libtoolize)} + + if [[ $1 == "--auto-ltdl" ]] ; then + shift + _at_uses_libltdl && set -- "$@" --ltdl + fi + + [[ -f GNUmakefile.am || -f Makefile.am ]] && set -- "$@" --automake + + autotools_run_tool ${LIBTOOLIZE} "$@" +} + +# @FUNCTION: eautoheader +# @DESCRIPTION: +# Runs autoheader. +eautoheader() { + _at_uses_autoheader || return 0 + autotools_run_tool --at-no-fail --at-m4flags autoheader "$@" +} + +# @FUNCTION: eautoconf +# @DESCRIPTION: +# Runs autoconf. +eautoconf() { + if [[ ! -f configure.ac && ! -f configure.in ]] ; then + echo + eerror "No configure.{ac,in} present in '${PWD}'!" + echo + die "No configure.{ac,in} present!" + fi + if [[ ${WANT_AUTOCONF} != "2.1" && -e configure.in ]] ; then + eqawarn "This package has a configure.in file which has long been deprecated. Please" + eqawarn "update it to use configure.ac instead as newer versions of autotools will die" + eqawarn "when it finds this file. See https://bugs.gentoo.org/426262 for details." + fi + + # Install config.guess and config.sub which are required by many macros + # in Autoconf >=2.70. + local _gnuconfig + case ${EAPI:-0} in + 0|1|2|3|4|5|6) + _gnuconfig="${EPREFIX}/usr/share/gnuconfig" + ;; + *) + _gnuconfig="${BROOT}/usr/share/gnuconfig" + ;; + esac + cp "${_gnuconfig}"/config.{guess,sub} . || die + + autotools_run_tool --at-m4flags autoconf "$@" +} + +# @FUNCTION: eautomake +# @DESCRIPTION: +# Runs automake. +eautomake() { + local extra_opts=() + local makefile_name + + # Run automake if: + # - a Makefile.am type file exists + # - the configure script is using the AM_INIT_AUTOMAKE directive + for makefile_name in {GNUmakefile,{M,m}akefile}.am "" ; do + [[ -f ${makefile_name} ]] && break + done + + _automake_version() { + autotools_run_tool --at-output automake --version 2>/dev/null | + sed -n -e '1{s:.*(GNU automake) ::p;q}' + } + + if [[ -z ${makefile_name} ]] ; then + _at_uses_automake || return 0 + + elif [[ -z ${FROM_EAUTORECONF} && -f ${makefile_name%.am}.in ]]; then + local used_automake + local installed_automake + + installed_automake=$(WANT_AUTOMAKE= _automake_version) + used_automake=$(head -n 1 < ${makefile_name%.am}.in | \ + sed -e 's:.*by automake \(.*\) from .*:\1:') + + if [[ ${installed_automake} != ${used_automake} ]]; then + ewarn "Automake used for the package (${used_automake}) differs from" \ + "the installed version (${installed_automake})." + ewarn "Forcing a full rebuild of the autotools to workaround." + eautoreconf + return 0 + fi + fi + + [[ -f INSTALL && -f AUTHORS && -f ChangeLog && -f NEWS && -f README ]] \ + || extra_opts+=( --foreign ) + + # Older versions of automake do not support --force-missing. But we want + # to use this whenever possible to update random bundled files #133489. + case $(_automake_version) in + 1.4|1.4[.-]*) ;; + *) extra_opts+=( --force-missing ) ;; + esac + + autotools_run_tool automake --add-missing --copy "${extra_opts[@]}" "$@" +} + +# @FUNCTION: eautopoint +# @DESCRIPTION: +# Runs autopoint (from the gettext package). +eautopoint() { + autotools_run_tool autopoint "$@" +} + +# @FUNCTION: config_rpath_update +# @USAGE: [destination] +# @DESCRIPTION: +# Some packages utilize the config.rpath helper script, but don't +# use gettext directly. So we have to copy it in manually since +# we can't let `autopoint` do it for us. +config_rpath_update() { + local dst src=$(type -P gettext | sed 's:bin/gettext:share/gettext/config.rpath:') + + [[ $# -eq 0 ]] && set -- $(find -name config.rpath) + [[ $# -eq 0 ]] && return 0 + + einfo "Updating all config.rpath files" + for dst in "$@" ; do + einfo " ${dst}" + cp "${src}" "${dst}" || die + done +} + +# @FUNCTION: autotools_env_setup +# @INTERNAL +# @DESCRIPTION: +# Process the WANT_AUTO{CONF,MAKE} flags. +autotools_env_setup() { + # We do the "latest" → version switch here because it solves + # possible order problems, see bug #270010 as an example. + if [[ ${WANT_AUTOMAKE} == "latest" ]]; then + local pv + for pv in ${_LATEST_AUTOMAKE[@]/#*:} ; do + # Break on first hit to respect _LATEST_AUTOMAKE order. + local hv_args="" + case ${EAPI:-0} in + 5|6) + hv_args="--host-root" + ;; + 7) + hv_args="-b" + ;; + esac + ROOT=/ has_version ${hv_args} "=sys-devel/automake-${pv}*" && export WANT_AUTOMAKE="${pv}" && break + done + [[ ${WANT_AUTOMAKE} == "latest" ]] && \ + die "Cannot find the latest automake! Tried ${_LATEST_AUTOMAKE[*]}" + fi + [[ ${WANT_AUTOCONF} == "latest" ]] && export WANT_AUTOCONF=2.5 +} + +# @FUNCTION: autotools_run_tool +# @USAGE: [--at-no-fail] [--at-m4flags] [--at-missing] [--at-output] [tool-specific flags] +# @INTERNAL +# @DESCRIPTION: +# Run the specified autotool helper, but do logging and error checking +# around it in the process. +autotools_run_tool() { + # Process our own internal flags first + local autofail=true m4flags=false missing_ok=false return_output=false + while [[ -n $1 ]] ; do + case $1 in + --at-no-fail) autofail=false;; + --at-m4flags) m4flags=true;; + --at-missing) missing_ok=true;; + --at-output) return_output=true;; + # whatever is left goes to the actual tool + *) break;; + esac + shift + done + + if [[ ${EBUILD_PHASE} != "unpack" && ${EBUILD_PHASE} != "prepare" ]]; then + ewarn "QA Warning: running $1 in ${EBUILD_PHASE} phase" + fi + + if ${missing_ok} && ! type -P ${1} >/dev/null ; then + einfo "Skipping '$*' due $1 not installed" + return 0 + fi + + autotools_env_setup + + # Allow people to pass in full paths. #549268 + local STDERR_TARGET="${T}/${1##*/}.out" + # most of the time, there will only be one run, but if there are + # more, make sure we get unique log filenames + if [[ -e ${STDERR_TARGET} ]] ; then + local i=1 + while :; do + STDERR_TARGET="${T}/${1##*/}-${i}.out" + [[ -e ${STDERR_TARGET} ]] || break + : $(( i++ )) + done + fi + + if ${m4flags} ; then + set -- "${1}" $(autotools_m4dir_include) $(autotools_m4sysdir_include) "${@:2}" + fi + + # If the caller wants to probe something, then let them do it directly. + if ${return_output} ; then + "$@" + return + fi + + printf "***** $1 *****\n***** PWD: ${PWD}\n***** $*\n\n" > "${STDERR_TARGET}" + + ebegin "Running $@" + "$@" >> "${STDERR_TARGET}" 2>&1 + if ! eend $? && ${autofail} ; then + echo + eerror "Failed Running $1 !" + eerror + eerror "Include in your bugreport the contents of:" + eerror + eerror " ${STDERR_TARGET}" + echo + die "Failed Running $1 !" + fi +} + +# Internal function to check for support + +# Keep a list of all the macros we might use so that we only +# have to run the trace code once. Order doesn't matter. +ALL_AUTOTOOLS_MACROS=( + A{C,M}_PROG_LIBTOOL LT_INIT LT_CONFIG_LTDL_DIR + A{C,M}_CONFIG_HEADER{S,} + AC_CONFIG_SUBDIRS + AC_CONFIG_AUX_DIR AC_CONFIG_MACRO_DIR + AM_INIT_AUTOMAKE + AM_GLIB_GNU_GETTEXT + AM_GNU_GETTEXT_{,REQUIRE_}VERSION + {AC,IT}_PROG_INTLTOOL + GTK_DOC_CHECK + GNOME_DOC_INIT +) +autotools_check_macro() { + [[ -f configure.ac || -f configure.in ]] || return 0 + + # We can run in multiple dirs, so we have to cache the trace + # data in $PWD rather than an env var. + local trace_file=".__autoconf_trace_data" + if [[ ! -e ${trace_file} ]] || [[ ! aclocal.m4 -ot ${trace_file} ]] ; then + WANT_AUTOCONF="2.5" autoconf \ + $(autotools_m4dir_include) \ + ${ALL_AUTOTOOLS_MACROS[@]/#/--trace=} > ${trace_file} 2>/dev/null + fi + + local macro args=() + for macro ; do + has ${macro} ${ALL_AUTOTOOLS_MACROS[@]} || die "internal error: add ${macro} to ALL_AUTOTOOLS_MACROS" + args+=( -e ":${macro}:" ) + done + grep "${args[@]}" ${trace_file} +} + +# @FUNCTION: autotools_check_macro_val +# @USAGE: [macros] +# @INTERNAL +# @DESCRIPTION: +# Look for a macro and extract its value. +autotools_check_macro_val() { + local macro scan_out + + for macro ; do + autotools_check_macro "${macro}" | \ + gawk -v macro="${macro}" \ + '($0 !~ /^[[:space:]]*(#|dnl)/) { + if (match($0, macro ":(.*)$", res)) + print res[1] + }' | uniq + done + + return 0 +} + +_autotools_m4dir_include() { + local x include_opts flag + + # Use the right flag to autoconf based on the version #448986 + [[ ${WANT_AUTOCONF} == "2.1" ]] \ + && flag="l" \ + || flag="I" + + for x in "$@" ; do + case ${x} in + # We handle it below + -${flag}) ;; + *) + [[ ! -d ${x} ]] && ewarn "autotools.eclass: '${x}' does not exist" + include_opts+=" -${flag} ${x}" + ;; + esac + done + + echo ${include_opts} +} +autotools_m4dir_include() { _autotools_m4dir_include ${AT_M4DIR} ; } +autotools_m4sysdir_include() { + # First try to use the paths the system integrator has set up. + local paths=( $(eval echo ${AT_SYS_M4DIR}) ) + + if [[ ${#paths[@]} -eq 0 && -n ${SYSROOT} ]] ; then + # If they didn't give us anything, then default to the SYSROOT. + # This helps when cross-compiling. + local path="${SYSROOT}/usr/share/aclocal" + [[ -d ${path} ]] && paths+=( "${path}" ) + fi + _autotools_m4dir_include "${paths[@]}" +} + +fi diff --git a/eclass/base.eclass b/eclass/base.eclass new file mode 100644 index 0000000..0f9a2e5 --- /dev/null +++ b/eclass/base.eclass @@ -0,0 +1,215 @@ +# Copyright 1999-2020 Gentoo Authors +# Distributed under the terms of the GNU General Public License v2 + +# DEPRECATED +# This eclass has been deprecated and must not be used by any new +# ebuilds or eclasses. Replacements for particular phase functions +# in EAPI 2+: +# +# base_src_unpack() - default (or unpacker_src_unpack if unpacker.eclass +# was inherited) +# base_src_prepare() - inherit eutils, inline: +# epatch "${PATCHES[@]}" # if PATCHES defined as array +# epatch ${PATCHES} # if PATCHES defined as string +# epatch_user +# base_src_configure() - default +# base_src_compile() - default +# base_src_install() - default +# base_src_install_docs() - einstalldocs from eutils.eclass + +# @ECLASS: base.eclass +# @MAINTAINER: +# QA Team +# @AUTHOR: +# Original author: Dan Armak +# @SUPPORTED_EAPIS: 0 1 2 3 4 5 +# @BLURB: The base eclass defines some default functions and variables. +# @DEPRECATED: none +# @DESCRIPTION: +# The base eclass defines some default functions and variables. + +if [[ -z ${_BASE_ECLASS} ]]; then +_BASE_ECLASS=1 + +inherit eutils + +BASE_EXPF="src_unpack src_compile src_install" +case "${EAPI:-0}" in + 0|1) ;; + 2|3|4|5) BASE_EXPF+=" src_prepare src_configure" ;; + *) die "${ECLASS}.eclass is banned in EAPI ${EAPI}";; +esac + +EXPORT_FUNCTIONS ${BASE_EXPF} + +# @ECLASS-VARIABLE: DOCS +# @DEFAULT_UNSET +# @DESCRIPTION: +# Array containing documents passed to dodoc command. +# +# DOCS=( "${S}/doc/document.txt" "${S}/doc/doc_folder/" ) + +# @ECLASS-VARIABLE: HTML_DOCS +# @DEFAULT_UNSET +# @DESCRIPTION: +# Array containing documents passed to dohtml command. +# +# HTML_DOCS=( "${S}/doc/document.html" "${S}/doc/html_folder/" ) + +# @ECLASS-VARIABLE: PATCHES +# @DEFAULT_UNSET +# @DESCRIPTION: +# PATCHES array variable containing all various patches to be applied. +# This variable is expected to be defined in global scope of ebuild. +# Make sure to specify the full path. This variable is utilised in +# src_unpack/src_prepare phase based on EAPI. +# +# NOTE: if using patches folders with special file suffixes you have to +# define one additional variable EPATCH_SUFFIX="something" +# +# PATCHES=( "${FILESDIR}/mypatch.patch" "${FILESDIR}/patches_folder/" ) + + +# @FUNCTION: base_src_unpack +# @DESCRIPTION: +# The base src_unpack function, which is exported. +# Calls also src_prepare with eapi older than 2. +base_src_unpack() { + debug-print-function $FUNCNAME "$@" + + pushd "${WORKDIR}" > /dev/null + + if [[ $(type -t unpacker_src_unpack) == "function" ]] ; then + unpacker_src_unpack + elif [[ -n ${A} ]] ; then + unpack ${A} + fi + has src_prepare ${BASE_EXPF} || base_src_prepare + + popd > /dev/null +} + +# @FUNCTION: base_src_prepare +# @DESCRIPTION: +# The base src_prepare function, which is exported +# EAPI is greater or equal to 2. Here the PATCHES array is evaluated. +base_src_prepare() { + debug-print-function $FUNCNAME "$@" + debug-print "$FUNCNAME: PATCHES=$PATCHES" + + local patches_failed=0 + + pushd "${S}" > /dev/null + if [[ "$(declare -p PATCHES 2>/dev/null 2>&1)" == "declare -a"* ]]; then + for x in "${PATCHES[@]}"; do + debug-print "$FUNCNAME: applying patch from ${x}" + if [[ -d "${x}" ]]; then + # Use standardized names and locations with bulk patching + # Patch directory is ${WORKDIR}/patch + # See epatch() in eutils.eclass for more documentation + EPATCH_SUFFIX=${EPATCH_SUFFIX:=patch} + + # in order to preserve normal EPATCH_SOURCE value that can + # be used other way than with base eclass store in local + # variable and restore later + oldval=${EPATCH_SOURCE} + EPATCH_SOURCE=${x} + EPATCH_FORCE=yes + epatch + EPATCH_SOURCE=${oldval} + elif [[ -f "${x}" ]]; then + epatch "${x}" + else + ewarn "QA: File or directory \"${x}\" does not exist." + ewarn "QA: Check your PATCHES array or add missing file/directory." + patches_failed=1 + fi + done + [[ ${patches_failed} -eq 1 ]] && die "Some patches failed. See above messages." + else + for x in ${PATCHES}; do + debug-print "$FUNCNAME: patching from ${x}" + epatch "${x}" + done + fi + + # Apply user patches + debug-print "$FUNCNAME: applying user patches" + epatch_user + + popd > /dev/null +} + +# @FUNCTION: base_src_configure +# @DESCRIPTION: +# The base src_configure function, which is exported when +# EAPI is greater or equal to 2. Runs basic econf. +base_src_configure() { + debug-print-function $FUNCNAME "$@" + + # there is no pushd ${S} so we can override its place where to run + [[ -x ${ECONF_SOURCE:-.}/configure ]] && econf "$@" +} + +# @FUNCTION: base_src_compile +# @DESCRIPTION: +# The base src_compile function, calls src_configure with +# EAPI older than 2. +base_src_compile() { + debug-print-function $FUNCNAME "$@" + + has src_configure ${BASE_EXPF} || base_src_configure + base_src_make "$@" +} + +# @FUNCTION: base_src_make +# @DESCRIPTION: +# Actual function that runs emake command. +base_src_make() { + debug-print-function $FUNCNAME "$@" + + if [[ -f Makefile || -f GNUmakefile || -f makefile ]]; then + emake "$@" || die "died running emake, $FUNCNAME" + fi +} + +# @FUNCTION: base_src_install +# @DESCRIPTION: +# The base src_install function. Runs make install and +# installs documents and html documents from DOCS and HTML_DOCS +# arrays. +base_src_install() { + debug-print-function $FUNCNAME "$@" + + emake DESTDIR="${D}" "$@" install || die "died running make install, $FUNCNAME" + base_src_install_docs +} + +# @FUNCTION: base_src_install_docs +# @DESCRIPTION: +# Actual function that install documentation from +# DOCS and HTML_DOCS arrays. +base_src_install_docs() { + debug-print-function $FUNCNAME "$@" + + local x + + pushd "${S}" > /dev/null + + if [[ "$(declare -p DOCS 2>/dev/null 2>&1)" == "declare -a"* ]]; then + for x in "${DOCS[@]}"; do + debug-print "$FUNCNAME: docs: creating document from ${x}" + dodoc "${x}" || die "dodoc failed" + done + fi + if [[ "$(declare -p HTML_DOCS 2>/dev/null 2>&1)" == "declare -a"* ]]; then + for x in "${HTML_DOCS[@]}"; do + debug-print "$FUNCNAME: docs: creating html document from ${x}" + dohtml -r "${x}" || die "dohtml failed" + done + fi + + popd > /dev/null +} + +fi diff --git a/eclass/bash-completion-r1.eclass b/eclass/bash-completion-r1.eclass new file mode 100644 index 0000000..70d40a2 --- /dev/null +++ b/eclass/bash-completion-r1.eclass @@ -0,0 +1,138 @@ +# Copyright 1999-2020 Gentoo Authors +# Distributed under the terms of the GNU General Public License v2 + +# @ECLASS: bash-completion-r1.eclass +# @MAINTAINER: +# mgorny@gentoo.org +# @SUPPORTED_EAPIS: 0 1 2 3 4 5 6 7 +# @BLURB: A few quick functions to install bash-completion files +# @EXAMPLE: +# +# @CODE +# EAPI=5 +# +# src_configure() { +# econf \ +# --with-bash-completion-dir="$(get_bashcompdir)" +# } +# +# src_install() { +# default +# +# newbashcomp contrib/${PN}.bash-completion ${PN} +# } +# @CODE + +inherit toolchain-funcs + +case ${EAPI:-0} in + 0|1|2|3|4|5|6|7) ;; + *) die "EAPI ${EAPI} unsupported (yet)." +esac + +# @FUNCTION: _bash-completion-r1_get_bashdir +# @INTERNAL +# @DESCRIPTION: +# First argument is name of the string in bash-completion.pc +# Second argument is the fallback directory if the string is not found +# @EXAMPLE: +# _bash-completion-r1_get_bashdir completionsdir /usr/share/bash-completion +_bash-completion-r1_get_bashdir() { + debug-print-function ${FUNCNAME} "${@}" + + if $(tc-getPKG_CONFIG) --exists bash-completion &>/dev/null; then + local path + path=$($(tc-getPKG_CONFIG) --variable="${1}" bash-completion) || die + # we need to return unprefixed, so strip from what pkg-config returns + # to us, bug #477692 + echo "${path#${EPREFIX}}" + else + echo "${2}" + fi +} + +# @FUNCTION: _bash-completion-r1_get_bashcompdir +# @INTERNAL +# @DESCRIPTION: +# Get unprefixed bash-completion completions directory. +_bash-completion-r1_get_bashcompdir() { + debug-print-function ${FUNCNAME} "${@}" + + _bash-completion-r1_get_bashdir completionsdir /usr/share/bash-completion/completions +} + +# @FUNCTION: _bash-completion-r1_get_helpersdir +# @INTERNAL +# @DESCRIPTION: +# Get unprefixed bash-completion helpers directory. +_bash-completion-r1_get_bashhelpersdir() { + debug-print-function ${FUNCNAME} "${@}" + + _bash-completion-r1_get_bashdir helpersdir /usr/share/bash-completion/helpers +} + +# @FUNCTION: get_bashcompdir +# @DESCRIPTION: +# Get the bash-completion completions directory. +get_bashcompdir() { + debug-print-function ${FUNCNAME} "${@}" + + echo "${EPREFIX}$(_bash-completion-r1_get_bashcompdir)" +} + +# @FUNCTION: get_bashhelpersdir +# @INTERNAL +# @DESCRIPTION: +# Get the bash-completion helpers directory. +get_bashhelpersdir() { + debug-print-function ${FUNCNAME} "${@}" + + echo "${EPREFIX}$(_bash-completion-r1_get_bashhelpersdir)" +} + +# @FUNCTION: dobashcomp +# @USAGE: [...] +# @DESCRIPTION: +# Install bash-completion files passed as args. Has EAPI-dependant failure +# behavior (like doins). +dobashcomp() { + debug-print-function ${FUNCNAME} "${@}" + + ( + insopts -m 0644 + insinto "$(_bash-completion-r1_get_bashcompdir)" + doins "${@}" + ) +} + +# @FUNCTION: newbashcomp +# @USAGE: +# @DESCRIPTION: +# Install bash-completion file under a new name. Has EAPI-dependant failure +# behavior (like newins). +newbashcomp() { + debug-print-function ${FUNCNAME} "${@}" + + ( + insopts -m 0644 + insinto "$(_bash-completion-r1_get_bashcompdir)" + newins "${@}" + ) +} + +# @FUNCTION: bashcomp_alias +# @USAGE: ... +# @DESCRIPTION: +# Alias completion to one or more commands (es). +bashcomp_alias() { + debug-print-function ${FUNCNAME} "${@}" + + [[ ${#} -lt 2 ]] && die "Usage: ${FUNCNAME} ..." + local base=${1} f + shift + + for f; do + dosym "${base}" "$(_bash-completion-r1_get_bashcompdir)/${f}" \ + || return + done +} diff --git a/eclass/bazel.eclass b/eclass/bazel.eclass new file mode 100644 index 0000000..ac7ca24 --- /dev/null +++ b/eclass/bazel.eclass @@ -0,0 +1,222 @@ +# Copyright 1999-2020 Gentoo Authors +# Distributed under the terms of the GNU General Public License v2 + +# @ECLASS: bazel.eclass +# @MAINTAINER: +# Jason Zaman +# @AUTHOR: +# Jason Zaman +# @SUPPORTED_EAPIS: 7 +# @BLURB: Utility functions for packages using Bazel Build +# @DESCRIPTION: +# A utility eclass providing functions to run the Bazel Build system. +# +# This eclass does not export any phase functions. + +case "${EAPI:-0}" in + 0|1|2|3|4|5|6) + die "Unsupported EAPI=${EAPI:-0} (too old) for ${ECLASS}" + ;; + 7) + ;; + *) + die "Unsupported EAPI=${EAPI} (unknown) for ${ECLASS}" + ;; +esac + +if [[ ! ${_BAZEL_ECLASS} ]]; then + +inherit multiprocessing toolchain-funcs + +BDEPEND=">=dev-util/bazel-0.20" + +# @FUNCTION: bazel_get_flags +# @DESCRIPTION: +# Obtain and print the bazel flags for target and host *FLAGS. +# +# To add more flags to this, append the flags to the +# appropriate variable before calling this function +bazel_get_flags() { + local i fs=() + for i in ${CFLAGS}; do + fs+=( "--conlyopt=${i}" ) + done + for i in ${BUILD_CFLAGS}; do + fs+=( "--host_conlyopt=${i}" ) + done + for i in ${CXXFLAGS}; do + fs+=( "--cxxopt=${i}" ) + done + for i in ${BUILD_CXXFLAGS}; do + fs+=( "--host_cxxopt=${i}" ) + done + for i in ${CPPFLAGS}; do + fs+=( "--conlyopt=${i}" "--cxxopt=${i}" ) + done + for i in ${BUILD_CPPFLAGS}; do + fs+=( "--host_conlyopt=${i}" "--host_cxxopt=${i}" ) + done + for i in ${LDFLAGS}; do + fs+=( "--linkopt=${i}" ) + done + for i in ${BUILD_LDFLAGS}; do + fs+=( "--host_linkopt=${i}" ) + done + echo "${fs[*]}" +} + +# @FUNCTION: bazel_setup_bazelrc +# @DESCRIPTION: +# Creates the bazelrc with common options that will be passed +# to bazel. This will be called by ebazel automatically so +# does not need to be called from the ebuild. +bazel_setup_bazelrc() { + if [[ -f "${T}/bazelrc" ]]; then + return + fi + + # F: fopen_wr + # P: /proc/self/setgroups + # Even with standalone enabled, the Bazel sandbox binary is run for feature test: + # https://github.com/bazelbuild/bazel/blob/7b091c1397a82258e26ab5336df6c8dae1d97384/src/main/java/com/google/devtools/build/lib/sandbox/LinuxSandboxedSpawnRunner.java#L61 + # https://github.com/bazelbuild/bazel/blob/76555482873ffcf1d32fb40106f89231b37f850a/src/main/tools/linux-sandbox-pid1.cc#L113 + addpredict /proc + + mkdir -p "${T}/bazel-cache" || die + mkdir -p "${T}/bazel-distdir" || die + + cat > "${T}/bazelrc" <<-EOF || die + startup --batch + + # dont strip HOME, portage sets a temp per-package dir + build --action_env HOME + + # make bazel respect MAKEOPTS + build --jobs=$(makeopts_jobs) + build --compilation_mode=opt --host_compilation_mode=opt + + # FLAGS + build $(bazel_get_flags) + + # Use standalone strategy to deactivate the bazel sandbox, since it + # conflicts with FEATURES=sandbox. + build --spawn_strategy=standalone --genrule_strategy=standalone + test --spawn_strategy=standalone --genrule_strategy=standalone + + build --strip=never + build --verbose_failures --noshow_loading_progress + test --verbose_test_summary --verbose_failures --noshow_loading_progress + + # make bazel only fetch distfiles from the cache + fetch --repository_cache="${T}/bazel-cache/" --distdir="${T}/bazel-distdir/" + build --repository_cache="${T}/bazel-cache/" --distdir="${T}/bazel-distdir/" + + build --define=PREFIX=${EPREFIX%/}/usr + build --define=LIBDIR=\$(PREFIX)/$(get_libdir) + build --define=INCLUDEDIR=\$(PREFIX)/include + EOF + + if tc-is-cross-compiler; then + echo "build --nodistinct_host_configuration" >> "${T}/bazelrc" || die + fi +} + +# @FUNCTION: ebazel +# @USAGE: [...] +# @DESCRIPTION: +# Run bazel with the bazelrc and output_base. +# +# output_base will be specific to $BUILD_DIR (if unset, $S). +# bazel_setup_bazelrc will be called and the created bazelrc +# will be passed to bazel. +# +# Will automatically die if bazel does not exit cleanly. +ebazel() { + bazel_setup_bazelrc + + # Use different build folders for each multibuild variant. + local output_base="${BUILD_DIR:-${S}}" + output_base="${output_base%/}-bazel-base" + mkdir -p "${output_base}" || die + + set -- bazel --bazelrc="${T}/bazelrc" --output_base="${output_base}" ${@} + echo "${*}" >&2 + "${@}" || die "ebazel failed" +} + +# @FUNCTION: bazel_load_distfiles +# @USAGE: ... +# @DESCRIPTION: +# Populate the bazel distdir to fetch from since it cannot use +# the network. Bazel looks in distdir but will only look for the +# original filename, not the possibly renamed one that portage +# downloaded. If the line has -> we to rename it back. This also +# handles use-conditionals that SRC_URI does. +# +# Example: +# @CODE +# bazel_external_uris="http://a/file-2.0.tgz +# python? ( http://b/1.0.tgz -> foo-1.0.tgz )" +# SRC_URI="http://c/${PV}.tgz +# ${bazel_external_uris}" +# +# src_unpack() { +# unpack ${PV}.tgz +# bazel_load_distfiles "${bazel_external_uris}" +# } +# @CODE +bazel_load_distfiles() { + local file="" + local rename=0 + + [[ "${@}" ]] || die "Missing args" + mkdir -p "${T}/bazel-distdir" || die + + for word in ${@} + do + if [[ "${word}" == "->" ]]; then + # next word is a dest filename + rename=1 + elif [[ "${word}" == ")" ]]; then + # close conditional block + continue + elif [[ "${word}" == "(" ]]; then + # open conditional block + continue + elif [[ "${word}" == ?(\!)[A-Za-z0-9]*([A-Za-z0-9+_@-])\? ]]; then + # use-conditional block + # USE-flags can contain [A-Za-z0-9+_@-], and start with alphanum + # https://dev.gentoo.org/~ulm/pms/head/pms.html#x1-200003.1.4 + # ?(\!) matches zero-or-one !'s + # *(...) zero-or-more characters + # ends with a ? + continue + elif [[ ${rename} -eq 1 ]]; then + # Make sure the distfile is used + if [[ "${A}" == *"${word}"* ]]; then + echo "Copying ${word} to bazel distdir as ${file}" + ln -s "${DISTDIR}/${word}" "${T}/bazel-distdir/${file}" || die + fi + rename=0 + file="" + else + # another URL, current one may or may not be a rename + # if there was a previous one, its not renamed so copy it now + if [[ -n "${file}" && "${A}" == *"${file}"* ]]; then + echo "Copying ${file} to bazel distdir" + ln -s "${DISTDIR}/${file}" "${T}/bazel-distdir/${file}" || die + fi + # save the current URL, later we will find out if its a rename or not. + file="${word##*/}" + fi + done + + # handle last file + if [[ -n "${file}" ]]; then + echo "Copying ${file} to bazel distdir" + ln -s "${DISTDIR}/${file}" "${T}/bazel-distdir/${file}" || die + fi +} + +_BAZEL_ECLASS=1 +fi diff --git a/eclass/cannadic.eclass b/eclass/cannadic.eclass new file mode 100644 index 0000000..7392d5c --- /dev/null +++ b/eclass/cannadic.eclass @@ -0,0 +1,141 @@ +# Copyright 1999-2017 Gentoo Foundation +# Distributed under the terms of the GNU General Public License v2 + +# @ECLASS: cannadic.eclass +# @MAINTAINER: +# cjk@gentoo.org +# @AUTHOR: +# Mamoru KOMACHI +# @BLURB: Function for Canna compatible dictionaries +# @DESCRIPTION: +# The cannadic eclass is used for installation and setup of Canna +# compatible dictionaries within the Portage system. + +inherit eutils + +EXPORT_FUNCTIONS pkg_setup pkg_postinst pkg_postrm src_install + +HOMEPAGE="http://canna.osdn.jp/" # you need to change this! +SRC_URI="mirror://gentoo/${P}.tar.gz" + +DICSDIRFILE="${FILESDIR}/*.dics.dir" +CANNADICS="${CANNADICS}" # (optional) + +# You don't need to modify these +CANNADIC_CANNA_DIR="${EROOT:-${ROOT}}"var/lib/canna/dic/canna +CANNADIC_DICS_DIR="${EROOT:-${ROOT}}"var/lib/canna/dic/dics.d +readonly CANNADIC_CANNA_DIR CANNADIC_DICS_DIR + +# @FUNCTION: cannadic_pkg_setup +# @DESCRIPTION: +# Sets up ${CANNADIC_CANNA_DIR} +cannadic_pkg_setup() { + keepdir "${CANNADIC_CANNA_DIR}" + fowners bin:bin "${CANNADIC_CANNA_DIR}" + fperms 0775 "${CANNADIC_CANNA_DIR}" +} + +# @FUNCTION: cannadic-install +# @DESCRIPTION: +# Installs dictionaries to ${CANNADIC_CANNA_DIR} +cannadic-install() { + insinto "${CANNADIC_CANNA_DIR}" + insopts -m 0664 -o bin -g bin + doins "${@}" +} + +# @FUNCTION: dicsdir-install +# @DESCRIPTION: +# Installs dics.dir from ${DICSDIRFILE} +dicsdir-install() { + insinto "${CANNADIC_DICS_DIR}" + doins "${DICSDIRFILE}" +} + +# @FUNCTION: cannadic_src_install +# @DESCRIPTION: +# Installs all dictionaries under ${WORKDIR} +# plus dics.dir and docs +cannadic_src_install() { + local f + for f in *.c[btl]d *.t; do + if [[ -s "${f}" ]]; then + cannadic-install "${f}" + fi + done 2> /dev/null + + dicsdir-install || die + + einstalldocs +} + +# @FUNCTION: update-cannadic-dir +# @DESCRIPTION: +# Updates dics.dir for Canna Server, script for this part taken from Debian GNU/Linux +# +# compiles dics.dir files for Canna Server +# Copyright 2001 ISHIKAWA Mutsumi +# Licensed under the GNU General Public License, version 2. See the file +# /usr/portage/license/GPL-2 or . +update-cannadic-dir() { + einfo + einfo "Updating dics.dir for Canna ..." + einfo + + # write new dics.dir file in case we are interrupted + cat <<-EOF > "${CANNADIC_CANNA_DIR}"/dics.dir.update-new + # dics.dir -- automatically generated file by Portage. + # DO NOT EDIT BY HAND. + EOF + + local f + for f in "${CANNADIC_DICS_DIR}"/*.dics.dir; do + echo "# ${f}" >> "${CANNADIC_CANNA_DIR}"/dics.dir.update-new + cat "${f}" >> "${CANNADIC_CANNA_DIR}"/dics.dir.update-new + einfo "Added ${f}." + done + + mv "${CANNADIC_CANNA_DIR}"/dics.dir.update-new "${CANNADIC_CANNA_DIR}"/dics.dir + + einfo + einfo "Done." + einfo +} + +# @FUNCTION: cannadic_pkg_postinst +# @DESCRIPTION: +# Updates dics.dir and print out notice after install +cannadic_pkg_postinst() { + update-cannadic-dir + + einfo + einfo "Please restart cannaserver to fit the changes." + einfo "You need to modify your config file (~/.canna) to enable dictionaries." + + if [[ -n "${CANNADICS}" ]]; then + einfo "e.g) add $(for d in ${CANNADICS}; do echo -n "\"${d}\" "; done)to section use-dictionary()." + einfo "For details, see documents under /usr/share/doc/${PF}." + fi + + einfo "If you do not have ~/.canna, you can find sample files in /usr/share/canna." + ewarn "If you are upgrading from existing dictionary, you may need to recreate" + ewarn "user dictionary if you have one." + einfo +} + +# @FUNCTION: cannadic_pkg_postrm +# @DESCRIPTION: +# Updates dics.dir and print out notice after uninstall +cannadic_pkg_postrm() { + update-cannadic-dir + + einfo + einfo "Please restart cannaserver to fit changes." + einfo "and modify your config file (~/.canna) to disable dictionary." + + if [[ -n "${CANNADICS}" ]]; then + einfo "e.g) delete $(for d in ${CANNADICS}; do echo -n "\"${d}\" "; done)from section use-dictionary()." + fi + + einfo +} diff --git a/eclass/cargo.eclass b/eclass/cargo.eclass new file mode 100644 index 0000000..7f7a681 --- /dev/null +++ b/eclass/cargo.eclass @@ -0,0 +1,397 @@ +# Copyright 1999-2020 Gentoo Authors +# Distributed under the terms of the GNU General Public License v2 + +# @ECLASS: cargo.eclass +# @MAINTAINER: +# rust@gentoo.org +# @AUTHOR: +# Doug Goldstein +# @SUPPORTED_EAPIS: 6 7 +# @BLURB: common functions and variables for cargo builds + +if [[ -z ${_CARGO_ECLASS} ]]; then +_CARGO_ECLASS=1 + +# we need this for 'cargo vendor' subcommand and net.offline config knob +RUST_DEPEND=">=virtual/rust-1.37.0" + +case "${EAPI:-0}" in + 0|1|2|3|4|5|6) + die "Unsupported EAPI=${EAPI:-0} (too old) for ${ECLASS}" + ;; + 7) + ;; + *) + die "Unsupported EAPI=${EAPI} (unknown) for ${ECLASS}" + ;; +esac + +inherit multiprocessing toolchain-funcs + +if [[ ! ${CARGO_OPTIONAL} ]]; then + BDEPEND="${RUST_DEPEND}" + EXPORT_FUNCTIONS src_unpack src_configure src_compile src_install src_test +fi + +IUSE="${IUSE} debug" + +ECARGO_HOME="${WORKDIR}/cargo_home" +ECARGO_VENDOR="${ECARGO_HOME}/gentoo" + +# @ECLASS-VARIABLE: CARGO_OPTIONAL +# @DEFAULT_UNSET +# @PRE_INHERIT +# @DESCRIPTION: +# If set to a non-null value, before inherit cargo part of the ebuild will +# be considered optional. No dependencies will be added and no phase +# functions will be exported. +# +# If you enable CARGO_OPTIONAL, you have to set BDEPEND on virtual/rust +# for your package and call at least cargo_gen_config manually before using +# other src_ functions of this eclass. +# note that cargo_gen_config is automatically called by cargo_src_unpack. + +# @VARIABLE: myfeatures +# @DEFAULT_UNSET +# @DESCRIPTION: +# Optional cargo features defined as bash array. +# Should be defined before calling cargo_src_configure(). +# +# Example package that has x11 and wayland as features, and disables default. +# @CODE +# src_configure() { +# local myfeatures=( +# $(usex X x11 '') +# $(usev wayland) +# ) +# cargo_src_configure --no-default-features +# } +# @CODE + +# @ECLASS-VARIABLE: ECARGO_REGISTRY_DIR +# @USER_VARIABLE +# @DEFAULT_UNSET +# @DESCRIPTION: +# Storage directory for cargo registry. +# Used by cargo_live_src_unpack to cache downloads. +# This is intended to be set by users. +# Ebuilds must not set it. +# +# Defaults to "${DISTDIR}/cargo-registry" it not set. + +# @ECLASS-VARIABLE: ECARGO_OFFLINE +# @USER_VARIABLE +# @DEFAULT_UNSET +# @DESCRIPTION: +# If non-empty, this variable prevents online operations in +# cargo_live_src_unpack. +# Inherits value of EVCS_OFFLINE if not set explicitly. + +# @ECLASS-VARIABLE: EVCS_UMASK +# @USER_VARIABLE +# @DEFAULT_UNSET +# @DESCRIPTION: +# Set this variable to a custom umask. This is intended to be set by +# users. By setting this to something like 002, it can make life easier +# for people who use cargo in a home directory, but are in the portage +# group, and then switch over to building with FEATURES=userpriv. +# Or vice-versa. + +# @FUNCTION: cargo_crate_uris +# @DESCRIPTION: +# Generates the URIs to put in SRC_URI to help fetch dependencies. +cargo_crate_uris() { + local -r regex='^([a-zA-Z0-9_\-]+)-([0-9]+\.[0-9]+\.[0-9]+.*)$' + local crate + for crate in "$@"; do + local name version url + [[ $crate =~ $regex ]] || die "Could not parse name and version from crate: $crate" + name="${BASH_REMATCH[1]}" + version="${BASH_REMATCH[2]}" + url="https://crates.io/api/v1/crates/${name}/${version}/download -> ${crate}.crate" + echo "${url}" + done +} + +# @FUNCTION: cargo_gen_config +# @DESCRIPTION: +# Generate the $CARGO_HOME/config necessary to use our local registry and settings. +# Cargo can also be configured through environment variables in addition to the TOML syntax below. +# For each configuration key below of the form foo.bar the environment variable CARGO_FOO_BAR +# can also be used to define the value. +# Environment variables will take precedent over TOML configuration, +# and currently only integer, boolean, and string keys are supported. +# For example the build.jobs key can also be defined by CARGO_BUILD_JOBS. +# Or setting CARGO_TERM_VERBOSE=false in make.conf will make build quieter. +cargo_gen_config() { + debug-print-function ${FUNCNAME} "$@" + + mkdir -p "${ECARGO_HOME}" || die + + cat > "${ECARGO_HOME}/config" <<- _EOF_ || die "Failed to create cargo config" + [source.gentoo] + directory = "${ECARGO_VENDOR}" + + [source.crates-io] + replace-with = "gentoo" + local-registry = "/nonexistant" + + [net] + offline = true + + [build] + jobs = $(makeopts_jobs) + + [term] + verbose = true + $([[ "${NOCOLOR}" = true || "${NOCOLOR}" = yes ]] && echo "color = 'never'") + _EOF_ + + export CARGO_HOME="${ECARGO_HOME}" + _CARGO_GEN_CONFIG_HAS_RUN=1 +} + +# @FUNCTION: cargo_src_unpack +# @DESCRIPTION: +# Unpacks the package and the cargo registry +cargo_src_unpack() { + debug-print-function ${FUNCNAME} "$@" + + mkdir -p "${ECARGO_VENDOR}" || die + mkdir -p "${S}" || die + + local archive shasum pkg + for archive in ${A}; do + case "${archive}" in + *.crate) + ebegin "Loading ${archive} into Cargo registry" + tar -xf "${DISTDIR}"/${archive} -C "${ECARGO_VENDOR}/" || die + # generate sha256sum of the crate itself as cargo needs this + shasum=$(sha256sum "${DISTDIR}"/${archive} | cut -d ' ' -f 1) + pkg=$(basename ${archive} .crate) + cat <<- EOF > ${ECARGO_VENDOR}/${pkg}/.cargo-checksum.json + { + "package": "${shasum}", + "files": {} + } + EOF + # if this is our target package we need it in ${WORKDIR} too + # to make ${S} (and handle any revisions too) + if [[ ${P} == ${pkg}* ]]; then + tar -xf "${DISTDIR}"/${archive} -C "${WORKDIR}" || die + fi + eend $? + ;; + cargo-snapshot*) + ebegin "Unpacking ${archive}" + mkdir -p "${S}"/target/snapshot + tar -xzf "${DISTDIR}"/${archive} -C "${S}"/target/snapshot --strip-components 2 || die + # cargo's makefile needs this otherwise it will try to + # download it + touch "${S}"/target/snapshot/bin/cargo || die + eend $? + ;; + *) + unpack ${archive} + ;; + esac + done + + cargo_gen_config +} + +# @FUNCTION: cargo_live_src_unpack +# @DESCRIPTION: +# Runs 'cargo fetch' and vendors downloaded crates for offline use, used in live ebuilds + +cargo_live_src_unpack() { + debug-print-function ${FUNCNAME} "$@" + + [[ "${PV}" == *9999* ]] || die "${FUNCNAME} only allowed in live/9999 ebuilds" + [[ "${EBUILD_PHASE}" == unpack ]] || die "${FUNCNAME} only allowed in src_unpack" + + mkdir -p "${S}" || die + mkdir -p "${ECARGO_VENDOR}" || die + mkdir -p "${ECARGO_HOME}" || die + + local distdir=${PORTAGE_ACTUAL_DISTDIR:-${DISTDIR}} + : ${ECARGO_REGISTRY_DIR:=${distdir}/cargo-registry} + + local offline="${ECARGO_OFFLINE:-${EVCS_OFFLINE}}" + + if [[ ! -d ${ECARGO_REGISTRY_DIR} && ! ${offline} ]]; then + ( + addwrite "${ECARGO_REGISTRY_DIR}" + mkdir -p "${ECARGO_REGISTRY_DIR}" + ) || die "Unable to create ${ECARGO_REGISTRY_DIR}" + fi + + if [[ ${offline} ]]; then + local subdir + for subdir in cache index src; do + if [[ ! -d ${ECARGO_REGISTRY_DIR}/registry/${subdir} ]]; then + eerror "Networking activity has been disabled via ECARGO_OFFLINE or EVCS_OFFLINE" + eerror "However, no valid cargo registry available at ${ECARGO_REGISTRY_DIR}" + die "Unable to proceed with ECARGO_OFFLINE/EVCS_OFFLINE." + fi + done + fi + + if [[ ${EVCS_UMASK} ]]; then + local saved_umask=$(umask) + umask "${EVCS_UMASK}" || die "Bad options to umask: ${EVCS_UMASK}" + fi + + pushd "${S}" > /dev/null || die + + # Respect user settings befire cargo_gen_config is called. + if [[ ! ${CARGO_TERM_COLOR} ]]; then + [[ "${NOCOLOR}" = true || "${NOCOLOR}" = yes ]] && export CARGO_TERM_COLOR=never + local unset_color=true + fi + if [[ ! ${CARGO_TERM_VERBOSE} ]]; then + export CARGO_TERM_VERBOSE=true + local unset_verbose=true + fi + + # Let cargo fetch to system-wide location. + # It will keep directory organized by itself. + addwrite "${ECARGO_REGISTRY_DIR}" + export CARGO_HOME="${ECARGO_REGISTRY_DIR}" + + # Absence of quotes around offline arg is intentional, as cargo bails out if it encounters '' + einfo "cargo fetch ${offline:+--offline}" + cargo fetch ${offline:+--offline} || die #nowarn + + # Let cargo copy all required crates to "${WORKDIR}" for offline use in later phases. + einfo "cargo vendor ${offline:+--offline} ${ECARGO_VENDOR}" + cargo vendor ${offline:+--offline} "${ECARGO_VENDOR}" || die #nowarn + + # Users may have git checkouts made by cargo. + # While cargo vendors the sources, it still needs git checkout to be present. + # Copying full dir is an overkill, so just symlink it. + if [[ -d ${ECARGO_REGISTRY_DIR}/git ]]; then + ln -sv "${ECARGO_REGISTRY_DIR}/git" "${ECARGO_HOME}/git" || die + fi + + popd > /dev/null || die + + # Restore settings if needed. + [[ ${unset_color} ]] && unset CARGO_TERM_COLOR + [[ ${unset_verbose} ]] && unset CARGO_TERM_VERBOSE + if [[ ${saved_umask} ]]; then + umask "${saved_umask}" || die + fi + + # After following calls, cargo will no longer use ${ECARGO_REGISTRY_DIR} as CARGO_HOME + # It will be forced into offline mode to prevent network access. + # But since we already vendored crates and symlinked git, it has all it needs to build. + unset CARGO_HOME + cargo_gen_config +} + +# @FUNCTION: cargo_src_configure +# @DESCRIPTION: +# Configure cargo package features and arguments. +# Extra positional arguments supplied to this function +# will be passed to cargo in all phases. +# Make sure all cargo subcommands support flags passed here. +# +# Example for package that explicitly builds only 'baz' binary and +# enables 'barfeature' and optional 'foo' feature. +# will pass '--features barfeature --features foo --bin baz' +# in src_{compile,test,install} +# +# @CODE +# src_configure() { +# local myfeatures=( +# barfeature +# $(usev foo) +# ) +# cargo_src_configure --bin baz +# } +# @CODE +# +# In some cases crates may need '--no-default-features' option, +# as there is no way to disable single feature, except disabling all. +# It can be passed directly to cargo_src_configure(). + +cargo_src_configure() { + debug-print-function ${FUNCNAME} "$@" + + [[ -z ${myfeatures} ]] && declare -a myfeatures=() + local myfeaturestype=$(declare -p myfeatures 2>&-) + if [[ "${myfeaturestype}" != "declare -a myfeatures="* ]]; then + die "myfeatures must be declared as array" + fi + + # transform array from simple feature list + # to multiple cargo args: + # --features feature1 --features feature2 ... + # this format is chosen because 2 other methods of + # listing features (space OR comma separated) require + # more fiddling with strings we'd like to avoid here. + myfeatures=( ${myfeatures[@]/#/--features } ) + + readonly ECARGO_ARGS=( ${myfeatures[@]} ${@} ${ECARGO_EXTRA_ARGS} ) + + [[ ${ECARGO_ARGS[@]} ]] && einfo "Configured with: ${ECARGO_ARGS[@]}" +} + +# @FUNCTION: cargo_src_compile +# @DESCRIPTION: +# Build the package using cargo build +cargo_src_compile() { + debug-print-function ${FUNCNAME} "$@" + + [[ ${_CARGO_GEN_CONFIG_HAS_RUN} ]] || \ + die "FATAL: please call cargo_gen_config before using ${FUNCNAME}" + + tc-export AR CC CXX PKG_CONFIG + + set -- cargo build $(usex debug "" --release) ${ECARGO_ARGS[@]} "$@" + einfo "${@}" + "${@}" || die "cargo build failed" +} + +# @FUNCTION: cargo_src_install +# @DESCRIPTION: +# Installs the binaries generated by cargo +# In come case workspaces need alternative --path parameter +# default is '--path ./' if nothing specified. +# '--path ./somedir' can be passed directly to cargo_src_install() + +cargo_src_install() { + debug-print-function ${FUNCNAME} "$@" + + [[ ${_CARGO_GEN_CONFIG_HAS_RUN} ]] || \ + die "FATAL: please call cargo_gen_config before using ${FUNCNAME}" + + set -- cargo install $(has --path ${@} || echo --path ./) \ + --root "${ED}/usr" \ + $(usex debug --debug "") \ + ${ECARGO_ARGS[@]} "$@" + einfo "${@}" + "${@}" || die "cargo install failed" + + rm -f "${ED}/usr/.crates.toml" || die + rm -f "${ED}/usr/.crates2.json" || die + + [ -d "${S}/man" ] && doman "${S}/man" || return 0 +} + +# @FUNCTION: cargo_src_test +# @DESCRIPTION: +# Test the package using cargo test +cargo_src_test() { + debug-print-function ${FUNCNAME} "$@" + + [[ ${_CARGO_GEN_CONFIG_HAS_RUN} ]] || \ + die "FATAL: please call cargo_gen_config before using ${FUNCNAME}" + + set -- cargo test $(usex debug "" --release) ${ECARGO_ARGS[@]} "$@" + einfo "${@}" + "${@}" || die "cargo test failed" +} + +fi diff --git a/eclass/cdrom.eclass b/eclass/cdrom.eclass new file mode 100644 index 0000000..4bbe6aa --- /dev/null +++ b/eclass/cdrom.eclass @@ -0,0 +1,308 @@ +# Copyright 1999-2020 Gentoo Authors +# Distributed under the terms of the GNU General Public License v2 + +# @ECLASS: cdrom.eclass +# @MAINTAINER: +# games@gentoo.org +# @BLURB: Functions for CD-ROM handling +# @DESCRIPTION: +# Acquire CD(s) for those lovely CD-based emerges. Yes, this violates +# the whole "non-interactive" policy, but damnit I want CD support! +# +# Do not call these functions in pkg_* phases like pkg_setup as they +# should not be used for binary packages. Most packages using this +# eclass will require RESTRICT="bindist" but the point still stands. +# The functions are generally called in src_unpack. + +if [[ -z ${_CDROM_ECLASS} ]]; then +_CDROM_ECLASS=1 + +inherit portability + +# @ECLASS-VARIABLE: CDROM_OPTIONAL +# @DEFAULT_UNSET +# @DESCRIPTION: +# By default, the eclass sets PROPERTIES="interactive" on the assumption +# that people will be using these. If your package optionally supports +# disc-based installs then set this to "yes" and we'll set things +# conditionally based on USE="cdinstall". +if [[ ${CDROM_OPTIONAL} == "yes" ]] ; then + IUSE="cdinstall" + PROPERTIES+=" cdinstall? ( interactive )" +else + PROPERTIES+=" interactive" +fi + +# @FUNCTION: cdrom_get_cds +# @USAGE: [:alt cd1 file] [cd2 file[:alt cd2 file]] [...] +# @DESCRIPTION: +# Attempt to locate a CD based upon a file that is on the CD. +# +# If the data spans multiple discs then additional arguments can be +# given to check for more files. Call cdrom_load_next_cd() to scan for +# the next disc in the set. +# +# Sometimes it is necessary to support alternative CD "sets" where the +# contents differ. Alternative files for each disc can be appended to +# each argument, separated by the : character. This feature is +# frequently used to support installing from an existing installation. +# Note that after the first disc is detected, the set is locked so +# cdrom_load_next_cd() will only scan for files in that specific set on +# subsequent discs. +# +# The given files can be within named subdirectories. It is not +# necessary to specify different casings of the same filename as +# matching is done case-insensitively. Filenames can include special +# characters such as spaces. Only : is not allowed. +# +# If you don't want each disc to be referred to as "CD #1", "CD #2", +# etc. then you can optionally provide your own names. Set CDROM_NAME +# for a single disc, CDROM_NAMES as an array for multiple discs, or +# individual CDROM_NAME_# variables for each disc starting from 1. +# +# Despite what you may have seen in older ebuilds, it has never been +# possible to provide per-set disc names. This would not make sense as +# all the names are initially displayed before the first disc has been +# detected. As a workaround, you can redefine the name variable(s) +# after the first disc has been detected. +# +# This function ends with a cdrom_load_next_cd() call to scan for the +# first disc. For more details about variables read and written by this +# eclass, see that function's description. +cdrom_get_cds() { + unset CDROM_SET + export CDROM_CURRENT_CD=0 + export CDROM_NUM_CDS="${#}" + local i + for i in $(seq ${#}); do + export CDROM_CHECK_${i}="${!i}" + done + + # If the user has set CD_ROOT or CD_ROOT_1, don't bother informing + # them about which discs are needed as they presumably already know. + if [[ -n ${CD_ROOT}${CD_ROOT_1} ]] ; then + : + + # Single disc info. + elif [[ ${#} -eq 1 ]] ; then + einfo "This ebuild will need the ${CDROM_NAME:-CD for ${PN}}" + echo + einfo "If you do not have the CD, but have the data files" + einfo "mounted somewhere on your filesystem, just export" + einfo "the variable CD_ROOT so that it points to the" + einfo "directory containing the files." + echo + einfo "For example:" + einfo "export CD_ROOT=/mnt/cdrom" + echo + + # Multi disc info. + else + _cdrom_set_names + einfo "This package may need access to ${#} CDs." + local cdcnt + for cdcnt in $(seq ${#}); do + local var=CDROM_NAME_${cdcnt} + [[ ! -z ${!var} ]] && einfo " CD ${cdcnt}: ${!var}" + done + echo + einfo "If you do not have the CDs, but have the data files" + einfo "mounted somewhere on your filesystem, just export" + einfo "the following variables so they point to the right place:" + einfo $(printf "CD_ROOT_%d " $(seq ${#})) + echo + einfo "Or, if you have all the files in the same place, or" + einfo "you only have one CD, you can export CD_ROOT" + einfo "and that place will be used as the same data source" + einfo "for all the CDs." + echo + einfo "For example:" + einfo "export CD_ROOT=/mnt/cdrom" + echo + fi + + # Scan for the first disc. + cdrom_load_next_cd +} + +# @FUNCTION: cdrom_load_next_cd +# @DESCRIPTION: +# If multiple arguments were given to cdrom_get_cds() then you can call +# this function to scan for the next disc. This function is also called +# implicitly to scan for the first disc. +# +# The file(s) given to cdrom_get_cds() are scanned for on any mounted +# filesystem that resembles optical media. If no match is found then +# the user is prompted to insert and mount the disc and press enter to +# rescan. This will loop continuously until a match is found or the +# user aborts with Ctrl+C. +# +# The user can override the scan location by setting CD_ROOT for a +# single disc, CD_ROOT if multiple discs are merged into the same +# directory tree (useful for existing installations), or individual +# CD_ROOT_# variables for each disc starting from 1. If no match is +# found then the function dies with an error as a rescan will not help +# in this instance. +# +# Users wanting to set CD_ROOT or CD_ROOT_# for specific packages +# persistently can do so using Portage's /etc/portage/env feature. +# +# Regardless of which scanning method is used, several variables are set +# by this function for you to use: +# +# CDROM_ROOT: Root path of the detected disc. +# CDROM_MATCH: Path of the matched file, relative to CDROM_ROOT. +# CDROM_ABSMATCH: Absolute path of the matched file. +# CDROM_SET: The matching set number, starting from 0. +# +# The casing of CDROM_MATCH may not be the same as the argument given to +# cdrom_get_cds() as matching is done case-insensitively. You should +# therefore use this variable (or CDROM_ABSMATCH) when performing file +# operations to ensure the file is found. Use newins rather than doins +# to keep the final result consistent and take advantage of Bash +# case-conversion features like ${FOO,,}. +# +# Chances are that you'll need more than just the matched file from each +# disc though. You should not assume the casing of these files either +# but dealing with this goes beyond the scope of this ebuild. For a +# good example, see games-action/descent2-data, which combines advanced +# globbing with advanced tar features to concisely deal with +# case-insensitive matching, case conversion, file moves, and +# conditional exclusion. +# +# Copying directly from a mounted disc using doins/newins will remove +# any read-only permissions but be aware of these when copying to an +# intermediate directory first. Attempting to clean a build directory +# containing read-only files as a non-root user will result in an error. +# If you're using tar as suggested above then you can easily work around +# this with --mode=u+w. +# +# Note that you can only go forwards in the disc list, so make sure you +# only call this function when you're done using the current disc. +# +# If you cd to any location within CDROM_ROOT then remember to leave the +# directory before calling this function again, otherwise the user won't +# be able to unmount the current disc. +cdrom_load_next_cd() { + local showedmsg=0 showjolietmsg=0 + + unset CDROM_ROOT + ((++CDROM_CURRENT_CD)) + + _cdrom_set_names + + while true ; do + local i cdset + : CD_ROOT_${CDROM_CURRENT_CD} + export CDROM_ROOT=${CD_ROOT:-${!_}} + local var="CDROM_CHECK_${CDROM_CURRENT_CD}" + IFS=: read -r -a cdset -d "" <<< "${!var}" + + for i in $(seq ${CDROM_SET:-0} ${CDROM_SET:-$((${#cdset[@]} - 1))}); do + local f=${cdset[${i}]} point= node= fs= opts= + + if [[ -z ${CDROM_ROOT} ]] ; then + while read point node fs opts ; do + has "${fs}" cd9660 iso9660 udf || continue + point=${point//\040/ } + export CDROM_MATCH=$(_cdrom_glob_match "${point}" "${f}") + [[ -z ${CDROM_MATCH} ]] && continue + export CDROM_ROOT=${point} + done <<< "$(get_mounts)" + else + export CDROM_MATCH=$(_cdrom_glob_match "${CDROM_ROOT}" "${f}") + fi + + if [[ -n ${CDROM_MATCH} ]] ; then + export CDROM_ABSMATCH=${CDROM_ROOT}/${CDROM_MATCH} + export CDROM_SET=${i} + break 2 + fi + done + + # If we get here then we were unable to locate a match. If + # CDROM_ROOT is non-empty then this implies that a CD_ROOT + # variable was given and we should therefore abort immediately. + if [[ -n ${CDROM_ROOT} ]] ; then + die "unable to locate CD #${CDROM_CURRENT_CD} root at ${CDROM_ROOT}" + fi + + if [[ ${showedmsg} -eq 0 ]] ; then + if [[ ${CDROM_NUM_CDS} -eq 1 ]] ; then + einfo "Please insert+mount the ${CDROM_NAME:-CD for ${PN}} now !" + else + local var="CDROM_NAME_${CDROM_CURRENT_CD}" + if [[ -z ${!var} ]] ; then + einfo "Please insert+mount CD #${CDROM_CURRENT_CD} for ${PN} now !" + else + einfo "Please insert+mount the ${!var} now !" + fi + fi + showedmsg=1 + fi + + einfo "Press return to scan for the CD again" + einfo "or hit CTRL+C to abort the emerge." + + if [[ ${showjolietmsg} -eq 0 ]] ; then + showjolietmsg=1 + else + echo + ewarn "If you are having trouble with the detection" + ewarn "of your CD, it is possible that you do not have" + ewarn "Joliet support enabled in your kernel. Please" + ewarn "check that CONFIG_JOLIET is enabled in your kernel." + fi + read || die "something is screwed with your system" + done + + einfo "Found CD #${CDROM_CURRENT_CD} root at ${CDROM_ROOT}" +} + +# @FUNCTION: _cdrom_glob_match +# @USAGE: +# @INTERNAL +# @DESCRIPTION: +# Locates the given path ($2) within the given root directory ($1) +# case-insensitively and returns the first actual matching path. This +# eclass previously used "find -iname" but it only checked the file +# case-insensitively and not the directories. There is "find -ipath" +# but this does not intelligently skip non-matching paths, making it +# slow. Case-insensitive matching can only be applied to patterns so +# extended globbing is used to turn regular strings into patterns. All +# special characters are escaped so don't worry about breaking this. +_cdrom_glob_match() { + # The following line turns this: + # foo*foo/bar bar/baz/file.zip + # + # Into this: + # ?(foo\*foo)/?(bar\ bar)/?(baz)/?(file\.zip) + # + # This turns every path component into an escaped extended glob + # pattern to allow case-insensitive matching. Globs cannot span + # directories so each component becomes an individual pattern. + local p=\?\($(sed -e 's:[^A-Za-z0-9/]:\\\0:g' -e 's:/:)/?(:g' <<< "$2" || die)\) + ( + cd "$1" 2>/dev/null || return + shopt -s extglob nocaseglob nullglob || die + # The first person to make this work without an eval wins a + # cookie. It breaks without it when spaces are present. + eval "ARRAY=( ${p%\?()} )" + echo ${ARRAY[0]} + ) +} + +# @FUNCTION: _cdrom_set_names +# @INTERNAL +# @DESCRIPTION: +# Populate CDROM_NAME_# variables with the CDROM_NAMES array. +_cdrom_set_names() { + if [[ -n ${CDROM_NAMES} ]] ; then + local i + for i in $(seq ${#CDROM_NAMES[@]}); do + export CDROM_NAME_${i}="${CDROM_NAMES[$((${i} - 1))]}" + done + fi +} + +fi diff --git a/eclass/check-reqs.eclass b/eclass/check-reqs.eclass new file mode 100644 index 0000000..a45cbd1 --- /dev/null +++ b/eclass/check-reqs.eclass @@ -0,0 +1,361 @@ +# Copyright 2004-2020 Gentoo Authors +# Distributed under the terms of the GNU General Public License v2 + +# @ECLASS: check-reqs.eclass +# @MAINTAINER: +# QA Team +# @AUTHOR: +# Bo Ørsted Andresen +# Original Author: Ciaran McCreesh +# @SUPPORTED_EAPIS: 4 5 6 7 +# @BLURB: Provides a uniform way of handling ebuild which have very high build requirements +# @DESCRIPTION: +# This eclass provides a uniform way of handling ebuilds which have very high +# build requirements in terms of memory or disk space. It provides a function +# which should usually be called during pkg_setup(). +# +# The chosen action only happens when the system's resources are detected +# correctly and only if they are below the threshold specified by the package. +# +# @CODE +# # need this much memory (does *not* check swap) +# CHECKREQS_MEMORY="256M" +# +# # need this much temporary build space +# CHECKREQS_DISK_BUILD="2G" +# +# # install will need this much space in /usr +# CHECKREQS_DISK_USR="1G" +# +# # install will need this much space in /var +# CHECKREQS_DISK_VAR="1024M" +# +# @CODE +# +# If you don't specify a value for, say, CHECKREQS_MEMORY, then the test is not +# carried out. +# +# These checks should probably mostly work on non-Linux, and they should +# probably degrade gracefully if they don't. Probably. + +if [[ ! ${_CHECK_REQS_ECLASS_} ]]; then + +# @ECLASS-VARIABLE: CHECKREQS_MEMORY +# @DEFAULT_UNSET +# @DESCRIPTION: +# How much RAM is needed? Eg.: CHECKREQS_MEMORY=15M + +# @ECLASS-VARIABLE: CHECKREQS_DISK_BUILD +# @DEFAULT_UNSET +# @DESCRIPTION: +# How much diskspace is needed to build the package? Eg.: CHECKREQS_DISK_BUILD=2T + +# @ECLASS-VARIABLE: CHECKREQS_DISK_USR +# @DEFAULT_UNSET +# @DESCRIPTION: +# How much space in /usr is needed to install the package? Eg.: CHECKREQS_DISK_USR=15G + +# @ECLASS-VARIABLE: CHECKREQS_DISK_VAR +# @DEFAULT_UNSET +# @DESCRIPTION: +# How much space is needed in /var? Eg.: CHECKREQS_DISK_VAR=3000M + +case ${EAPI:-0} in + 4|5|6|7) ;; + *) die "${ECLASS}: EAPI=${EAPI:-0} is not supported" ;; +esac + +EXPORT_FUNCTIONS pkg_pretend pkg_setup + +# Obsolete function executing all the checks and printing out results +check_reqs() { + eerror "Package calling old ${FUNCNAME} function." + eerror "It should call check-reqs_pkg_pretend and check-reqs_pkg_setup." + die "${FUNCNAME} is banned" +} + +# @FUNCTION: check-reqs_pkg_setup +# @DESCRIPTION: +# Exported function running the resources checks in pkg_setup phase. +# It should be run in both phases to ensure condition changes between +# pkg_pretend and pkg_setup won't affect the build. +check-reqs_pkg_setup() { + debug-print-function ${FUNCNAME} "$@" + + check-reqs_prepare + check-reqs_run + check-reqs_output +} + +# @FUNCTION: check-reqs_pkg_pretend +# @DESCRIPTION: +# Exported function running the resources checks in pkg_pretend phase. +check-reqs_pkg_pretend() { + debug-print-function ${FUNCNAME} "$@" + + check-reqs_pkg_setup "$@" +} + +# @FUNCTION: check-reqs_prepare +# @INTERNAL +# @DESCRIPTION: +# Internal function that checks the variables that should be defined. +check-reqs_prepare() { + debug-print-function ${FUNCNAME} "$@" + + if [[ -z ${CHECKREQS_MEMORY} && + -z ${CHECKREQS_DISK_BUILD} && + -z ${CHECKREQS_DISK_USR} && + -z ${CHECKREQS_DISK_VAR} ]]; then + eerror "Set some check-reqs eclass variables if you want to use it." + eerror "If you are user and see this message file a bug against the package." + die "${FUNCNAME}: check-reqs eclass called but not actually used!" + fi +} + +# @FUNCTION: check-reqs_run +# @INTERNAL +# @DESCRIPTION: +# Internal function that runs the check based on variable settings. +check-reqs_run() { + debug-print-function ${FUNCNAME} "$@" + + # some people are *censored* + unset CHECKREQS_FAILED + + if [[ ${MERGE_TYPE} != binary ]]; then + [[ -n ${CHECKREQS_MEMORY} ]] && \ + check-reqs_memory \ + ${CHECKREQS_MEMORY} + + [[ -n ${CHECKREQS_DISK_BUILD} ]] && \ + check-reqs_disk \ + "${T}" \ + "${CHECKREQS_DISK_BUILD}" + fi + + if [[ ${MERGE_TYPE} != buildonly ]]; then + [[ -n ${CHECKREQS_DISK_USR} ]] && \ + check-reqs_disk \ + "${EROOT%/}/usr" \ + "${CHECKREQS_DISK_USR}" + + [[ -n ${CHECKREQS_DISK_VAR} ]] && \ + check-reqs_disk \ + "${EROOT%/}/var" \ + "${CHECKREQS_DISK_VAR}" + fi +} + +# @FUNCTION: check-reqs_get_kibibytes +# @INTERNAL +# @DESCRIPTION: +# Internal function that returns number in KiB. +# Returns 1024**2 for 1G or 1024**3 for 1T. +check-reqs_get_kibibytes() { + debug-print-function ${FUNCNAME} "$@" + + [[ -z ${1} ]] && die "Usage: ${FUNCNAME} [size]" + + local unit=${1:(-1)} + local size=${1%[GMT]} + + case ${unit} in + M) echo $((1024 * size)) ;; + G) echo $((1024 * 1024 * size)) ;; + T) echo $((1024 * 1024 * 1024 * size)) ;; + *) + die "${FUNCNAME}: Unknown unit: ${unit}" + ;; + esac +} + +# @FUNCTION: check-reqs_get_number +# @INTERNAL +# @DESCRIPTION: +# Internal function that returns the numerical value without the unit. +# Returns "1" for "1G" or "150" for "150T". +check-reqs_get_number() { + debug-print-function ${FUNCNAME} "$@" + + [[ -z ${1} ]] && die "Usage: ${FUNCNAME} [size]" + + local size=${1%[GMT]} + [[ ${size} == ${1} ]] && die "${FUNCNAME}: Missing unit: ${1}" + + echo ${size} +} + +# @FUNCTION: check-reqs_get_unit +# @INTERNAL +# @DESCRIPTION: +# Internal function that returns the unit without the numerical value. +# Returns "GiB" for "1G" or "TiB" for "150T". +check-reqs_get_unit() { + debug-print-function ${FUNCNAME} "$@" + + [[ -z ${1} ]] && die "Usage: ${FUNCNAME} [size]" + + local unit=${1:(-1)} + + case ${unit} in + M) echo "MiB" ;; + G) echo "GiB" ;; + T) echo "TiB" ;; + *) + die "${FUNCNAME}: Unknown unit: ${unit}" + ;; + esac +} + +# @FUNCTION: check-reqs_output +# @INTERNAL +# @DESCRIPTION: +# Internal function that prints the warning and dies if required based on +# the test results. +check-reqs_output() { + debug-print-function ${FUNCNAME} "$@" + + local msg="ewarn" + + [[ ${EBUILD_PHASE} == "pretend" && -z ${I_KNOW_WHAT_I_AM_DOING} ]] && msg="eerror" + if [[ -n ${CHECKREQS_FAILED} ]]; then + ${msg} + ${msg} "Space constraints set in the ebuild were not met!" + ${msg} "The build will most probably fail, you should enhance the space" + ${msg} "as per failed tests." + ${msg} + + [[ ${EBUILD_PHASE} == "pretend" && -z ${I_KNOW_WHAT_I_AM_DOING} ]] && \ + die "Build requirements not met!" + fi +} + +# @FUNCTION: check-reqs_memory +# @INTERNAL +# @DESCRIPTION: +# Internal function that checks size of RAM. +check-reqs_memory() { + debug-print-function ${FUNCNAME} "$@" + + [[ -z ${1} ]] && die "Usage: ${FUNCNAME} [size]" + + local size=${1} + local actual_memory + local actual_swap + + check-reqs_start_phase \ + ${size} \ + "RAM" + + if [[ -r /proc/meminfo ]] ; then + actual_memory=$(awk '/MemTotal/ { print $2 }' /proc/meminfo) + actual_swap=$(awk '/SwapTotal/ { print $2 }' /proc/meminfo) + else + actual_memory=$(sysctl hw.physmem 2>/dev/null) + [[ $? -eq 0 ]] && actual_memory=$(echo "${actual_memory}" \ + | sed -e 's/^[^:=]*[:=][[:space:]]*//') + actual_swap=$(sysctl vm.swap_total 2>/dev/null) + [[ $? -eq 0 ]] && actual_swap=$(echo "${actual_swap}" \ + | sed -e 's/^[^:=]*[:=][[:space:]]*//') + fi + if [[ -n ${actual_memory} ]] ; then + if [[ ${actual_memory} -ge $(check-reqs_get_kibibytes ${size}) ]] ; then + eend 0 + elif [[ -n ${actual_swap} && $((${actual_memory} + ${actual_swap})) \ + -ge $(check-reqs_get_kibibytes ${size}) ]] ; then + ewarn "Amount of main memory is insufficient, but amount" + ewarn "of main memory combined with swap is sufficient." + ewarn "Build process may make computer very slow!" + eend 0 + else + eend 1 + check-reqs_unsatisfied \ + ${size} \ + "RAM" + fi + else + eend 1 + ewarn "Couldn't determine amount of memory, skipping..." + fi +} + +# @FUNCTION: check-reqs_disk +# @INTERNAL +# @DESCRIPTION: +# Internal function that checks space on the harddrive. +check-reqs_disk() { + debug-print-function ${FUNCNAME} "$@" + + [[ -z ${2} ]] && die "Usage: ${FUNCNAME} [path] [size]" + + local path=${1} + local size=${2} + local space_kbi + + check-reqs_start_phase \ + ${size} \ + "disk space at \"${path}\"" + + space_kbi=$(df -Pk "${1}" 2>/dev/null | awk 'FNR == 2 {print $4}') + + if [[ $? == 0 && -n ${space_kbi} ]] ; then + if [[ ${space_kbi} -lt $(check-reqs_get_kibibytes ${size}) ]] ; then + eend 1 + check-reqs_unsatisfied \ + ${size} \ + "disk space at \"${path}\"" + else + eend 0 + fi + else + eend 1 + ewarn "Couldn't determine disk space, skipping..." + fi +} + +# @FUNCTION: check-reqs_start_phase +# @INTERNAL +# @DESCRIPTION: +# Internal function that inform about started check +check-reqs_start_phase() { + debug-print-function ${FUNCNAME} "$@" + + [[ -z ${2} ]] && die "Usage: ${FUNCNAME} [size] [location]" + + local size=${1} + local location=${2} + local sizeunit="$(check-reqs_get_number ${size}) $(check-reqs_get_unit ${size})" + + ebegin "Checking for at least ${sizeunit} ${location}" +} + +# @FUNCTION: check-reqs_unsatisfied +# @INTERNAL +# @DESCRIPTION: +# Internal function that inform about check result. +# It has different output between pretend and setup phase, +# where in pretend phase it is fatal. +check-reqs_unsatisfied() { + debug-print-function ${FUNCNAME} "$@" + + [[ -z ${2} ]] && die "Usage: ${FUNCNAME} [size] [location]" + + local msg="ewarn" + local size=${1} + local location=${2} + local sizeunit="$(check-reqs_get_number ${size}) $(check-reqs_get_unit ${size})" + + [[ ${EBUILD_PHASE} == "pretend" && -z ${I_KNOW_WHAT_I_AM_DOING} ]] && msg="eerror" + ${msg} "There is NOT at least ${sizeunit} ${location}" + + # @ECLASS-VARIABLE: CHECKREQS_FAILED + # @DESCRIPTION: + # @INTERNAL + # If set the checks failed and eclass should abort the build. + # Internal, do not set yourself. + CHECKREQS_FAILED="true" +} + +_CHECK_REQS_ECLASS_=1 +fi diff --git a/eclass/chromium-2.eclass b/eclass/chromium-2.eclass new file mode 100644 index 0000000..b3d63f3 --- /dev/null +++ b/eclass/chromium-2.eclass @@ -0,0 +1,178 @@ +# Copyright 1999-2020 Gentoo Authors +# Distributed under the terms of the GNU General Public License v2 + +# @ECLASS: chromium-2.eclass +# @MAINTAINER: +# Chromium Herd +# @AUTHOR: +# Mike Gilbert +# @BLURB: Shared functions for chromium and google-chrome + +inherit eutils linux-info + +if [[ ${PN} == chromium ]]; then + IUSE+=" custom-cflags" +fi + +# @FUNCTION: chromium_suid_sandbox_check_kernel_config +# @USAGE: +# @DESCRIPTION: +# Ensures the system kernel supports features needed for SUID sandbox to work. +chromium_suid_sandbox_check_kernel_config() { + has "${EAPI:-0}" 0 1 2 3 && die "EAPI=${EAPI} is not supported" + + if [[ "${MERGE_TYPE}" == "source" || "${MERGE_TYPE}" == "binary" ]]; then + # Warn if the kernel does not support features needed for sandboxing. + # Bug #363987. + ERROR_PID_NS="PID_NS is required for sandbox to work" + ERROR_NET_NS="NET_NS is required for sandbox to work" + ERROR_USER_NS="USER_NS is required for sandbox to work" + ERROR_SECCOMP_FILTER="SECCOMP_FILTER is required for sandbox to work" + # Warn if the kernel does not support features needed for the browser to work + # (bug #552576, bug #556286). + ERROR_ADVISE_SYSCALLS="CONFIG_ADVISE_SYSCALLS is required for the renderer (bug #552576)" + ERROR_COMPAT_VDSO="CONFIG_COMPAT_VDSO causes segfaults (bug #556286)" + ERROR_GRKERNSEC="CONFIG_GRKERNSEC breaks sandbox (bug #613668)" + CONFIG_CHECK="~PID_NS ~NET_NS ~SECCOMP_FILTER ~USER_NS ~ADVISE_SYSCALLS ~!COMPAT_VDSO ~!GRKERNSEC" + check_extra_config + fi +} + +# @ECLASS-VARIABLE: CHROMIUM_LANGS +# @DEFAULT_UNSET +# @DESCRIPTION: +# List of language packs available for this package. + +_chromium_set_l10n_IUSE() { + [[ ${EAPI:-0} == 0 ]] && die "EAPI=${EAPI} is not supported" + + local lang + for lang in ${CHROMIUM_LANGS}; do + # Default to enabled since we bundle them anyway. + # USE-expansion will take care of disabling the langs the user has not + # selected via L10N. + IUSE+=" +l10n_${lang}" + done +} + +if [[ ${CHROMIUM_LANGS} ]]; then + _chromium_set_l10n_IUSE +fi + +# @FUNCTION: chromium_remove_language_paks +# @USAGE: +# @DESCRIPTION: +# Removes pak files from the current directory for languages that the user has +# not selected via the L10N variable. +# Also performs QA checks to ensure CHROMIUM_LANGS has been set correctly. +chromium_remove_language_paks() { + local lang pak + + # Look for missing pak files. + for lang in ${CHROMIUM_LANGS}; do + if [[ ! -e ${lang}.pak ]]; then + eqawarn "L10N warning: no .pak file for ${lang} (${lang}.pak not found)" + fi + done + + # Bug 588198 + rm -f fake-bidi.pak || die + rm -f fake-bidi.pak.info || die + + # Look for extra pak files. + # Remove pak files that the user does not want. + for pak in *.pak; do + lang=${pak%.pak} + + if [[ ${lang} == en-US ]]; then + continue + fi + + if ! has ${lang} ${CHROMIUM_LANGS}; then + eqawarn "L10N warning: no ${lang} in LANGS" + continue + fi + + if ! use l10n_${lang}; then + rm "${pak}" || die + rm -f "${pak}.info" || die + fi + done +} + +chromium_pkg_die() { + if [[ "${EBUILD_PHASE}" != "compile" ]]; then + return + fi + + # Prevent user problems like bug #348235. + if ( shopt -s extglob; is-flagq '-g?(gdb)?([1-9])' ); then + ewarn + ewarn "You have enabled debug info (i.e. -g or -ggdb in your CFLAGS/CXXFLAGS)." + ewarn "This produces very large build files causes the linker to consume large" + ewarn "amounts of memory." + ewarn + ewarn "Please try removing -g{,gdb} before reporting a bug." + ewarn + fi + + # ccache often causes bogus compile failures, especially when the cache gets + # corrupted. + if has ccache ${FEATURES}; then + ewarn + ewarn "You have enabled ccache. Please try disabling ccache" + ewarn "before reporting a bug." + ewarn + fi + + # No ricer bugs. + if in_iuse custom-cflags && use custom-cflags; then + ewarn + ewarn "You have enabled the custom-cflags USE flag." + ewarn "Please disable it before reporting a bug." + ewarn + fi + + # If the system doesn't have enough memory, the compilation is known to + # fail. Print info about memory to recognize this condition. + einfo + einfo "$(grep MemTotal /proc/meminfo)" + einfo "$(grep SwapTotal /proc/meminfo)" + einfo +} + +# @VARIABLE: EGYP_CHROMIUM_COMMAND +# @DESCRIPTION: +# Path to the gyp_chromium script. +: ${EGYP_CHROMIUM_COMMAND:=build/gyp_chromium} + +# @VARIABLE: EGYP_CHROMIUM_DEPTH +# @DESCRIPTION: +# Depth for egyp_chromium. +: ${EGYP_CHROMIUM_DEPTH:=.} + +# @FUNCTION: egyp_chromium +# @USAGE: [gyp arguments] +# @DESCRIPTION: +# Calls EGYP_CHROMIUM_COMMAND with depth EGYP_CHROMIUM_DEPTH and given +# arguments. The full command line is echoed for logging. +egyp_chromium() { + set -- "${EGYP_CHROMIUM_COMMAND}" --depth="${EGYP_CHROMIUM_DEPTH}" "$@" + echo "$@" + "$@" +} + +# @FUNCTION: gyp_use +# @USAGE: [GYP flag] [true suffix] [false suffix] +# @DESCRIPTION: +# If USE flag is set, echo -D[GYP flag]=[true suffix]. +# +# If USE flag is not set, echo -D[GYP flag]=[false suffix]. +# +# [GYP flag] defaults to use_[USE flag] with hyphens converted to underscores. +# +# [true suffix] defaults to 1. [false suffix] defaults to 0. +gyp_use() { + local gypflag="-D${2:-use_${1//-/_}}=" + usex "$1" "${gypflag}" "${gypflag}" "${3-1}" "${4-0}" +} diff --git a/eclass/cmake-multilib.eclass b/eclass/cmake-multilib.eclass new file mode 100644 index 0000000..2693d9c --- /dev/null +++ b/eclass/cmake-multilib.eclass @@ -0,0 +1,87 @@ +# Copyright 1999-2019 Gentoo Authors +# Distributed under the terms of the GNU General Public License v2 + +# @ECLASS: cmake-multilib.eclass +# @MAINTAINER: +# gx86-multilib team +# @AUTHOR: +# Author: Michał Górny +# @SUPPORTED_EAPIS: 6 7 +# @BLURB: cmake-utils wrapper for multilib builds +# @DESCRIPTION: +# The cmake-multilib.eclass provides a glue between cmake-utils.eclass(5) +# and multilib-minimal.eclass(5), aiming to provide a convenient way +# to build packages using cmake for multiple ABIs. +# +# Inheriting this eclass sets IUSE and exports default multilib_src_*() +# sub-phases that call cmake-utils phase functions for each ABI enabled. +# The multilib_src_*() functions can be defined in ebuild just like +# in multilib-minimal, yet they ought to call appropriate cmake-utils +# phase rather than 'default'. + +# @ECLASS-VARIABLE: CMAKE_ECLASS +# @DESCRIPTION: +# Default is "cmake-utils" for compatibility. Specify "cmake" for ebuilds +# that ported from cmake-utils.eclass to cmake.eclass already. +: ${CMAKE_ECLASS:=cmake-utils} + +case ${EAPI:-0} in + [67]) ;; + *) die "EAPI=${EAPI} is not supported" ;; +esac + +if [[ ${CMAKE_IN_SOURCE_BUILD} ]]; then + die "${ECLASS}: multilib support requires out-of-source builds." +fi + +case ${CMAKE_ECLASS} in + cmake-utils|cmake) ;; + *) + eerror "Unknown value for \${CMAKE_ECLASS}" + die "Value ${CMAKE_ECLASS} is not supported" + ;; +esac + +inherit ${CMAKE_ECLASS} multilib-minimal + +EXPORT_FUNCTIONS src_configure src_compile src_test src_install + +cmake-multilib_src_configure() { + local _cmake_args=( "${@}" ) + + multilib-minimal_src_configure +} + +multilib_src_configure() { + ${CMAKE_ECLASS}_src_configure "${_cmake_args[@]}" +} + +cmake-multilib_src_compile() { + local _cmake_args=( "${@}" ) + + multilib-minimal_src_compile +} + +multilib_src_compile() { + ${CMAKE_ECLASS}_src_compile "${_cmake_args[@]}" +} + +cmake-multilib_src_test() { + local _cmake_args=( "${@}" ) + + multilib-minimal_src_test +} + +multilib_src_test() { + ${CMAKE_ECLASS}_src_test "${_cmake_args[@]}" +} + +cmake-multilib_src_install() { + local _cmake_args=( "${@}" ) + + multilib-minimal_src_install +} + +multilib_src_install() { + ${CMAKE_ECLASS}_src_install "${_cmake_args[@]}" +} diff --git a/eclass/cmake-utils.eclass b/eclass/cmake-utils.eclass new file mode 100644 index 0000000..8127a66 --- /dev/null +++ b/eclass/cmake-utils.eclass @@ -0,0 +1,845 @@ +# Copyright 1999-2019 Gentoo Authors +# Distributed under the terms of the GNU General Public License v2 + +# @ECLASS: cmake-utils.eclass +# @MAINTAINER: +# kde@gentoo.org +# @AUTHOR: +# Tomáš Chvátal +# Maciej Mrozowski +# (undisclosed contributors) +# Original author: Zephyrus (zephyrus@mirach.it) +# @SUPPORTED_EAPIS: 5 6 7 +# @BLURB: common ebuild functions for cmake-based packages +# @DESCRIPTION: +# DEPRECATED: This no longer receives any changes. Everyone must port to cmake.eclass. +# The cmake-utils eclass makes creating ebuilds for cmake-based packages much easier. +# It provides all inherited features (DOCS, HTML_DOCS, PATCHES) along with out-of-source +# builds (default), in-source builds and an implementation of the well-known use_enable +# and use_with functions for CMake. + +if [[ -z ${_CMAKE_UTILS_ECLASS} ]]; then +_CMAKE_UTILS_ECLASS=1 + +# @ECLASS-VARIABLE: BUILD_DIR +# @DESCRIPTION: +# Build directory where all cmake processed files should be generated. +# For in-source build it's fixed to ${CMAKE_USE_DIR}. +# For out-of-source build it can be overridden, by default it uses +# ${WORKDIR}/${P}_build. +# +# This variable has been called CMAKE_BUILD_DIR formerly. +# It is set under that name for compatibility. + +# @ECLASS-VARIABLE: CMAKE_BINARY +# @DESCRIPTION: +# Eclass can use different cmake binary than the one provided in by system. +: ${CMAKE_BINARY:=cmake} + +# @ECLASS-VARIABLE: CMAKE_BUILD_TYPE +# @DESCRIPTION: +# Set to override default CMAKE_BUILD_TYPE. Only useful for packages +# known to make use of "if (CMAKE_BUILD_TYPE MATCHES xxx)". +# If about to be set - needs to be set before invoking cmake-utils_src_configure. +# You usualy do *NOT* want nor need to set it as it pulls CMake default build-type +# specific compiler flags overriding make.conf. +: ${CMAKE_BUILD_TYPE:=Gentoo} + +# @ECLASS-VARIABLE: CMAKE_IN_SOURCE_BUILD +# @DEFAULT_UNSET +# @DESCRIPTION: +# Set to enable in-source build. + +# @ECLASS-VARIABLE: CMAKE_MAKEFILE_GENERATOR +# @DEFAULT_UNSET +# @DESCRIPTION: +# Specify a makefile generator to be used by cmake. +# At this point only "emake" and "ninja" are supported. +# In EAPI 7 and above, the default is set to "ninja", +# whereas in EAPIs below 7, it is set to "emake". + +# @ECLASS-VARIABLE: CMAKE_MIN_VERSION +# @DESCRIPTION: +# Specify the minimum required CMake version. +: ${CMAKE_MIN_VERSION:=3.9.6} + +# @ECLASS-VARIABLE: CMAKE_REMOVE_MODULES +# @DESCRIPTION: +# Do we want to remove anything? yes or whatever else for no +: ${CMAKE_REMOVE_MODULES:=yes} + +# @ECLASS-VARIABLE: CMAKE_REMOVE_MODULES_LIST +# @DESCRIPTION: +# Space-separated list of CMake modules that will be removed in $S during src_prepare, +# in order to force packages to use the system version. +: ${CMAKE_REMOVE_MODULES_LIST:=FindBLAS FindLAPACK} + +# @ECLASS-VARIABLE: CMAKE_USE_DIR +# @DESCRIPTION: +# Sets the directory where we are working with cmake. +# For example when application uses autotools and only one +# plugin needs to be done by cmake. +# By default it uses ${S}. + +# @ECLASS-VARIABLE: CMAKE_VERBOSE +# @DESCRIPTION: +# Set to OFF to disable verbose messages during compilation +: ${CMAKE_VERBOSE:=ON} + +# @ECLASS-VARIABLE: CMAKE_WARN_UNUSED_CLI +# @DESCRIPTION: +# Warn about variables that are declared on the command line +# but not used. Might give false-positives. +# "no" to disable (default) or anything else to enable. + +# @ECLASS-VARIABLE: CMAKE_EXTRA_CACHE_FILE +# @DEFAULT_UNSET +# @DESCRIPTION: +# Specifies an extra cache file to pass to cmake. This is the analog of EXTRA_ECONF +# for econf and is needed to pass TRY_RUN results when cross-compiling. +# Should be set by user in a per-package basis in /etc/portage/package.env. + +# @ECLASS-VARIABLE: CMAKE_UTILS_QA_SRC_DIR_READONLY +# @DEFAULT_UNSET +# @DESCRIPTION: +# After running cmake-utils_src_prepare, sets ${S} to read-only. This is +# a user flag and should under _no circumstances_ be set in the ebuild. +# Helps in improving QA of build systems that write to source tree. + +case ${EAPI} in + 5) : ${CMAKE_WARN_UNUSED_CLI:=no} ;; + 6|7) : ${CMAKE_WARN_UNUSED_CLI:=yes} ;; + *) die "EAPI=${EAPI:-0} is not supported" ;; +esac + +inherit toolchain-funcs ninja-utils flag-o-matic multiprocessing xdg-utils + +case ${EAPI} in + [56]) + : ${CMAKE_MAKEFILE_GENERATOR:=emake} + inherit eutils multilib + ;; + *) + : ${CMAKE_MAKEFILE_GENERATOR:=ninja} + ;; +esac + +EXPORT_FUNCTIONS src_prepare src_configure src_compile src_test src_install + +if [[ ${WANT_CMAKE} ]]; then + if [[ ${EAPI} != [56] ]]; then + die "\${WANT_CMAKE} has been removed and is a no-op now" + else + eqawarn "\${WANT_CMAKE} has been removed and is a no-op now" + fi +fi +[[ ${PREFIX} ]] && die "\${PREFIX} has been removed and is a no-op now" + +case ${CMAKE_MAKEFILE_GENERATOR} in + emake) + BDEPEND="sys-devel/make" + ;; + ninja) + BDEPEND="dev-util/ninja" + ;; + *) + eerror "Unknown value for \${CMAKE_MAKEFILE_GENERATOR}" + die "Value ${CMAKE_MAKEFILE_GENERATOR} is not supported" + ;; +esac + +if [[ ${PN} != cmake ]]; then + BDEPEND+=" >=dev-util/cmake-${CMAKE_MIN_VERSION}" +fi + +case ${EAPI} in + 7) ;; + *) DEPEND=" ${BDEPEND}" ;; +esac + +# Internal functions used by cmake-utils_use_* +_cmake_use_me_now() { + debug-print-function ${FUNCNAME} "$@" + + local arg=$2 + [[ ! -z $3 ]] && arg=$3 + + [[ ${EAPI} == 5 ]] || die "${FUNCNAME[1]} is banned in EAPI 6 and later: use -D$1=\"\$(usex $2)\" instead" + + local uper capitalised x + [[ -z $2 ]] && die "cmake-utils_use-$1 []" + if [[ ! -z $3 ]]; then + # user specified the use name so use it + echo "-D$1$3=$(use $2 && echo ON || echo OFF)" + else + # use all various most used combinations + uper=$(echo ${2} | tr '[:lower:]' '[:upper:]') + capitalised=$(echo ${2} | sed 's/\<\(.\)\([^ ]*\)/\u\1\L\2/g') + for x in $2 $uper $capitalised; do + echo "-D$1$x=$(use $2 && echo ON || echo OFF) " + done + fi +} +_cmake_use_me_now_inverted() { + debug-print-function ${FUNCNAME} "$@" + + local arg=$2 + [[ ! -z $3 ]] && arg=$3 + + if [[ ${EAPI} != 5 && "${FUNCNAME[1]}" != cmake-utils_use_find_package ]] ; then + die "${FUNCNAME[1]} is banned in EAPI 6 and later: use -D$1=\"\$(usex $2)\" instead" + fi + + local uper capitalised x + [[ -z $2 ]] && die "cmake-utils_use-$1 []" + if [[ ! -z $3 ]]; then + # user specified the use name so use it + echo "-D$1$3=$(use $2 && echo OFF || echo ON)" + else + # use all various most used combinations + uper=$(echo ${2} | tr '[:lower:]' '[:upper:]') + capitalised=$(echo ${2} | sed 's/\<\(.\)\([^ ]*\)/\u\1\L\2/g') + for x in $2 $uper $capitalised; do + echo "-D$1$x=$(use $2 && echo OFF || echo ON) " + done + fi +} + +# Determine using IN or OUT source build +_cmake_check_build_dir() { + : ${CMAKE_USE_DIR:=${S}} + if [[ -n ${CMAKE_IN_SOURCE_BUILD} ]]; then + # we build in source dir + BUILD_DIR="${CMAKE_USE_DIR}" + else + # Respect both the old variable and the new one, depending + # on which one was set by the ebuild. + if [[ ! ${BUILD_DIR} && ${CMAKE_BUILD_DIR} ]]; then + if [[ ${EAPI} != [56] ]]; then + eerror "The CMAKE_BUILD_DIR variable has been renamed to BUILD_DIR." + die "The ebuild must be migrated to BUILD_DIR." + else + eqawarn "The CMAKE_BUILD_DIR variable has been renamed to BUILD_DIR." + eqawarn "Please migrate the ebuild to use the new one." + fi + + # In the next call, both variables will be set already + # and we'd have to know which one takes precedence. + _RESPECT_CMAKE_BUILD_DIR=1 + fi + + if [[ ${_RESPECT_CMAKE_BUILD_DIR} ]]; then + BUILD_DIR=${CMAKE_BUILD_DIR:-${WORKDIR}/${P}_build} + else + : ${BUILD_DIR:=${WORKDIR}/${P}_build} + fi + fi + + # Backwards compatibility for getting the value. + [[ ${EAPI} == [56] ]] && CMAKE_BUILD_DIR=${BUILD_DIR} + + mkdir -p "${BUILD_DIR}" || die + echo ">>> Working in BUILD_DIR: \"$BUILD_DIR\"" +} + +# Determine which generator to use +_cmake_generator_to_use() { + local generator_name + + case ${CMAKE_MAKEFILE_GENERATOR} in + ninja) + # if ninja is enabled but not installed, the build could fail + # this could happen if ninja is manually enabled (eg. make.conf) but not installed + case ${EAPI} in + 5|6) + if ! ROOT=/ has_version dev-util/ninja; then + die "CMAKE_MAKEFILE_GENERATOR is set to ninja, but ninja is not installed. Please install dev-util/ninja or unset CMAKE_MAKEFILE_GENERATOR." + fi + ;; + *) + if ! has_version -b dev-util/ninja; then + die "CMAKE_MAKEFILE_GENERATOR is set to ninja, but ninja is not installed. Please install dev-util/ninja or unset CMAKE_MAKEFILE_GENERATOR." + fi + ;; + esac + generator_name="Ninja" + ;; + emake) + generator_name="Unix Makefiles" + ;; + *) + eerror "Unknown value for \${CMAKE_MAKEFILE_GENERATOR}" + die "Value ${CMAKE_MAKEFILE_GENERATOR} is not supported" + ;; + esac + + echo ${generator_name} +} + +# @FUNCTION: cmake_comment_add_subdirectory +# @USAGE: +# @DESCRIPTION: +# Comment out one or more add_subdirectory calls in CMakeLists.txt in the current directory +cmake_comment_add_subdirectory() { + if [[ -z ${1} ]]; then + die "comment_add_subdirectory must be passed at least one directory name to comment" + fi + + if [[ -e "CMakeLists.txt" ]]; then + local d + for d in $@; do + sed -e "/add_subdirectory[[:space:]]*([[:space:]]*${d//\//\\/}[[:space:]]*)/I s/^/#DONOTCOMPILE /" \ + -i CMakeLists.txt || die "failed to comment add_subdirectory(${d})" + done + fi +} + +# @FUNCTION: comment_add_subdirectory +# @USAGE: +# @DESCRIPTION: +# Comment out an add_subdirectory call in CMakeLists.txt in the current directory +# Banned in EAPI 6 and later - use cmake_comment_add_subdirectory instead. +comment_add_subdirectory() { + [[ ${EAPI} == 5 ]] || die "comment_add_subdirectory is banned in EAPI 6 and later - use cmake_comment_add_subdirectory instead" + + cmake_comment_add_subdirectory "$@" +} + +# @FUNCTION: cmake-utils_use_with +# @USAGE: [flag name] +# @DESCRIPTION: +# Based on use_with. See ebuild(5). +# +# `cmake-utils_use_with foo FOO` echoes -DWITH_FOO=ON if foo is enabled +# and -DWITH_FOO=OFF if it is disabled. +cmake-utils_use_with() { _cmake_use_me_now WITH_ "$@" ; } + +# @FUNCTION: cmake-utils_use_enable +# @USAGE: [flag name] +# @DESCRIPTION: +# Based on use_enable. See ebuild(5). +# +# `cmake-utils_use_enable foo FOO` echoes -DENABLE_FOO=ON if foo is enabled +# and -DENABLE_FOO=OFF if it is disabled. +cmake-utils_use_enable() { _cmake_use_me_now ENABLE_ "$@" ; } + +# @FUNCTION: cmake-utils_use_find_package +# @USAGE: +# @DESCRIPTION: +# Based on use_enable. See ebuild(5). +# +# `cmake-utils_use_find_package foo LibFoo` echoes -DCMAKE_DISABLE_FIND_PACKAGE_LibFoo=OFF +# if foo is enabled and -DCMAKE_DISABLE_FIND_PACKAGE_LibFoo=ON if it is disabled. +# This can be used to make find_package optional. +cmake-utils_use_find_package() { + if [[ ${EAPI} != 5 && "$#" != 2 ]] ; then + die "Usage: cmake-utils_use_find_package " + fi + + _cmake_use_me_now_inverted CMAKE_DISABLE_FIND_PACKAGE_ "$@" ; +} + +# @FUNCTION: cmake_use_find_package +# @USAGE: +# @DESCRIPTION: +# Alias for cmake-utils_use_find_package. +cmake_use_find_package() { + if [[ "$#" != 2 ]] ; then + die "Usage: cmake_use_find_package " + fi + + cmake-utils_use_find_package "$@" ; +} + +# @FUNCTION: cmake-utils_use_disable +# @USAGE: [flag name] +# @DESCRIPTION: +# Based on inversion of use_enable. See ebuild(5). +# +# `cmake-utils_use_enable foo FOO` echoes -DDISABLE_FOO=OFF if foo is enabled +# and -DDISABLE_FOO=ON if it is disabled. +cmake-utils_use_disable() { _cmake_use_me_now_inverted DISABLE_ "$@" ; } + +# @FUNCTION: cmake-utils_use_no +# @USAGE: [flag name] +# @DESCRIPTION: +# Based on use_disable. See ebuild(5). +# +# `cmake-utils_use_no foo FOO` echoes -DNO_FOO=OFF if foo is enabled +# and -DNO_FOO=ON if it is disabled. +cmake-utils_use_no() { _cmake_use_me_now_inverted NO_ "$@" ; } + +# @FUNCTION: cmake-utils_use_want +# @USAGE: [flag name] +# @DESCRIPTION: +# Based on use_enable. See ebuild(5). +# +# `cmake-utils_use_want foo FOO` echoes -DWANT_FOO=ON if foo is enabled +# and -DWANT_FOO=OFF if it is disabled. +cmake-utils_use_want() { _cmake_use_me_now WANT_ "$@" ; } + +# @FUNCTION: cmake-utils_use_build +# @USAGE: [flag name] +# @DESCRIPTION: +# Based on use_enable. See ebuild(5). +# +# `cmake-utils_use_build foo FOO` echoes -DBUILD_FOO=ON if foo is enabled +# and -DBUILD_FOO=OFF if it is disabled. +cmake-utils_use_build() { _cmake_use_me_now BUILD_ "$@" ; } + +# @FUNCTION: cmake-utils_use_has +# @USAGE: [flag name] +# @DESCRIPTION: +# Based on use_enable. See ebuild(5). +# +# `cmake-utils_use_has foo FOO` echoes -DHAVE_FOO=ON if foo is enabled +# and -DHAVE_FOO=OFF if it is disabled. +cmake-utils_use_has() { _cmake_use_me_now HAVE_ "$@" ; } + +# @FUNCTION: cmake-utils_use_use +# @USAGE: [flag name] +# @DESCRIPTION: +# Based on use_enable. See ebuild(5). +# +# `cmake-utils_use_use foo FOO` echoes -DUSE_FOO=ON if foo is enabled +# and -DUSE_FOO=OFF if it is disabled. +cmake-utils_use_use() { _cmake_use_me_now USE_ "$@" ; } + +# @FUNCTION: cmake-utils_use +# @USAGE: [flag name] +# @DESCRIPTION: +# Based on use_enable. See ebuild(5). +# +# `cmake-utils_use foo FOO` echoes -DFOO=ON if foo is enabled +# and -DFOO=OFF if it is disabled. +cmake-utils_use() { _cmake_use_me_now "" "$@" ; } + +# @FUNCTION: cmake-utils_useno +# @USAGE: [flag name] +# @DESCRIPTION: +# Based on use_enable. See ebuild(5). +# +# `cmake-utils_useno foo NOFOO` echoes -DNOFOO=OFF if foo is enabled +# and -DNOFOO=ON if it is disabled. +cmake-utils_useno() { _cmake_use_me_now_inverted "" "$@" ; } + +# Internal function for modifying hardcoded definitions. +# Removes dangerous definitions that override Gentoo settings. +_cmake_modify-cmakelists() { + debug-print-function ${FUNCNAME} "$@" + + # Only edit the files once + grep -qs "<<< Gentoo configuration >>>" "${CMAKE_USE_DIR}"/CMakeLists.txt && return 0 + + # Comment out all set ( value) + find "${CMAKE_USE_DIR}" -name CMakeLists.txt -exec sed \ + -e '/^[[:space:]]*set[[:space:]]*([[:space:]]*CMAKE_BUILD_TYPE\([[:space:]].*)\|)\)/I{s/^/#_cmake_modify_IGNORE /g}' \ + -e '/^[[:space:]]*set[[:space:]]*([[:space:]]*CMAKE_COLOR_MAKEFILE[[:space:]].*)/I{s/^/#_cmake_modify_IGNORE /g}' \ + -e '/^[[:space:]]*set[[:space:]]*([[:space:]]*CMAKE_INSTALL_PREFIX[[:space:]].*)/I{s/^/#_cmake_modify_IGNORE /g}' \ + -e '/^[[:space:]]*set[[:space:]]*([[:space:]]*CMAKE_VERBOSE_MAKEFILE[[:space:]].*)/I{s/^/#_cmake_modify_IGNORE /g}' \ + -i {} + || die "${LINENO}: failed to disable hardcoded settings" + local x + for x in $(find "${CMAKE_USE_DIR}" -name CMakeLists.txt -exec grep -l "^#_cmake_modify_IGNORE" {} +;); do + einfo "Hardcoded definition(s) removed in $(echo "${x}" | cut -c $((${#CMAKE_USE_DIR}+2))-):" + einfo "$(grep -se '^#_cmake_modify_IGNORE' ${x} | cut -c 22-99)" + done + + # NOTE Append some useful summary here + cat >> "${CMAKE_USE_DIR}"/CMakeLists.txt <<- _EOF_ || die + + MESSAGE(STATUS "<<< Gentoo configuration >>> + Build type \${CMAKE_BUILD_TYPE} + Install path \${CMAKE_INSTALL_PREFIX} + Compiler flags: + C \${CMAKE_C_FLAGS} + C++ \${CMAKE_CXX_FLAGS} + Linker flags: + Executable \${CMAKE_EXE_LINKER_FLAGS} + Module \${CMAKE_MODULE_LINKER_FLAGS} + Shared \${CMAKE_SHARED_LINKER_FLAGS}\n") + _EOF_ +} + +# temporary function for moving cmake cleanups from from src_configure -> src_prepare. +# bug #378850 +_cmake_cleanup_cmake() { + : ${CMAKE_USE_DIR:=${S}} + + if [[ "${CMAKE_REMOVE_MODULES}" == "yes" ]] ; then + local name + for name in ${CMAKE_REMOVE_MODULES_LIST} ; do + find "${S}" -name ${name}.cmake -exec rm -v {} + || die + done + fi + + # check if CMakeLists.txt exist and if no then die + if [[ ! -e ${CMAKE_USE_DIR}/CMakeLists.txt ]] ; then + eerror "Unable to locate CMakeLists.txt under:" + eerror "\"${CMAKE_USE_DIR}/CMakeLists.txt\"" + eerror "Consider not inheriting the cmake eclass." + die "FATAL: Unable to find CMakeLists.txt" + fi + + # Remove dangerous things. + _cmake_modify-cmakelists +} + +# @FUNCTION: cmake-utils_src_prepare +# @DESCRIPTION: +# Apply ebuild and user patches. +cmake-utils_src_prepare() { + debug-print-function ${FUNCNAME} "$@" + + pushd "${S}" > /dev/null || die + + if [[ ${EAPI} != 5 ]]; then + default_src_prepare + _cmake_cleanup_cmake + else + debug-print "$FUNCNAME: PATCHES=$PATCHES" + [[ ${PATCHES[@]} ]] && epatch "${PATCHES[@]}" + + debug-print "$FUNCNAME: applying user patches" + epatch_user + fi + + popd > /dev/null || die + + # make ${S} read-only in order to detect broken build-systems + if [[ ${CMAKE_UTILS_QA_SRC_DIR_READONLY} && ! ${CMAKE_IN_SOURCE_BUILD} ]]; then + chmod -R a-w "${S}" + fi + + _CMAKE_UTILS_SRC_PREPARE_HAS_RUN=1 +} + +# @VARIABLE: mycmakeargs +# @DEFAULT_UNSET +# @DESCRIPTION: +# Optional cmake defines as a bash array. Should be defined before calling +# src_configure. +# @CODE +# src_configure() { +# local mycmakeargs=( +# $(cmake-utils_use_with openconnect) +# ) +# +# cmake-utils_src_configure +# } +# @CODE + +# @FUNCTION: cmake-utils_src_configure +# @DESCRIPTION: +# General function for configuring with cmake. Default behaviour is to start an +# out-of-source build. +cmake-utils_src_configure() { + debug-print-function ${FUNCNAME} "$@" + + if [[ ! ${_CMAKE_UTILS_SRC_PREPARE_HAS_RUN} ]]; then + if [[ ${EAPI} != [56] ]]; then + die "FATAL: cmake-utils_src_prepare has not been run" + else + eqawarn "cmake-utils_src_prepare has not been run, please open a bug on https://bugs.gentoo.org/" + fi + fi + + [[ ${EAPI} == 5 ]] && _cmake_cleanup_cmake + + _cmake_check_build_dir + + # Fix xdg collision with sandbox + xdg_environment_reset + + # @SEE CMAKE_BUILD_TYPE + if [[ ${CMAKE_BUILD_TYPE} = Gentoo ]]; then + # Handle release builds + if ! has debug ${IUSE//+} || ! use debug; then + local CPPFLAGS=${CPPFLAGS} + append-cppflags -DNDEBUG + fi + fi + + # Prepare Gentoo override rules (set valid compiler, append CPPFLAGS etc.) + local build_rules=${BUILD_DIR}/gentoo_rules.cmake + + cat > "${build_rules}" <<- _EOF_ || die + SET (CMAKE_ASM_COMPILE_OBJECT " ${CPPFLAGS} -o -c " CACHE STRING "ASM compile command" FORCE) + SET (CMAKE_ASM-ATT_COMPILE_OBJECT " ${CPPFLAGS} -o -c -x assembler " CACHE STRING "ASM-ATT compile command" FORCE) + SET (CMAKE_ASM-ATT_LINK_FLAGS "-nostdlib" CACHE STRING "ASM-ATT link flags" FORCE) + SET (CMAKE_C_COMPILE_OBJECT " ${CPPFLAGS} -o -c " CACHE STRING "C compile command" FORCE) + SET (CMAKE_CXX_COMPILE_OBJECT " ${CPPFLAGS} -o -c " CACHE STRING "C++ compile command" FORCE) + SET (CMAKE_Fortran_COMPILE_OBJECT " ${FCFLAGS} -o -c " CACHE STRING "Fortran compile command" FORCE) + _EOF_ + + local myCC=$(tc-getCC) myCXX=$(tc-getCXX) myFC=$(tc-getFC) + + # !!! IMPORTANT NOTE !!! + # Single slash below is intentional. CMake is weird and wants the + # CMAKE_*_VARIABLES split into two elements: the first one with + # compiler path, and the second one with all command-line options, + # space separated. + local toolchain_file=${BUILD_DIR}/gentoo_toolchain.cmake + cat > ${toolchain_file} <<- _EOF_ || die + SET (CMAKE_ASM_COMPILER "${myCC/ /;}") + SET (CMAKE_ASM-ATT_COMPILER "${myCC/ /;}") + SET (CMAKE_C_COMPILER "${myCC/ /;}") + SET (CMAKE_CXX_COMPILER "${myCXX/ /;}") + SET (CMAKE_Fortran_COMPILER "${myFC/ /;}") + SET (CMAKE_AR $(type -P $(tc-getAR)) CACHE FILEPATH "Archive manager" FORCE) + SET (CMAKE_RANLIB $(type -P $(tc-getRANLIB)) CACHE FILEPATH "Archive index generator" FORCE) + SET (CMAKE_SYSTEM_PROCESSOR "${CHOST%%-*}") + _EOF_ + + # We are using the C compiler for assembly by default. + local -x ASMFLAGS=${CFLAGS} + local -x PKG_CONFIG=$(tc-getPKG_CONFIG) + + if tc-is-cross-compiler; then + local sysname + case "${KERNEL:-linux}" in + Cygwin) sysname="CYGWIN_NT-5.1" ;; + HPUX) sysname="HP-UX" ;; + linux) sysname="Linux" ;; + Winnt) + sysname="Windows" + cat >> "${toolchain_file}" <<- _EOF_ || die + SET (CMAKE_RC_COMPILER $(tc-getRC)) + _EOF_ + ;; + *) sysname="${KERNEL}" ;; + esac + + cat >> "${toolchain_file}" <<- _EOF_ || die + SET (CMAKE_SYSTEM_NAME "${sysname}") + _EOF_ + + if [ "${SYSROOT:-/}" != "/" ] ; then + # When cross-compiling with a sysroot (e.g. with crossdev's emerge wrappers) + # we need to tell cmake to use libs/headers from the sysroot but programs from / only. + cat >> "${toolchain_file}" <<- _EOF_ || die + SET (CMAKE_FIND_ROOT_PATH "${SYSROOT}") + SET (CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER) + SET (CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY) + SET (CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY) + _EOF_ + fi + fi + + if use prefix-guest; then + cat >> "${build_rules}" <<- _EOF_ || die + # in Prefix we need rpath and must ensure cmake gets our default linker path + # right ... except for Darwin hosts + IF (NOT APPLE) + SET (CMAKE_SKIP_RPATH OFF CACHE BOOL "" FORCE) + SET (CMAKE_PLATFORM_REQUIRED_RUNTIME_PATH "${EPREFIX}/usr/${CHOST}/lib/gcc;${EPREFIX}/usr/${CHOST}/lib;${EPREFIX}/usr/$(get_libdir);${EPREFIX}/$(get_libdir)" + CACHE STRING "" FORCE) + + ELSE () + + SET (CMAKE_PREFIX_PATH "${EPREFIX}/usr" CACHE STRING "" FORCE) + SET (CMAKE_MACOSX_RPATH ON CACHE BOOL "" FORCE) + SET (CMAKE_SKIP_BUILD_RPATH OFF CACHE BOOL "" FORCE) + SET (CMAKE_SKIP_RPATH OFF CACHE BOOL "" FORCE) + SET (CMAKE_INSTALL_RPATH_USE_LINK_PATH TRUE CACHE BOOL "" FORCE) + + ENDIF (NOT APPLE) + _EOF_ + fi + + # Common configure parameters (invariants) + local common_config=${BUILD_DIR}/gentoo_common_config.cmake + local libdir=$(get_libdir) + cat > "${common_config}" <<- _EOF_ || die + SET (CMAKE_GENTOO_BUILD ON CACHE BOOL "Indicate Gentoo package build") + SET (LIB_SUFFIX ${libdir/lib} CACHE STRING "library path suffix" FORCE) + SET (CMAKE_INSTALL_LIBDIR ${libdir} CACHE PATH "Output directory for libraries") + SET (CMAKE_INSTALL_INFODIR "${EPREFIX}/usr/share/info" CACHE PATH "") + SET (CMAKE_INSTALL_MANDIR "${EPREFIX}/usr/share/man" CACHE PATH "") + SET (CMAKE_USER_MAKE_RULES_OVERRIDE "${build_rules}" CACHE FILEPATH "Gentoo override rules") + _EOF_ + + # See bug 689410 + if [[ "${ARCH}" == riscv ]]; then + echo 'SET (CMAKE_FIND_LIBRARY_CUSTOM_LIB_SUFFIX '"${libdir#lib}"' CACHE STRING "library search suffix" FORCE)' >> "${common_config}" || die + fi + + [[ "${NOCOLOR}" = true || "${NOCOLOR}" = yes ]] && echo 'SET (CMAKE_COLOR_MAKEFILE OFF CACHE BOOL "pretty colors during make" FORCE)' >> "${common_config}" + + if [[ ${EAPI} != [56] ]]; then + cat >> "${common_config}" <<- _EOF_ || die + SET (CMAKE_INSTALL_DOCDIR "${EPREFIX}/usr/share/doc/${PF}" CACHE PATH "") + SET (BUILD_SHARED_LIBS ON CACHE BOOL "") + _EOF_ + fi + + # Wipe the default optimization flags out of CMake + if [[ ${CMAKE_BUILD_TYPE} != Gentoo && ${EAPI} != 5 ]]; then + cat >> ${common_config} <<- _EOF_ || die + SET (CMAKE_ASM_FLAGS_${CMAKE_BUILD_TYPE^^} "" CACHE STRING "") + SET (CMAKE_ASM-ATT_FLAGS_${CMAKE_BUILD_TYPE^^} "" CACHE STRING "") + SET (CMAKE_C_FLAGS_${CMAKE_BUILD_TYPE^^} "" CACHE STRING "") + SET (CMAKE_CXX_FLAGS_${CMAKE_BUILD_TYPE^^} "" CACHE STRING "") + SET (CMAKE_Fortran_FLAGS_${CMAKE_BUILD_TYPE^^} "" CACHE STRING "") + SET (CMAKE_EXE_LINKER_FLAGS_${CMAKE_BUILD_TYPE^^} "" CACHE STRING "") + SET (CMAKE_MODULE_LINKER_FLAGS_${CMAKE_BUILD_TYPE^^} "" CACHE STRING "") + SET (CMAKE_SHARED_LINKER_FLAGS_${CMAKE_BUILD_TYPE^^} "" CACHE STRING "") + SET (CMAKE_STATIC_LINKER_FLAGS_${CMAKE_BUILD_TYPE^^} "" CACHE STRING "") + _EOF_ + fi + + # Convert mycmakeargs to an array, for backwards compatibility + # Make the array a local variable since <=portage-2.1.6.x does not + # support global arrays (see bug #297255). + local mycmakeargstype=$(declare -p mycmakeargs 2>&-) + if [[ "${mycmakeargstype}" != "declare -a mycmakeargs="* ]]; then + if [[ -n "${mycmakeargstype}" ]] ; then + if [[ ${EAPI} == 5 ]]; then + eqawarn "Declaring mycmakeargs as a variable is deprecated. Please use an array instead." + else + die "Declaring mycmakeargs as a variable is banned in EAPI=${EAPI}. Please use an array instead." + fi + fi + local mycmakeargs_local=(${mycmakeargs}) + else + local mycmakeargs_local=("${mycmakeargs[@]}") + fi + + if [[ ${CMAKE_WARN_UNUSED_CLI} == no ]] ; then + local warn_unused_cli="--no-warn-unused-cli" + else + local warn_unused_cli="" + fi + + # Common configure parameters (overridable) + # NOTE CMAKE_BUILD_TYPE can be only overridden via CMAKE_BUILD_TYPE eclass variable + # No -DCMAKE_BUILD_TYPE=xxx definitions will be in effect. + local cmakeargs=( + ${warn_unused_cli} + -C "${common_config}" + -G "$(_cmake_generator_to_use)" + -DCMAKE_INSTALL_PREFIX="${EPREFIX}/usr" + "${mycmakeargs_local[@]}" + -DCMAKE_BUILD_TYPE="${CMAKE_BUILD_TYPE}" + $([[ ${EAPI} == 5 ]] && echo -DCMAKE_INSTALL_DO_STRIP=OFF) + -DCMAKE_TOOLCHAIN_FILE="${toolchain_file}" + "${MYCMAKEARGS}" + ) + + if [[ -n "${CMAKE_EXTRA_CACHE_FILE}" ]] ; then + cmakeargs+=( -C "${CMAKE_EXTRA_CACHE_FILE}" ) + fi + + pushd "${BUILD_DIR}" > /dev/null || die + debug-print "${LINENO} ${ECLASS} ${FUNCNAME}: mycmakeargs is ${mycmakeargs_local[*]}" + echo "${CMAKE_BINARY}" "${cmakeargs[@]}" "${CMAKE_USE_DIR}" + "${CMAKE_BINARY}" "${cmakeargs[@]}" "${CMAKE_USE_DIR}" || die "cmake failed" + popd > /dev/null || die +} + +# @FUNCTION: cmake-utils_src_compile +# @DESCRIPTION: +# General function for compiling with cmake. +# Automatically detects the build type. All arguments are passed to emake. +cmake-utils_src_compile() { + debug-print-function ${FUNCNAME} "$@" + + cmake-utils_src_make "$@" +} + +# @FUNCTION: _cmake_ninja_src_make +# @INTERNAL +# @DESCRIPTION: +# Build the package using ninja generator +_cmake_ninja_src_make() { + debug-print-function ${FUNCNAME} "$@" + + [[ -e build.ninja ]] || die "build.ninja not found. Error during configure stage." + + eninja "$@" +} + +# @FUNCTION: _cmake_emake_src_make +# @INTERNAL +# @DESCRIPTION: +# Build the package using make generator +_cmake_emake_src_make() { + debug-print-function ${FUNCNAME} "$@" + + [[ -e Makefile ]] || die "Makefile not found. Error during configure stage." + + if [[ "${CMAKE_VERBOSE}" != "OFF" ]]; then + emake VERBOSE=1 "$@" || die + else + emake "$@" || die + fi + +} + +# @FUNCTION: cmake-utils_src_make +# @DESCRIPTION: +# Function for building the package. Automatically detects the build type. +# All arguments are passed to emake. +cmake-utils_src_make() { + debug-print-function ${FUNCNAME} "$@" + + _cmake_check_build_dir + pushd "${BUILD_DIR}" > /dev/null || die + + _cmake_${CMAKE_MAKEFILE_GENERATOR}_src_make "$@" + + popd > /dev/null || die +} + +# @FUNCTION: cmake-utils_src_test +# @DESCRIPTION: +# Function for testing the package. Automatically detects the build type. +cmake-utils_src_test() { + debug-print-function ${FUNCNAME} "$@" + + _cmake_check_build_dir + pushd "${BUILD_DIR}" > /dev/null || die + [[ -e CTestTestfile.cmake ]] || { echo "No tests found. Skipping."; return 0 ; } + + [[ -n ${TEST_VERBOSE} ]] && myctestargs+=( --extra-verbose --output-on-failure ) + + set -- ctest -j "$(makeopts_jobs)" --test-load "$(makeopts_loadavg)" "${myctestargs[@]}" "$@" + echo "$@" >&2 + if "$@" ; then + einfo "Tests succeeded." + popd > /dev/null || die + return 0 + else + if [[ -n "${CMAKE_YES_I_WANT_TO_SEE_THE_TEST_LOG}" ]] ; then + # on request from Diego + eerror "Tests failed. Test log ${BUILD_DIR}/Testing/Temporary/LastTest.log follows:" + eerror "--START TEST LOG--------------------------------------------------------------" + cat "${BUILD_DIR}/Testing/Temporary/LastTest.log" + eerror "--END TEST LOG----------------------------------------------------------------" + die "Tests failed." + else + die "Tests failed. When you file a bug, please attach the following file: \n\t${BUILD_DIR}/Testing/Temporary/LastTest.log" + fi + + # die might not die due to nonfatal + popd > /dev/null || die + return 1 + fi +} + +# @FUNCTION: cmake-utils_src_install +# @DESCRIPTION: +# Function for installing the package. Automatically detects the build type. +cmake-utils_src_install() { + debug-print-function ${FUNCNAME} "$@" + + _cmake_check_build_dir + pushd "${BUILD_DIR}" > /dev/null || die + DESTDIR="${D}" ${CMAKE_MAKEFILE_GENERATOR} install "$@" || die "died running ${CMAKE_MAKEFILE_GENERATOR} install" + popd > /dev/null || die + + pushd "${S}" > /dev/null || die + einstalldocs + popd > /dev/null || die +} + +fi diff --git a/eclass/cmake.eclass b/eclass/cmake.eclass new file mode 100644 index 0000000..62fa027 --- /dev/null +++ b/eclass/cmake.eclass @@ -0,0 +1,660 @@ +# Copyright 1999-2020 Gentoo Authors +# Distributed under the terms of the GNU General Public License v2 + +# @ECLASS: cmake.eclass +# @MAINTAINER: +# kde@gentoo.org +# @AUTHOR: +# Tomáš Chvátal +# Maciej Mrozowski +# (undisclosed contributors) +# Original author: Zephyrus (zephyrus@mirach.it) +# @SUPPORTED_EAPIS: 7 +# @BLURB: common ebuild functions for cmake-based packages +# @DESCRIPTION: +# The cmake eclass makes creating ebuilds for cmake-based packages much easier. +# It provides all inherited features (DOCS, HTML_DOCS, PATCHES) along with +# out-of-source builds (default), in-source builds and an implementation of the +# well-known use_enable function for CMake. + +if [[ -z ${_CMAKE_ECLASS} ]]; then +_CMAKE_ECLASS=1 + +# @ECLASS-VARIABLE: BUILD_DIR +# @DESCRIPTION: +# Build directory where all cmake processed files should be generated. +# For in-source build it's fixed to ${CMAKE_USE_DIR}. +# For out-of-source build it can be overridden, by default it uses +# ${WORKDIR}/${P}_build. +: ${BUILD_DIR:=${WORKDIR}/${P}_build} + +# @ECLASS-VARIABLE: CMAKE_BINARY +# @DESCRIPTION: +# Eclass can use different cmake binary than the one provided in by system. +: ${CMAKE_BINARY:=cmake} + +# @ECLASS-VARIABLE: CMAKE_BUILD_TYPE +# @DESCRIPTION: +# Set to override default CMAKE_BUILD_TYPE. Only useful for packages +# known to make use of "if (CMAKE_BUILD_TYPE MATCHES xxx)". +# If about to be set - needs to be set before invoking cmake_src_configure. +# You usually do *NOT* want nor need to set it as it pulls CMake default +# build-type specific compiler flags overriding make.conf. +: ${CMAKE_BUILD_TYPE:=Gentoo} + +# @ECLASS-VARIABLE: CMAKE_IN_SOURCE_BUILD +# @DEFAULT_UNSET +# @DESCRIPTION: +# Set to enable in-source build. + +# @ECLASS-VARIABLE: CMAKE_MAKEFILE_GENERATOR +# @DEFAULT_UNSET +# @DESCRIPTION: +# Specify a makefile generator to be used by cmake. +# At this point only "emake" and "ninja" are supported. +# The default is set to "ninja". +: ${CMAKE_MAKEFILE_GENERATOR:=ninja} + +# @ECLASS-VARIABLE: CMAKE_REMOVE_MODULES_LIST +# @DESCRIPTION: +# Array of CMake modules that will be removed in $S during src_prepare, +# in order to force packages to use the system version. +# Set to "none" to disable removing modules entirely. +: ${CMAKE_REMOVE_MODULES_LIST:=FindBLAS FindLAPACK} + +# @ECLASS-VARIABLE: CMAKE_USE_DIR +# @DESCRIPTION: +# Sets the directory where we are working with cmake, for example when +# application uses autotools and only one plugin needs to be done by cmake. +# By default it uses ${S}. + +# @ECLASS-VARIABLE: CMAKE_VERBOSE +# @DESCRIPTION: +# Set to OFF to disable verbose messages during compilation +: ${CMAKE_VERBOSE:=ON} + +# @ECLASS-VARIABLE: CMAKE_WARN_UNUSED_CLI +# @DESCRIPTION: +# Warn about variables that are declared on the command line +# but not used. Might give false-positives. +# "no" to disable (default) or anything else to enable. +: ${CMAKE_WARN_UNUSED_CLI:=yes} + +# @ECLASS-VARIABLE: CMAKE_EXTRA_CACHE_FILE +# @DEFAULT_UNSET +# @DESCRIPTION: +# Specifies an extra cache file to pass to cmake. This is the analog of EXTRA_ECONF +# for econf and is needed to pass TRY_RUN results when cross-compiling. +# Should be set by user in a per-package basis in /etc/portage/package.env. + +# @ECLASS-VARIABLE: CMAKE_QA_SRC_DIR_READONLY +# @DEFAULT_UNSET +# @DESCRIPTION: +# After running cmake_src_prepare, sets ${S} to read-only. This is +# a user flag and should under _no circumstances_ be set in the ebuild. +# Helps in improving QA of build systems that write to source tree. + +case ${EAPI} in + 7) ;; + *) die "EAPI=${EAPI:-0} is not supported" ;; +esac + +inherit toolchain-funcs ninja-utils flag-o-matic multiprocessing xdg-utils + +EXPORT_FUNCTIONS src_prepare src_configure src_compile src_test src_install + +[[ ${CMAKE_MIN_VERSION} ]] && die "CMAKE_MIN_VERSION is banned; if necessary, set BDEPEND=\">=dev-util/cmake-${CMAKE_MIN_VERSION}\" directly" +[[ ${CMAKE_BUILD_DIR} ]] && die "The ebuild must be migrated to BUILD_DIR" +[[ ${CMAKE_REMOVE_MODULES} ]] && die "CMAKE_REMOVE_MODULES is banned, set CMAKE_REMOVE_MODULES_LIST=\"\" instead" +[[ ${CMAKE_UTILS_QA_SRC_DIR_READONLY} ]] && die "Use CMAKE_QA_SRC_DIR_READONLY instead" +[[ ${WANT_CMAKE} ]] && die "WANT_CMAKE has been removed and is a no-op" +[[ ${PREFIX} ]] && die "PREFIX has been removed and is a no-op" + +case ${CMAKE_MAKEFILE_GENERATOR} in + emake) + BDEPEND="sys-devel/make" + ;; + ninja) + BDEPEND="dev-util/ninja" + ;; + *) + eerror "Unknown value for \${CMAKE_MAKEFILE_GENERATOR}" + die "Value ${CMAKE_MAKEFILE_GENERATOR} is not supported" + ;; +esac + +if [[ ${PN} != cmake ]]; then + BDEPEND+=" dev-util/cmake" +fi + +# @FUNCTION: _cmake_banned_func +# @INTERNAL +# @DESCRIPTION: +# Banned functions are banned. +_cmake_banned_func() { + die "${FUNCNAME[1]} is banned. use -D$1=\"\$(usex $2)\" instead" +} + +# Determine using IN or OUT source build +_cmake_check_build_dir() { + : ${CMAKE_USE_DIR:=${S}} + if [[ -n ${CMAKE_IN_SOURCE_BUILD} ]]; then + # we build in source dir + BUILD_DIR="${CMAKE_USE_DIR}" + fi + + mkdir -p "${BUILD_DIR}" || die + einfo "Working in BUILD_DIR: \"$BUILD_DIR\"" +} + +# @FUNCTION: cmake_run_in +# @USAGE: +# @DESCRIPTION: +# Set the desired working dir for a function or command. +cmake_run_in() { + if [[ -z ${2} ]]; then + die "${FUNCNAME[0]} must be passed at least two arguments" + fi + + [[ -e ${1} ]] || die "${FUNCNAME[0]}: Nonexistent path: ${1}" + + pushd ${1} > /dev/null || die + "${@:2}" + popd > /dev/null || die +} + +# @FUNCTION: cmake_comment_add_subdirectory +# @USAGE: +# @DESCRIPTION: +# Comment out one or more add_subdirectory calls in CMakeLists.txt in the current directory +cmake_comment_add_subdirectory() { + if [[ -z ${1} ]]; then + die "${FUNCNAME[0]} must be passed at least one directory name to comment" + fi + + [[ -e "CMakeLists.txt" ]] || return + + local d + for d in $@; do + d=${d//\//\\/} + sed -e "/add_subdirectory[[:space:]]*([[:space:]]*${d}[[:space:]]*)/I s/^/#DONOTCOMPILE /" \ + -i CMakeLists.txt || die "failed to comment add_subdirectory(${d})" + done +} + +# @FUNCTION: comment_add_subdirectory +# @INTERNAL +# @DESCRIPTION: +# Banned. Use cmake_comment_add_subdirectory instead. +comment_add_subdirectory() { + die "comment_add_subdirectory is banned. Use cmake_comment_add_subdirectory instead" +} + +# @FUNCTION: cmake-utils_use_with +# @INTERNAL +# @DESCRIPTION: +# Banned. Use -DWITH_FOO=$(usex foo) instead. +cmake-utils_use_with() { _cmake_banned_func WITH_ "$@" ; } + +# @FUNCTION: cmake-utils_use_enable +# @INTERNAL +# @DESCRIPTION: +# Banned. Use -DENABLE_FOO=$(usex foo) instead. +cmake-utils_use_enable() { _cmake_banned_func ENABLE_ "$@" ; } + +# @FUNCTION: cmake_use_find_package +# @USAGE: +# @DESCRIPTION: +# Based on use_enable. See ebuild(5). +# +# `cmake_use_find_package foo LibFoo` echoes -DCMAKE_DISABLE_FIND_PACKAGE_LibFoo=OFF +# if foo is enabled and -DCMAKE_DISABLE_FIND_PACKAGE_LibFoo=ON if it is disabled. +# This can be used to make find_package optional. +cmake_use_find_package() { + debug-print-function ${FUNCNAME} "$@" + + if [[ "$#" != 2 || -z $1 ]] ; then + die "Usage: cmake_use_find_package " + fi + + echo "-DCMAKE_DISABLE_FIND_PACKAGE_$2=$(use $1 && echo OFF || echo ON)" +} + +# @FUNCTION: cmake-utils_use_disable +# @INTERNAL +# @DESCRIPTION: +# Banned. Use -DDISABLE_FOO=$(usex !foo) instead. +cmake-utils_use_disable() { _cmake_banned_func DISABLE_ "$@" ; } + +# @FUNCTION: cmake-utils_use_no +# @INTERNAL +# @DESCRIPTION: +# Banned. Use -DNO_FOO=$(usex !foo) instead. +cmake-utils_use_no() { _cmake_banned_func NO_ "$@" ; } + +# @FUNCTION: cmake-utils_use_want +# @INTERNAL +# @DESCRIPTION: +# Banned. Use -DWANT_FOO=$(usex foo) instead. +cmake-utils_use_want() { _cmake_banned_func WANT_ "$@" ; } + +# @FUNCTION: cmake-utils_use_build +# @INTERNAL +# @DESCRIPTION: +# Banned. Use -DBUILD_FOO=$(usex foo) instead. +cmake-utils_use_build() { _cmake_banned_func BUILD_ "$@" ; } + +# @FUNCTION: cmake-utils_use_has +# @INTERNAL +# @DESCRIPTION: +# Banned. Use -DHAVE_FOO=$(usex foo) instead. +cmake-utils_use_has() { _cmake_banned_func HAVE_ "$@" ; } + +# @FUNCTION: cmake-utils_use_use +# @INTERNAL +# @DESCRIPTION: +# Banned. Use -DUSE_FOO=$(usex foo) instead. +cmake-utils_use_use() { _cmake_banned_func USE_ "$@" ; } + +# @FUNCTION: cmake-utils_use +# @INTERNAL +# @DESCRIPTION: +# Banned. Use -DFOO=$(usex foo) instead. +cmake-utils_use() { _cmake_banned_func "" "$@" ; } + +# @FUNCTION: cmake-utils_useno +# @INTERNAL +# @DESCRIPTION: +# Banned. Use -DNOFOO=$(usex !foo) instead. +cmake-utils_useno() { _cmake_banned_func "" "$@" ; } + +# Internal function for modifying hardcoded definitions. +# Removes dangerous definitions that override Gentoo settings. +_cmake_modify-cmakelists() { + debug-print-function ${FUNCNAME} "$@" + + # Only edit the files once + grep -qs "<<< Gentoo configuration >>>" "${CMAKE_USE_DIR}"/CMakeLists.txt && return 0 + + # Comment out all set ( value) + find "${CMAKE_USE_DIR}" -name CMakeLists.txt -exec sed \ + -e '/^[[:space:]]*set[[:space:]]*([[:space:]]*CMAKE_BUILD_TYPE\([[:space:]].*)\|)\)/I{s/^/#_cmake_modify_IGNORE /g}' \ + -e '/^[[:space:]]*set[[:space:]]*([[:space:]]*CMAKE_COLOR_MAKEFILE[[:space:]].*)/I{s/^/#_cmake_modify_IGNORE /g}' \ + -e '/^[[:space:]]*set[[:space:]]*([[:space:]]*CMAKE_INSTALL_PREFIX[[:space:]].*)/I{s/^/#_cmake_modify_IGNORE /g}' \ + -e '/^[[:space:]]*set[[:space:]]*([[:space:]]*CMAKE_VERBOSE_MAKEFILE[[:space:]].*)/I{s/^/#_cmake_modify_IGNORE /g}' \ + -i {} + || die "${LINENO}: failed to disable hardcoded settings" + local x + for x in $(find "${CMAKE_USE_DIR}" -name CMakeLists.txt -exec grep -l "^#_cmake_modify_IGNORE" {} +;); do + einfo "Hardcoded definition(s) removed in $(echo "${x}" | cut -c $((${#CMAKE_USE_DIR}+2))-):" + einfo "$(grep -se '^#_cmake_modify_IGNORE' ${x} | cut -c 22-99)" + done + + # NOTE Append some useful summary here + cat >> "${CMAKE_USE_DIR}"/CMakeLists.txt <<- _EOF_ || die + + message(STATUS "<<< Gentoo configuration >>> + Build type \${CMAKE_BUILD_TYPE} + Install path \${CMAKE_INSTALL_PREFIX} + Compiler flags: + C \${CMAKE_C_FLAGS} + C++ \${CMAKE_CXX_FLAGS} + Linker flags: + Executable \${CMAKE_EXE_LINKER_FLAGS} + Module \${CMAKE_MODULE_LINKER_FLAGS} + Shared \${CMAKE_SHARED_LINKER_FLAGS}\n") + _EOF_ +} + +# @FUNCTION: cmake_src_prepare +# @DESCRIPTION: +# Apply ebuild and user patches. +cmake_src_prepare() { + debug-print-function ${FUNCNAME} "$@" + + # FIXME: workaround from cmake-utils; use current working directory instead, bug #704524 + # esp. test with 'special' pkgs like: app-arch/brotli, media-gfx/gmic, net-libs/quiche + pushd "${S}" > /dev/null || die + + default_src_prepare + _cmake_check_build_dir + + # check if CMakeLists.txt exist and if no then die + if [[ ! -e ${CMAKE_USE_DIR}/CMakeLists.txt ]] ; then + eerror "Unable to locate CMakeLists.txt under:" + eerror "\"${CMAKE_USE_DIR}/CMakeLists.txt\"" + eerror "Consider not inheriting the cmake eclass." + die "FATAL: Unable to find CMakeLists.txt" + fi + + # if ninja is enabled but not installed, the build could fail + # this could happen if ninja is manually enabled (eg. make.conf) but not installed + if [[ ${CMAKE_MAKEFILE_GENERATOR} == ninja ]] && ! has_version -b dev-util/ninja; then + eerror "CMAKE_MAKEFILE_GENERATOR is set to ninja, but ninja is not installed." + die "Please install dev-util/ninja or unset CMAKE_MAKEFILE_GENERATOR." + fi + + local modules_list + if [[ $(declare -p CMAKE_REMOVE_MODULES_LIST) == "declare -a"* ]]; then + modules_list=( "${CMAKE_REMOVE_MODULES_LIST[@]}" ) + else + modules_list=( ${CMAKE_REMOVE_MODULES_LIST} ) + fi + + local name + for name in "${modules_list[@]}" ; do + find "${S}" -name ${name}.cmake -exec rm -v {} + || die + done + + # Remove dangerous things. + _cmake_modify-cmakelists + + popd > /dev/null || die + + # make ${S} read-only in order to detect broken build-systems + if [[ ${CMAKE_QA_SRC_DIR_READONLY} && ! ${CMAKE_IN_SOURCE_BUILD} ]]; then + chmod -R a-w "${S}" + fi + + _CMAKE_SRC_PREPARE_HAS_RUN=1 +} + +# @VARIABLE: mycmakeargs +# @DEFAULT_UNSET +# @DESCRIPTION: +# Optional cmake defines as a bash array. Should be defined before calling +# src_configure. +# @CODE +# src_configure() { +# local mycmakeargs=( +# $(cmake_use_with openconnect) +# ) +# +# cmake_src_configure +# } +# @CODE + +# @FUNCTION: cmake_src_configure +# @DESCRIPTION: +# General function for configuring with cmake. Default behaviour is to start an +# out-of-source build. +cmake_src_configure() { + debug-print-function ${FUNCNAME} "$@" + + [[ ${_CMAKE_SRC_PREPARE_HAS_RUN} ]] || \ + die "FATAL: cmake_src_prepare has not been run" + + _cmake_check_build_dir + + # Fix xdg collision with sandbox + xdg_environment_reset + + # Prepare Gentoo override rules (set valid compiler, append CPPFLAGS etc.) + local build_rules=${BUILD_DIR}/gentoo_rules.cmake + + cat > "${build_rules}" <<- _EOF_ || die + set(CMAKE_ASM_COMPILE_OBJECT " ${CPPFLAGS} -o -c " CACHE STRING "ASM compile command" FORCE) + set(CMAKE_ASM-ATT_COMPILE_OBJECT " ${CPPFLAGS} -o -c -x assembler " CACHE STRING "ASM-ATT compile command" FORCE) + set(CMAKE_ASM-ATT_LINK_FLAGS "-nostdlib" CACHE STRING "ASM-ATT link flags" FORCE) + set(CMAKE_C_COMPILE_OBJECT " ${CPPFLAGS} -o -c " CACHE STRING "C compile command" FORCE) + set(CMAKE_CXX_COMPILE_OBJECT " ${CPPFLAGS} -o -c " CACHE STRING "C++ compile command" FORCE) + set(CMAKE_Fortran_COMPILE_OBJECT " ${FCFLAGS} -o -c " CACHE STRING "Fortran compile command" FORCE) + _EOF_ + + local myCC=$(tc-getCC) myCXX=$(tc-getCXX) myFC=$(tc-getFC) + + # !!! IMPORTANT NOTE !!! + # Single slash below is intentional. CMake is weird and wants the + # CMAKE_*_VARIABLES split into two elements: the first one with + # compiler path, and the second one with all command-line options, + # space separated. + local toolchain_file=${BUILD_DIR}/gentoo_toolchain.cmake + cat > ${toolchain_file} <<- _EOF_ || die + set(CMAKE_ASM_COMPILER "${myCC/ /;}") + set(CMAKE_ASM-ATT_COMPILER "${myCC/ /;}") + set(CMAKE_C_COMPILER "${myCC/ /;}") + set(CMAKE_CXX_COMPILER "${myCXX/ /;}") + set(CMAKE_Fortran_COMPILER "${myFC/ /;}") + set(CMAKE_AR $(type -P $(tc-getAR)) CACHE FILEPATH "Archive manager" FORCE) + set(CMAKE_RANLIB $(type -P $(tc-getRANLIB)) CACHE FILEPATH "Archive index generator" FORCE) + set(CMAKE_SYSTEM_PROCESSOR "${CHOST%%-*}") + _EOF_ + + # We are using the C compiler for assembly by default. + local -x ASMFLAGS=${CFLAGS} + local -x PKG_CONFIG=$(tc-getPKG_CONFIG) + + if tc-is-cross-compiler; then + local sysname + case "${KERNEL:-linux}" in + Cygwin) sysname="CYGWIN_NT-5.1" ;; + HPUX) sysname="HP-UX" ;; + linux) sysname="Linux" ;; + Winnt) + sysname="Windows" + cat >> "${toolchain_file}" <<- _EOF_ || die + set(CMAKE_RC_COMPILER $(tc-getRC)) + _EOF_ + ;; + *) sysname="${KERNEL}" ;; + esac + + cat >> "${toolchain_file}" <<- _EOF_ || die + set(CMAKE_SYSTEM_NAME "${sysname}") + _EOF_ + + if [ "${SYSROOT:-/}" != "/" ] ; then + # When cross-compiling with a sysroot (e.g. with crossdev's emerge wrappers) + # we need to tell cmake to use libs/headers from the sysroot but programs from / only. + cat >> "${toolchain_file}" <<- _EOF_ || die + set(CMAKE_FIND_ROOT_PATH "${SYSROOT}") + set(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER) + set(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY) + set(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY) + _EOF_ + fi + fi + + if use prefix-guest; then + cat >> "${build_rules}" <<- _EOF_ || die + # in Prefix we need rpath and must ensure cmake gets our default linker path + # right ... except for Darwin hosts + if(NOT APPLE) + set(CMAKE_SKIP_RPATH OFF CACHE BOOL "" FORCE) + set(CMAKE_PLATFORM_REQUIRED_RUNTIME_PATH "${EPREFIX}/usr/${CHOST}/lib/gcc;${EPREFIX}/usr/${CHOST}/lib;${EPREFIX}/usr/$(get_libdir);${EPREFIX}/$(get_libdir)" CACHE STRING "" FORCE) + else() + set(CMAKE_PREFIX_PATH "${EPREFIX}/usr" CACHE STRING "" FORCE) + set(CMAKE_MACOSX_RPATH ON CACHE BOOL "" FORCE) + set(CMAKE_SKIP_BUILD_RPATH OFF CACHE BOOL "" FORCE) + set(CMAKE_SKIP_RPATH OFF CACHE BOOL "" FORCE) + set(CMAKE_INSTALL_RPATH_USE_LINK_PATH TRUE CACHE BOOL "" FORCE) + endif() + _EOF_ + fi + + # Common configure parameters (invariants) + local common_config=${BUILD_DIR}/gentoo_common_config.cmake + local libdir=$(get_libdir) + cat > "${common_config}" <<- _EOF_ || die + set(CMAKE_GENTOO_BUILD ON CACHE BOOL "Indicate Gentoo package build") + set(LIB_SUFFIX ${libdir/lib} CACHE STRING "library path suffix" FORCE) + set(CMAKE_INSTALL_LIBDIR ${libdir} CACHE PATH "Output directory for libraries") + set(CMAKE_INSTALL_INFODIR "${EPREFIX}/usr/share/info" CACHE PATH "") + set(CMAKE_INSTALL_MANDIR "${EPREFIX}/usr/share/man" CACHE PATH "") + set(CMAKE_USER_MAKE_RULES_OVERRIDE "${build_rules}" CACHE FILEPATH "Gentoo override rules") + set(CMAKE_INSTALL_DOCDIR "${EPREFIX}/usr/share/doc/${PF}" CACHE PATH "") + set(BUILD_SHARED_LIBS ON CACHE BOOL "") + _EOF_ + + if [[ -n ${_ECM_ECLASS} ]]; then + echo 'set(ECM_DISABLE_QMLPLUGINDUMP ON CACHE BOOL "")' >> "${common_config}" || die + fi + + # See bug 689410 + if [[ "${ARCH}" == riscv ]]; then + echo 'set(CMAKE_FIND_LIBRARY_CUSTOM_LIB_SUFFIX '"${libdir#lib}"' CACHE STRING "library search suffix" FORCE)' >> "${common_config}" || die + fi + + if [[ "${NOCOLOR}" = true || "${NOCOLOR}" = yes ]]; then + echo 'set(CMAKE_COLOR_MAKEFILE OFF CACHE BOOL "pretty colors during make" FORCE)' >> "${common_config}" || die + fi + + # Wipe the default optimization flags out of CMake + if [[ ${CMAKE_BUILD_TYPE} != Gentoo ]]; then + cat >> ${common_config} <<- _EOF_ || die + set(CMAKE_ASM_FLAGS_${CMAKE_BUILD_TYPE^^} "" CACHE STRING "") + set(CMAKE_ASM-ATT_FLAGS_${CMAKE_BUILD_TYPE^^} "" CACHE STRING "") + set(CMAKE_C_FLAGS_${CMAKE_BUILD_TYPE^^} "" CACHE STRING "") + set(CMAKE_CXX_FLAGS_${CMAKE_BUILD_TYPE^^} "" CACHE STRING "") + set(CMAKE_Fortran_FLAGS_${CMAKE_BUILD_TYPE^^} "" CACHE STRING "") + set(CMAKE_EXE_LINKER_FLAGS_${CMAKE_BUILD_TYPE^^} "" CACHE STRING "") + set(CMAKE_MODULE_LINKER_FLAGS_${CMAKE_BUILD_TYPE^^} "" CACHE STRING "") + set(CMAKE_SHARED_LINKER_FLAGS_${CMAKE_BUILD_TYPE^^} "" CACHE STRING "") + set(CMAKE_STATIC_LINKER_FLAGS_${CMAKE_BUILD_TYPE^^} "" CACHE STRING "") + _EOF_ + fi + + # Make the array a local variable since <=portage-2.1.6.x does not support + # global arrays (see bug #297255). But first make sure it is initialised. + [[ -z ${mycmakeargs} ]] && declare -a mycmakeargs=() + local mycmakeargstype=$(declare -p mycmakeargs 2>&-) + if [[ "${mycmakeargstype}" != "declare -a mycmakeargs="* ]]; then + die "mycmakeargs must be declared as array" + fi + + local mycmakeargs_local=( "${mycmakeargs[@]}" ) + + local warn_unused_cli="" + if [[ ${CMAKE_WARN_UNUSED_CLI} == no ]] ; then + warn_unused_cli="--no-warn-unused-cli" + fi + + local generator_name + case ${CMAKE_MAKEFILE_GENERATOR} in + ninja) generator_name="Ninja" ;; + emake) generator_name="Unix Makefiles" ;; + esac + + # Common configure parameters (overridable) + # NOTE CMAKE_BUILD_TYPE can be only overridden via CMAKE_BUILD_TYPE eclass variable + # No -DCMAKE_BUILD_TYPE=xxx definitions will be in effect. + local cmakeargs=( + ${warn_unused_cli} + -C "${common_config}" + -G "${generator_name}" + -DCMAKE_INSTALL_PREFIX="${EPREFIX}/usr" + "${mycmakeargs_local[@]}" + -DCMAKE_BUILD_TYPE="${CMAKE_BUILD_TYPE}" + -DCMAKE_TOOLCHAIN_FILE="${toolchain_file}" + "${MYCMAKEARGS}" + ) + + if [[ -n "${CMAKE_EXTRA_CACHE_FILE}" ]] ; then + cmakeargs+=( -C "${CMAKE_EXTRA_CACHE_FILE}" ) + fi + + pushd "${BUILD_DIR}" > /dev/null || die + debug-print "${LINENO} ${ECLASS} ${FUNCNAME}: mycmakeargs is ${mycmakeargs_local[*]}" + echo "${CMAKE_BINARY}" "${cmakeargs[@]}" "${CMAKE_USE_DIR}" + "${CMAKE_BINARY}" "${cmakeargs[@]}" "${CMAKE_USE_DIR}" || die "cmake failed" + popd > /dev/null || die +} + +# @FUNCTION: cmake_src_compile +# @DESCRIPTION: +# General function for compiling with cmake. +# Automatically detects the build type. All arguments are passed to emake. +cmake_src_compile() { + debug-print-function ${FUNCNAME} "$@" + + cmake_build "$@" +} + +# @FUNCTION: cmake_build +# @DESCRIPTION: +# Function for building the package. Automatically detects the build type. +# All arguments are passed to emake. +cmake_build() { + debug-print-function ${FUNCNAME} "$@" + + _cmake_check_build_dir + pushd "${BUILD_DIR}" > /dev/null || die + + case ${CMAKE_MAKEFILE_GENERATOR} in + emake) + [[ -e Makefile ]] || die "Makefile not found. Error during configure stage." + case ${CMAKE_VERBOSE} in + OFF) emake "$@" ;; + *) emake VERBOSE=1 "$@" ;; + esac + ;; + ninja) + [[ -e build.ninja ]] || die "build.ninja not found. Error during configure stage." + eninja "$@" + ;; + esac + + popd > /dev/null || die +} + +# @FUNCTION: cmake-utils_src_make +# @INTERNAL +# @DESCRIPTION: +# Banned. Use cmake_build instead. +cmake-utils_src_make() { + die "cmake-utils_src_make is banned. Use cmake_build instead" +} + +# @FUNCTION: cmake_src_test +# @DESCRIPTION: +# Function for testing the package. Automatically detects the build type. +cmake_src_test() { + debug-print-function ${FUNCNAME} "$@" + + _cmake_check_build_dir + pushd "${BUILD_DIR}" > /dev/null || die + [[ -e CTestTestfile.cmake ]] || { echo "No tests found. Skipping."; return 0 ; } + + [[ -n ${TEST_VERBOSE} ]] && myctestargs+=( --extra-verbose --output-on-failure ) + + set -- ctest -j "$(makeopts_jobs)" --test-load "$(makeopts_loadavg)" "${myctestargs[@]}" "$@" + echo "$@" >&2 + if "$@" ; then + einfo "Tests succeeded." + popd > /dev/null || die + return 0 + else + if [[ -n "${CMAKE_YES_I_WANT_TO_SEE_THE_TEST_LOG}" ]] ; then + # on request from Diego + eerror "Tests failed. Test log ${BUILD_DIR}/Testing/Temporary/LastTest.log follows:" + eerror "--START TEST LOG--------------------------------------------------------------" + cat "${BUILD_DIR}/Testing/Temporary/LastTest.log" + eerror "--END TEST LOG----------------------------------------------------------------" + die "Tests failed." + else + die "Tests failed. When you file a bug, please attach the following file: \n\t${BUILD_DIR}/Testing/Temporary/LastTest.log" + fi + + # die might not die due to nonfatal + popd > /dev/null || die + return 1 + fi +} + +# @FUNCTION: cmake_src_install +# @DESCRIPTION: +# Function for installing the package. Automatically detects the build type. +cmake_src_install() { + debug-print-function ${FUNCNAME} "$@" + + _cmake_check_build_dir + pushd "${BUILD_DIR}" > /dev/null || die + DESTDIR="${D}" ${CMAKE_MAKEFILE_GENERATOR} install "$@" || + die "died running ${CMAKE_MAKEFILE_GENERATOR} install" + popd > /dev/null || die + + pushd "${S}" > /dev/null || die + einstalldocs + popd > /dev/null || die +} + +fi diff --git a/eclass/common-lisp-3.eclass b/eclass/common-lisp-3.eclass new file mode 100644 index 0000000..5d5b68e --- /dev/null +++ b/eclass/common-lisp-3.eclass @@ -0,0 +1,236 @@ +# Copyright 1999-2019 Gentoo Authors +# Distributed under the terms of the GNU General Public License v2 + +# @ECLASS: common-lisp-3.eclass +# @MAINTAINER: +# Common Lisp project +# @BLURB: functions to support the installation of Common Lisp libraries +# @DESCRIPTION: +# Since Common Lisp libraries share similar structure, this eclass aims +# to provide a simple way to write ebuilds with these characteristics. + +inherit eutils + +# @ECLASS-VARIABLE: CLIMPLEMENTATIONS +# @DESCRIPTION: +# Common Lisp implementations +CLIMPLEMENTATIONS="sbcl clisp clozurecl cmucl ecls gcl abcl" + +# @ECLASS-VARIABLE: CLSOURCEROOT +# @DESCRIPTION: +# Default path of Common Lisp libraries sources. Sources will +# be installed into ${CLSOURCEROOT}/${CLPACKAGE}. +CLSOURCEROOT="${ROOT%/}"/usr/share/common-lisp/source + +# @ECLASS-VARIABLE: CLSYSTEMROOT +# @DESCRIPTION: +# Default path to find any asdf file. Any asdf files will be +# symlinked in ${CLSYSTEMROOT}/${CLSYSTEM} as they may be in +# an arbitrarily deeply nested directory under ${CLSOURCEROOT}/${CLPACKAGE}. +CLSYSTEMROOT="${ROOT%/}"/usr/share/common-lisp/systems + +# @ECLASS-VARIABLE: CLPACKAGE +# @DESCRIPTION: +# Default package name. To override, set these after inheriting this eclass. +CLPACKAGE="${PN}" + +PDEPEND="virtual/commonlisp" + +EXPORT_FUNCTIONS src_compile src_install + +# @FUNCTION: common-lisp-3_src_compile +# @DESCRIPTION: +# Since there's nothing to build in most cases, default doesn't do +# anything. +common-lisp-3_src_compile() { + true; +} + +# @FUNCTION: absolute-path-p +# @DESCRIPTION: +# Returns true if ${1} is an absolute path. +absolute-path-p() { + [[ $# -eq 1 ]] || die "${FUNCNAME[0]} must receive one argument" + [[ ${1} == /* ]] +} + +# @FUNCTION: common-lisp-install-one-source +# @DESCRIPTION: +# Installs ${2} source file in ${3} inside CLSOURCEROOT/CLPACKAGE. +common-lisp-install-one-source() { + [[ $# -eq 3 ]] || die "${FUNCNAME[0]} must receive exactly three arguments" + + local fpredicate=${1} + local source=${2} + local target="${CLSOURCEROOT}/${CLPACKAGE}/${3}" + + if absolute-path-p "${source}" ; then + die "Cannot install files with absolute path: ${source}" + fi + + if ${fpredicate} "${source}" ; then + insinto "${target}" + doins "${source}" || die "Failed to install ${source} into $(dirname "${target}")" + fi +} + +# @FUNCTION: lisp-file-p +# @USAGE: +# @DESCRIPTION: +# Returns true if ${1} is lisp source file. +lisp-file-p() { + [[ $# -eq 1 ]] || die "${FUNCNAME[0]} must receive one argument" + + [[ ${1} =~ \.(lisp|lsp|cl)$ ]] +} + +# @FUNCTION: common-lisp-get-fpredicate +# @USAGE: +# @DESCRIPTION: +# Outputs the corresponding predicate to check files of type ${1}. +common-lisp-get-fpredicate() { + [[ $# -eq 1 ]] || die "${FUNCNAME[0]} must receive one argument" + + local ftype=${1} + case ${ftype} in + "lisp") echo "lisp-file-p" ;; + "all" ) echo "true" ;; + * ) die "Unknown filetype specifier ${ftype}" ;; + esac +} + +# @FUNCTION: common-lisp-install-sources +# @USAGE: [...] +# @DESCRIPTION: +# Recursively install lisp sources of type ${2} if ${1} is -t or +# Lisp by default. When given a directory, it will be recursively +# scanned for Lisp source files with suffixes: .lisp, .lsp or .cl. +common-lisp-install-sources() { + local ftype="lisp" + if [[ ${1} == "-t" ]] ; then + ftype=${2} + shift ; shift + fi + + [[ $# -ge 1 ]] || die "${FUNCNAME[0]} must receive one non-option argument" + + local fpredicate=$(common-lisp-get-fpredicate "${ftype}") + + for path in "${@}" ; do + if [[ -f ${path} ]] ; then + common-lisp-install-one-source ${fpredicate} "${path}" "$(dirname "${path}")" + elif [[ -d ${path} ]] ; then + common-lisp-install-sources -t ${ftype} $(find "${path}" -type f) + else + die "${path} is neither a regular file nor a directory" + fi + done +} + +# @FUNCTION: common-lisp-install-one-asdf +# @USAGE: +# @DESCRIPTION: +# Installs ${1} asdf file in CLSOURCEROOT/CLPACKAGE and symlinks it in +# CLSYSTEMROOT. +common-lisp-install-one-asdf() { + [[ $# != 1 ]] && die "${FUNCNAME[0]} must receive exactly one argument" + + # the suffix «.asd» is optional + local source=${1/.asd}.asd + common-lisp-install-one-source true "${source}" "$(dirname "${source}")" + local target="${CLSOURCEROOT%/}/${CLPACKAGE}/${source}" + dosym "${target}" "${CLSYSTEMROOT%/}/$(basename ${target})" +} + +# @FUNCTION: common-lisp-install-asdf +# @USAGE: [...] +# @DESCRIPTION: +# Installs all ASDF files and creates symlinks in CLSYSTEMROOT. +# When given a directory, it will be recursively scanned for ASDF +# files with extension .asd. +common-lisp-install-asdf() { + dodir "${CLSYSTEMROOT}" + + [[ $# = 0 ]] && set - ${CLSYSTEMS} + [[ $# = 0 ]] && set - $(find . -type f -name \*.asd) + for sys in "${@}" ; do + common-lisp-install-one-asdf ${sys} + done +} + +# @FUNCTION: common-lisp-3_src_install +# @DESCRIPTION: +# Recursively install Lisp sources, asdf files and most common doc files. +common-lisp-3_src_install() { + common-lisp-install-sources . + common-lisp-install-asdf + for i in AUTHORS README* HEADER TODO* CHANGELOG Change[lL]og CHANGES BUGS CONTRIBUTORS *NEWS* ; do + [[ -f ${i} ]] && dodoc ${i} + done +} + +# @FUNCTION: common-lisp-find-lisp-impl +# @DESCRIPTION: +# Outputs an installed Common Lisp implementation. Transverses +# CLIMPLEMENTATIONS to find it. +common-lisp-find-lisp-impl() { + for lisp in ${CLIMPLEMENTATIONS} ; do + [[ "$(best_version dev-lisp/${lisp})" ]] && echo "${lisp}" && return + done + die "No CommonLisp implementation found" +} + +# @FUNCTION: common-lisp-export-impl-args +# @USAGE: +# @DESCRIPTION: +# Export a few variables containing the switches necessary +# to make the CL implementation perform basic functions: +# * CL_BINARY: Common Lisp implementation +# * CL_NORC: don't load syste-wide or user-specific initfiles +# * CL_LOAD: load a certain file +# * CL_EVAL: eval a certain expression at startup +common-lisp-export-impl-args() { + if [[ $# != 1 ]]; then + eerror "Usage: ${FUNCNAME[0]} lisp-implementation" + die "${FUNCNAME[0]}: wrong number of arguments: $#" + fi + CL_BINARY="${1}" + case "${CL_BINARY}" in + sbcl) + CL_NORC="--sysinit /dev/null --userinit /dev/null" + CL_LOAD="--load" + CL_EVAL="--eval" + ;; + clisp) + CL_NORC="-norc" + CL_LOAD="-i" + CL_EVAL="-x" + ;; + clozure | clozurecl | ccl | openmcl) + CL_BINARY="ccl" + CL_NORC="--no-init" + CL_LOAD="--load" + CL_EVAL="--eval" + ;; + cmucl) + CL_NORC="-nositeinit -noinit" + CL_LOAD="-load" + CL_EVAL="-eval" + ;; + ecl | ecls) + CL_BINARY="ecl" + CL_NORC="-norc" + CL_LOAD="-load" + CL_EVAL="-eval" + ;; + abcl) + CL_NORC="--noinit" + CL_LOAD="--load" + CL_EVAL="--eval" + ;; + *) + die "${CL_BINARY} is not supported by ${0}" + ;; + esac + export CL_BINARY CL_NORC CL_LOAD CL_EVAL +} diff --git a/eclass/cron.eclass b/eclass/cron.eclass new file mode 100644 index 0000000..b9f436a --- /dev/null +++ b/eclass/cron.eclass @@ -0,0 +1,160 @@ +# Copyright 1999-2019 Gentoo Authors +# Distributed under the terms of the GNU General Public License v2 + +# @ECLASS: cron.eclass +# @MAINTAINER: +# maintainer-needed@gentoo.org +# @AUTHOR: +# Original Author: Aaron Walker +# @BLURB: Some functions for cron +# @DESCRIPTION: +# Purpose: The main motivation for this eclass was to simplify +# the jungle known as src_install() in cron ebuilds. Using these +# functions also ensures that permissions are *always* reset, +# preventing the accidental installation of files with wrong perms. +# +# NOTE on defaults: the default settings in the below functions were +# chosen based on the most common setting among cron ebuilds. +# +# Please assign any bugs regarding this eclass to cron-bugs@gentoo.org. + +inherit eutils flag-o-matic + +EXPORT_FUNCTIONS pkg_postinst + +SLOT="0" + +DEPEND=">=sys-apps/sed-4.0.5" + +RDEPEND=">=sys-process/cronbase-0.3.2" +for pn in vixie-cron bcron cronie dcron fcron; do + [[ ${pn} == "${PN}" ]] || RDEPEND="${RDEPEND} !sys-process/${pn}" +done + +# @FUNCTION: docrondir +# @USAGE: [ dir ] [ perms ] +# @DESCRIPTION: +# Creates crontab directory +# +# Both arguments are optional. Everything after 'dir' is considered +# the permissions (same format as insopts). +# +# ex: docrondir /some/dir -m 0770 -o root -g cron +# docrondir /some/dir (uses default perms) +# docrondir -m0700 (uses default dir) + +docrondir() { + # defaults + local perms="-m0750 -o root -g cron" dir="/var/spool/cron/crontabs" + + if [[ -n $1 ]] ; then + case "$1" in + */*) + dir=$1 + shift + [[ -n $1 ]] && perms="$@" + ;; + *) + perms="$@" + ;; + esac + fi + + diropts ${perms} + keepdir ${dir} + + # reset perms to default + diropts -m0755 +} + +# @FUNCTION: docron +# @USAGE: [ exe ] [ perms ] +# @DESCRIPTION: +# Install cron executable +# +# Both arguments are optional. +# +# ex: docron -m 0700 -o root -g root ('exe' defaults to "cron") +# docron crond -m 0110 + +docron() { + local cron="cron" perms="-m 0750 -o root -g wheel" + + if [[ -n $1 ]] ; then + case "$1" in + -*) + perms="$@" + ;; + *) + cron=$1 + shift + [[ -n $1 ]] && perms="$@" + ;; + esac + fi + + exeopts ${perms} + exeinto /usr/sbin + doexe ${cron} || die "failed to install ${cron}" + + # reset perms to default + exeopts -m0755 +} + +# @FUNCTION: docrontab +# @USAGE: [ exe ] [ perms ] +# @DESCRIPTION: +# Install crontab executable +# +# Uses same semantics as docron. + +docrontab() { + local crontab="crontab" perms="-m 4750 -o root -g cron" + + if [[ -n $1 ]] ; then + case "$1" in + -*) + perms="$@" + ;; + *) + crontab=$1 + shift + [[ -n $1 ]] && perms="$@" + ;; + esac + fi + + exeopts ${perms} + exeinto /usr/bin + doexe ${crontab} || die "failed to install ${crontab}" + + # reset perms to default + exeopts -m0755 + + # users expect /usr/bin/crontab to exist... + if [[ "${crontab##*/}" != "crontab" ]] ; then + dosym ${crontab##*/} /usr/bin/crontab || \ + die "failed to create /usr/bin/crontab symlink" + fi +} + +# @FUNCTION: cron_pkg_postinst +# @DESCRIPTION: +# Outputs a message about system crontabs +# daemons that have a true system crontab set CRON_SYSTEM_CRONTAB="yes" +cron_pkg_postinst() { + echo + # daemons that have a true system crontab set CRON_SYSTEM_CRONTAB="yes" + if [ "${CRON_SYSTEM_CRONTAB:-no}" != "yes" ] ; then + einfo "To activate /etc/cron.{hourly|daily|weekly|monthly} please run:" + einfo " crontab /etc/crontab" + einfo + einfo "!!! That will replace root's current crontab !!!" + einfo + fi + + einfo "You may wish to read the Gentoo Linux Cron Guide, which can be" + einfo "found online at:" + einfo " https://wiki.gentoo.org/wiki/Cron" + echo +} diff --git a/eclass/cuda.eclass b/eclass/cuda.eclass new file mode 100644 index 0000000..b1da77c --- /dev/null +++ b/eclass/cuda.eclass @@ -0,0 +1,201 @@ +# Copyright 1999-2020 Gentoo Authors +# Distributed under the terms of the GNU General Public License v2 + +case "${EAPI:-0}" in + 0|1|2|3|4) + die "Unsupported EAPI=${EAPI:-0} (too old) for ${ECLASS}" + ;; + 5|6|7) + ;; + *) + die "Unsupported EAPI=${EAPI} (unknown) for ${ECLASS}" + ;; +esac + +# @ECLASS: cuda.eclass +# @MAINTAINER: +# Gentoo Science Project +# @SUPPORTED_EAPIS: 5 6 7 +# @BLURB: Common functions for cuda packages +# @DESCRIPTION: +# This eclass contains functions to be used with cuda package. Currently it is +# setting and/or sanitizing NVCCFLAGS, the compiler flags for nvcc. This is +# automatically done and exported in src_prepare() or manually by calling +# cuda_sanatize. +# @EXAMPLE: +# inherit cuda + +if [[ -z ${_CUDA_ECLASS} ]]; then + +inherit flag-o-matic toolchain-funcs +[[ ${EAPI} == [56] ]] && inherit eapi7-ver + +# @ECLASS-VARIABLE: NVCCFLAGS +# @DESCRIPTION: +# nvcc compiler flags (see nvcc --help), which should be used like +# CFLAGS for c compiler +: ${NVCCFLAGS:=-O2} + +# @ECLASS-VARIABLE: CUDA_VERBOSE +# @DESCRIPTION: +# Being verbose during compilation to see underlying commands +: ${CUDA_VERBOSE:=true} + +# @FUNCTION: cuda_gccdir +# @USAGE: [-f] +# @RETURN: gcc bindir compatible with current cuda, optionally (-f) prefixed with "--compiler-bindir " +# @DESCRIPTION: +# Helper for determination of the latest gcc bindir supported by +# then current nvidia cuda toolkit. +# +# Example: +# @CODE +# cuda_gccdir -f +# -> --compiler-bindir "/usr/x86_64-pc-linux-gnu/gcc-bin/4.6.3" +# @CODE +cuda_gccdir() { + debug-print-function ${FUNCNAME} "$@" + + local dirs gcc_bindir ver vers="" flag + + # Currently we only support the gnu compiler suite + if ! tc-is-gcc ; then + ewarn "Currently we only support the gnu compiler suite" + return 2 + fi + + while [[ "$1" ]]; do + case $1 in + -f) + flag="--compiler-bindir " + ;; + *) + ;; + esac + shift + done + + if ! vers="$(cuda-config -s)"; then + eerror "Could not execute cuda-config" + eerror "Make sure >=dev-util/nvidia-cuda-toolkit-4.2.9-r1 is installed" + die "cuda-config not found" + fi + if [[ -z ${vers} ]]; then + die "Could not determine supported gcc versions from cuda-config" + fi + + # Try the current gcc version first + ver=$(gcc-version) + if [[ -n "${ver}" ]] && [[ ${vers} =~ ${ver} ]]; then + dirs=( ${EPREFIX}/usr/*pc-linux-gnu/gcc-bin/${ver}*/ ) + gcc_bindir="${dirs[${#dirs[@]}-1]}" + fi + + if [[ -z ${gcc_bindir} ]]; then + ver=$(best_version "sys-devel/gcc") + ver=$(ver_cut 1-2 "${ver##*sys-devel/gcc-}") + + if [[ -n "${ver}" ]] && [[ ${vers} =~ ${ver} ]]; then + dirs=( ${EPREFIX}/usr/*pc-linux-gnu/gcc-bin/${ver}*/ ) + gcc_bindir="${dirs[${#dirs[@]}-1]}" + fi + fi + + for ver in ${vers}; do + if has_version "=sys-devel/gcc-${ver}*"; then + dirs=( ${EPREFIX}/usr/*pc-linux-gnu/gcc-bin/${ver}*/ ) + gcc_bindir="${dirs[${#dirs[@]}-1]}" + fi + done + + if [[ -n ${gcc_bindir} ]]; then + if [[ -n ${flag} ]]; then + echo "${flag}\"${gcc_bindir%/}\"" + else + echo "${gcc_bindir%/}" + fi + return 0 + else + eerror "Only gcc version(s) ${vers} are supported," + eerror "of which none is installed" + die "Only gcc version(s) ${vers} are supported" + return 1 + fi +} + +# @FUNCTION: cuda_sanitize +# @DESCRIPTION: +# Correct NVCCFLAGS by adding the necessary reference to gcc bindir and +# passing CXXFLAGS to underlying compiler without disturbing nvcc. +cuda_sanitize() { + debug-print-function ${FUNCNAME} "$@" + + local rawldflags=$(raw-ldflags) + # Be verbose if wanted + [[ "${CUDA_VERBOSE}" == true ]] && NVCCFLAGS+=" -v" + + # Tell nvcc where to find a compatible compiler + NVCCFLAGS+=" $(cuda_gccdir -f)" + + # Tell nvcc which flags should be used for underlying C compiler + NVCCFLAGS+=" --compiler-options \"${CXXFLAGS}\" --linker-options \"${rawldflags// /,}\"" + + debug-print "Using ${NVCCFLAGS} for cuda" + export NVCCFLAGS +} + +# @FUNCTION: cuda_add_sandbox +# @USAGE: [-w] +# @DESCRIPTION: +# Add nvidia dev nodes to the sandbox predict list. +# with -w, add to the sandbox write list. +cuda_add_sandbox() { + debug-print-function ${FUNCNAME} "$@" + + local i + for i in /dev/nvidia*; do + if [[ $1 == '-w' ]]; then + addwrite $i + else + addpredict $i + fi + done +} + +# @FUNCTION: cuda_toolkit_version +# @DESCRIPTION: +# echo the installed version of dev-util/nvidia-cuda-toolkit +cuda_toolkit_version() { + debug-print-function ${FUNCNAME} "$@" + + local v + v="$(best_version dev-util/nvidia-cuda-toolkit)" + v="${v##*cuda-toolkit-}" + ver_cut 1-2 "${v}" +} + +# @FUNCTION: cuda_cudnn_version +# @DESCRIPTION: +# echo the installed version of dev-libs/cudnn +cuda_cudnn_version() { + debug-print-function ${FUNCNAME} "$@" + + local v + v="$(best_version dev-libs/cudnn)" + v="${v##*cudnn-}" + ver_cut 1-2 "${v}" +} + +# @FUNCTION: cuda_src_prepare +# @DESCRIPTION: +# Sanitise and export NVCCFLAGS by default +cuda_src_prepare() { + debug-print-function ${FUNCNAME} "$@" + + cuda_sanitize +} + +EXPORT_FUNCTIONS src_prepare + +_CUDA_ECLASS=1 +fi diff --git a/eclass/cvs.eclass b/eclass/cvs.eclass new file mode 100644 index 0000000..dd3cbe1 --- /dev/null +++ b/eclass/cvs.eclass @@ -0,0 +1,538 @@ +# Copyright 1999-2020 Gentoo Authors +# Distributed under the terms of the GNU General Public License v2 + +# @ECLASS: cvs.eclass +# @MAINTAINER: +# vapier@gentoo.org (and anyone who wants to help) +# @SUPPORTED_EAPIS: 4 5 6 7 +# @BLURB: This eclass provides generic cvs fetching functions +# @DESCRIPTION: +# This eclass provides the generic cvs fetching functions. To use this from an +# ebuild, set the ECLASS VARIABLES as specified below in your ebuild before +# inheriting. Then either leave the default src_unpack or extend over +# cvs_src_unpack. If you find that you need to call the cvs_* functions +# directly, I'd be interested to hear about it. + +if [[ -z ${_CVS_ECLASS} ]]; then +_CVS_ECLASS=1 + +# TODO: + +# Implement more auth types (gserver?, kserver?) + +# Support additional remote shells with `ext' authentication (does +# anyone actually need to use it with anything other than SSH?) + + +# Users shouldn't change these settings! The ebuild/eclass inheriting +# this eclass will take care of that. If you want to set the global +# KDE cvs ebuilds' settings, see the comments in kde-source.eclass. + +# @ECLASS-VARIABLE: ECVS_CVS_COMPRESS +# @DESCRIPTION: +# Set the default compression level. Has no effect when ECVS_CVS_COMMAND +# is defined by ebuild/user. +: ${ECVS_CVS_COMPRESS:=-z1} + +# @ECLASS-VARIABLE: ECVS_CVS_OPTIONS +# @DESCRIPTION: +# Additional options to the cvs commands. Has no effect when ECVS_CVS_COMMAND +# is defined by ebuild/user. +: ${ECVS_CVS_OPTIONS:=-q -f} + +# @ECLASS-VARIABLE: ECVS_CVS_COMMAND +# @DESCRIPTION: +# CVS command to run +# +# You can set, for example, "cvs -t" for extensive debug information +# on the cvs connection. The default of "cvs -q -f -z4" means to be +# quiet, to disregard the ~/.cvsrc config file and to use maximum +# compression. +: ${ECVS_CVS_COMMAND:=cvs ${ECVS_CVS_OPTIONS} ${ECVS_CVS_COMPRESS}} + +# @ECLASS-VARIABLE: ECVS_UP_OPTS +# @DESCRIPTION: +# CVS options given after the cvs update command. Don't remove "-dP" or things +# won't work. +: ${ECVS_UP_OPTS:=-dP} + +# @ECLASS-VARIABLE: ECVS_CO_OPTS +# @DEFAULT_UNSET +# @DESCRIPTION: +# CVS options given after the cvs checkout command. + +# @ECLASS-VARIABLE: ECVS_OFFLINE +# @DESCRIPTION: +# Set this variable to a non-empty value to disable the automatic updating of +# a CVS source tree. This is intended to be set outside the cvs source +# tree by users. +: ${ECVS_OFFLINE:=${EVCS_OFFLINE}} + +# @ECLASS-VARIABLE: ECVS_LOCAL +# @DEFAULT_UNSET +# @DESCRIPTION: +# If this is set, the CVS module will be fetched non-recursively. +# Refer to the information in the CVS man page regarding the -l +# command option (not the -l global option). + +# @ECLASS-VARIABLE: ECVS_LOCALNAME +# @DEFAULT_UNSET +# @DESCRIPTION: +# Local name of checkout directory +# +# This is useful if the module on the server is called something +# common like 'driver' or is nested deep in a tree, and you don't like +# useless empty directories. +# +# WARNING: Set this only from within ebuilds! If set in your shell or +# some such, things will break because the ebuild won't expect it and +# have e.g. a wrong $S setting. + +# @ECLASS-VARIABLE: ECVS_TOP_DIR +# @DESCRIPTION: +# The directory under which CVS modules are checked out. +: ${ECVS_TOP_DIR:="${PORTAGE_ACTUAL_DISTDIR-${DISTDIR}}/cvs-src"} + +# @ECLASS-VARIABLE: ECVS_SERVER +# @DESCRIPTION: +# CVS path +# +# The format is "server:/dir", e.g. "anoncvs.kde.org:/home/kde". +# Remove the other parts of the full CVSROOT, which might look like +# ":pserver:anonymous@anoncvs.kde.org:/home/kde"; this is generated +# using other settings also. +# +# Set this to "offline" to disable fetching (i.e. to assume the module +# is already checked out in ECVS_TOP_DIR). +: ${ECVS_SERVER:="offline"} + +# @ECLASS-VARIABLE: ECVS_MODULE +# @REQUIRED +# @DESCRIPTION: +# The name of the CVS module to be fetched +# +# This must be set when cvs_src_unpack is called. This can include +# several directory levels, i.e. "foo/bar/baz" +#[[ -z ${ECVS_MODULE} ]] && die "$ECLASS: error: ECVS_MODULE not set, cannot continue" + +# @ECLASS-VARIABLE: ECVS_DATE +# @DEFAULT_UNSET +# @DESCRIPTION: +# The date of the checkout. See the -D date_spec option in the cvs +# man page for more details. + +# @ECLASS-VARIABLE: ECVS_BRANCH +# @DEFAULT_UNSET +# @DESCRIPTION: +# The name of the branch/tag to use +# +# The default is "HEAD". The following default _will_ reset your +# branch checkout to head if used. +#: ${ECVS_BRANCH:="HEAD"} + +# @ECLASS-VARIABLE: ECVS_AUTH +# @DESCRIPTION: +# Authentication method to use +# +# Possible values are "pserver" and "ext". If `ext' authentication is +# used, the remote shell to use can be specified in CVS_RSH (SSH is +# used by default). Currently, the only supported remote shell for +# `ext' authentication is SSH. +# +# Armando Di Cianno 2004/09/27 +# - Added "no" as a server type, which uses no AUTH method, nor +# does it login +# e.g. +# "cvs -danoncvs@savannah.gnu.org:/cvsroot/backbone co System" +# ( from gnustep-apps/textedit ) +: ${ECVS_AUTH:="pserver"} + +# @ECLASS-VARIABLE: ECVS_USER +# @DESCRIPTION: +# Username to use for authentication on the remote server. +: ${ECVS_USER:="anonymous"} + +# @ECLASS-VARIABLE: ECVS_PASS +# @DEFAULT_UNSET +# @DESCRIPTION: +# Password to use for authentication on the remote server + +# @ECLASS-VARIABLE: ECVS_SSH_HOST_KEY +# @DEFAULT_UNSET +# @DESCRIPTION: +# If SSH is used for `ext' authentication, use this variable to +# specify the host key of the remote server. The format of the value +# should be the same format that is used for the SSH known hosts file. +# +# WARNING: If a SSH host key is not specified using this variable, the +# remote host key will not be verified. + +# @ECLASS-VARIABLE: ECVS_CLEAN +# @DEFAULT_UNSET +# @DESCRIPTION: +# Set this to get a clean copy when updating (passes the +# -C option to cvs update) + +PROPERTIES+=" live" + +# add cvs to deps +# ssh is used for ext auth +DEPEND="dev-vcs/cvs" + +if [[ ${ECVS_AUTH} == "ext" ]] ; then + #default to ssh + [[ -z ${CVS_RSH} ]] && export CVS_RSH="ssh" + if [[ ${CVS_RSH} != "ssh" ]] ; then + die "Support for ext auth with clients other than ssh has not been implemented yet" + fi + DEPEND+=" net-misc/openssh" +fi + +case ${EAPI:-0} in + 4|5|6) ;; + 7) BDEPEND="${DEPEND}"; DEPEND="" ;; + *) die "${ECLASS}: EAPI ${EAPI:-0} is not supported" ;; +esac + +# called from cvs_src_unpack +cvs_fetch() { + # Make these options local variables so that the global values are + # not affected by modifications in this function. + + local ECVS_COMMAND=${ECVS_COMMAND} + local ECVS_UP_OPTS=${ECVS_UP_OPTS} + local ECVS_CO_OPTS=${ECVS_CO_OPTS} + + debug-print-function ${FUNCNAME} "$@" + + # Update variables that are modified by ebuild parameters, which + # should be effective every time cvs_fetch is called, and not just + # every time cvs.eclass is inherited + + # Handle parameter for local (non-recursive) fetching + + if [[ -n ${ECVS_LOCAL} ]] ; then + ECVS_UP_OPTS+=" -l" + ECVS_CO_OPTS+=" -l" + fi + + # Handle ECVS_BRANCH option + # + # Because CVS auto-switches branches, we just have to pass the + # correct -rBRANCH option when updating. + + if [[ -n ${ECVS_BRANCH} ]] ; then + ECVS_UP_OPTS+=" -r${ECVS_BRANCH}" + ECVS_CO_OPTS+=" -r${ECVS_BRANCH}" + fi + + # Handle ECVS_LOCALNAME, which specifies the local directory name + # to use. Note that the -d command option is not equivalent to + # the global -d option. + + if [[ ${ECVS_LOCALNAME} != "${ECVS_MODULE}" ]] ; then + ECVS_CO_OPTS+=" -d ${ECVS_LOCALNAME}" + fi + + if [[ -n ${ECVS_CLEAN} ]] ; then + ECVS_UP_OPTS+=" -C" + fi + + if [[ -n ${ECVS_DATE} ]] ; then + ECVS_CO_OPTS+=" -D ${ECVS_DATE}" + ECVS_UP_OPTS+=" -D ${ECVS_DATE}" + fi + + # Create the top dir if needed + + if [[ ! -d ${ECVS_TOP_DIR} ]] ; then + # Note that the addwrite statements in this block are only + # there to allow creating ECVS_TOP_DIR; we allow writing + # inside it separately. + + # This is because it's simpler than trying to find out the + # parent path of the directory, which would need to be the + # real path and not a symlink for things to work (so we can't + # just remove the last path element in the string) + + debug-print "${FUNCNAME}: checkout mode. creating cvs directory" + addwrite /foobar + addwrite / + mkdir -p "/${ECVS_TOP_DIR}" + export SANDBOX_WRITE="${SANDBOX_WRITE//:\/foobar:\/}" + fi + + # In case ECVS_TOP_DIR is a symlink to a dir, get the real path, + # otherwise addwrite() doesn't work. + + cd -P "${ECVS_TOP_DIR}" >/dev/null + ECVS_TOP_DIR=$(pwd) + + # Disable the sandbox for this dir + addwrite "${ECVS_TOP_DIR}" + + # Determine the CVS command mode (checkout or update) + if [[ ! -d ${ECVS_TOP_DIR}/${ECVS_LOCALNAME}/CVS ]] ; then + mode=checkout + else + mode=update + fi + + # Our server string (i.e. CVSROOT) without the password so it can + # be put in Root + local connection="${ECVS_AUTH}" + if [[ ${ECVS_AUTH} == "no" ]] ; then + local server="${ECVS_USER}@${ECVS_SERVER}" + else + [[ -n ${ECVS_PROXY} ]] && connection+=";proxy=${ECVS_PROXY}" + [[ -n ${ECVS_PROXY_PORT} ]] && connection+=";proxyport=${ECVS_PROXY_PORT}" + local server=":${connection}:${ECVS_USER}@${ECVS_SERVER}" + fi + + # Switch servers automagically if needed + if [[ ${mode} == "update" ]] ; then + cd "/${ECVS_TOP_DIR}/${ECVS_LOCALNAME}" + local oldserver=$(cat CVS/Root) + if [[ ${server} != "${oldserver}" ]] ; then + einfo "Changing the CVS server from ${oldserver} to ${server}:" + debug-print "${FUNCNAME}: Changing the CVS server from ${oldserver} to ${server}:" + + einfo "Searching for CVS directories ..." + local cvsdirs=$(find . -iname CVS -print) + debug-print "${FUNCNAME}: CVS directories found:" + debug-print "${cvsdirs}" + + einfo "Modifying CVS directories ..." + local x + for x in ${cvsdirs} ; do + debug-print "In ${x}" + echo "${server}" > "${x}/Root" + done + fi + fi + + # Prepare a cvspass file just for this session, we don't want to + # mess with ~/.cvspass + touch "${T}/cvspass" + export CVS_PASSFILE="${T}/cvspass" + + # The server string with the password in it, for login (only used for pserver) + cvsroot_pass=":${connection}:${ECVS_USER}:${ECVS_PASS}@${ECVS_SERVER}" + + # Ditto without the password, for checkout/update after login, so + # that the CVS/Root files don't contain the password in plaintext + if [[ ${ECVS_AUTH} == "no" ]] ; then + cvsroot_nopass="${ECVS_USER}@${ECVS_SERVER}" + else + cvsroot_nopass=":${connection}:${ECVS_USER}@${ECVS_SERVER}" + fi + + # Commands to run + cmdlogin=( ${ECVS_CVS_COMMAND} -d "${cvsroot_pass}" login ) + cmdupdate=( ${ECVS_CVS_COMMAND} -d "${cvsroot_nopass}" update ${ECVS_UP_OPTS} ${ECVS_LOCALNAME} ) + cmdcheckout=( ${ECVS_CVS_COMMAND} -d "${cvsroot_nopass}" checkout ${ECVS_CO_OPTS} ${ECVS_MODULE} ) + + # Execute commands + + cd "${ECVS_TOP_DIR}" + if [[ ${ECVS_AUTH} == "pserver" ]] ; then + einfo "Running ${cmdlogin[*]}" + "${cmdlogin[@]}" || die "cvs login command failed" + if [[ ${mode} == "update" ]] ; then + einfo "Running ${cmdupdate[*]}" + "${cmdupdate[@]}" || die "cvs update command failed" + elif [[ ${mode} == "checkout" ]] ; then + einfo "Running ${cmdcheckout[*]}" + "${cmdcheckout[@]}" || die "cvs checkout command failed" + fi + elif [[ ${ECVS_AUTH} == "ext" || ${ECVS_AUTH} == "no" ]] ; then + # Hack to support SSH password authentication + + # Backup environment variable values + local CVS_ECLASS_ORIG_CVS_RSH="${CVS_RSH}" + + if [[ ${SSH_ASKPASS+set} == "set" ]] ; then + local CVS_ECLASS_ORIG_SSH_ASKPASS="${SSH_ASKPASS}" + else + unset CVS_ECLASS_ORIG_SSH_ASKPASS + fi + + if [[ ${DISPLAY+set} == "set" ]] ; then + local CVS_ECLASS_ORIG_DISPLAY="${DISPLAY}" + else + unset CVS_ECLASS_ORIG_DISPLAY + fi + + if [[ ${CVS_RSH} == "ssh" ]] ; then + # Force SSH to use SSH_ASKPASS by creating python wrapper + + export CVS_RSH="${T}/cvs_sshwrapper" + cat > "${CVS_RSH}"< + echo "newarglist.insert(1, '-oClearAllForwardings=yes')" \ + >> "${CVS_RSH}" + echo "newarglist.insert(1, '-oForwardX11=no')" \ + >> "${CVS_RSH}" + + # Handle SSH host key checking + + local CVS_ECLASS_KNOWN_HOSTS="${T}/cvs_ssh_known_hosts" + echo "newarglist.insert(1, '-oUserKnownHostsFile=${CVS_ECLASS_KNOWN_HOSTS}')" \ + >> "${CVS_RSH}" + + if [[ -z ${ECVS_SSH_HOST_KEY} ]] ; then + ewarn "Warning: The SSH host key of the remote server will not be verified." + einfo "A temporary known hosts list will be used." + local CVS_ECLASS_STRICT_HOST_CHECKING="no" + touch "${CVS_ECLASS_KNOWN_HOSTS}" + else + local CVS_ECLASS_STRICT_HOST_CHECKING="yes" + echo "${ECVS_SSH_HOST_KEY}" > "${CVS_ECLASS_KNOWN_HOSTS}" + fi + + echo -n "newarglist.insert(1, '-oStrictHostKeyChecking=" \ + >> "${CVS_RSH}" + echo "${CVS_ECLASS_STRICT_HOST_CHECKING}')" \ + >> "${CVS_RSH}" + echo "os.execv('${EPREFIX}/usr/bin/ssh', newarglist)" \ + >> "${CVS_RSH}" + + chmod a+x "${CVS_RSH}" + + # Make sure DISPLAY is set (SSH will not use SSH_ASKPASS + # if DISPLAY is not set) + + : ${DISPLAY:="DISPLAY"} + export DISPLAY + + # Create a dummy executable to echo ${ECVS_PASS} + + export SSH_ASKPASS="${T}/cvs_sshechopass" + if [[ ${ECVS_AUTH} != "no" ]] ; then + echo -en "#!/bin/bash\necho \"${ECVS_PASS}\"\n" \ + > "${SSH_ASKPASS}" + else + echo -en "#!/bin/bash\nreturn\n" \ + > "${SSH_ASKPASS}" + fi + chmod a+x "${SSH_ASKPASS}" + fi + + if [[ ${mode} == "update" ]] ; then + einfo "Running ${cmdupdate[*]}" + "${cmdupdate[@]}" || die "cvs update command failed" + elif [[ ${mode} == "checkout" ]] ; then + einfo "Running ${cmdcheckout[*]}" + "${cmdcheckout[@]}" || die "cvs checkout command failed" + fi + + # Restore environment variable values + export CVS_RSH="${CVS_ECLASS_ORIG_CVS_RSH}" + if [[ ${CVS_ECLASS_ORIG_SSH_ASKPASS+set} == "set" ]] ; then + export SSH_ASKPASS="${CVS_ECLASS_ORIG_SSH_ASKPASS}" + else + unset SSH_ASKPASS + fi + + if [[ ${CVS_ECLASS_ORIG_DISPLAY+set} == "set" ]] ; then + export DISPLAY="${CVS_ECLASS_ORIG_DISPLAY}" + else + unset DISPLAY + fi + fi +} + +# @FUNCTION: cvs_src_unpack +# @DESCRIPTION: +# The cvs src_unpack function, which will be exported +cvs_src_unpack() { + + debug-print-function ${FUNCNAME} "$@" + + debug-print "${FUNCNAME}: init: + ECVS_CVS_COMMAND=${ECVS_CVS_COMMAND} + ECVS_UP_OPTS=${ECVS_UP_OPTS} + ECVS_CO_OPTS=${ECVS_CO_OPTS} + ECVS_TOP_DIR=${ECVS_TOP_DIR} + ECVS_SERVER=${ECVS_SERVER} + ECVS_USER=${ECVS_USER} + ECVS_PASS=${ECVS_PASS} + ECVS_MODULE=${ECVS_MODULE} + ECVS_LOCAL=${ECVS_LOCAL} + ECVS_LOCALNAME=${ECVS_LOCALNAME}" + + [[ -z ${ECVS_MODULE} ]] && die "ERROR: CVS module not set, cannot continue." + + local ECVS_LOCALNAME=${ECVS_LOCALNAME:-${ECVS_MODULE}} + + local sanitized_pn=$(echo "${PN}" | LC_ALL=C sed -e 's:[^A-Za-z0-9_]:_:g') + local offline_pkg_var="ECVS_OFFLINE_${sanitized_pn}" + if [[ -n ${!offline_pkg_var}${ECVS_OFFLINE} ]] || [[ ${ECVS_SERVER} == "offline" ]] ; then + # We're not required to fetch anything; the module already + # exists and shouldn't be updated. + if [[ -d ${ECVS_TOP_DIR}/${ECVS_LOCALNAME} ]] ; then + debug-print "${FUNCNAME}: offline mode" + else + debug-print "${FUNCNAME}: Offline mode specified but directory ${ECVS_TOP_DIR}/${ECVS_LOCALNAME} not found, exiting with error" + die "ERROR: Offline mode specified, but directory ${ECVS_TOP_DIR}/${ECVS_LOCALNAME} not found. Aborting." + fi + elif [[ -n ${ECVS_SERVER} ]] ; then # ECVS_SERVER!=offline --> real fetching mode + einfo "Fetching CVS module ${ECVS_MODULE} into ${ECVS_TOP_DIR} ..." + cvs_fetch + else # ECVS_SERVER not set + die "ERROR: CVS server not specified, cannot continue." + fi + + einfo "Copying ${ECVS_MODULE} from ${ECVS_TOP_DIR} ..." + debug-print "Copying module ${ECVS_MODULE} local_mode=${ECVS_LOCAL} from ${ECVS_TOP_DIR} ..." + + # This is probably redundant, but best to make sure. + mkdir -p "${WORKDIR}/${ECVS_LOCALNAME}" + + if [[ -n ${ECVS_LOCAL} ]] ; then + cp -f "${ECVS_TOP_DIR}/${ECVS_LOCALNAME}"/* "${WORKDIR}/${ECVS_LOCALNAME}" + else + cp -Rf "${ECVS_TOP_DIR}/${ECVS_LOCALNAME}" "${WORKDIR}/${ECVS_LOCALNAME}/.." + fi + + # Not exactly perfect, but should be pretty close #333773 + export ECVS_VERSION=$( + find "${ECVS_TOP_DIR}/${ECVS_LOCALNAME}/" -ipath '*/CVS/Entries' -exec cat {} + | \ + LC_ALL=C sort | \ + sha1sum | \ + awk '{print $1}' + ) + + # If the directory is empty, remove it; empty directories cannot + # exist in cvs. This happens when, for example, kde-source + # requests module/doc/subdir which doesn't exist. Still create + # the empty directory in workdir though. + if [[ $(ls -A "${ECVS_TOP_DIR}/${ECVS_LOCALNAME}") == "CVS" ]] ; then + debug-print "${FUNCNAME}: removing empty CVS directory ${ECVS_LOCALNAME}" + rm -rf "${ECVS_TOP_DIR}/${ECVS_LOCALNAME}" + fi + + einfo "CVS module ${ECVS_MODULE} is now in ${WORKDIR}" +} + +EXPORT_FUNCTIONS src_unpack + +fi diff --git a/eclass/darcs.eclass b/eclass/darcs.eclass new file mode 100644 index 0000000..12e7289 --- /dev/null +++ b/eclass/darcs.eclass @@ -0,0 +1,220 @@ +# Copyright 1999-2020 Gentoo Authors +# Distributed under the terms of the GNU General Public License v2 + +# @ECLASS: darcs.eclass +# @MAINTAINER: +# "Gentoo's Haskell Language team" +# Sergei Trofimovich +# @AUTHOR: +# Original Author: Jeffrey Yasskin +# (tla eclass author) +# Andres Loeh (darcs.eclass author) +# Alexander Vershilov (various contributions) +# @BLURB: This eclass provides functions for fetch and unpack darcs repositories +# @DEPRECATED: none +# @DESCRIPTION: +# This eclass provides the generic darcs fetching functions. +# +# Define the EDARCS_REPOSITORY variable at least. +# The ${S} variable is set to ${WORKDIR}/${P}. + +# TODO: + +# support for tags + +# eshopts_{push,pop} +case "${EAPI:-0}" in + 4|5|6) inherit eutils ;; + 7) inherit estack ;; + *) ;; +esac + +# Don't download anything other than the darcs repository +SRC_URI="" + +# You shouldn't change these settings yourself! The ebuild/eclass inheriting +# this eclass will take care of that. + +# --- begin ebuild-configurable settings + +# darcs command to run +# @ECLASS-VARIABLE: EDARCS_DARCS_CMD +# @DESCRIPTION: +# Path to darcs binary. +: ${EDARCS_DARCS_CMD:=darcs} + +# darcs commands with command-specific options + +# @ECLASS-VARIABLE: EDARCS_GET_CMD +# @DESCRIPTION: +# First fetch darcs command. +: ${EDARCS_GET_CMD:=get --lazy} + +# @ECLASS-VARIABLE: EDARCS_UPDATE_CMD +# @DESCRIPTION: +# Repo update darcs command. +: ${EDARCS_UPDATE_CMD:=pull} + +# @ECLASS-VARIABLE: EDARCS_OPTIONS +# @DESCRIPTION: +# Options to pass to both the "get" and "update" commands +: ${EDARCS_OPTIONS:=--set-scripts-executable} + +# @ECLASS-VARIABLE: EDARCS_TOP_DIR +# @DESCRIPTION: +# Where the darcs repositories are stored/accessed +: ${EDARCS_TOP_DIR:=${PORTAGE_ACTUAL_DISTDIR-${DISTDIR}}/darcs-src} + +# @ECLASS-VARIABLE: EDARCS_REPOSITORY +# @DESCRIPTION: +# The URI to the repository. +: ${EDARCS_REPOSITORY:=} + +# @ECLASS-VARIABLE: EDARCS_OFFLINE +# @DESCRIPTION: +# Set this variable to a non-empty value to disable the automatic updating of +# a darcs repository. This is intended to be set outside the darcs source +# tree by users. Defaults to EVCS_OFFLINE value. +: ${EDARCS_OFFLINE:=${EVCS_OFFLINE}} + +# @ECLASS-VARIABLE: EDARCS_CLEAN +# @DESCRIPTION: +# Set this to something to get a clean copy when updating +# (removes the working directory, then uses EDARCS_GET_CMD to +# re-download it.) +: ${EDARCS_CLEAN:=} + +# --- end ebuild-configurable settings --- + +PROPERTIES+=" live" + +case ${EAPI:-0} in + [0-6]) # no need to care about 5-HDEPEND and similar + DEPEND="dev-vcs/darcs + net-misc/rsync" + ;; + *) + BDEPEND="dev-vcs/darcs + net-misc/rsync" + ;; +esac + +# @FUNCTION: darcs_patchcount +# @DESCRIPTION: +# Internal function to determine amount of patches in repository. +darcs_patchcount() { + set -- $(HOME="${EDARCS_TOP_DIR}" ${EDARCS_DARCS_CMD} show repo --repodir="${EDARCS_TOP_DIR}/${EDARCS_LOCALREPO}" | grep "Num Patches") + # handle string like: " Num Patches: 3860" + echo ${3} +} + +# @FUNCTION: darcs_fetch +# @DESCRIPTION: +# Internal function is called from darcs_src_unpack +darcs_fetch() { + # The local directory to store the repository (useful to ensure a + # unique local name); relative to EDARCS_TOP_DIR + [[ -z ${EDARCS_LOCALREPO} ]] && [[ -n ${EDARCS_REPOSITORY} ]] \ + && EDARCS_LOCALREPO=${EDARCS_REPOSITORY%/} \ + && EDARCS_LOCALREPO=${EDARCS_LOCALREPO##*/} + + debug-print-function ${FUNCNAME} $* + + if [[ -n ${EDARCS_CLEAN} ]]; then + addwrite "${EDARCS_TOP_DIR}/${EDARCS_LOCALREPO}" + rm -rf "${EDARCS_TOP_DIR}/${EDARCS_LOCALREPO}" + fi + + # create the top dir if needed + if [[ ! -d ${EDARCS_TOP_DIR} ]]; then + # note that the addwrite statements in this block are only there to allow creating EDARCS_TOP_DIR; + # we've already allowed writing inside it + # this is because it's simpler than trying to find out the parent path of the directory, which + # would need to be the real path and not a symlink for things to work (so we can't just remove + # the last path element in the string) + debug-print "${FUNCNAME}: checkout mode. creating darcs directory" + addwrite /foobar + addwrite / + mkdir -p "${EDARCS_TOP_DIR}" + export SANDBOX_WRITE="${SANDBOX_WRITE//:\/foobar:\/}" + fi + + # in case EDARCS_DARCS_DIR is a symlink to a dir, get the real + # dir's path, otherwise addwrite() doesn't work. + pushd . || die + cd -P "${EDARCS_TOP_DIR}" > /dev/null + EDARCS_TOP_DIR="`/bin/pwd`" + + # disable the sandbox for this dir + addwrite "${EDARCS_TOP_DIR}" + + # determine checkout or update mode and change to the right directory. + if [[ ! -d "${EDARCS_TOP_DIR}/${EDARCS_LOCALREPO}/_darcs" ]]; then + mode=get + cd "${EDARCS_TOP_DIR}" + else + mode=update + cd "${EDARCS_TOP_DIR}/${EDARCS_LOCALREPO}" + fi + + # commands to run + local cmdget="${EDARCS_DARCS_CMD} ${EDARCS_GET_CMD} ${EDARCS_OPTIONS} --repo-name=${EDARCS_LOCALREPO} ${EDARCS_REPOSITORY}" + local cmdupdate="${EDARCS_DARCS_CMD} ${EDARCS_UPDATE_CMD} --all ${EDARCS_OPTIONS} ${EDARCS_REPOSITORY}" + + if [[ ${mode} == "get" ]]; then + einfo "Running ${cmdget}" + HOME="${EDARCS_TOP_DIR}" ${cmdget} || die "darcs get command failed" + elif [[ -n ${EDARCS_OFFLINE} ]] ; then + einfo "Offline update" + elif [[ ${mode} == "update" ]]; then + einfo "Running ${cmdupdate}" + HOME="${EDARCS_TOP_DIR}" ${cmdupdate} || die "darcs update command failed" + fi + + export EDARCS_PATCHCOUNT=$(darcs_patchcount) + einfo " patches in repo: ${EDARCS_PATCHCOUNT}" + + popd || die +} + +# @FUNCTION: darcs_src_unpack +# @DESCRIPTION: +# src_upack function +darcs_src_unpack() { + # The local directory to store the repository (useful to ensure a + # unique local name); relative to EDARCS_TOP_DIR + [[ -z ${EDARCS_LOCALREPO} ]] && [[ -n ${EDARCS_REPOSITORY} ]] \ + && EDARCS_LOCALREPO=${EDARCS_REPOSITORY%/} \ + && EDARCS_LOCALREPO=${EDARCS_LOCALREPO##*/} + + debug-print-function ${FUNCNAME} $* + + debug-print "${FUNCNAME}: init: + EDARCS_DARCS_CMD=${EDARCS_DARCS_CMD} + EDARCS_GET_CMD=${EDARCS_GET_CMD} + EDARCS_UPDATE_CMD=${EDARCS_UPDATE_CMD} + EDARCS_OPTIONS=${EDARCS_OPTIONS} + EDARCS_TOP_DIR=${EDARCS_TOP_DIR} + EDARCS_REPOSITORY=${EDARCS_REPOSITORY} + EDARCS_LOCALREPO=${EDARCS_LOCALREPO} + EDARCS_CLEAN=${EDARCS_CLEAN}" + + einfo "Fetching darcs repository ${EDARCS_REPOSITORY} into ${EDARCS_TOP_DIR}..." + darcs_fetch + + einfo "Copying ${EDARCS_LOCALREPO} from ${EDARCS_TOP_DIR}..." + debug-print "Copying ${EDARCS_LOCALREPO} from ${EDARCS_TOP_DIR}..." + + # probably redundant, but best to make sure + # Use ${WORKDIR}/${P} rather than ${S} so user can point ${S} to something inside. + mkdir -p "${WORKDIR}/${P}" + + eshopts_push -s dotglob # get any dotfiles too. + rsync -rlpgo "${EDARCS_TOP_DIR}/${EDARCS_LOCALREPO}"/* "${WORKDIR}/${P}" + eshopts_pop + + einfo "Darcs repository contents are now in ${WORKDIR}/${P}" + +} + +EXPORT_FUNCTIONS src_unpack diff --git a/eclass/db-use.eclass b/eclass/db-use.eclass new file mode 100644 index 0000000..7633425 --- /dev/null +++ b/eclass/db-use.eclass @@ -0,0 +1,119 @@ +# Copyright 1999-2020 Gentoo Authors +# Distributed under the terms of the GNU General Public License v2 +# This is a common location for functions that aid the use of sys-libs/db +# +# Bugs: maintainer-needed@gentoo.org + +# multilib is used for get_libname in all EAPI +case "${EAPI:-0}" in + 0|1|2|3|4|5|6) inherit eapi7-ver multilib ;; + *) inherit multilib ;; +esac + +#Convert a version to a db slot +db_ver_to_slot() { + if [ $# -ne 1 ]; then + eerror "Function db_ver_to_slot needs one argument" >&2 + eerror "args given:" >&2 + for f in $@ + do + eerror " - \"$@\"" >&2 + done + return 1 + fi + # 5.0.x uses 5.0 as slot value, so this replacement will break it; + # older sys-libs/db might have been using this but it's no longer + # the case, so make it work for latest rather than older stuff. + # echo -n "${1/.0/}" + echo -n "$1" +} + +#Find the version that correspond to the given atom +db_findver() { + has "${EAPI:-0}" 0 1 2 && ! use prefix && EPREFIX= + if [ $# -ne 1 ]; then + eerror "Function db_findver needs one argument" >&2 + eerror "args given:" >&2 + for f in $@ + do + eerror " - \"$@\"" >&2 + done + return 1 + fi + + PKG="$(best_version $1)" + VER="$(ver_cut 1-2 "${PKG/*db-/}")" + if [ -d "${EPREFIX}"/usr/include/db$(db_ver_to_slot "$VER") ]; then + #einfo "Found db version ${VER}" >&2 + echo -n "$VER" + return 0 + else + return 1 + fi +} + +# Get the include dir for berkeley db. +# This function has two modes. Without any arguments it will give the best +# version available. With arguments that form the versions of db packages +# to test for, it will aim to find the library corresponding to it. + +db_includedir() { + has "${EAPI:-0}" 0 1 2 && ! use prefix && EPREFIX= + if [ $# -eq 0 ]; then + VER="$(db_findver sys-libs/db)" || return 1 + VER="$(db_ver_to_slot "$VER")" + echo "include version ${VER}" >&2 + if [ -d "${EPREFIX}/usr/include/db${VER}" ]; then + echo -n "${EPREFIX}/usr/include/db${VER}" + return 0 + else + eerror "sys-libs/db package requested, but headers not found" >&2 + return 1 + fi + else + #arguments given + for x in $@ + do + if VER=$(db_findver "=sys-libs/db-${x}*") && + [ -d "${EPREFIX}/usr/include/db$(db_ver_to_slot $VER)" ]; then + echo -n "${EPREFIX}/usr/include/db$(db_ver_to_slot $VER)" + return 0 + fi + done + eerror "No suitable db version found" + return 1 + fi +} + + +# Get the library name for berkeley db. Something like "db-4.2" will be the +# outcome. This function has two modes. Without any arguments it will give +# the best version available. With arguments that form the versions of db +# packages to test for, it will aim to find the library corresponding to it. + +db_libname() { + has "${EAPI:-0}" 0 1 2 && ! use prefix && EPREFIX= + if [ $# -eq 0 ]; then + VER="$(db_findver sys-libs/db)" || return 1 + if [ -e "${EPREFIX}/usr/$(get_libdir)/libdb-${VER}$(get_libname)" ]; then + echo -n "db-${VER}" + return 0 + else + eerror "sys-libs/db package requested, but library not found" >&2 + return 1 + fi + else + #arguments given + for x in $@ + do + if VER=$(db_findver "=sys-libs/db-${x}*"); then + if [ -e "${EPREFIX}/usr/$(get_libdir)/libdb-${VER}$(get_libname)" ]; then + echo -n "db-${VER}" + return 0 + fi + fi + done + eerror "No suitable db version found" >&2 + return 1 + fi +} diff --git a/eclass/db.eclass b/eclass/db.eclass new file mode 100644 index 0000000..96669c6 --- /dev/null +++ b/eclass/db.eclass @@ -0,0 +1,203 @@ +# Copyright 1999-2021 Gentoo Authors +# Distributed under the terms of the GNU General Public License v2 + +# @ECLASS: db.eclass +# @MAINTAINER: +# base-system@gentoo.org +# @BLURB: Internal eclass used by sys-libs/db ebuilds + +inherit eutils multilib multiprocessing + +IUSE="doc test examples" + +EXPORT_FUNCTIONS src_test + +DEPEND="test? ( >=dev-lang/tcl-8.4 )" + +RDEPEND="" + +db_fix_so() { + has "${EAPI:-0}" 0 1 2 && ! use prefix && EROOT="${ROOT}" + LIB="${EROOT}/usr/$(get_libdir)" + + cd "${LIB}" || die + + # first clean up old symlinks + local soext=$(get_libname) + find "${LIB}" -maxdepth 1 -type l -name 'libdb[1._-]*'"${soext#.}" -delete || die + soext=$(get_libname "[23]") + find "${LIB}" -maxdepth 1 -type l -name 'libdb[1._-]*'"${soext#.}" -delete || die + find "${LIB}" -maxdepth 1 -type l -name 'libdb[1._-]*a' -delete || die + + # now rebuild all the correct ones + local ext + for ext in so dylib a; do + for name in libdb libdb_{cxx,tcl,java,sql,stl}; do + target="$(find . -maxdepth 1 -type f -name "${name}-*.${ext}" |sort -V |tail -n 1)" + [[ -n "${target}" ]] && ln -sf ${target//.\//} ${name}.${ext} + done; + done; + + # db[23] gets some extra-special stuff + if [[ -f libdb1$(get_libname 2) ]]; then + ln -sf libdb1$(get_libname 2) libdb$(get_libname 2) + ln -sf libdb1$(get_libname 2) libdb1$(get_libname) + ln -sf libdb1$(get_libname 2) libdb-1$(get_libname) + fi + # what do we do if we ever get 3.3 ? + local i + for i in libdb libdb_{cxx,tcl,java,sql,stl}; do + if [[ -f $i-3.2$(get_libname) ]]; then + ln -sf $i-3.2$(get_libname) $i-3$(get_libname) + ln -sf $i-3.2$(get_libname) $i$(get_libname 3) + fi + done + + # do the same for headers now + # but since there are only two of them, just overwrite them + cd "${EROOT}"/usr/include + target="$(find . -maxdepth 1 -type d -name 'db[0-9]*' | sort -V |cut -d/ -f2- | tail -n1)" + if [[ -n "${target}" ]] && [[ -e "${target}/db.h" ]] && ( ! [[ -e db.h ]] || [[ -h db.h ]] ); then + einfo "Creating db.h symlinks to ${target}" + ln -sf "${target}"/db.h . + ln -sf "${target}"/db_185.h . + elif [[ ! -e "${target}/db.h" ]]; then + if [[ -n "${target}" ]]; then + ewarn "Could not find ${target}/db.h" + elif [[ -h db.h ]]; then + einfo "Apparently you just removed the last instance of $PN. Removing the symlinks" + rm -f db.h db_185.h + fi + fi +} + +db_src_install_doc() { + has "${EAPI:-0}" 0 1 2 && ! use prefix && ED="${D}" + # not everybody wants this wad of documentation as it is primarily API docs + if use doc; then + dodir /usr/share/doc/${PF}/html + mv "${ED}"/usr/docs/* "${ED}"/usr/share/doc/${PF}/html/ || die + rm -rf "${ED}"/usr/docs + else + rm -rf "${ED}"/usr/docs + fi + + db_src_install_examples +} + +db_src_install_examples() { + has "${EAPI:-0}" 0 1 2 && ! use prefix && ED="${D}" + if use examples ; then + local langs=( c cxx stl ) + [[ "${IUSE/java}" != "${IUSE}" ]] \ + && use java \ + && langs+=( java ) + local i + for i in ${langs[@]} ; do + destdir="/usr/share/doc/${PF}/" + src="${S}/../examples_${i}/" + if [[ -f "${src}" ]]; then + dodir "${destdir}" + cp -ra "${src}" "${ED}${destdir}/" || die + fi + done + fi +} + +db_src_install_usrbinslot() { + has "${EAPI:-0}" 0 1 2 && ! use prefix && ED="${D}" + # slot all program names to avoid overwriting + local fname + for fname in "${ED}"/usr/bin/db* + do + dn="$(dirname "${fname}")" + bn="$(basename "${fname}")" + bn="${bn/db/db${SLOT}}" + mv "${fname}" "${dn}/${bn}" || \ + die "Failed to rename ${fname} to ${dn}/${bn}" + done +} + +db_src_install_headerslot() { + has "${EAPI:-0}" 0 1 2 && ! use prefix && ED="${D}" + # install all headers in a slotted location + dodir /usr/include/db${SLOT} + mv "${ED}"/usr/include/*.h "${ED}"/usr/include/db${SLOT}/ || die +} + +db_src_install_usrlibcleanup() { + has "${EAPI:-0}" 0 1 2 && ! use prefix && ED="${D}" + LIB="${ED}/usr/$(get_libdir)" + # Clean out the symlinks so that they will not be recorded in the + # contents (bug #60732) + + if [[ "${ED}" = "" ]]; then + die "Calling clean_links while \${ED} not defined" + fi + + if [[ -e "${LIB}"/libdb.a ]] && [[ ! -e "${LIB}"/libdb-${SLOT}.a ]]; then + einfo "Moving libdb.a to a versioned name" + mv "${LIB}/libdb.a" "${LIB}/libdb-${SLOT}.a" || die + fi + + if [[ -e "${LIB}"/libdb_cxx.a ]] && [[ ! -e "${LIB}"/libdb_cxx-${SLOT}.a ]]; then + einfo "Moving libdb_cxx.a to a versioned name" + mv "${LIB}/libdb_cxx.a" "${LIB}/libdb_cxx-${SLOT}.a" || die + fi + + local soext=$(get_libname) + find "${LIB}" -maxdepth 1 -type l -name 'libdb[1._-]*'"${soext#.}" -delete || die + soext=$(get_libname "[23]") + find "${LIB}" -maxdepth 1 -type l -name 'libdb[1._-]*'"${soext#.}" -delete || die + einfo "removing unversioned static archives" + find "${LIB}" -maxdepth 1 -type l -name 'libdb[1._-]*a' -delete || die + + rm -f \ + "${ED}"/usr/include/{db,db_185}.h \ + "${LIB}"/libdb{,_{cxx,sql,stl,java,tcl}}.a +} + +db_src_test() { + if [[ $UID -eq 0 ]]; then + M="You must run the testsuite as non-root, skipping" + ewarn "${M}" + elog "${M}" + return 0 + fi + + if use tcl; then + einfo "Running sys-libs/db testsuite" + ewarn "This can take 6+ hours on modern machines" + # Fix stuff that fails with relative paths, and upstream moving files + # around... + local test_parallel='' t + for t in \ + "${S}"/test/parallel.tcl \ + "${S}"/../test/parallel.tcl \ + "${S}"/test/tcl/parallel.tcl \ + "${S}"/../test/tcl/parallel.tcl \ + ; do + [[ -f "${t}" ]] && test_parallel="${t}" && break + done + + sed -ri \ + -e '/regsub .test_path ./s,(regsub),#\1,g' \ + -e '/regsub .src_root ./s,(regsub),#\1,g' \ + -e '/regsub .tcl_utils ./s,(regsub),#\1,g' \ + "${test_parallel}" + cd "${S}" + for t in \ + ../test/test.tcl \ + ../test/tcl/test.tcl \ + ; do + [[ -f "${t}" ]] && testbase="${t}" && break + done + echo "source ${t}" > testrunner.tcl + echo "run_parallel $(makeopts_jobs) run_std" >> testrunner.tcl + + tclsh testrunner.tcl + grep -Eqs '^FAIL' ALL.OUT* && die "Some tests failed, please see ${S}/ALL.OUT*" + else + eerror "You must have USE=tcl to run the sys-libs/db testsuite." + fi +} diff --git a/eclass/depend.apache.eclass b/eclass/depend.apache.eclass new file mode 100644 index 0000000..5aa5525 --- /dev/null +++ b/eclass/depend.apache.eclass @@ -0,0 +1,381 @@ +# Copyright 1999-2020 Gentoo Authors +# Distributed under the terms of the GNU General Public License v2 + +# @ECLASS: depend.apache.eclass +# @MAINTAINER: +# apache-devs@gentoo.org +# @SUPPORTED_EAPIS: 0 2 3 4 5 6 7 +# @BLURB: Functions to allow ebuilds to depend on apache +# @DESCRIPTION: +# This eclass handles depending on apache in a sane way and provides information +# about where certain binaries and configuration files are located. +# +# To make use of this eclass simply call one of the need/want_apache functions +# described below. Make sure you use the need/want_apache call after you have +# defined DEPEND and RDEPEND. Also note that you can not rely on the automatic +# RDEPEND=DEPEND that portage does if you use this eclass. +# +# See Bug 107127 for more information. +# +# @EXAMPLE: +# +# Here is an example of an ebuild depending on apache: +# +# @CODE +# DEPEND="virtual/Perl-CGI" +# RDEPEND="${DEPEND}" +# need_apache2 +# @CODE +# +# Another example which demonstrates non-standard IUSE options for optional +# apache support: +# +# @CODE +# DEPEND="server? ( virtual/Perl-CGI )" +# RDEPEND="${DEPEND}" +# want_apache2 server +# +# pkg_setup() { +# depend.apache_pkg_setup server +# } +# @CODE + +case ${EAPI:-0} in + 0|2|3|4|5) + inherit multilib + ;; + 6|7) + ;; + *) + die "EAPI=${EAPI} is not supported by depend.apache.eclass" + ;; +esac + +# ============================================================================== +# INTERNAL VARIABLES +# ============================================================================== + +# @ECLASS-VARIABLE: APACHE_VERSION +# @DESCRIPTION: +# Stores the version of apache we are going to be ebuilding. +# This variable is set by the want/need_apache functions. + +# @ECLASS-VARIABLE: APXS +# @DESCRIPTION: +# Path to the apxs tool. +# This variable is set by the want/need_apache functions. + +# @ECLASS-VARIABLE: APACHE_BIN +# @DESCRIPTION: +# Path to the apache binary. +# This variable is set by the want/need_apache functions. + +# @ECLASS-VARIABLE: APACHE_CTL +# @DESCRIPTION: +# Path to the apachectl tool. +# This variable is set by the want/need_apache functions. + +# @ECLASS-VARIABLE: APACHE_BASEDIR +# @DESCRIPTION: +# Path to the server root directory. +# This variable is set by the want/need_apache functions (EAPI=0 through 5) +# or depend.apache_pkg_setup (EAPI=6 and later). + +# @ECLASS-VARIABLE: APACHE_CONFDIR +# @DESCRIPTION: +# Path to the configuration file directory. +# This variable is set by the want/need_apache functions. + +# @ECLASS-VARIABLE: APACHE_MODULES_CONFDIR +# @DESCRIPTION: +# Path where module configuration files are kept. +# This variable is set by the want/need_apache functions. + +# @ECLASS-VARIABLE: APACHE_VHOSTS_CONFDIR +# @DESCRIPTION: +# Path where virtual host configuration files are kept. +# This variable is set by the want/need_apache functions. + +# @ECLASS-VARIABLE: APACHE_MODULESDIR +# @DESCRIPTION: +# Path where we install modules. +# This variable is set by the want/need_apache functions (EAPI=0 through 5) +# or depend.apache_pkg_setup (EAPI=6 and later). + +# @ECLASS-VARIABLE: APACHE_DEPEND +# @DESCRIPTION: +# Dependencies for Apache +APACHE_DEPEND="www-servers/apache" + +# @ECLASS-VARIABLE: APACHE2_DEPEND +# @DESCRIPTION: +# Dependencies for Apache 2.x +APACHE2_DEPEND="=www-servers/apache-2*" + +# @ECLASS-VARIABLE: APACHE2_2_DEPEND +# @DESCRIPTION: +# Dependencies for Apache 2.2.x +APACHE2_2_DEPEND="=www-servers/apache-2.2*" + +# @ECLASS-VARIABLE: APACHE2_4_DEPEND +# @DESCRIPTION: +# Dependencies for Apache 2.4.x +APACHE2_4_DEPEND="=www-servers/apache-2.4*" + + +# ============================================================================== +# INTERNAL FUNCTIONS +# ============================================================================== + +_init_apache2() { + debug-print-function $FUNCNAME $* + + # WARNING: Do not use these variables with anything that is put + # into the dependency cache (DEPEND/RDEPEND/etc) + APACHE_VERSION="2" + APXS="/usr/bin/apxs" + APACHE_BIN="/usr/sbin/apache2" + APACHE_CTL="/usr/sbin/apache2ctl" + APACHE_INCLUDEDIR="/usr/include/apache2" + APACHE_CONFDIR="/etc/apache2" + APACHE_MODULES_CONFDIR="${APACHE_CONFDIR}/modules.d" + APACHE_VHOSTS_CONFDIR="${APACHE_CONFDIR}/vhosts.d" + + case ${EAPI:-0} in + 0|2|3|4|5) + _init_apache2_late + ;; + esac +} + +_init_apache2_late() { + APACHE_BASEDIR="/usr/$(get_libdir)/apache2" + APACHE_MODULESDIR="${APACHE_BASEDIR}/modules" +} + +_init_no_apache() { + debug-print-function $FUNCNAME $* + APACHE_VERSION="0" +} + +# ============================================================================== +# PUBLIC FUNCTIONS +# ============================================================================== + +# @FUNCTION: depend.apache_pkg_setup +# @USAGE: [myiuse] +# @DESCRIPTION: +# An ebuild calls this in pkg_setup() to initialize variables for optional +# apache-2.x support. If the myiuse parameter is not given it defaults to +# apache2. +depend.apache_pkg_setup() { + debug-print-function $FUNCNAME $* + + if [[ "${EBUILD_PHASE}" != "setup" ]]; then + die "$FUNCNAME() should be called in pkg_setup()" + fi + + local myiuse=${1:-apache2} + + case ${EAPI:-0} in + 0|2|3|4|5) + if has ${myiuse} ${IUSE}; then + if use ${myiuse}; then + _init_apache2 + else + _init_no_apache + fi + fi + ;; + *) + if in_iuse ${myiuse}; then + if use ${myiuse}; then + _init_apache2 + _init_apache2_late + else + _init_no_apache + fi + fi + ;; + esac +} + +# @FUNCTION: want_apache +# @USAGE: [myiuse] +# @DESCRIPTION: +# An ebuild calls this to get the dependency information for optional apache +# support. If the myiuse parameter is not given it defaults to apache2. +# An ebuild should additionally call depend.apache_pkg_setup() in pkg_setup() +# with the same myiuse parameter. +want_apache() { + debug-print-function $FUNCNAME $* + want_apache2 "$@" +} + +# @FUNCTION: want_apache2 +# @USAGE: [myiuse] +# @DESCRIPTION: +# An ebuild calls this to get the dependency information for optional apache-2.x +# support. If the myiuse parameter is not given it defaults to apache2. +# An ebuild should additionally call depend.apache_pkg_setup() in pkg_setup() +# with the same myiuse parameter. +want_apache2() { + debug-print-function $FUNCNAME $* + + local myiuse=${1:-apache2} + IUSE="${IUSE} ${myiuse}" + DEPEND="${DEPEND} ${myiuse}? ( ${APACHE2_DEPEND} )" + RDEPEND="${RDEPEND} ${myiuse}? ( ${APACHE2_DEPEND} )" +} + +# @FUNCTION: want_apache2_2 +# @USAGE: [myiuse] +# @DESCRIPTION: +# An ebuild calls this to get the dependency information for optional +# apache-2.2.x support. If the myiuse parameter is not given it defaults to +# apache2. +# An ebuild should additionally call depend.apache_pkg_setup() in pkg_setup() +# with the same myiuse parameter. +want_apache2_2() { + debug-print-function $FUNCNAME $* + + local myiuse=${1:-apache2} + IUSE="${IUSE} ${myiuse}" + DEPEND="${DEPEND} ${myiuse}? ( ${APACHE2_2_DEPEND} )" + RDEPEND="${RDEPEND} ${myiuse}? ( ${APACHE2_2_DEPEND} )" +} + +# @FUNCTION: want_apache2_4 +# @USAGE: [myiuse] +# @DESCRIPTION: +# An ebuild calls this to get the dependency information for optional +# apache-2.4.x support. If the myiuse parameter is not given it defaults to +# apache2. +# An ebuild should additionally call depend.apache_pkg_setup() in pkg_setup() +# with the same myiuse parameter. +want_apache2_4() { + debug-print-function $FUNCNAME $* + + local myiuse=${1:-apache2} + IUSE="${IUSE} ${myiuse}" + DEPEND="${DEPEND} ${myiuse}? ( ${APACHE2_4_DEPEND} )" + RDEPEND="${RDEPEND} ${myiuse}? ( ${APACHE2_4_DEPEND} )" +} + +# @FUNCTION: need_apache +# @DESCRIPTION: +# An ebuild calls this to get the dependency information for apache. +need_apache() { + debug-print-function $FUNCNAME $* + need_apache2 +} + +# @FUNCTION: need_apache2 +# @DESCRIPTION: +# An ebuild calls this to get the dependency information for apache-2.x. +need_apache2() { + debug-print-function $FUNCNAME $* + + DEPEND="${DEPEND} ${APACHE2_DEPEND}" + RDEPEND="${RDEPEND} ${APACHE2_DEPEND}" + _init_apache2 +} + +# @FUNCTION: need_apache2_2 +# @DESCRIPTION: +# An ebuild calls this to get the dependency information for apache-2.2.x. +need_apache2_2() { + debug-print-function $FUNCNAME $* + + DEPEND="${DEPEND} ${APACHE2_2_DEPEND}" + RDEPEND="${RDEPEND} ${APACHE2_2_DEPEND}" + _init_apache2 +} + +# @FUNCTION: need_apache2_4 +# @DESCRIPTION: +# An ebuild calls this to get the dependency information for apache-2.4.x. +need_apache2_4() { + debug-print-function $FUNCNAME $* + + DEPEND="${DEPEND} ${APACHE2_4_DEPEND}" + RDEPEND="${RDEPEND} ${APACHE2_4_DEPEND}" + _init_apache2 +} + +# @FUNCTION: has_apache +# @DESCRIPTION: +# An ebuild calls this to get runtime variables for an indirect apache +# dependency without USE-flag, in which case want_apache does not work. +# DO NOT call this function in global scope. +has_apache() { + debug-print-function $FUNCNAME $* + + if has_version '>=www-servers/apache-2'; then + _init_apache2 + else + _init_no_apache + fi +} + +# @FUNCTION: has_apache_threads +# @USAGE: [myflag] +# @DESCRIPTION: +# An ebuild calls this to make sure thread-safety is enabled if apache has been +# built with a threaded MPM. If the myflag parameter is not given it defaults to +# threads. +has_apache_threads() { + debug-print-function $FUNCNAME $* + + case ${EAPI:-0} in + 0|1) + die "depend.apache.eclass: has_apache_threads is not supported for EAPI=${EAPI:-0}" + ;; + esac + + if ! has_version 'www-servers/apache[threads]'; then + return + fi + + local myflag="${1:-threads}" + + if ! use ${myflag}; then + echo + eerror "You need to enable USE flag '${myflag}' to build a thread-safe version" + eerror "of ${CATEGORY}/${PN} for use with www-servers/apache" + die "Need missing USE flag '${myflag}'" + fi +} + +# @FUNCTION: has_apache_threads_in +# @USAGE: [myflag] +# @DESCRIPTION: +# An ebuild calls this to make sure thread-safety is enabled in a foreign +# package if apache has been built with a threaded MPM. If the myflag parameter +# is not given it defaults to threads. +has_apache_threads_in() { + debug-print-function $FUNCNAME $* + + case ${EAPI:-0} in + 0|1) + die "depend.apache.eclass: has_apache_threads_in is not supported for EAPI=${EAPI:-0}" + ;; + esac + + if ! has_version 'www-servers/apache[threads]'; then + return + fi + + local myforeign="$1" + local myflag="${2:-threads}" + + if ! has_version "${myforeign}[${myflag}]"; then + echo + eerror "You need to enable USE flag '${myflag}' in ${myforeign} to" + eerror "build a thread-safe version of ${CATEGORY}/${PN} for use" + eerror "with www-servers/apache" + die "Need missing USE flag '${myflag}' in ${myforeign}" + fi +} + +EXPORT_FUNCTIONS pkg_setup diff --git a/eclass/desktop.eclass b/eclass/desktop.eclass new file mode 100644 index 0000000..7d5c0f0 --- /dev/null +++ b/eclass/desktop.eclass @@ -0,0 +1,398 @@ +# Copyright 1999-2020 Gentoo Authors +# Distributed under the terms of the GNU General Public License v2 + +# @ECLASS: desktop.eclass +# @MAINTAINER: +# base-system@gentoo.org +# @BLURB: support for desktop files, menus, and icons + +if [[ -z ${_DESKTOP_ECLASS} ]]; then +_DESKTOP_ECLASS=1 + +# @FUNCTION: make_desktop_entry +# @USAGE: [name] [icon] [type] [fields] +# @DESCRIPTION: +# Make a .desktop file. +# +# @CODE +# binary: what command does the app run with ? +# name: the name that will show up in the menu +# icon: the icon to use in the menu entry +# this can be relative (to /usr/share/pixmaps) or +# a full path to an icon +# type: what kind of application is this? +# for categories: +# https://specifications.freedesktop.org/menu-spec/latest/apa.html +# if unset, function tries to guess from package's category +# fields: extra fields to append to the desktop file; a printf string +# @CODE +make_desktop_entry() { + [[ -z $1 ]] && die "make_desktop_entry: You must specify the executable" + + local exec=${1} + local name=${2:-${PN}} + local icon=${3:-${PN}} + local type=${4} + local fields=${5} + + if [[ -z ${type} ]] ; then + local catmaj=${CATEGORY%%-*} + local catmin=${CATEGORY##*-} + case ${catmaj} in + app) + case ${catmin} in + accessibility) type="Utility;Accessibility";; + admin) type=System;; + antivirus) type=System;; + arch) type="Utility;Archiving";; + backup) type="Utility;Archiving";; + cdr) type="AudioVideo;DiscBurning";; + dicts) type="Office;Dictionary";; + doc) type=Documentation;; + editors) type="Utility;TextEditor";; + emacs) type="Development;TextEditor";; + emulation) type="System;Emulator";; + laptop) type="Settings;HardwareSettings";; + office) type=Office;; + pda) type="Office;PDA";; + vim) type="Development;TextEditor";; + xemacs) type="Development;TextEditor";; + esac + ;; + + dev) + type="Development" + ;; + + games) + case ${catmin} in + action|fps) type=ActionGame;; + arcade) type=ArcadeGame;; + board) type=BoardGame;; + emulation) type=Emulator;; + kids) type=KidsGame;; + puzzle) type=LogicGame;; + roguelike) type=RolePlaying;; + rpg) type=RolePlaying;; + simulation) type=Simulation;; + sports) type=SportsGame;; + strategy) type=StrategyGame;; + esac + type="Game;${type}" + ;; + + gnome) + type="Gnome;GTK" + ;; + + kde) + type="KDE;Qt" + ;; + + mail) + type="Network;Email" + ;; + + media) + case ${catmin} in + gfx) + type=Graphics + ;; + *) + case ${catmin} in + radio) type=Tuner;; + sound) type=Audio;; + tv) type=TV;; + video) type=Video;; + esac + type="AudioVideo;${type}" + ;; + esac + ;; + + net) + case ${catmin} in + dialup) type=Dialup;; + ftp) type=FileTransfer;; + im) type=InstantMessaging;; + irc) type=IRCClient;; + mail) type=Email;; + news) type=News;; + nntp) type=News;; + p2p) type=FileTransfer;; + voip) type=Telephony;; + esac + type="Network;${type}" + ;; + + sci) + case ${catmin} in + astro*) type=Astronomy;; + bio*) type=Biology;; + calc*) type=Calculator;; + chem*) type=Chemistry;; + elec*) type=Electronics;; + geo*) type=Geology;; + math*) type=Math;; + physics) type=Physics;; + visual*) type=DataVisualization;; + esac + type="Education;Science;${type}" + ;; + + sys) + type="System" + ;; + + www) + case ${catmin} in + client) type=WebBrowser;; + esac + type="Network;${type}" + ;; + + *) + type= + ;; + esac + fi + local slot=${SLOT%/*} + if [[ ${slot} == "0" ]] ; then + local desktop_name="${PN}" + else + local desktop_name="${PN}-${slot}" + fi + local desktop="${exec%%[[:space:]]*}" + desktop="${T}/${desktop##*/}-${desktop_name}.desktop" + + # Don't append another ";" when a valid category value is provided. + type=${type%;}${type:+;} + + if [[ -n ${icon} && ${icon} != /* ]] && [[ ${icon} == *.xpm || ${icon} == *.png || ${icon} == *.svg ]]; then + ewarn "As described in the Icon Theme Specification, icon file extensions are not" + ewarn "allowed in .desktop files if the value is not an absolute path." + icon=${icon%.*} + fi + + cat <<-EOF > "${desktop}" || die + [Desktop Entry] + Name=${name} + Type=Application + Comment=${DESCRIPTION} + Exec=${exec} + TryExec=${exec%% *} + Icon=${icon} + Categories=${type} + EOF + + if [[ ${fields:-=} != *=* ]] ; then + # 5th arg used to be value to Path= + ewarn "make_desktop_entry: update your 5th arg to read Path=${fields}" + fields="Path=${fields}" + fi + if [[ -n ${fields} ]]; then + printf '%b\n' "${fields}" >> "${desktop}" || die + fi + + ( + # wrap the env here so that the 'insinto' call + # doesn't corrupt the env of the caller + insopts -m 0644 + insinto /usr/share/applications + doins "${desktop}" + ) || die "installing desktop file failed" +} + +# @FUNCTION: make_session_desktop +# @USAGE: <command> [command args...] +# @DESCRIPTION: +# Make a GDM/KDM Session file. The title is the file to execute to start the +# Window Manager. The command is the name of the Window Manager. +# +# You can set the name of the file via the ${wm} variable. +make_session_desktop() { + [[ -z $1 ]] && eerror "$0: You must specify the title" && return 1 + [[ -z $2 ]] && eerror "$0: You must specify the command" && return 1 + + local title=$1 + local command=$2 + local desktop=${T}/${wm:-${PN}}.desktop + shift 2 + + cat <<-EOF > "${desktop}" || die + [Desktop Entry] + Name=${title} + Comment=This session logs you into ${title} + Exec=${command} $* + TryExec=${command} + Type=XSession + EOF + + ( + # wrap the env here so that the 'insinto' call + # doesn't corrupt the env of the caller + insopts -m 0644 + insinto /usr/share/xsessions + doins "${desktop}" + ) +} + +# @FUNCTION: domenu +# @USAGE: <menus> +# @DESCRIPTION: +# Install the list of .desktop menu files into the appropriate directory +# (/usr/share/applications). +domenu() { + ( + # wrap the env here so that the 'insinto' call + # doesn't corrupt the env of the caller + local i ret=0 + insopts -m 0644 + insinto /usr/share/applications + for i in "$@" ; do + if [[ -d ${i} ]] ; then + doins "${i}"/*.desktop + ((ret|=$?)) + else + doins "${i}" + ((ret|=$?)) + fi + done + exit ${ret} + ) +} + +# @FUNCTION: newmenu +# @USAGE: <menu> <newname> +# @DESCRIPTION: +# Like all other new* functions, install the specified menu as newname. +newmenu() { + ( + # wrap the env here so that the 'insinto' call + # doesn't corrupt the env of the caller + insopts -m 0644 + insinto /usr/share/applications + newins "$@" + ) +} + +# @FUNCTION: _iconins +# @INTERNAL +# @DESCRIPTION: +# function for use in doicon and newicon +_iconins() { + ( + # wrap the env here so that the 'insinto' call + # doesn't corrupt the env of the caller + insopts -m 0644 + local funcname=$1; shift + local size dir + local context=apps + local theme=hicolor + + while [[ $# -gt 0 ]] ; do + case $1 in + -s|--size) + if [[ ${2%%x*}x${2%%x*} == "$2" ]] ; then + size=${2%%x*} + else + size=${2} + fi + case ${size} in + 16|22|24|32|36|48|64|72|96|128|192|256|512) + size=${size}x${size};; + scalable) + ;; + *) + eerror "${size} is an unsupported icon size!" + exit 1;; + esac + shift 2;; + -t|--theme) + theme=${2} + shift 2;; + -c|--context) + context=${2} + shift 2;; + *) + if [[ -z ${size} ]] ; then + insinto /usr/share/pixmaps + else + insinto /usr/share/icons/${theme}/${size}/${context} + fi + + if [[ ${funcname} == doicon ]] ; then + if [[ -f $1 ]] ; then + doins "${1}" + elif [[ -d $1 ]] ; then + shopt -s nullglob + doins "${1}"/*.{png,svg} + shopt -u nullglob + else + eerror "${1} is not a valid file/directory!" + exit 1 + fi + else + break + fi + shift 1;; + esac + done + if [[ ${funcname} == newicon ]] ; then + newins "$@" + fi + ) || die +} + +# @FUNCTION: doicon +# @USAGE: [options] <icons> +# @DESCRIPTION: +# Install icon into the icon directory /usr/share/icons or into +# /usr/share/pixmaps if "--size" is not set. +# This is useful in conjunction with creating desktop/menu files. +# +# @CODE +# options: +# -s, --size +# !!! must specify to install into /usr/share/icons/... !!! +# size of the icon, like 48 or 48x48 +# supported icon sizes are: +# 16 22 24 32 36 48 64 72 96 128 192 256 512 scalable +# -c, --context +# defaults to "apps" +# -t, --theme +# defaults to "hicolor" +# +# icons: list of icons +# +# example 1: doicon foobar.png fuqbar.svg suckbar.png +# results in: insinto /usr/share/pixmaps +# doins foobar.png fuqbar.svg suckbar.png +# +# example 2: doicon -s 48 foobar.png fuqbar.png blobbar.png +# results in: insinto /usr/share/icons/hicolor/48x48/apps +# doins foobar.png fuqbar.png blobbar.png +# @CODE +doicon() { + _iconins ${FUNCNAME} "$@" +} + +# @FUNCTION: newicon +# @USAGE: [options] <icon> <newname> +# @DESCRIPTION: +# Like doicon, install the specified icon as newname. +# +# @CODE +# example 1: newicon foobar.png NEWNAME.png +# results in: insinto /usr/share/pixmaps +# newins foobar.png NEWNAME.png +# +# example 2: newicon -s 48 foobar.png NEWNAME.png +# results in: insinto /usr/share/icons/hicolor/48x48/apps +# newins foobar.png NEWNAME.png +# @CODE +newicon() { + _iconins ${FUNCNAME} "$@" +} + +fi diff --git a/eclass/dist-kernel-utils.eclass b/eclass/dist-kernel-utils.eclass new file mode 100644 index 0000000..9ab65b0 --- /dev/null +++ b/eclass/dist-kernel-utils.eclass @@ -0,0 +1,161 @@ +# Copyright 2020-2021 Gentoo Authors +# Distributed under the terms of the GNU General Public License v2 + +# @ECLASS: dist-kernel-utils.eclass +# @MAINTAINER: +# Distribution Kernel Project <dist-kernel@gentoo.org> +# @AUTHOR: +# Michał Górny <mgorny@gentoo.org> +# @SUPPORTED_EAPIS: 7 +# @BLURB: Utility functions related to Distribution Kernels +# @DESCRIPTION: +# This eclass provides various utility functions related to Distribution +# Kernels. + +if [[ ! ${_DIST_KERNEL_UTILS} ]]; then + +case "${EAPI:-0}" in + 0|1|2|3|4|5|6) + die "Unsupported EAPI=${EAPI:-0} (too old) for ${ECLASS}" + ;; + 7) + ;; + *) + die "Unsupported EAPI=${EAPI} (unknown) for ${ECLASS}" + ;; +esac + +# @FUNCTION: dist-kernel_build_initramfs +# @USAGE: <output> <version> +# @DESCRIPTION: +# Build an initramfs for the kernel. <output> specifies the absolute +# path where initramfs will be created, while <version> specifies +# the kernel version, used to find modules. +# +# Note: while this function uses dracut at the moment, other initramfs +# variants may be supported in the future. +dist-kernel_build_initramfs() { + debug-print-function ${FUNCNAME} "${@}" + + [[ ${#} -eq 2 ]] || die "${FUNCNAME}: invalid arguments" + local output=${1} + local version=${2} + + local rel_image_path=$(dist-kernel_get_image_path) + local image=${output%/*}/${rel_image_path##*/} + + local args=( + --force + # if uefi=yes is used, dracut needs to locate the kernel image + --kernel-image "${image}" + + # positional arguments + "${output}" "${version}" + ) + + ebegin "Building initramfs via dracut" + dracut "${args[@]}" + eend ${?} || die -n "Building initramfs failed" +} + +# @FUNCTION: dist-kernel_get_image_path +# @DESCRIPTION: +# Get relative kernel image path specific to the current ${ARCH}. +dist-kernel_get_image_path() { + case ${ARCH} in + amd64|x86) + echo arch/x86/boot/bzImage + ;; + arm64) + echo arch/arm64/boot/Image.gz + ;; + arm) + echo arch/arm/boot/zImage + ;; + ppc64) + # ./ is required because of ${image_path%/*} + # substitutions in the code + echo ./vmlinux + ;; + *) + die "${FUNCNAME}: unsupported ARCH=${ARCH}" + ;; + esac +} + +# @FUNCTION: dist-kernel_install_kernel +# @USAGE: <version> <image> <system.map> +# @DESCRIPTION: +# Install kernel using installkernel tool. <version> specifies +# the kernel version, <image> full path to the image, <system.map> +# full path to System.map. +dist-kernel_install_kernel() { + debug-print-function ${FUNCNAME} "${@}" + + [[ ${#} -eq 3 ]] || die "${FUNCNAME}: invalid arguments" + local version=${1} + local image=${2} + local map=${3} + + # if dracut is used in uefi=yes mode, initrd will actually + # be a combined kernel+initramfs UEFI executable. we can easily + # recognize it by PE magic (vs cpio for a regular initramfs) + local initrd=${image%/*}/initrd + local magic + [[ -s ${initrd} ]] && read -n 2 magic < "${initrd}" + if [[ ${magic} == MZ ]]; then + einfo "Combined UEFI kernel+initramfs executable found" + # install the combined executable in place of kernel + image=${initrd}.uefi + mv "${initrd}" "${image}" || die + # put an empty file in place of initrd. installing a duplicate + # file would waste disk space, and removing it entirely provokes + # kernel-install to regenerate it via dracut. + > "${initrd}" + fi + + ebegin "Installing the kernel via installkernel" + # note: .config is taken relatively to System.map; + # initrd relatively to bzImage + installkernel "${version}" "${image}" "${map}" + eend ${?} || die -n "Installing the kernel failed" +} + +# @FUNCTION: dist-kernel_reinstall_initramfs +# @USAGE: <kv-dir> <kv-full> +# @DESCRIPTION: +# Rebuild and install initramfs for the specified dist-kernel. +# <kv-dir> is the kernel source directory (${KV_DIR} from linux-info), +# while <kv-full> is the full kernel version (${KV_FULL}). +# The function will determine whether <kernel-dir> is actually +# a dist-kernel, and whether initramfs was used. +# +# This function is to be used in pkg_postinst() of ebuilds installing +# kernel modules that are included in the initramfs. +dist-kernel_reinstall_initramfs() { + debug-print-function ${FUNCNAME} "${@}" + + [[ ${#} -eq 2 ]] || die "${FUNCNAME}: invalid arguments" + local kernel_dir=${1} + local ver=${2} + + local image_path=${kernel_dir}/$(dist-kernel_get_image_path) + local initramfs_path=${image_path%/*}/initrd + if [[ ! -f ${image_path} ]]; then + eerror "Kernel install missing, image not found:" + eerror " ${image_path}" + eerror "Initramfs will not be updated. Please reinstall your kernel." + return + fi + if [[ ! -f ${initramfs_path} ]]; then + einfo "No initramfs found at ${initramfs_path}" + return + fi + + dist-kernel_build_initramfs "${initramfs_path}" "${ver}" + dist-kernel_install_kernel "${ver}" "${image_path}" \ + "${kernel_dir}/System.map" +} + +_DIST_KERNEL_UTILS=1 +fi diff --git a/eclass/distutils-r1.eclass b/eclass/distutils-r1.eclass new file mode 100644 index 0000000..d5bb0df --- /dev/null +++ b/eclass/distutils-r1.eclass @@ -0,0 +1,1222 @@ +# Copyright 1999-2021 Gentoo Authors +# Distributed under the terms of the GNU General Public License v2 + +# @ECLASS: distutils-r1.eclass +# @MAINTAINER: +# Python team <python@gentoo.org> +# @AUTHOR: +# Author: Michał Górny <mgorny@gentoo.org> +# Based on the work of: Krzysztof Pawlik <nelchael@gentoo.org> +# @SUPPORTED_EAPIS: 5 6 7 +# @BLURB: A simple eclass to build Python packages using distutils. +# @DESCRIPTION: +# A simple eclass providing functions to build Python packages using +# the distutils build system. It exports phase functions for all +# the src_* phases. Each of the phases runs two pseudo-phases: +# python_..._all() (e.g. python_prepare_all()) once in ${S}, then +# python_...() (e.g. python_prepare()) for each implementation +# (see: python_foreach_impl() in python-r1). +# +# In distutils-r1_src_prepare(), the 'all' function is run before +# per-implementation ones (because it creates the implementations), +# per-implementation functions are run in a random order. +# +# In remaining phase functions, the per-implementation functions are run +# before the 'all' one, and they are ordered from the least to the most +# preferred implementation (so that 'better' files overwrite 'worse' +# ones). +# +# If the ebuild doesn't specify a particular pseudo-phase function, +# the default one will be used (distutils-r1_...). Defaults are provided +# for all per-implementation pseudo-phases, python_prepare_all() +# and python_install_all(); whenever writing your own pseudo-phase +# functions, you should consider calling the defaults (and especially +# distutils-r1_python_prepare_all). +# +# Please note that distutils-r1 sets RDEPEND and DEPEND unconditionally +# for you. +# +# Also, please note that distutils-r1 will always inherit python-r1 +# as well. Thus, all the variables defined and documented there are +# relevant to the packages using distutils-r1. +# +# For more information, please see the Python Guide: +# https://dev.gentoo.org/~mgorny/python-guide/ + +case "${EAPI:-0}" in + 0|1|2|3|4) + die "Unsupported EAPI=${EAPI:-0} (too old) for ${ECLASS}" + ;; + 5|6|7) + ;; + *) + die "Unsupported EAPI=${EAPI} (unknown) for ${ECLASS}" + ;; +esac + +# @ECLASS-VARIABLE: DISTUTILS_OPTIONAL +# @DEFAULT_UNSET +# @DESCRIPTION: +# If set to a non-null value, distutils part in the ebuild will +# be considered optional. No dependencies will be added and no phase +# functions will be exported. +# +# If you enable DISTUTILS_OPTIONAL, you have to set proper dependencies +# for your package (using ${PYTHON_DEPS}) and to either call +# distutils-r1 default phase functions or call the build system +# manually. + +# @ECLASS-VARIABLE: DISTUTILS_SINGLE_IMPL +# @DEFAULT_UNSET +# @DESCRIPTION: +# If set to a non-null value, the ebuild will support setting a single +# Python implementation only. It will effectively replace the python-r1 +# eclass inherit with python-single-r1. +# +# Note that inheriting python-single-r1 will cause pkg_setup() +# to be exported. It must be run in order for the eclass functions +# to function properly. + +# @ECLASS-VARIABLE: DISTUTILS_USE_SETUPTOOLS +# @PRE_INHERIT +# @DESCRIPTION: +# Controls adding dev-python/setuptools dependency. The allowed values +# are: +# +# - no -- do not add the dependency (pure distutils package) +# - bdepend -- add it to BDEPEND (the default) +# - rdepend -- add it to BDEPEND+RDEPEND (when using entry_points) +# - pyproject.toml -- use pyproject2setuptools to install a project +# using pyproject.toml (flit, poetry...) +# - manual -- do not add the depedency and suppress the checks +# (assumes you will take care of doing it correctly) +# +# This variable is effective only if DISTUTILS_OPTIONAL is disabled. +# It needs to be set before the inherit line. +: ${DISTUTILS_USE_SETUPTOOLS:=bdepend} + +if [[ ! ${_DISTUTILS_R1} ]]; then + +[[ ${EAPI} == [456] ]] && inherit eutils +[[ ${EAPI} == [56] ]] && inherit xdg-utils +inherit multiprocessing toolchain-funcs + +if [[ ! ${DISTUTILS_SINGLE_IMPL} ]]; then + inherit python-r1 +else + inherit python-single-r1 +fi + +fi + +if [[ ! ${DISTUTILS_OPTIONAL} ]]; then + EXPORT_FUNCTIONS src_prepare src_configure src_compile src_test src_install +fi + +if [[ ! ${_DISTUTILS_R1} ]]; then + +_distutils_set_globals() { + local rdep bdep + local setuptools_dep='>=dev-python/setuptools-42.0.2[${PYTHON_USEDEP}]' + + case ${DISTUTILS_USE_SETUPTOOLS} in + no|manual) + ;; + bdepend) + bdep+=" ${setuptools_dep}" + ;; + rdepend) + bdep+=" ${setuptools_dep}" + rdep+=" ${setuptools_dep}" + ;; + pyproject.toml) + bdep+=' dev-python/pyproject2setuppy[${PYTHON_USEDEP}]' + ;; + *) + die "Invalid DISTUTILS_USE_SETUPTOOLS=${DISTUTILS_USE_SETUPTOOLS}" + ;; + esac + + if [[ ! ${DISTUTILS_SINGLE_IMPL} ]]; then + bdep=${bdep//\$\{PYTHON_USEDEP\}/${PYTHON_USEDEP}} + rdep=${rdep//\$\{PYTHON_USEDEP\}/${PYTHON_USEDEP}} + else + [[ -n ${bdep} ]] && bdep="$(python_gen_cond_dep "${bdep}")" + [[ -n ${rdep} ]] && rdep="$(python_gen_cond_dep "${rdep}")" + fi + + RDEPEND="${PYTHON_DEPS} ${rdep}" + if [[ ${EAPI} != [56] ]]; then + BDEPEND="${PYTHON_DEPS} ${bdep}" + else + DEPEND="${PYTHON_DEPS} ${bdep}" + fi + REQUIRED_USE=${PYTHON_REQUIRED_USE} +} +[[ ! ${DISTUTILS_OPTIONAL} ]] && _distutils_set_globals +unset -f _distutils_set_globals + +# @ECLASS-VARIABLE: PATCHES +# @DEFAULT_UNSET +# @DESCRIPTION: +# An array containing patches to be applied to the sources before +# copying them. +# +# If unset, no custom patches will be applied. +# +# Please note, however, that at some point the eclass may apply +# additional distutils patches/quirks independently of this variable. +# +# Example: +# @CODE +# PATCHES=( "${FILESDIR}"/${P}-make-gentoo-happy.patch ) +# @CODE + +# @ECLASS-VARIABLE: DOCS +# @DEFAULT_UNSET +# @DESCRIPTION: +# An array containing documents installed using dodoc. The files listed +# there must exist in the directory from which +# distutils-r1_python_install_all() is run (${S} by default). +# +# If unset, the function will instead look up files matching default +# filename pattern list (from the Package Manager Specification), +# and install those found. +# +# Example: +# @CODE +# DOCS=( NEWS README ) +# @CODE + +# @ECLASS-VARIABLE: HTML_DOCS +# @DEFAULT_UNSET +# @DESCRIPTION: +# An array containing documents installed using dohtml. The files +# and directories listed there must exist in the directory from which +# distutils-r1_python_install_all() is run (${S} by default). +# +# If unset, no HTML docs will be installed. +# +# Example: +# @CODE +# HTML_DOCS=( doc/html/. ) +# @CODE + +# @ECLASS-VARIABLE: EXAMPLES +# @DEFAULT_UNSET +# @DESCRIPTION: +# OBSOLETE: this variable is deprecated and banned in EAPI 6 +# +# An array containing examples installed into 'examples' doc +# subdirectory. The files and directories listed there must exist +# in the directory from which distutils-r1_python_install_all() is run +# (${S} by default). +# +# The 'examples' subdirectory will be marked not to be compressed +# automatically. +# +# If unset, no examples will be installed. +# +# Example: +# @CODE +# EXAMPLES=( examples/. demos/. ) +# @CODE + +# @ECLASS-VARIABLE: DISTUTILS_IN_SOURCE_BUILD +# @DEFAULT_UNSET +# @DESCRIPTION: +# If set to a non-null value, in-source builds will be enabled. +# If unset, the default is to use in-source builds when python_prepare() +# is declared, and out-of-source builds otherwise. +# +# If in-source builds are used, the eclass will create a copy of package +# sources for each Python implementation in python_prepare_all(), +# and work on that copy afterwards. +# +# If out-of-source builds are used, the eclass will instead work +# on the sources directly, prepending setup.py arguments with +# 'build --build-base ${BUILD_DIR}' to enforce keeping & using built +# files in the specific root. + +# @ECLASS-VARIABLE: DISTUTILS_ALL_SUBPHASE_IMPLS +# @DEFAULT_UNSET +# @DESCRIPTION: +# An array of patterns specifying which implementations can be used +# for *_all() sub-phase functions. If undefined, defaults to '*' +# (allowing any implementation). If multiple values are specified, +# implementations matching any of the patterns will be accepted. +# +# The patterns can be either fnmatch-style patterns (matched via bash +# == operator against PYTHON_COMPAT values) or '-2' / '-3' to indicate +# appropriately all enabled Python 2/3 implementations (alike +# python_is_python3). Remember to escape or quote the fnmatch patterns +# to prevent accidental shell filename expansion. +# +# If the restriction needs to apply conditionally to a USE flag, +# the variable should be set conditionally as well (e.g. in an early +# phase function or other convenient location). +# +# Please remember to add a matching || block to REQUIRED_USE, +# to ensure that at least one implementation matching the patterns will +# be enabled. +# +# Example: +# @CODE +# REQUIRED_USE="doc? ( || ( $(python_gen_useflags 'python2*') ) )" +# +# pkg_setup() { +# use doc && DISTUTILS_ALL_SUBPHASE_IMPLS=( 'python2*' ) +# } +# @CODE + +# @ECLASS-VARIABLE: mydistutilsargs +# @DEFAULT_UNSET +# @DESCRIPTION: +# An array containing options to be passed to setup.py. +# +# Example: +# @CODE +# python_configure_all() { +# mydistutilsargs=( --enable-my-hidden-option ) +# } +# @CODE + +# @FUNCTION: distutils_enable_sphinx +# @USAGE: <subdir> [--no-autodoc | <plugin-pkgs>...] +# @DESCRIPTION: +# Set up IUSE, BDEPEND, python_check_deps() and python_compile_all() for +# building HTML docs via dev-python/sphinx. python_compile_all() will +# append to HTML_DOCS if docs are enabled. +# +# This helper is meant for the most common case, that is a single Sphinx +# subdirectory with standard layout, building and installing HTML docs +# behind USE=doc. It assumes it's the only consumer of the three +# aforementioned functions. If you need to use a custom implemention, +# you can't use it. +# +# If your package uses additional Sphinx plugins, they should be passed +# (without PYTHON_USEDEP) as <plugin-pkgs>. The function will take care +# of setting appropriate any-of dep and python_check_deps(). +# +# If no plugin packages are specified, the eclass will still utilize +# any-r1 API to support autodoc (documenting source code). +# If the package uses neither autodoc nor additional plugins, you should +# pass --no-autodoc to disable this API and simplify the resulting code. +# +# This function must be called in global scope. Take care not to +# overwrite the variables set by it. If you need to extend +# python_compile_all(), you can call the original implementation +# as sphinx_compile_all. +distutils_enable_sphinx() { + debug-print-function ${FUNCNAME} "${@}" + [[ ${#} -ge 1 ]] || die "${FUNCNAME} takes at least one arg: <subdir>" + + _DISTUTILS_SPHINX_SUBDIR=${1} + shift + _DISTUTILS_SPHINX_PLUGINS=( "${@}" ) + + local deps autodoc=1 d + deps="dev-python/sphinx[\${PYTHON_USEDEP}]" + for d; do + if [[ ${d} == --no-autodoc ]]; then + autodoc= + else + deps+=" + ${d}[\${PYTHON_USEDEP}]" + if [[ ! ${autodoc} ]]; then + die "${FUNCNAME}: do not pass --no-autodoc if external plugins are used" + fi + fi + done + + if [[ ${autodoc} ]]; then + if [[ ${DISTUTILS_SINGLE_IMPL} ]]; then + deps="$(python_gen_cond_dep "${deps}")" + else + deps="$(python_gen_any_dep "${deps}")" + fi + + python_check_deps() { + use doc || return 0 + local p + for p in dev-python/sphinx "${_DISTUTILS_SPHINX_PLUGINS[@]}"; do + has_version "${p}[${PYTHON_USEDEP}]" || return 1 + done + } + else + deps="dev-python/sphinx" + fi + + sphinx_compile_all() { + use doc || return + + local confpy=${_DISTUTILS_SPHINX_SUBDIR}/conf.py + [[ -f ${confpy} ]] || + die "${confpy} not found, distutils_enable_sphinx call wrong" + + if [[ ${_DISTUTILS_SPHINX_PLUGINS[0]} == --no-autodoc ]]; then + if grep -F -q 'sphinx.ext.autodoc' "${confpy}"; then + die "distutils_enable_sphinx: --no-autodoc passed but sphinx.ext.autodoc found in ${confpy}" + fi + elif [[ -z ${_DISTUTILS_SPHINX_PLUGINS[@]} ]]; then + if ! grep -F -q 'sphinx.ext.autodoc' "${confpy}"; then + die "distutils_enable_sphinx: sphinx.ext.autodoc not found in ${confpy}, pass --no-autodoc" + fi + fi + + build_sphinx "${_DISTUTILS_SPHINX_SUBDIR}" + } + python_compile_all() { sphinx_compile_all; } + + IUSE+=" doc" + if [[ ${EAPI} == [56] ]]; then + DEPEND+=" doc? ( ${deps} )" + else + BDEPEND+=" doc? ( ${deps} )" + fi + + # we need to ensure successful return in case we're called last, + # otherwise Portage may wrongly assume sourcing failed + return 0 +} + +# @FUNCTION: distutils_enable_tests +# @USAGE: [--install] <test-runner> +# @DESCRIPTION: +# Set up IUSE, RESTRICT, BDEPEND and python_test() for running tests +# with the specified test runner. Also copies the current value +# of RDEPEND to test?-BDEPEND. The test-runner argument must be one of: +# +# - nose: nosetests (dev-python/nose) +# - pytest: dev-python/pytest +# - setup.py: setup.py test (no deps included) +# - unittest: for built-in Python unittest module +# +# Additionally, if --install is passed as the first parameter, +# 'distutils_install_for_testing --via-root' is called before running +# the test suite. +# +# This function is meant as a helper for common use cases, and it only +# takes care of basic setup. You still need to list additional test +# dependencies manually. If you have uncommon use case, you should +# not use it and instead enable tests manually. +# +# This function must be called in global scope, after RDEPEND has been +# declared. Take care not to overwrite the variables set by it. +distutils_enable_tests() { + debug-print-function ${FUNCNAME} "${@}" + + local do_install= + case ${1} in + --install) + do_install=1 + shift + ;; + esac + + [[ ${#} -eq 1 ]] || die "${FUNCNAME} takes exactly one argument: test-runner" + local test_pkg + case ${1} in + nose) + test_pkg=">=dev-python/nose-1.3.7-r4" + if [[ ${do_install} ]]; then + python_test() { + distutils_install_for_testing --via-root + nosetests -v || die "Tests fail with ${EPYTHON}" + } + else + python_test() { + nosetests -v || die "Tests fail with ${EPYTHON}" + } + fi + ;; + pytest) + test_pkg=">=dev-python/pytest-4.5.0" + if [[ ${do_install} ]]; then + python_test() { + distutils_install_for_testing --via-root + pytest -vv || die "Tests fail with ${EPYTHON}" + } + else + python_test() { + pytest -vv || die "Tests fail with ${EPYTHON}" + } + fi + ;; + setup.py) + if [[ ${do_install} ]]; then + python_test() { + distutils_install_for_testing --via-root + nonfatal esetup.py test --verbose || + die "Tests fail with ${EPYTHON}" + } + else + python_test() { + nonfatal esetup.py test --verbose || + die "Tests fail with ${EPYTHON}" + } + fi + ;; + unittest) + if [[ ${do_install} ]]; then + python_test() { + distutils_install_for_testing --via-root + "${EPYTHON}" -m unittest discover -v || + die "Tests fail with ${EPYTHON}" + } + else + python_test() { + "${EPYTHON}" -m unittest discover -v || + die "Tests fail with ${EPYTHON}" + } + fi + ;; + *) + die "${FUNCNAME}: unsupported argument: ${1}" + esac + + local test_deps=${RDEPEND} + if [[ -n ${test_pkg} ]]; then + if [[ ! ${DISTUTILS_SINGLE_IMPL} ]]; then + test_deps+=" ${test_pkg}[${PYTHON_USEDEP}]" + else + test_deps+=" $(python_gen_cond_dep " + ${test_pkg}[\${PYTHON_MULTI_USEDEP}] + ")" + fi + fi + if [[ -n ${test_deps} ]]; then + IUSE+=" test" + RESTRICT+=" !test? ( test )" + if [[ ${EAPI} == [56] ]]; then + DEPEND+=" test? ( ${test_deps} )" + else + BDEPEND+=" test? ( ${test_deps} )" + fi + fi + + # we need to ensure successful return in case we're called last, + # otherwise Portage may wrongly assume sourcing failed + return 0 +} + +# @FUNCTION: esetup.py +# @USAGE: [<args>...] +# @DESCRIPTION: +# Run setup.py using currently selected Python interpreter +# (if ${EPYTHON} is set; fallback 'python' otherwise). +# +# setup.py will be passed the following, in order: +# 1. ${mydistutilsargs[@]} +# 2. additional arguments passed to the esetup.py function. +# +# Please note that setup.py will respect defaults (unless overridden +# via command-line options) from setup.cfg that is created +# in distutils-r1_python_compile and in distutils-r1_python_install. +# +# This command dies on failure. +esetup.py() { + debug-print-function ${FUNCNAME} "${@}" + + local die_args=() + [[ ${EAPI} != [45] ]] && die_args+=( -n ) + + [[ ${BUILD_DIR} ]] && _distutils-r1_create_setup_cfg + + set -- "${EPYTHON:-python}" setup.py "${mydistutilsargs[@]}" "${@}" + + echo "${@}" >&2 + "${@}" || die "${die_args[@]}" + local ret=${?} + + if [[ ${BUILD_DIR} ]]; then + rm "${HOME}"/.pydistutils.cfg || die "${die_args[@]}" + fi + + return ${ret} +} + +# @FUNCTION: distutils_install_for_testing +# @USAGE: [--via-root|--via-home] [<args>...] +# @DESCRIPTION: +# Install the package into a temporary location for running tests. +# Update PYTHONPATH appropriately and set TEST_DIR to the test +# installation root. The Python packages will be installed in 'lib' +# subdir, and scripts in 'scripts' subdir (like in BUILD_DIR). +# +# Please note that this function should be only used if package uses +# namespaces (and therefore proper install needs to be done to enforce +# PYTHONPATH) or tests rely on the results of install command. +# For most of the packages, tests built in BUILD_DIR are good enough. +# +# The function supports two install modes. The current default is +# --via-root mode. Previously, the function defaulted to --via-home +# mode but it has been broken by new versions of setuptools (50.3.0+). +# If you find that --via-root does not work but --via-home does, please +# file a bug to let us know. Please note that proper testing sometimes +# requires unmerging the package first. +distutils_install_for_testing() { + debug-print-function ${FUNCNAME} "${@}" + + # A few notes: + # 1) because of namespaces, we can't use 'install --root' + # (NB: this is probably no longer true with py3), + # 2) 'install --home' is terribly broken on pypy, so we need + # to override --install-lib and --install-scripts, + # 3) non-root 'install' complains about PYTHONPATH and missing dirs, + # so we need to set it properly and mkdir them, + # 4) it runs a bunch of commands which write random files to cwd, + # in order to avoid that, we add the necessary path overrides + # in _distutils-r1_create_setup_cfg. + + TEST_DIR=${BUILD_DIR}/test + local bindir=${TEST_DIR}/scripts + local libdir=${TEST_DIR}/lib + PATH=${bindir}:${PATH} + PYTHONPATH=${libdir}:${PYTHONPATH} + + local install_method=root + case ${1} in + --via-home) + install_method=home + shift + ;; + --via-root) + install_method=root + shift + ;; + esac + + local -a add_args + case ${install_method} in + home) + add_args=( + install + --home="${TEST_DIR}" + --install-lib="${libdir}" + --install-scripts="${bindir}" + ) + mkdir -p "${libdir}" || die + ;; + root) + add_args=( + install + --root="${TEST_DIR}" + --install-lib=lib + --install-scripts=scripts + ) + ;; + esac + + esetup.py "${add_args[@]}" "${@}" +} + +# @FUNCTION: _distutils-r1_disable_ez_setup +# @INTERNAL +# @DESCRIPTION: +# Stub out ez_setup.py and distribute_setup.py to prevent packages +# from trying to download a local copy of setuptools. +_distutils-r1_disable_ez_setup() { + local stub="def use_setuptools(*args, **kwargs): pass" + if [[ -f ez_setup.py ]]; then + echo "${stub}" > ez_setup.py || die + fi + if [[ -f distribute_setup.py ]]; then + echo "${stub}" > distribute_setup.py || die + fi +} + +# @FUNCTION: _distutils-r1_handle_pyproject_toml +# @INTERNAL +# @DESCRIPTION: +# Generate setup.py for pyproject.toml if requested. +_distutils-r1_handle_pyproject_toml() { + if [[ ! -f setup.py && -f pyproject.toml ]]; then + if [[ ${DISTUTILS_USE_SETUPTOOLS} == pyproject.toml ]]; then + cat > setup.py <<-EOF || die + #!/usr/bin/env python + from pyproject2setuppy.main import main + main() + EOF + chmod +x setup.py || die + else + eerror "No setup.py found but pyproject.toml is present. In order to enable" + eerror "pyproject.toml support in distutils-r1, set:" + eerror " DISTUTILS_USE_SETUPTOOLS=pyproject.toml" + die "No setup.py found and DISTUTILS_USE_SETUPTOOLS!=pyproject.toml" + fi + fi +} + +# @FUNCTION: distutils-r1_python_prepare_all +# @DESCRIPTION: +# The default python_prepare_all(). It applies the patches from PATCHES +# array, then user patches and finally calls python_copy_sources to +# create copies of resulting sources for each Python implementation. +# +# At some point in the future, it may also apply eclass-specific +# distutils patches and/or quirks. +distutils-r1_python_prepare_all() { + debug-print-function ${FUNCNAME} "${@}" + + if [[ ! ${DISTUTILS_OPTIONAL} ]]; then + if [[ ${EAPI} != [45] ]]; then + default + else + [[ ${PATCHES} ]] && epatch "${PATCHES[@]}" + epatch_user + fi + fi + + # by default, use in-source build if python_prepare() is used + if [[ ! ${DISTUTILS_IN_SOURCE_BUILD+1} ]]; then + if declare -f python_prepare >/dev/null; then + DISTUTILS_IN_SOURCE_BUILD=1 + fi + fi + + _distutils-r1_disable_ez_setup + _distutils-r1_handle_pyproject_toml + + if [[ ${DISTUTILS_IN_SOURCE_BUILD} && ! ${DISTUTILS_SINGLE_IMPL} ]] + then + # create source copies for each implementation + python_copy_sources + fi + + _DISTUTILS_DEFAULT_CALLED=1 +} + +# @FUNCTION: distutils-r1_python_prepare +# @DESCRIPTION: +# The default python_prepare(). A no-op. +distutils-r1_python_prepare() { + debug-print-function ${FUNCNAME} "${@}" + + [[ ${EAPI} == [45] ]] || die "${FUNCNAME} is banned in EAPI 6 (it was a no-op)" +} + +# @FUNCTION: distutils-r1_python_configure +# @DESCRIPTION: +# The default python_configure(). A no-op. +distutils-r1_python_configure() { + debug-print-function ${FUNCNAME} "${@}" + + [[ ${EAPI} == [45] ]] || die "${FUNCNAME} is banned in EAPI 6 (it was a no-op)" +} + +# @FUNCTION: _distutils-r1_create_setup_cfg +# @INTERNAL +# @DESCRIPTION: +# Create implementation-specific configuration file for distutils, +# setting proper build-dir (and install-dir) paths. +_distutils-r1_create_setup_cfg() { + cat > "${HOME}"/.pydistutils.cfg <<-_EOF_ || die + [build] + build-base = ${BUILD_DIR} + + # using a single directory for them helps us export + # ${PYTHONPATH} and ebuilds find the sources independently + # of whether the package installs extensions or not + # + # note: due to some packages (wxpython) relying on separate + # platlib & purelib dirs, we do not set --build-lib (which + # can not be overridden with --build-*lib) + build-platlib = %(build-base)s/lib + build-purelib = %(build-base)s/lib + + # make the ebuild writer lives easier + build-scripts = %(build-base)s/scripts + + # this is needed by distutils_install_for_testing since + # setuptools like to create .egg files for install --home. + [bdist_egg] + dist-dir = ${BUILD_DIR}/dist + _EOF_ + + # we can't refer to ${D} before src_install() + if [[ ${EBUILD_PHASE} == install ]]; then + cat >> "${HOME}"/.pydistutils.cfg <<-_EOF_ || die + + # installation paths -- allow calling extra install targets + # without the default 'install' + [install] + compile = True + optimize = 2 + root = ${D%/} + _EOF_ + + if [[ ! ${DISTUTILS_SINGLE_IMPL} ]]; then + cat >> "${HOME}"/.pydistutils.cfg <<-_EOF_ || die + install-scripts = $(python_get_scriptdir) + _EOF_ + fi + fi +} + +# @FUNCTION: _distutils-r1_copy_egg_info +# @INTERNAL +# @DESCRIPTION: +# Copy egg-info files to the ${BUILD_DIR} (that's going to become +# egg-base in esetup.py). This way, we respect whatever's in upstream +# egg-info. +_distutils-r1_copy_egg_info() { + mkdir -p "${BUILD_DIR}" || die + # stupid freebsd can't do 'cp -t ${BUILD_DIR} {} +' + find -name '*.egg-info' -type d -exec cp -R -p {} "${BUILD_DIR}"/ ';' || die +} + +# @FUNCTION: distutils-r1_python_compile +# @USAGE: [additional-args...] +# @DESCRIPTION: +# The default python_compile(). Runs 'esetup.py build'. Any parameters +# passed to this function will be appended to setup.py invocation, +# i.e. passed as options to the 'build' command. +# +# This phase also sets up initial setup.cfg with build directories +# and copies upstream egg-info files if supplied. +distutils-r1_python_compile() { + debug-print-function ${FUNCNAME} "${@}" + + _distutils-r1_copy_egg_info + + # distutils is parallel-capable since py3.5 + local jobs=$(makeopts_jobs "${MAKEOPTS}" INF) + if [[ ${jobs} == INF ]]; then + local nproc=$(get_nproc) + jobs=$(( nproc + 1 )) + fi + + esetup.py build -j "${jobs}" "${@}" +} + +# @FUNCTION: _distutils-r1_wrap_scripts +# @USAGE: <path> <bindir> +# @INTERNAL +# @DESCRIPTION: +# Moves and wraps all installed scripts/executables as necessary. +_distutils-r1_wrap_scripts() { + debug-print-function ${FUNCNAME} "${@}" + + [[ ${#} -eq 2 ]] || die "usage: ${FUNCNAME} <path> <bindir>" + local path=${1} + local bindir=${2} + + local scriptdir=$(python_get_scriptdir) + local f python_files=() non_python_files=() + + if [[ -d ${path}${scriptdir} ]]; then + for f in "${path}${scriptdir}"/*; do + [[ -d ${f} ]] && die "Unexpected directory: ${f}" + debug-print "${FUNCNAME}: found executable at ${f#${path}/}" + + local shebang + read -r shebang < "${f}" + if [[ ${shebang} == '#!'*${EPYTHON}* ]]; then + debug-print "${FUNCNAME}: matching shebang: ${shebang}" + python_files+=( "${f}" ) + else + debug-print "${FUNCNAME}: non-matching shebang: ${shebang}" + non_python_files+=( "${f}" ) + fi + + mkdir -p "${path}${bindir}" || die + done + + for f in "${python_files[@]}"; do + local basename=${f##*/} + + debug-print "${FUNCNAME}: installing wrapper at ${bindir}/${basename}" + _python_ln_rel "${path}${EPREFIX}"/usr/lib/python-exec/python-exec2 \ + "${path}${bindir}/${basename}" || die + done + + for f in "${non_python_files[@]}"; do + local basename=${f##*/} + + debug-print "${FUNCNAME}: moving ${f#${path}/} to ${bindir}/${basename}" + mv "${f}" "${path}${bindir}/${basename}" || die + done + fi +} + +# @FUNCTION: distutils-r1_python_install +# @USAGE: [additional-args...] +# @DESCRIPTION: +# The default python_install(). Runs 'esetup.py install', doing +# intermediate root install and handling script wrapping afterwards. +# Any parameters passed to this function will be appended +# to the setup.py invocation (i.e. as options to the 'install' command). +# +# This phase updates the setup.cfg file with install directories. +distutils-r1_python_install() { + debug-print-function ${FUNCNAME} "${@}" + + local args=( "${@}" ) + + # enable compilation for the install phase. + local -x PYTHONDONTWRITEBYTECODE= + + # python likes to compile any module it sees, which triggers sandbox + # failures if some packages haven't compiled their modules yet. + addpredict "${EPREFIX}/usr/lib/${EPYTHON}" + addpredict /usr/lib/pypy3.6 + addpredict /usr/lib/pypy3.7 + addpredict /usr/lib/portage/pym + addpredict /usr/local # bug 498232 + + if [[ ! ${DISTUTILS_SINGLE_IMPL} ]]; then + # user may override --install-scripts + # note: this is poor but distutils argv parsing is dumb + local mydistutilsargs=( "${mydistutilsargs[@]}" ) + local scriptdir=${EPREFIX}/usr/bin + + # construct a list of mydistutilsargs[0] args[0] args[1]... + local arg arg_vars + [[ ${mydistutilsargs[@]} ]] && eval arg_vars+=( + 'mydistutilsargs['{0..$(( ${#mydistutilsargs[@]} - 1 ))}']' + ) + [[ ${args[@]} ]] && eval arg_vars+=( + 'args['{0..$(( ${#args[@]} - 1 ))}']' + ) + + set -- "${arg_vars[@]}" + while [[ ${@} ]]; do + local arg_var=${1} + shift + local a=${!arg_var} + + case "${a}" in + --install-scripts=*) + scriptdir=${a#--install-scripts=} + unset "${arg_var}" + ;; + --install-scripts) + scriptdir=${!1} + unset "${arg_var}" "${1}" + shift + ;; + esac + done + fi + + local root=${D%/}/_${EPYTHON} + [[ ${DISTUTILS_SINGLE_IMPL} ]] && root=${D%/} + + esetup.py install --skip-build --root="${root}" "${args[@]}" + + local forbidden_package_names=( examples test tests .pytest_cache ) + local p + for p in "${forbidden_package_names[@]}"; do + if [[ -d ${root}$(python_get_sitedir)/${p} ]]; then + die "Package installs '${p}' package which is forbidden and likely a bug in the build system." + fi + done + + local shopt_save=$(shopt -p nullglob) + shopt -s nullglob + local pypy_dirs=( + "${root}/usr/$(get_libdir)"/pypy*/share + "${root}/usr/lib"/pypy*/share + ) + ${shopt_save} + + if [[ -n ${pypy_dirs} ]]; then + die "Package installs 'share' in PyPy prefix, see bug #465546." + fi + + if [[ ! ${DISTUTILS_SINGLE_IMPL} ]]; then + _distutils-r1_wrap_scripts "${root}" "${scriptdir}" + multibuild_merge_root "${root}" "${D%/}" + fi +} + +# @FUNCTION: distutils-r1_python_install_all +# @DESCRIPTION: +# The default python_install_all(). It installs the documentation. +distutils-r1_python_install_all() { + debug-print-function ${FUNCNAME} "${@}" + + einstalldocs + + if declare -p EXAMPLES &>/dev/null; then + [[ ${EAPI} != [45] ]] && die "EXAMPLES are banned in EAPI ${EAPI}" + + ( + docinto examples + dodoc -r "${EXAMPLES[@]}" + ) + docompress -x "/usr/share/doc/${PF}/examples" + fi +} + +# @FUNCTION: distutils-r1_run_phase +# @USAGE: [<argv>...] +# @INTERNAL +# @DESCRIPTION: +# Run the given command. +# +# If out-of-source builds are used, the phase function is run in source +# directory, with BUILD_DIR pointing at the build directory +# and PYTHONPATH having an entry for the module build directory. +# +# If in-source builds are used, the command is executed in the directory +# holding the per-implementation copy of sources. BUILD_DIR points +# to the 'build' subdirectory. +distutils-r1_run_phase() { + debug-print-function ${FUNCNAME} "${@}" + + if [[ ${DISTUTILS_IN_SOURCE_BUILD} ]]; then + # only force BUILD_DIR if implementation is explicitly enabled + # for building; any-r1 API may select one that is not + # https://bugs.gentoo.org/701506 + if [[ ! ${DISTUTILS_SINGLE_IMPL} ]] && + has "${EPYTHON/./_}" ${PYTHON_TARGETS}; then + cd "${BUILD_DIR}" || die + fi + local BUILD_DIR=${BUILD_DIR}/build + fi + local -x PYTHONPATH="${BUILD_DIR}/lib:${PYTHONPATH}" + + # make PATH local for distutils_install_for_testing calls + # it makes little sense to let user modify PATH in per-impl phases + # and _all() already localizes it + local -x PATH=${PATH} + + # Bug 559644 + # using PYTHONPATH when the ${BUILD_DIR}/lib is not created yet might lead to + # problems in setup.py scripts that try to import modules/packages from that path + # during the build process (Python at startup evaluates PYTHONPATH, if the dir is + # not valid then associates a NullImporter object to ${BUILD_DIR}/lib storing it + # in the sys.path_importer_cache) + mkdir -p "${BUILD_DIR}/lib" || die + + # Set up build environment, bug #513664. + local -x AR=${AR} CC=${CC} CPP=${CPP} CXX=${CXX} + tc-export AR CC CPP CXX + + # How to build Python modules in different worlds... + local ldopts + case "${CHOST}" in + # provided by haubi, 2014-07-08 + *-aix*) ldopts='-shared -Wl,-berok';; # good enough + # provided by grobian, 2014-06-22, bug #513664 c7 + *-darwin*) ldopts='-bundle -undefined dynamic_lookup';; + *) ldopts='-shared';; + esac + + local -x LDSHARED="${CC} ${ldopts}" LDCXXSHARED="${CXX} ${ldopts}" + + "${@}" + + cd "${_DISTUTILS_INITIAL_CWD}" || die +} + +# @FUNCTION: _distutils-r1_run_common_phase +# @USAGE: [<argv>...] +# @INTERNAL +# @DESCRIPTION: +# Run the given command, restoring the state for a most preferred Python +# implementation matching DISTUTILS_ALL_SUBPHASE_IMPLS. +# +# If in-source build is used, the command will be run in the copy +# of sources made for the selected Python interpreter. +_distutils-r1_run_common_phase() { + local DISTUTILS_ORIG_BUILD_DIR=${BUILD_DIR} + + if [[ ${DISTUTILS_SINGLE_IMPL} ]]; then + # reuse the dedicated code branch + _distutils-r1_run_foreach_impl "${@}" + else + local -x EPYTHON PYTHON + local -x PATH=${PATH} PKG_CONFIG_PATH=${PKG_CONFIG_PATH} + python_setup "${DISTUTILS_ALL_SUBPHASE_IMPLS[@]}" + + local MULTIBUILD_VARIANTS=( "${EPYTHON/./_}" ) + # store for restoring after distutils-r1_run_phase. + local _DISTUTILS_INITIAL_CWD=${PWD} + multibuild_foreach_variant \ + distutils-r1_run_phase "${@}" + fi +} + +# @FUNCTION: _distutils-r1_run_foreach_impl +# @INTERNAL +# @DESCRIPTION: +# Run the given phase for each implementation if multiple implementations +# are enabled, once otherwise. +_distutils-r1_run_foreach_impl() { + debug-print-function ${FUNCNAME} "${@}" + + # store for restoring after distutils-r1_run_phase. + local _DISTUTILS_INITIAL_CWD=${PWD} + set -- distutils-r1_run_phase "${@}" + + if [[ ! ${DISTUTILS_SINGLE_IMPL} ]]; then + python_foreach_impl "${@}" + else + if [[ ! ${EPYTHON} ]]; then + die "EPYTHON unset, python-single-r1_pkg_setup not called?!" + fi + local BUILD_DIR=${BUILD_DIR:-${S}} + BUILD_DIR=${BUILD_DIR%%/}_${EPYTHON} + + "${@}" + fi +} + +distutils-r1_src_prepare() { + debug-print-function ${FUNCNAME} "${@}" + + local _DISTUTILS_DEFAULT_CALLED + + # common preparations + if declare -f python_prepare_all >/dev/null; then + python_prepare_all + else + distutils-r1_python_prepare_all + fi + + if [[ ! ${_DISTUTILS_DEFAULT_CALLED} ]]; then + local cmd=die + [[ ${EAPI} == [45] ]] && cmd=eqawarn + + "${cmd}" "QA: python_prepare_all() didn't call distutils-r1_python_prepare_all" + fi + + if declare -f python_prepare >/dev/null; then + _distutils-r1_run_foreach_impl python_prepare + fi +} + +distutils-r1_src_configure() { + python_export_utf8_locale + [[ ${EAPI} == [56] ]] && xdg_environment_reset # Bug 577704 + + if declare -f python_configure >/dev/null; then + _distutils-r1_run_foreach_impl python_configure + fi + + if declare -f python_configure_all >/dev/null; then + _distutils-r1_run_common_phase python_configure_all + fi +} + +distutils-r1_src_compile() { + debug-print-function ${FUNCNAME} "${@}" + + if declare -f python_compile >/dev/null; then + _distutils-r1_run_foreach_impl python_compile + else + _distutils-r1_run_foreach_impl distutils-r1_python_compile + fi + + if declare -f python_compile_all >/dev/null; then + _distutils-r1_run_common_phase python_compile_all + fi +} + +# @FUNCTION: _distutils-r1_clean_egg_info +# @INTERNAL +# @DESCRIPTION: +# Clean up potential stray egg-info files left by setuptools test phase. +# Those files ended up being unversioned, and caused issues: +# https://bugs.gentoo.org/534058 +_distutils-r1_clean_egg_info() { + rm -rf "${BUILD_DIR}"/lib/*.egg-info || die +} + +distutils-r1_src_test() { + debug-print-function ${FUNCNAME} "${@}" + + if declare -f python_test >/dev/null; then + _distutils-r1_run_foreach_impl python_test + _distutils-r1_run_foreach_impl _distutils-r1_clean_egg_info + fi + + if declare -f python_test_all >/dev/null; then + _distutils-r1_run_common_phase python_test_all + fi +} + +# @FUNCTION: _distutils-r1_check_namespace_pth +# @INTERNAL +# @DESCRIPTION: +# Check if any *-nspkg.pth files were installed (by setuptools) +# and warn about the policy non-conformance if they were. +_distutils-r1_check_namespace_pth() { + local f pth=() + + while IFS= read -r -d '' f; do + pth+=( "${f}" ) + done < <(find "${ED%/}" -name '*-nspkg.pth' -print0) + + if [[ ${pth[@]} ]]; then + ewarn "The following *-nspkg.pth files were found installed:" + ewarn + for f in "${pth[@]}"; do + ewarn " ${f#${ED%/}}" + done + ewarn + ewarn "The presence of those files may break namespaces in Python 3.5+. Please" + ewarn "read our documentation on reliable handling of namespaces and update" + ewarn "the ebuild accordingly:" + ewarn + ewarn " https://wiki.gentoo.org/wiki/Project:Python/Namespace_packages" + fi +} + +distutils-r1_src_install() { + debug-print-function ${FUNCNAME} "${@}" + + if declare -f python_install >/dev/null; then + _distutils-r1_run_foreach_impl python_install + else + _distutils-r1_run_foreach_impl distutils-r1_python_install + fi + + if declare -f python_install_all >/dev/null; then + _distutils-r1_run_common_phase python_install_all + else + _distutils-r1_run_common_phase distutils-r1_python_install_all + fi + + _distutils-r1_check_namespace_pth +} + +# -- distutils.eclass functions -- + +distutils_get_intermediate_installation_image() { + die "${FUNCNAME}() is invalid for distutils-r1" +} + +distutils_src_unpack() { + die "${FUNCNAME}() is invalid for distutils-r1, and you don't want it in EAPI ${EAPI} anyway" +} + +distutils_src_prepare() { + die "${FUNCNAME}() is invalid for distutils-r1, you probably want: ${FUNCNAME/_/-r1_}" +} + +distutils_src_compile() { + die "${FUNCNAME}() is invalid for distutils-r1, you probably want: ${FUNCNAME/_/-r1_}" +} + +distutils_src_test() { + die "${FUNCNAME}() is invalid for distutils-r1, you probably want: ${FUNCNAME/_/-r1_}" +} + +distutils_src_install() { + die "${FUNCNAME}() is invalid for distutils-r1, you probably want: ${FUNCNAME/_/-r1_}" +} + +distutils_pkg_postinst() { + die "${FUNCNAME}() is invalid for distutils-r1, and pkg_postinst is unnecessary" +} + +distutils_pkg_postrm() { + die "${FUNCNAME}() is invalid for distutils-r1, and pkg_postrm is unnecessary" +} + +_DISTUTILS_R1=1 +fi diff --git a/eclass/docs.eclass b/eclass/docs.eclass new file mode 100644 index 0000000..b67b268 --- /dev/null +++ b/eclass/docs.eclass @@ -0,0 +1,396 @@ +# Copyright 1999-2021 Gentoo Authors +# Distributed under the terms of the GNU General Public License v2 + +# @ECLASS: docs.eclass +# @MAINTAINER: +# Andrew Ammerlaan <andrewammerlaan@riseup.net> +# @AUTHOR: +# Author: Andrew Ammerlaan <andrewammerlaan@riseup.net> +# Based on the work of: Michał Górny <mgorny@gentoo.org> +# @SUPPORTED_EAPIS: 6 7 +# @BLURB: A simple eclass to build documentation. +# @DESCRIPTION: +# A simple eclass providing basic functions and variables to build +# documentation. +# +# Please note that this eclass appends to RDEPEND and DEPEND +# unconditionally for you. +# +# This eclass also appends "doc" to IUSE, and sets HTML_DOCS +# to the location of the compiled documentation automatically, +# 'einstalldocs' will then automatically install the documentation +# to the correct directory. +# +# The aim of this eclass is to make it easy to add additional +# doc builders. To do this, add a <DOCS_BUILDER>_deps and +# <DOCS_BUILDER>_compile function for your doc builder. +# For python based doc builders you can use the +# python_append_deps function to append [${PYTHON_USEDEP}] +# automatically to additional dependencies. +# +# Example use doxygen: +# @CODE +# DOCS_BUILDER="doxygen" +# DOCS_DEPEND="media-gfx/imagemagick" +# DOCS_DIR="docs" +# +# inherit docs +# +# ... +# +# src_compile() { +# default +# docs_compile +# } +# @CODE +# +# Example use mkdocs with distutils-r1: +# @CODE +# DOCS_BUILDER="mkdocs" +# DOCS_DEPEND="dev-python/mkdocs-material" +# DOCS_DIR="doc" +# +# PYTHON_COMPAT=( python3_{7,8,9} ) +# +# inherit distutils-r1 docs +# +# ... +# @CODE + +case "${EAPI:-0}" in + 0|1|2|3|4|5) + die "Unsupported EAPI=${EAPI:-0} (too old) for ${ECLASS}" + ;; + 6|7) + ;; + *) + die "Unsupported EAPI=${EAPI} (unknown) for ${ECLASS}" + ;; +esac + +# @ECLASS-VARIABLE: DOCS_BUILDER +# @REQUIRED +# @PRE_INHERIT +# @DESCRIPTION: +# Sets the doc builder to use, currently supports +# sphinx, mkdocs and doxygen. +# PYTHON_COMPAT should be set for python based +# doc builders: sphinx and mkdocs + +# @ECLASS-VARIABLE: DOCS_DIR +# @DESCRIPTION: +# Path containing the doc builder config file(s). +# +# For sphinx this is the location of "conf.py" +# +# For mkdocs this is the location of "mkdocs.yml" +# Note that mkdocs.yml often does not reside +# in the same directory as the actual doc files +# +# For doxygen the default name is Doxyfile, but +# package may use a non-standard name. If this +# is the case one should set DOCS_CONFIG_NAME to +# the correct name +# +# Defaults to ${S} + +# @ECLASS-VARIABLE: DOCS_DEPEND +# @DEFAULT_UNSET +# @PRE_INHERIT +# @DESCRIPTION: +# Sets additional dependencies required to build the +# documentation. +# For sphinx and mkdocs these dependencies should +# be specified *without* [${PYTHON_USEDEP}], this +# is added by the eclass. E.g. to depend on mkdocs-material: +# +# @CODE +# DOCS_DEPEND="dev-python/mkdocs-material" +# @CODE +# +# This eclass appends to this variable, this makes it +# possible to call it later in your ebuild again if +# necessary. + +# @ECLASS-VARIABLE: DOCS_AUTODOC +# @PRE_INHERIT +# @DESCRIPTION: +# Sets whether to use sphinx.ext.autodoc/mkautodoc +# Defaults to 1 (True) for sphinx, and 0 (False) for mkdocs. +# Not relevant for doxygen. + +# @ECLASS-VARIABLE: DOCS_OUTDIR +# @DESCRIPTION: +# Sets the directory where the documentation should +# be built into. There is no real reason to change this. +# However, this variable is useful if the package should +# also install other HTML files. +# +# Example use: +# @CODE +# HTML_DOCS=( "${yourdocs}" "${DOCS_OUTDIR}/." ) +# @CODE +# +# Defaults to ${S}/_build/html + +# @ECLASS-VARIABLE: DOCS_CONFIG_NAME +# @DESCRIPTION: +# Name of the doc builder config file. +# +# Only relevant for doxygen, as it allows +# config files with non-standard names. +# Does not do anything for mkdocs or sphinx. +# +# Defaults to Doxyfile for doxygen + +if [[ ! ${_DOCS} ]]; then + +# For the python based DOCS_BUILDERS we need to inherit any python eclass +case ${DOCS_BUILDER} in + "sphinx"|"mkdocs") + # We need the python_gen_any_dep function + if [[ ! ${_PYTHON_R1} && ! ${_PYTHON_ANY_R1} && ! ${_PYTHON_SINGLE_R1} ]]; then + die "distutils-r1, python-r1, python-single-r1 or python-any-r1 needs to be inherited to use python based documentation builders" + fi + ;; + "doxygen") + # do not need to inherit anything for doxygen + ;; + "") + die "DOCS_BUILDER unset, should be set to use ${ECLASS}" + ;; + *) + die "Unsupported DOCS_BUILDER=${DOCS_BUILDER} (unknown) for ${ECLASS}" + ;; +esac + +# @FUNCTION: python_append_dep +# @INTERNAL +# @DESCRIPTION: +# Appends [\${PYTHON_USEDEP}] to all dependencies +# for python based DOCS_BUILDERs such as mkdocs or +# sphinx. +python_append_deps() { + debug-print-function ${FUNCNAME} + + local temp + local dep + for dep in ${DOCS_DEPEND[@]}; do + temp+=" ${dep}[\${PYTHON_USEDEP}]" + done + DOCS_DEPEND=${temp} +} + +# @FUNCTION: sphinx_deps +# @INTERNAL +# @DESCRIPTION: +# Sets dependencies for sphinx +sphinx_deps() { + debug-print-function ${FUNCNAME} + + : ${DOCS_AUTODOC:=1} + + deps="dev-python/sphinx[\${PYTHON_USEDEP}] + ${DOCS_DEPEND}" + if [[ ${DOCS_AUTODOC} == 0 ]]; then + if [[ -n "${DOCS_DEPEND}" ]]; then + die "${FUNCNAME}: do not set DOCS_AUTODOC to 0 if external plugins are used" + fi + elif [[ ${DOCS_AUTODOC} != 0 && ${DOCS_AUTODOC} != 1 ]]; then + die "${FUNCNAME}: DOCS_AUTODOC should be set to 0 or 1" + fi + if [[ ${_PYTHON_SINGLE_R1} ]]; then + DOCS_DEPEND="$(python_gen_cond_dep "${deps}")" + else + DOCS_DEPEND="$(python_gen_any_dep "${deps}")" + fi +} + +# @FUNCTION: sphinx_compile +# @INTERNAL +# @DESCRIPTION: +# Calls sphinx to build docs. +# +# If you overwrite python_compile_all do not call +# this function, call docs_compile instead +sphinx_compile() { + debug-print-function ${FUNCNAME} + use doc || return + + local confpy=${DOCS_DIR}/conf.py + [[ -f ${confpy} ]] || + die "${FUNCNAME}: ${confpy} not found, DOCS_DIR=${DOCS_DIR} call wrong" + + if [[ ${DOCS_AUTODOC} == 0 ]]; then + if grep -F -q 'sphinx.ext.autodoc' "${confpy}"; then + die "${FUNCNAME}: autodoc disabled but sphinx.ext.autodoc found in ${confpy}" + fi + elif [[ ${DOCS_AUTODOC} == 1 ]]; then + if ! grep -F -q 'sphinx.ext.autodoc' "${confpy}"; then + die "${FUNCNAME}: sphinx.ext.autodoc not found in ${confpy}, set DOCS_AUTODOC=0" + fi + fi + + sed -i -e 's:^intersphinx_mapping:disabled_&:' \ + "${DOCS_DIR}"/conf.py || die + # not all packages include the Makefile in pypi tarball + sphinx-build -b html -d "${DOCS_OUTDIR}"/_build/doctrees "${DOCS_DIR}" \ + "${DOCS_OUTDIR}" || die "${FUNCNAME}: sphinx-build failed" +} + +# @FUNCTION: mkdocs_deps +# @INTERNAL +# @DESCRIPTION: +# Sets dependencies for mkdocs +mkdocs_deps() { + debug-print-function ${FUNCNAME} + + : ${DOCS_AUTODOC:=0} + + deps="dev-python/mkdocs[\${PYTHON_USEDEP}] + ${DOCS_DEPEND}" + if [[ ${DOCS_AUTODOC} == 1 ]]; then + deps="dev-python/mkautodoc[\${PYTHON_USEDEP}] + ${deps}" + elif [[ ${DOCS_AUTODOC} != 0 && ${DOCS_AUTODOC} != 1 ]]; then + die "${FUNCNAME}: DOCS_AUTODOC should be set to 0 or 1" + fi + if [[ ${_PYTHON_SINGLE_R1} ]]; then + DOCS_DEPEND="$(python_gen_cond_dep "${deps}")" + else + DOCS_DEPEND="$(python_gen_any_dep "${deps}")" + fi +} + +# @FUNCTION: mkdocs_compile +# @INTERNAL +# @DESCRIPTION: +# Calls mkdocs to build docs. +# +# If you overwrite python_compile_all do not call +# this function, call docs_compile instead +mkdocs_compile() { + debug-print-function ${FUNCNAME} + use doc || return + + local mkdocsyml=${DOCS_DIR}/mkdocs.yml + [[ -f ${mkdocsyml} ]] || + die "${FUNCNAME}: ${mkdocsyml} not found, DOCS_DIR=${DOCS_DIR} wrong" + + pushd "${DOCS_DIR}" || die + mkdocs build -d "${DOCS_OUTDIR}" || die "${FUNCNAME}: mkdocs build failed" + popd || die + + # remove generated .gz variants + # mkdocs currently has no option to disable this + # and portage complains: "Colliding files found by ecompress" + rm "${DOCS_OUTDIR}"/*.gz || die +} + +# @FUNCTION: doxygen_deps +# @INTERNAL +# @DESCRIPTION: +# Sets dependencies for doxygen +doxygen_deps() { + debug-print-function ${FUNCNAME} + + DOCS_DEPEND="app-doc/doxygen + ${DOCS_DEPEND}" +} + +# @FUNCTION: doxygen_compile +# @INTERNAL +# @DESCRIPTION: +# Calls doxygen to build docs. +doxygen_compile() { + debug-print-function ${FUNCNAME} + use doc || return + + : ${DOCS_CONFIG_NAME:="Doxyfile"} + + local doxyfile=${DOCS_DIR}/${DOCS_CONFIG_NAME} + [[ -f ${doxyfile} ]] || + die "${FUNCNAME}: ${doxyfile} not found, DOCS_DIR=${DOCS_DIR} or DOCS_CONFIG_NAME=${DOCS_CONFIG_NAME} wrong" + + # doxygen wants the HTML_OUTPUT dir to already exist + mkdir -p "${DOCS_OUTDIR}" || die + + pushd "${DOCS_DIR}" || die + (cat "${DOCS_CONFIG_NAME}" ; echo "HTML_OUTPUT=${DOCS_OUTDIR}") | doxygen - || die "${FUNCNAME}: doxygen failed" + popd || die +} + +# @FUNCTION: docs_compile +# @DESCRIPTION: +# Calls DOCS_BUILDER and sets HTML_DOCS +# +# This function must be called in src_compile. Take care not to +# overwrite the variables set by it. If distutils-r1 is inherited +# *before* this eclass, than docs_compile will be automatically +# added to python_compile_all() and there is no need to call +# it manually. Note that this function checks if USE="doc" is +# enabled, and if not automatically exits. Therefore, there is +# no need to wrap this function in a if statement. +# +# Example use: +# @CODE +# src_compile() { +# default +# docs_compile +# } +# @CODE +docs_compile() { + debug-print-function ${FUNCNAME} + use doc || return + + # Set a sensible default as DOCS_DIR + : ${DOCS_DIR:="${S}"} + + # Where to put the compiled files? + : ${DOCS_OUTDIR:="${S}/_build/html"} + + ${DOCS_BUILDER}_compile + + HTML_DOCS+=( "${DOCS_OUTDIR}/." ) + + # we need to ensure successful return in case we're called last, + # otherwise Portage may wrongly assume sourcing failed + return 0 +} + + +# This is where we setup the USE/(B)DEPEND variables +# and call the doc builder specific setup functions +IUSE+=" doc" + +# Call the correct setup function +case ${DOCS_BUILDER} in + "sphinx") + python_append_deps + sphinx_deps + ;; + "mkdocs") + python_append_deps + mkdocs_deps + ;; + "doxygen") + doxygen_deps + ;; +esac + +if [[ ${EAPI} == [7] ]]; then + BDEPEND+=" doc? ( ${DOCS_DEPEND} )" +else + DEPEND+=" doc? ( ${DOCS_DEPEND} )" +fi + +# If this is a python package using distutils-r1 +# then put the compile function in the specific +# python function, else docs_compile should be manually +# added to src_compile +if [[ ${_DISTUTILS_R1} && ( ${DOCS_BUILDER}="mkdocs" || ${DOCS_BUILDER}="sphinx" ) ]]; then + python_compile_all() { docs_compile; } +fi + +_DOCS=1 +fi diff --git a/eclass/dotnet.eclass b/eclass/dotnet.eclass new file mode 100644 index 0000000..ae861da --- /dev/null +++ b/eclass/dotnet.eclass @@ -0,0 +1,145 @@ +# Copyright 1999-2020 Gentoo Authors +# Distributed under the terms of the GNU General Public License v2 + +# @ECLASS: dotnet.eclass +# @MAINTAINER: dotnet@gentoo.org +# @SUPPORTED_EAPIS: 1 2 3 4 5 6 7 +# @BLURB: common settings and functions for mono and dotnet related packages +# @DESCRIPTION: +# The dotnet eclass contains common environment settings that are useful for +# dotnet packages. Currently, it provides no functions, just exports +# MONO_SHARED_DIR and sets LC_ALL in order to prevent errors during compilation +# of dotnet packages. + +case ${EAPI:-0} in + 0) + die "this eclass doesn't support EAPI 0" ;; + [1-6]) + inherit eapi7-ver multilib + DEPEND="dev-lang/mono" ;; + *) + BDEPEND="dev-lang/mono" ;; +esac + +inherit mono-env + +# @ECLASS-VARIABLE: USE_DOTNET +# @DESCRIPTION: +# Use flags added to IUSE + +# SET default use flags according on DOTNET_TARGETS +for x in ${USE_DOTNET}; do + case ${x} in + net45) if [[ ${DOTNET_TARGETS} == *net45* ]]; then IUSE+=" +net45"; else IUSE+=" net45"; fi;; + net40) if [[ ${DOTNET_TARGETS} == *net40* ]]; then IUSE+=" +net40"; else IUSE+=" net40"; fi;; + net35) if [[ ${DOTNET_TARGETS} == *net35* ]]; then IUSE+=" +net35"; else IUSE+=" net35"; fi;; + net20) if [[ ${DOTNET_TARGETS} == *net20* ]]; then IUSE+=" +net20"; else IUSE+=" net20"; fi;; + esac +done + +# @FUNCTION: dotnet_pkg_setup +# @DESCRIPTION: +# This function set FRAMEWORK. +dotnet_pkg_setup() { + for x in ${USE_DOTNET} ; do + case ${x} in + net45) if use net45; then F="4.5"; fi;; + net40) if use net40; then F="4.0"; fi;; + net35) if use net35; then F="3.5"; fi;; + net20) if use net20; then F="2.0"; fi;; + esac + if [[ -z ${FRAMEWORK} ]]; then + if [[ ${F} ]]; then + FRAMEWORK="${F}"; + fi + else + ver_test "${F}" -le "${FRAMEWORK}" || FRAMEWORK="${F}" + fi + done + if [[ -z ${FRAMEWORK} ]]; then + FRAMEWORK="4.0" + fi + einfo " -- USING .NET ${FRAMEWORK} FRAMEWORK -- " +} + +# >=mono-0.92 versions using mcs -pkg:foo-sharp require shared memory, so we set the +# shared dir to ${T} so that ${T}/.wapi can be used during the install process. +export MONO_SHARED_DIR="${T}" + +# Building mono, nant and many other dotnet packages is known to fail if LC_ALL +# variable is not set to C. To prevent this all mono related packages will be +# build with LC_ALL=C (see bugs #146424, #149817) +export LC_ALL=C + +# Monodevelop-using applications need this to be set or they will try to create config +# files in the user's ~ dir. + +export XDG_CONFIG_HOME="${T}" + +# Fix bug 83020: +# "Access Violations Arise When Emerging Mono-Related Packages with MONO_AOT_CACHE" + +unset MONO_AOT_CACHE + +# @FUNCTION: exbuild +# @DESCRIPTION: +# Run xbuild with Release configuration and configurated FRAMEWORK. +exbuild() { + elog "xbuild ""$@"" /p:Configuration=Release /tv:4.0 /p:TargetFrameworkVersion=v""${FRAMEWORK}"" || die" + xbuild "$@" /p:Configuration=Release /tv:4.0 /p:TargetFrameworkVersion=v"${FRAMEWORK}" || die +} + +# @FUNCTION: egacinstall +# @DESCRIPTION: +# Install package to GAC. +egacinstall() { + use !prefix && has "${EAPI:-0}" 0 1 2 && ED="${D}" + gacutil -i "${1}" \ + -root "${ED}"/usr/$(get_libdir) \ + -gacdir /usr/$(get_libdir) \ + -package ${2:-${GACPN:-${PN}}} \ + || die "installing ${1} into the Global Assembly Cache failed" +} + +# @FUNCTION: dotnet_multilib_comply +# @DESCRIPTION: +# multilib comply +dotnet_multilib_comply() { + use !prefix && has "${EAPI:-0}" 0 1 2 && ED="${D}" + local dir finddirs=() mv_command=${mv_command:-mv} + if [[ -d "${ED}/usr/lib" && "$(get_libdir)" != "lib" ]] + then + if ! [[ -d "${ED}"/usr/"$(get_libdir)" ]] + then + mkdir "${ED}"/usr/"$(get_libdir)" || die "Couldn't mkdir ${ED}/usr/$(get_libdir)" + fi + ${mv_command} "${ED}"/usr/lib/* "${ED}"/usr/"$(get_libdir)"/ || die "Moving files into correct libdir failed" + rm -rf "${ED}"/usr/lib + for dir in "${ED}"/usr/"$(get_libdir)"/pkgconfig "${ED}"/usr/share/pkgconfig + do + + if [[ -d "${dir}" && "$(find "${dir}" -name '*.pc')" != "" ]] + then + pushd "${dir}" &> /dev/null + sed -i -r -e 's:/(lib)([^a-zA-Z0-9]|$):/'"$(get_libdir)"'\2:g' \ + *.pc \ + || die "Sedding some sense into pkgconfig files failed." + popd "${dir}" &> /dev/null + fi + done + if [[ -d "${ED}/usr/bin" ]] + then + for exe in "${ED}/usr/bin"/* + do + if [[ "$(file "${exe}")" == *"shell script text"* ]] + then + sed -r -i -e ":/lib(/|$): s:/lib(/|$):/$(get_libdir)\1:" \ + "${exe}" || die "Sedding some sense into ${exe} failed" + fi + done + fi + + fi +} + +EXPORT_FUNCTIONS pkg_setup diff --git a/eclass/dune.eclass b/eclass/dune.eclass new file mode 100644 index 0000000..da1813d --- /dev/null +++ b/eclass/dune.eclass @@ -0,0 +1,72 @@ +# Copyright 1999-2020 Gentoo Authors +# Distributed under the terms of the GNU General Public License v2 + +# @ECLASS: dune.eclass +# @MAINTAINER: +# rkitover@gmail.com +# Mark Wright <gienah@gentoo.org> +# @AUTHOR: +# Rafael Kitover <rkitover@gmail.com> +# @SUPPORTED_EAPIS: 5 6 7 +# @BLURB: Provides functions for installing dune packages. +# @DESCRIPTION: +# Provides dependencies on dune and ocaml and default src_compile, src_test and +# src_install for dune-based packages. + +# @ECLASS-VARIABLE: DUNE_PKG_NAME +# @DESCRIPTION: +# Sets the actual dune package name, if different from gentoo package name. +# Set before inheriting the eclass. + +case ${EAPI:-0} in + 5|6|7) ;; + *) die "${ECLASS}: EAPI ${EAPI} not supported" ;; +esac + +# Do not complain about CFLAGS etc since ml projects do not use them. +QA_FLAGS_IGNORED='.*' + +EXPORT_FUNCTIONS src_compile src_test src_install + +RDEPEND=">=dev-lang/ocaml-4:=[ocamlopt?]" +case ${EAPI:-0} in + 0|1|2|3|4|5|6) DEPEND="${RDEPEND} dev-ml/dune";; + *) BDEPEND="dev-ml/dune dev-lang/ocaml"; DEPEND="${RDEPEND}" ;; +esac + +dune_src_compile() { + dune build @install || die +} + +dune_src_test() { + dune runtest || die +} + +# @FUNCTION: dune-install +# @USAGE: <list of packages> +# @DESCRIPTION: +# Installs the dune packages given as arguments. For each "${pkg}" element in +# that list, "${pkg}.install" must be readable from "${PWD}/_build/default" +dune-install() { + local pkg + for pkg ; do + dune install \ + --prefix="${ED%/}/usr" \ + --libdir="${D%/}$(ocamlc -where)" \ + --mandir="${ED%/}/usr/share/man" \ + "${pkg}" || die + done +} + +dune_src_install() { + local pkg="${1:-${DUNE_PKG_NAME:-${PN}}}" + + dune-install "${pkg}" + + # Move docs to the appropriate place. + if [ -d "${ED%/}/usr/doc/${pkg}" ] ; then + mkdir -p "${ED%/}/usr/share/doc/${PF}/" || die + mv "${ED%/}/usr/doc/${pkg}/"* "${ED%/}/usr/share/doc/${PF}/" || die + rm -rf "${ED%/}/usr/doc" || die + fi +} diff --git a/eclass/eapi7-ver.eclass b/eclass/eapi7-ver.eclass new file mode 100644 index 0000000..8f13fc9 --- /dev/null +++ b/eclass/eapi7-ver.eclass @@ -0,0 +1,308 @@ +# Copyright 1999-2020 Gentoo Authors +# Distributed under the terms of the GNU General Public License v2 + +# @ECLASS: eapi7-ver.eclass +# @MAINTAINER: +# PMS team <pms@gentoo.org> +# @AUTHOR: +# Ulrich Müller <ulm@gentoo.org> +# Michał Górny <mgorny@gentoo.org> +# @SUPPORTED_EAPIS: 0 1 2 3 4 5 6 +# @BLURB: Testing implementation of EAPI 7 version manipulators +# @DESCRIPTION: +# A stand-alone implementation of the version manipulation functions +# aimed for EAPI 7. Intended to be used for wider testing of +# the proposed functions and to allow ebuilds to switch to the new +# model early, with minimal change needed for actual EAPI 7. +# +# https://bugs.gentoo.org/482170 +# +# @SUBSECTION Version strings +# +# The functions support arbitrary version strings consisting of version +# components interspersed with (possibly empty) version separators. +# +# A version component can either consist purely of digits ([0-9]+) +# or purely of uppercase and lowercase letters ([A-Za-z]+). A version +# separator is either a string of any other characters ([^A-Za-z0-9]+), +# or it occurs at the transition between a sequence of letters +# and a sequence of digits, or vice versa. In the latter case, +# the version separator is an empty string. +# +# The version is processed left-to-right, and each successive component +# is assigned numbers starting with 1. The components are either split +# on version separators or on boundaries between digits and letters +# (in which case the separator between the components is empty). +# Version separators are assigned numbers starting with 1 for +# the separator between 1st and 2nd components. As a special case, +# if the version string starts with a separator, it is assigned index 0. +# +# Examples: +# +# @CODE +# 1.2b-alpha4 -> 1 . 2 '' b - alpha '' 4 +# c s c s c s c s c +# 1 1 2 2 3 3 4 4 5 +# +# .11. -> . 11 . +# s c s +# 0 1 1 +# @CODE +# +# @SUBSECTION Ranges +# +# A range can be specified as 'm' for m-th version component, 'm-' +# for all components starting with m-th or 'm-n' for components starting +# at m-th and ending at n-th (inclusive). If the range spans outside +# the version string, it is truncated silently. + +case ${EAPI:-0} in + 0|1|2|3|4|5|6) ;; + 7) die "${ECLASS}: EAPI=${EAPI} includes all functions from this eclass" ;; + *) die "${ECLASS}: EAPI=${EAPI} unknown" ;; +esac + +# @FUNCTION: _ver_parse_range +# @USAGE: <range> <max> +# @INTERNAL +# @DESCRIPTION: +# Parse the range string <range>, setting 'start' and 'end' variables +# to the appropriate bounds. <max> specifies the appropriate upper +# bound for the range; the user-specified value is truncated to this. +_ver_parse_range() { + local range=${1} + local max=${2} + + [[ ${range} == [0-9]* ]] \ + || die "${FUNCNAME}: range must start with a number" + start=${range%-*} + [[ ${range} == *-* ]] && end=${range#*-} || end=${start} + if [[ ${end} ]]; then + [[ ${start} -le ${end} ]] \ + || die "${FUNCNAME}: end of range must be >= start" + [[ ${end} -le ${max} ]] || end=${max} + else + end=${max} + fi +} + +# @FUNCTION: _ver_split +# @USAGE: <version> +# @INTERNAL +# @DESCRIPTION: +# Split the version string <version> into separator-component array. +# Sets 'comp' to an array of the form: ( s_0 c_1 s_1 c_2 s_2 c_3... ) +# where s_i are separators and c_i are components. +_ver_split() { + local v=${1} LC_ALL=C + + comp=() + + # get separators and components + local s c + while [[ ${v} ]]; do + # cut the separator + s=${v%%[a-zA-Z0-9]*} + v=${v:${#s}} + # cut the next component; it can be either digits or letters + [[ ${v} == [0-9]* ]] && c=${v%%[^0-9]*} || c=${v%%[^a-zA-Z]*} + v=${v:${#c}} + + comp+=( "${s}" "${c}" ) + done +} + +# @FUNCTION: ver_cut +# @USAGE: <range> [<version>] +# @DESCRIPTION: +# Print the substring of the version string containing components +# defined by the <range> and the version separators between them. +# Processes <version> if specified, ${PV} otherwise. +# +# For the syntax of versions and ranges, please see the eclass +# description. +ver_cut() { + local range=${1} + local v=${2:-${PV}} + local start end + local -a comp + + _ver_split "${v}" + local max=$((${#comp[@]}/2)) + _ver_parse_range "${range}" "${max}" + + if [[ ${start} -gt 0 ]]; then + start=$(( start*2 - 1 )) + fi + # Work around a bug in bash-3.2, where "${comp[*]:start:end*2-start}" + # inserts stray 0x7f characters for empty array elements + printf "%s" "${comp[@]:start:end*2-start}" $'\n' +} + +# @FUNCTION: ver_rs +# @USAGE: <range> <repl> [<range> <repl>...] [<version>] +# @DESCRIPTION: +# Print the version string after substituting the specified version +# separators at <range> with <repl> (string). Multiple '<range> <repl>' +# pairs can be specified. Processes <version> if specified, +# ${PV} otherwise. +# +# For the syntax of versions and ranges, please see the eclass +# description. +ver_rs() { + local v + (( ${#} & 1 )) && v=${@: -1} || v=${PV} + local start end i + local -a comp + + _ver_split "${v}" + local max=$((${#comp[@]}/2 - 1)) + + while [[ ${#} -ge 2 ]]; do + _ver_parse_range "${1}" "${max}" + for (( i = start*2; i <= end*2; i+=2 )); do + [[ ${i} -eq 0 && -z ${comp[i]} ]] && continue + comp[i]=${2} + done + shift 2 + done + + local IFS= + echo "${comp[*]}" +} + +# @FUNCTION: _ver_compare_int +# @USAGE: <a> <b> +# @RETURN: 0 if <a> -eq <b>, 1 if <a> -lt <b>, 3 if <a> -gt <b> +# @INTERNAL +# @DESCRIPTION: +# Compare two non-negative integers <a> and <b>, of arbitrary length. +# If <a> is equal to, less than, or greater than <b>, return 0, 1, or 3 +# as exit status, respectively. +_ver_compare_int() { + local a=$1 b=$2 d=$(( ${#1}-${#2} )) + + # Zero-pad to equal length if necessary. + if [[ ${d} -gt 0 ]]; then + printf -v b "%0${d}d%s" 0 "${b}" + elif [[ ${d} -lt 0 ]]; then + printf -v a "%0$(( -d ))d%s" 0 "${a}" + fi + + [[ ${a} > ${b} ]] && return 3 + [[ ${a} == "${b}" ]] +} + +# @FUNCTION: _ver_compare +# @USAGE: <va> <vb> +# @RETURN: 1 if <va> < <vb>, 2 if <va> = <vb>, 3 if <va> > <vb> +# @INTERNAL +# @DESCRIPTION: +# Compare two versions <va> and <vb>. If <va> is less than, equal to, +# or greater than <vb>, return 1, 2, or 3 as exit status, respectively. +_ver_compare() { + local va=${1} vb=${2} a an al as ar b bn bl bs br re LC_ALL=C + + re="^([0-9]+(\.[0-9]+)*)([a-z]?)((_(alpha|beta|pre|rc|p)[0-9]*)*)(-r[0-9]+)?$" + + [[ ${va} =~ ${re} ]] || die "${FUNCNAME}: invalid version: ${va}" + an=${BASH_REMATCH[1]} + al=${BASH_REMATCH[3]} + as=${BASH_REMATCH[4]} + ar=${BASH_REMATCH[7]} + + [[ ${vb} =~ ${re} ]] || die "${FUNCNAME}: invalid version: ${vb}" + bn=${BASH_REMATCH[1]} + bl=${BASH_REMATCH[3]} + bs=${BASH_REMATCH[4]} + br=${BASH_REMATCH[7]} + + # Compare numeric components (PMS algorithm 3.2) + # First component + _ver_compare_int "${an%%.*}" "${bn%%.*}" || return + + while [[ ${an} == *.* && ${bn} == *.* ]]; do + # Other components (PMS algorithm 3.3) + an=${an#*.} + bn=${bn#*.} + a=${an%%.*} + b=${bn%%.*} + if [[ ${a} == 0* || ${b} == 0* ]]; then + # Remove any trailing zeros + [[ ${a} =~ 0+$ ]] && a=${a%"${BASH_REMATCH[0]}"} + [[ ${b} =~ 0+$ ]] && b=${b%"${BASH_REMATCH[0]}"} + [[ ${a} > ${b} ]] && return 3 + [[ ${a} < ${b} ]] && return 1 + else + _ver_compare_int "${a}" "${b}" || return + fi + done + [[ ${an} == *.* ]] && return 3 + [[ ${bn} == *.* ]] && return 1 + + # Compare letter components (PMS algorithm 3.4) + [[ ${al} > ${bl} ]] && return 3 + [[ ${al} < ${bl} ]] && return 1 + + # Compare suffixes (PMS algorithm 3.5) + as=${as#_}${as:+_} + bs=${bs#_}${bs:+_} + while [[ -n ${as} && -n ${bs} ]]; do + # Compare each suffix (PMS algorithm 3.6) + a=${as%%_*} + b=${bs%%_*} + if [[ ${a%%[0-9]*} == "${b%%[0-9]*}" ]]; then + _ver_compare_int "${a##*[a-z]}" "${b##*[a-z]}" || return + else + # Check for p first + [[ ${a%%[0-9]*} == p ]] && return 3 + [[ ${b%%[0-9]*} == p ]] && return 1 + # Hack: Use that alpha < beta < pre < rc alphabetically + [[ ${a} > ${b} ]] && return 3 || return 1 + fi + as=${as#*_} + bs=${bs#*_} + done + if [[ -n ${as} ]]; then + [[ ${as} == p[_0-9]* ]] && return 3 || return 1 + elif [[ -n ${bs} ]]; then + [[ ${bs} == p[_0-9]* ]] && return 1 || return 3 + fi + + # Compare revision components (PMS algorithm 3.7) + _ver_compare_int "${ar#-r}" "${br#-r}" || return + + return 2 +} + +# @FUNCTION: ver_test +# @USAGE: [<v1>] <op> <v2> +# @DESCRIPTION: +# Check if the relation <v1> <op> <v2> is true. If <v1> is not specified, +# default to ${PVR}. <op> can be -gt, -ge, -eq, -ne, -le, -lt. +# Both versions must conform to the PMS version syntax (with optional +# revision parts), and the comparison is performed according to +# the algorithm specified in the PMS. +ver_test() { + local va op vb + + if [[ $# -eq 3 ]]; then + va=${1} + shift + else + va=${PVR} + fi + + [[ $# -eq 2 ]] || die "${FUNCNAME}: bad number of arguments" + + op=${1} + vb=${2} + + case ${op} in + -eq|-ne|-lt|-le|-gt|-ge) ;; + *) die "${FUNCNAME}: invalid operator: ${op}" ;; + esac + + _ver_compare "${va}" "${vb}" + test $? "${op}" 2 +} diff --git a/eclass/eapi8-dosym.eclass b/eclass/eapi8-dosym.eclass new file mode 100644 index 0000000..52f0ffe --- /dev/null +++ b/eclass/eapi8-dosym.eclass @@ -0,0 +1,108 @@ +# Copyright 2020 Gentoo Authors +# Distributed under the terms of the GNU General Public License v2 + +# @ECLASS: eapi8-dosym.eclass +# @MAINTAINER: +# PMS team <pms@gentoo.org> +# @AUTHOR: +# Ulrich Müller <ulm@gentoo.org> +# @SUPPORTED_EAPIS: 5 6 7 +# @BLURB: Testing implementation of EAPI 8 dosym -r option +# @DESCRIPTION: +# A stand-alone implementation of the dosym command aimed for EAPI 8. +# Intended to be used for wider testing of the proposed option and to +# allow ebuilds to switch to the new model early, with minimal change +# needed for actual EAPI 8. +# +# https://bugs.gentoo.org/708360 + +case ${EAPI} in + 5|6|7) ;; + *) die "${ECLASS}: EAPI=${EAPI:-0} not supported" ;; +esac + +# @FUNCTION: _dosym8_canonicalize +# @USAGE: <path> +# @INTERNAL +# @DESCRIPTION: +# Transparent bash-only replacement for GNU "realpath -m -s". +# Resolve references to "/./", "/../" and remove extra "/" characters +# from <path>, without touching any actual file. +_dosym8_canonicalize() { + local path slash i prev out IFS=/ + + path=( $1 ) + [[ $1 == /* ]] && slash=/ + + while true; do + # Find first instance of non-".." path component followed by "..", + # or as a special case, "/.." at the beginning of the path. + # Also drop empty and "." path components as we go along. + prev= + for i in ${!path[@]}; do + if [[ -z ${path[i]} || ${path[i]} == . ]]; then + unset "path[i]" + elif [[ ${path[i]} != .. ]]; then + prev=${i} + elif [[ ${prev} || ${slash} ]]; then + # Found, remove path components and reiterate + [[ ${prev} ]] && unset "path[prev]" + unset "path[i]" + continue 2 + fi + done + # No (further) instance found, so we're done + break + done + + out="${slash}${path[*]}" + echo "${out:-.}" +} + +# @FUNCTION: dosym8 +# @USAGE: [-r] <target> <link> +# @DESCRIPTION: +# Create a symbolic link <link>, pointing to <target>. If the +# directory containing the new link does not exist, create it. +# +# If called with option -r, expand <target> relative to the apparent +# path of the directory containing <link>. For example, "dosym8 -r +# /bin/foo /usr/bin/foo" will create a link named "../../bin/foo". +dosym8() { + local option_r + + case $1 in + -r) option_r=t; shift ;; + esac + + [[ $# -eq 2 ]] || die "${FUNCNAME}: bad number of arguments" + + local target=$1 link=$2 + + if [[ ${option_r} ]]; then + local linkdir comp + + # Expansion makes sense only for an absolute target path + [[ ${target} == /* ]] \ + || die "${FUNCNAME}: -r specified but no absolute target path" + + target=$(_dosym8_canonicalize "${target}") + linkdir=$(_dosym8_canonicalize "/${link#/}") + linkdir=${linkdir%/*} # poor man's dirname(1) + linkdir=${linkdir:-/} # always keep the initial "/" + + local ifs_save=${IFS-$' \t\n'} IFS=/ + for comp in ${linkdir}; do + if [[ ${target%%/*} == "${comp}" ]]; then + target=${target#"${comp}"} + target=${target#/} + else + target=..${target:+/}${target} + fi + done + IFS=${ifs_save} + target=${target:-.} + fi + + dosym "${target}" "${link}" +} diff --git a/eclass/ecm.eclass b/eclass/ecm.eclass new file mode 100644 index 0000000..c763957 --- /dev/null +++ b/eclass/ecm.eclass @@ -0,0 +1,588 @@ +# Copyright 1999-2020 Gentoo Authors +# Distributed under the terms of the GNU General Public License v2 + +# @ECLASS: ecm.eclass +# @MAINTAINER: +# kde@gentoo.org +# @SUPPORTED_EAPIS: 7 +# @BLURB: Support eclass for packages that use KDE Frameworks with ECM. +# @DESCRIPTION: +# This eclass is intended to streamline the creation of ebuilds for packages +# that use cmake and KDE Frameworks' extra-cmake-modules, thereby following +# some of their packaging conventions. It is primarily intended for the three +# upstream release groups (Frameworks, Plasma, Applications) but also for any +# other package that follows similar conventions. +# +# This eclass unconditionally inherits cmake.eclass and all its public +# variables and helper functions (not phase functions) may be considered as part +# of this eclass's API. +# +# This eclass's phase functions are not intended to be mixed and matched, so if +# any phase functions are overridden the version here should also be called. + +if [[ -z ${_ECM_ECLASS} ]]; then +_ECM_ECLASS=1 + +# @ECLASS-VARIABLE: VIRTUALX_REQUIRED +# @DESCRIPTION: +# For proper description see virtualx.eclass manpage. +# Here we redefine default value to be manual, if your package needs virtualx +# for tests you should proceed with setting VIRTUALX_REQUIRED=test. +: ${VIRTUALX_REQUIRED:=manual} + +# @ECLASS-VARIABLE: ECM_NONGUI +# @DEFAULT_UNSET +# @DESCRIPTION: +# By default, for all CATEGORIES except kde-frameworks, assume we are building +# a GUI application. Add dependency on kde-frameworks/breeze-icons or +# kde-frameworks/oxygen-icons and run the xdg.eclass routines for pkg_preinst, +# pkg_postinst and pkg_postrm. If set to "true", do nothing. +if [[ ${CATEGORY} = kde-frameworks ]] ; then + : ${ECM_NONGUI:=true} +fi +: ${ECM_NONGUI:=false} + +inherit cmake flag-o-matic toolchain-funcs virtualx + +if [[ ${ECM_NONGUI} = false ]] ; then + inherit xdg +fi + +case ${EAPI} in + 7) ;; + *) die "EAPI=${EAPI:-0} is not supported" ;; +esac + +if [[ -v KDE_GCC_MINIMAL ]]; then + EXPORT_FUNCTIONS pkg_pretend +fi + +EXPORT_FUNCTIONS pkg_setup src_prepare src_configure src_test pkg_preinst pkg_postinst pkg_postrm + +# @ECLASS-VARIABLE: ECM_KDEINSTALLDIRS +# @DESCRIPTION: +# Assume the package is using KDEInstallDirs macro and switch +# KDE_INSTALL_USE_QT_SYS_PATHS to ON. If set to "false", do nothing. +: ${ECM_KDEINSTALLDIRS:=true} + +# @ECLASS-VARIABLE: ECM_DEBUG +# @DESCRIPTION: +# Add "debug" to IUSE. If !debug, add -DQT_NO_DEBUG to CPPFLAGS. If set to +# "false", do nothing. +: ${ECM_DEBUG:=true} + +# @ECLASS-VARIABLE: ECM_DESIGNERPLUGIN +# @DESCRIPTION: +# If set to "true", add "designer" to IUSE to toggle build of designer plugins +# and add the necessary BDEPEND. If set to "false", do nothing. +: ${ECM_DESIGNERPLUGIN:=false} + +# @ECLASS-VARIABLE: ECM_EXAMPLES +# @DESCRIPTION: +# By default unconditionally ignore a top-level examples subdirectory. +# If set to "true", add "examples" to IUSE to toggle adding that subdirectory. +: ${ECM_EXAMPLES:=false} + +# @ECLASS-VARIABLE: ECM_HANDBOOK +# @DESCRIPTION: +# Will accept "true", "false", "optional", "forceoptional". If set to "false", +# do nothing. +# Otherwise, add "+handbook" to IUSE, add the appropriate dependency, and let +# KF5DocTools generate and install the handbook from docbook file(s) found in +# ECM_HANDBOOK_DIR. However if !handbook, disable build of ECM_HANDBOOK_DIR +# in CMakeLists.txt. +# If set to "optional", build with -DCMAKE_DISABLE_FIND_PACKAGE_KF5DocTools=ON +# when !handbook. In case package requires KF5KDELibs4Support, see next: +# If set to "forceoptional", remove a KF5DocTools dependency from the root +# CMakeLists.txt in addition to the above. +: ${ECM_HANDBOOK:=false} + +# @ECLASS-VARIABLE: ECM_HANDBOOK_DIR +# @DESCRIPTION: +# Specifies the directory containing the docbook file(s) relative to ${S} to +# be processed by KF5DocTools (kdoctools_install). +: ${ECM_HANDBOOK_DIR:=doc} + +# @ECLASS-VARIABLE: ECM_PO_DIRS +# @DESCRIPTION: +# Specifies directories of l10n files relative to ${S} to be processed by +# KF5I18n (ki18n_install). If IUSE nls exists and is disabled then disable +# build of these directories in CMakeLists.txt. +: ${ECM_PO_DIRS:="po poqm"} + +# @ECLASS-VARIABLE: ECM_QTHELP +# @DEFAULT_UNSET +# @DESCRIPTION: +# Default value for all CATEGORIES except kde-frameworks is "false". +# If set to "true", add "doc" to IUSE, add the appropriate dependency, let +# -DBUILD_QCH=ON generate and install Qt compressed help files when USE=doc. +# If set to "false", do nothing. +if [[ ${CATEGORY} = kde-frameworks ]]; then + : ${ECM_QTHELP:=true} +fi +: ${ECM_QTHELP:=false} + +# @ECLASS-VARIABLE: ECM_TEST +# @DEFAULT_UNSET +# @DESCRIPTION: +# Will accept "true", "false", "optional", "forceoptional", +# "forceoptional-recursive". +# Default value is "false", except for CATEGORY=kde-frameworks where it is +# set to "true". If set to "false", do nothing. +# For any other value, add "test" to IUSE and DEPEND on dev-qt/qttest:5. +# If set to "optional", build with -DCMAKE_DISABLE_FIND_PACKAGE_Qt5Test=ON +# when USE=!test. +# If set to "forceoptional", punt Qt5Test dependency and ignore "autotests", +# "test", "tests" subdirs from top-level CMakeLists.txt when USE=!test. +# If set to "forceoptional-recursive", punt Qt5Test dependencies and make +# autotest(s), unittest(s) and test(s) subdirs from *any* CMakeLists.txt in +# ${S} and below conditional on BUILD_TESTING when USE=!test. This is always +# meant as a short-term fix and creates ${T}/${P}-tests-optional.patch to +# refine and submit upstream. +if [[ ${CATEGORY} = kde-frameworks ]]; then + : ${ECM_TEST:=true} +fi +: ${ECM_TEST:=false} + +# @ECLASS-VARIABLE: KFMIN +# @DEFAULT_UNSET +# @DESCRIPTION: +# Minimum version of Frameworks to require. Default value for kde-frameworks +# is ${PV} and 5.64.0 baseline for everything else. This is not going to be +# changed unless we also bump EAPI, which usually implies (rev-)bumping. +# Version will later be used to differentiate between KF5/Qt5 and KF6/Qt6. +if [[ ${CATEGORY} = kde-frameworks ]]; then + : ${KFMIN:=$(ver_cut 1-2)} +fi +: ${KFMIN:=5.64.0} + +# @ECLASS-VARIABLE: KFSLOT +# @INTERNAL +# @DESCRIPTION: +# KDE Frameworks and Qt slot dependency, implied by KFMIN version. +: ${KFSLOT:=5} + +case ${ECM_NONGUI} in + true) ;; + false) + # gui applications need breeze or oxygen for basic iconset, bug #564838 + RDEPEND+=" || ( + kde-frameworks/breeze-icons:* + kde-frameworks/oxygen-icons:* + )" + ;; + *) + eerror "Unknown value for \${ECM_NONGUI}" + die "Value ${ECM_NONGUI} is not supported" + ;; +esac + +case ${ECM_DEBUG} in + true) + IUSE+=" debug" + ;; + false) ;; + *) + eerror "Unknown value for \${ECM_DEBUG}" + die "Value ${ECM_DEBUG} is not supported" + ;; +esac + +case ${ECM_DESIGNERPLUGIN} in + true) + IUSE+=" designer" + BDEPEND+=" designer? ( dev-qt/designer:${KFSLOT} )" + ;; + false) ;; + *) + eerror "Unknown value for \${ECM_DESIGNERPLUGIN}" + die "Value ${ECM_DESIGNERPLUGIN} is not supported" + ;; +esac + +case ${ECM_EXAMPLES} in + true) + IUSE+=" examples" + ;; + false) ;; + *) + eerror "Unknown value for \${ECM_EXAMPLES}" + die "Value ${ECM_EXAMPLES} is not supported" + ;; +esac + +case ${ECM_HANDBOOK} in + true|optional|forceoptional) + IUSE+=" +handbook" + BDEPEND+=" handbook? ( >=kde-frameworks/kdoctools-${KFMIN}:${KFSLOT} )" + ;; + false) ;; + *) + eerror "Unknown value for \${ECM_HANDBOOK}" + die "Value ${ECM_HANDBOOK} is not supported" + ;; +esac + +case ${ECM_QTHELP} in + true) + IUSE+=" doc" + COMMONDEPEND+=" doc? ( dev-qt/qt-docs:${KFSLOT} )" + BDEPEND+=" doc? ( + >=app-doc/doxygen-1.8.13-r1 + dev-qt/qthelp:${KFSLOT} + )" + ;; + false) ;; + *) + eerror "Unknown value for \${ECM_QTHELP}" + die "Value ${ECM_QTHELP} is not supported" + ;; +esac + +case ${ECM_TEST} in + true|optional|forceoptional|forceoptional-recursive) + IUSE+=" test" + DEPEND+=" test? ( dev-qt/qttest:${KFSLOT} )" + RESTRICT+=" !test? ( test )" + ;; + false) ;; + *) + eerror "Unknown value for \${ECM_TEST}" + die "Value ${ECM_TEST} is not supported" + ;; +esac + +BDEPEND+=" >=kde-frameworks/extra-cmake-modules-${KFMIN}:${KFSLOT}" +RDEPEND+=" >=kde-frameworks/kf-env-4" +COMMONDEPEND+=" dev-qt/qtcore:${KFSLOT}" + +DEPEND+=" ${COMMONDEPEND}" +RDEPEND+=" ${COMMONDEPEND}" +unset COMMONDEPEND + +# @ECLASS-VARIABLE: KDE_GCC_MINIMAL +# @DEFAULT_UNSET +# @DESCRIPTION: +# Minimum version of active GCC to require. This is checked in +# ecm_pkg_pretend and ecm_pkg_setup. + +# @FUNCTION: _ecm_check_gcc_version +# @INTERNAL +# @DESCRIPTION: +# Determine if the current GCC version is acceptable, otherwise die. +_ecm_check_gcc_version() { + if [[ ${MERGE_TYPE} != binary && -v KDE_GCC_MINIMAL ]] && tc-is-gcc; then + + local version=$(gcc-version) + + debug-print "GCC version check activated" + debug-print "Version detected: ${version}" + debug-print "Version required: ${KDE_GCC_MINIMAL}" + + ver_test ${version} -lt ${KDE_GCC_MINIMAL} && + die "Sorry, but gcc-${KDE_GCC_MINIMAL} or later is required for this package (found ${version})." + fi +} + +# @FUNCTION: _ecm_strip_handbook_translations +# @INTERNAL +# @DESCRIPTION: +# If LINGUAS is defined, enable only the requested translations when required. +_ecm_strip_handbook_translations() { + if ! [[ -v LINGUAS ]]; then + return + fi + + local lang po + for po in ${ECM_PO_DIRS}; do + if [[ -d ${po} ]] ; then + pushd ${po} > /dev/null || die + for lang in *; do + if [[ -e ${lang} ]] && ! has ${lang/.po/} ${LINGUAS} ; then + case ${lang} in + cmake_modules | \ + CMakeLists.txt | \ + ${PN}.pot) ;; + *) rm -r ${lang} || die ;; + esac + if [[ -e CMakeLists.txt ]] ; then + cmake_comment_add_subdirectory ${lang} + sed -e "/add_subdirectory([[:space:]]*${lang}\/.*[[:space:]]*)/d" \ + -i CMakeLists.txt || die + fi + fi + done + popd > /dev/null || die + fi + done +} + +# @FUNCTION: ecm_punt_bogus_dep +# @USAGE: <prefix> <dependency> +# @DESCRIPTION: +# Removes a specified dependency from a find_package call with multiple +# components. +ecm_punt_bogus_dep() { + local prefix=${1} + local dep=${2} + + if [[ ! -e "CMakeLists.txt" ]]; then + return + fi + + pcregrep -Mni "(?s)find_package\s*\(\s*${prefix}[^)]*?${dep}.*?\)" CMakeLists.txt > "${T}/bogus${dep}" + + # pcregrep returns non-zero on no matches/error + if [[ $? -ne 0 ]] ; then + return + fi + + local length=$(wc -l "${T}/bogus${dep}" | cut -d " " -f 1) + local first=$(head -n 1 "${T}/bogus${dep}" | cut -d ":" -f 1) + local last=$(( length + first - 1)) + + sed -e "${first},${last}s/${dep}//" -i CMakeLists.txt || die + + if [[ ${length} -eq 1 ]] ; then + sed -e "/find_package\s*(\s*${prefix}\(\s\+\(REQUIRED\|CONFIG\|COMPONENTS\|\${[A-Z0-9_]*}\)\)\+\s*)/Is/^/# removed by ecm.eclass - /" -i CMakeLists.txt || die + fi +} + +# @FUNCTION: ecm_pkg_pretend +# @DESCRIPTION: +# Checks if the active compiler meets the minimum version requirements. +# phase function is only exported if KDE_GCC_MINIMAL is defined. +ecm_pkg_pretend() { + debug-print-function ${FUNCNAME} "$@" + _ecm_check_gcc_version +} + +# @FUNCTION: ecm_pkg_setup +# @DESCRIPTION: +# Checks if the active compiler meets the minimum version requirements. +ecm_pkg_setup() { + debug-print-function ${FUNCNAME} "$@" + _ecm_check_gcc_version +} + +# @FUNCTION: ecm_src_prepare +# @DESCRIPTION: +# Wrapper for cmake_src_prepare with lots of extra logic for magic +# handling of linguas, tests, handbook etc. +ecm_src_prepare() { + debug-print-function ${FUNCNAME} "$@" + + cmake_src_prepare + + # only build examples when required + if ! { in_iuse examples && use examples; } ; then + cmake_comment_add_subdirectory examples + fi + + # only enable handbook when required + if in_iuse handbook && ! use handbook ; then + cmake_comment_add_subdirectory ${ECM_HANDBOOK_DIR} + + if [[ ${ECM_HANDBOOK} = forceoptional ]] ; then + ecm_punt_bogus_dep KF5 DocTools + sed -i -e "/kdoctools_install/ s/^/#DONT/" CMakeLists.txt || die + fi + fi + + # drop translations when nls is not wanted + if in_iuse nls && ! use nls ; then + local po + for po in ${ECM_PO_DIRS}; do + rm -rf ${po} || die + done + fi + + # limit playing field of locale stripping to kde-*/ categories + if [[ ${CATEGORY} = kde-* ]] ; then + # always install unconditionally for kconfigwidgets - if you use + # language X as system language, and there is a combobox with language + # names, the translated language name for language Y is taken from + # /usr/share/locale/Y/kf5_entry.desktop + [[ ${PN} != kconfigwidgets ]] && _ecm_strip_handbook_translations + fi + + # only build unit tests when required + if ! { in_iuse test && use test; } ; then + if [[ ${ECM_TEST} = forceoptional ]] ; then + ecm_punt_bogus_dep Qt5 Test + # if forceoptional, also cover non-kde categories + cmake_comment_add_subdirectory autotests test tests + elif [[ ${ECM_TEST} = forceoptional-recursive ]] ; then + ecm_punt_bogus_dep Qt5 Test + local f pf="${T}/${P}"-tests-optional.patch + touch ${pf} || die "Failed to touch patch file" + for f in $(find . -type f -name "CMakeLists.txt" -exec \ + grep -l "^\s*add_subdirectory\s*\(\s*.*\(auto|unit\)\?tests\?\s*)\s*\)" {} \;); do + cp ${f} ${f}.old || die "Failed to prepare patch origfile" + pushd ${f%/*} > /dev/null || die + ecm_punt_bogus_dep Qt5 Test + sed -i CMakeLists.txt -e \ + "/^#/! s/add_subdirectory\s*\(\s*.*\(auto|unit\)\?tests\?\s*)\s*\)/if(BUILD_TESTING)\n&\nendif()/" \ + || die + popd > /dev/null || die + diff -Naur ${f}.old ${f} 1>>${pf} + rm ${f}.old || die "Failed to clean up" + done + eqawarn "Build system was modified by ECM_TEST=forceoptional-recursive." + eqawarn "Unified diff file ready for pickup in:" + eqawarn " ${pf}" + eqawarn "Push it upstream to make this message go away." + elif [[ ${CATEGORY} = kde-frameworks || ${CATEGORY} = kde-plasma || ${CATEGORY} = kde-apps ]] ; then + cmake_comment_add_subdirectory autotests test tests + fi + fi + + # in frameworks, tests = manual tests so never build them + if [[ ${CATEGORY} = kde-frameworks ]] && [[ ${PN} != extra-cmake-modules ]]; then + cmake_comment_add_subdirectory tests + fi +} + +# @FUNCTION: ecm_src_configure +# @DESCRIPTION: +# Wrapper for cmake_src_configure with extra logic for magic handling of +# handbook, tests etc. +ecm_src_configure() { + debug-print-function ${FUNCNAME} "$@" + + if in_iuse debug && ! use debug; then + append-cppflags -DQT_NO_DEBUG + fi + + local cmakeargs + + if in_iuse test && ! use test ; then + cmakeargs+=( -DBUILD_TESTING=OFF ) + + if [[ ${ECM_TEST} = optional ]] ; then + cmakeargs+=( -DCMAKE_DISABLE_FIND_PACKAGE_Qt5Test=ON ) + fi + fi + + if [[ ${ECM_HANDBOOK} = optional ]] ; then + cmakeargs+=( -DCMAKE_DISABLE_FIND_PACKAGE_KF5DocTools=$(usex !handbook) ) + fi + + if in_iuse designer && [[ ${ECM_DESIGNERPLUGIN} = true ]]; then + cmakeargs+=( -DBUILD_DESIGNERPLUGIN=$(usex designer) ) + fi + + if [[ ${ECM_QTHELP} = true ]]; then + cmakeargs+=( -DBUILD_QCH=$(usex doc) ) + fi + + if [[ ${ECM_KDEINSTALLDIRS} = true ]] ; then + cmakeargs+=( + # install mkspecs in the same directory as Qt stuff + -DKDE_INSTALL_USE_QT_SYS_PATHS=ON + # move handbook outside of doc dir, bug 667138 + -DKDE_INSTALL_DOCBUNDLEDIR="${EPREFIX}/usr/share/help" + ) + fi + + # allow the ebuild to override what we set here + mycmakeargs=("${cmakeargs[@]}" "${mycmakeargs[@]}") + + cmake_src_configure +} + +# @FUNCTION: ecm_src_compile +# @DESCRIPTION: +# Wrapper for cmake_src_compile. Currently doesn't do anything extra, but +# is included as part of the API just in case it's needed in the future. +ecm_src_compile() { + debug-print-function ${FUNCNAME} "$@" + + cmake_src_compile "$@" +} + +# @FUNCTION: ecm_src_test +# @DESCRIPTION: +# Wrapper for cmake_src_test with extra logic for magic handling of dbus +# and virtualx. +ecm_src_test() { + debug-print-function ${FUNCNAME} "$@" + + _test_runner() { + if [[ -n "${VIRTUALDBUS_TEST}" ]]; then + export $(dbus-launch) + fi + + cmake_src_test + } + + # When run as normal user during ebuild development with the ebuild command, + # tests tend to access the session DBUS. This however is not possible in a + # real emerge or on the tinderbox. + # make sure it does not happen, so bad tests can be recognized and disabled + unset DBUS_SESSION_BUS_ADDRESS DBUS_SESSION_BUS_PID + + if [[ ${VIRTUALX_REQUIRED} = always || ${VIRTUALX_REQUIRED} = test ]]; then + virtx _test_runner + else + _test_runner + fi + + if [[ -n "${DBUS_SESSION_BUS_PID}" ]] ; then + kill ${DBUS_SESSION_BUS_PID} + fi +} + +# @FUNCTION: ecm_src_install +# @DESCRIPTION: +# Wrapper for cmake_src_install. Currently doesn't do anything extra, but +# is included as part of the API just in case it's needed in the future. +ecm_src_install() { + debug-print-function ${FUNCNAME} "$@" + + cmake_src_install +} + +# @FUNCTION: ecm_pkg_preinst +# @DESCRIPTION: +# Sets up environment variables required in ecm_pkg_postinst. +ecm_pkg_preinst() { + debug-print-function ${FUNCNAME} "$@" + + case ${ECM_NONGUI} in + false) xdg_pkg_preinst ;; + *) ;; + esac +} + +# @FUNCTION: ecm_pkg_postinst +# @DESCRIPTION: +# Updates the various XDG caches (icon, desktop, mime) if necessary. +ecm_pkg_postinst() { + debug-print-function ${FUNCNAME} "$@" + + case ${ECM_NONGUI} in + false) xdg_pkg_postinst ;; + *) ;; + esac + + if [[ -n ${_KDE_ORG_ECLASS} ]] && [[ -z ${I_KNOW_WHAT_I_AM_DOING} ]] && [[ ${KDE_BUILD_TYPE} = live ]]; then + einfo "WARNING! This is an experimental live ebuild of ${CATEGORY}/${PN}" + einfo "Use it at your own risk." + einfo "Do _NOT_ file bugs at bugs.gentoo.org because of this ebuild!" + fi +} + +# @FUNCTION: ecm_pkg_postrm +# @DESCRIPTION: +# Updates the various XDG caches (icon, desktop, mime) if necessary. +ecm_pkg_postrm() { + debug-print-function ${FUNCNAME} "$@" + + case ${ECM_NONGUI} in + false) xdg_pkg_postrm ;; + *) ;; + esac +} + +fi diff --git a/eclass/edos2unix.eclass b/eclass/edos2unix.eclass new file mode 100644 index 0000000..8b77484 --- /dev/null +++ b/eclass/edos2unix.eclass @@ -0,0 +1,21 @@ +# Copyright 1999-2020 Gentoo Authors +# Distributed under the terms of the GNU General Public License v2 + +# @ECLASS: edos2unix.eclass +# @MAINTAINER: +# base-system@gentoo.org +# @BLURB: convert files from DOS CRLF to UNIX LF line endings + +# @FUNCTION: edos2unix +# @USAGE: <file> [more files ...] +# @DESCRIPTION: +# A handy replacement for dos2unix, recode, fixdos, etc... This allows +# you to remove all of these text utilities from DEPEND variables +# because this is a script based solution. Just give it a list of files +# to convert and they will all be changed from the DOS CRLF format to +# the UNIX LF format. + +edos2unix() { + [[ $# -eq 0 ]] && return 0 + sed -i 's/\r$//' -- "$@" || die +} diff --git a/eclass/elisp-common.eclass b/eclass/elisp-common.eclass new file mode 100644 index 0000000..66a3a32 --- /dev/null +++ b/eclass/elisp-common.eclass @@ -0,0 +1,503 @@ +# Copyright 1999-2020 Gentoo Authors +# Distributed under the terms of the GNU General Public License v2 + +# @ECLASS: elisp-common.eclass +# @MAINTAINER: +# Gentoo GNU Emacs project <gnu-emacs@gentoo.org> +# @AUTHOR: +# Matthew Kennedy <mkennedy@gentoo.org> +# Jeremy Maitin-Shepard <jbms@attbi.com> +# Mamoru Komachi <usata@gentoo.org> +# Christian Faulhammer <fauli@gentoo.org> +# Ulrich Müller <ulm@gentoo.org> +# @BLURB: Emacs-related installation utilities +# @DESCRIPTION: +# +# Usually you want to use this eclass for (optional) GNU Emacs support +# of your package. This is NOT for XEmacs! +# +# Many of the steps here are sometimes done by the build system of your +# package (especially compilation), so this is mainly for standalone +# elisp files you gathered from somewhere else. +# +# When relying on the emacs USE flag, you need to add +# +# @CODE +# emacs? ( >=app-editors/emacs-23.1:* ) +# @CODE +# +# to your DEPEND/RDEPEND line and use the functions provided here to +# bring the files to the correct locations. +# +# If your package requires a minimum Emacs version, e.g. Emacs 26.1, +# then the dependency should be on >=app-editors/emacs-26.1:* instead. +# Because the user can select the Emacs executable with eselect, you +# should also make sure that the active Emacs version is sufficient. +# The eclass will automatically ensure this if you assign variable +# NEED_EMACS with the Emacs version, as in the following example: +# +# @CODE +# NEED_EMACS=26.1 +# @CODE +# +# Please note that this should be done only for packages that are known +# to fail with lower Emacs versions. +# +# @SUBSECTION src_compile() usage: +# +# An elisp file is compiled by the elisp-compile() function defined +# here and simply takes the source files as arguments. The case of +# interdependent elisp files is also supported, since the current +# directory is added to the load-path which makes sure that all files +# are loadable. +# +# @CODE +# elisp-compile *.el +# @CODE +# +# Function elisp-make-autoload-file() can be used to generate a file +# with autoload definitions for the lisp functions. It takes the output +# file name (default: "${PN}-autoloads.el") and a list of directories +# (default: working directory) as its arguments. Use of this function +# requires that the elisp source files contain magic ";;;###autoload" +# comments. See the Emacs Lisp Reference Manual (node "Autoload") for +# a detailed explanation. +# +# @SUBSECTION src_install() usage: +# +# The resulting compiled files (.elc) should be put in a subdirectory of +# /usr/share/emacs/site-lisp/ which is named after the first argument +# of elisp-install(). The following parameters are the files to be put +# in that directory. Usually the subdirectory should be ${PN}, you can +# choose something else, but remember to tell elisp-site-file-install() +# (see below) the change, as it defaults to ${PN}. +# +# @CODE +# elisp-install ${PN} *.el *.elc +# @CODE +# +# To let the Emacs support be activated by Emacs on startup, you need +# to provide a site file (shipped in ${FILESDIR}) which contains the +# startup code (have a look in the documentation of your software). +# Normally this would look like this: +# +# @CODE +# (add-to-list 'load-path "@SITELISP@") +# (add-to-list 'auto-mode-alist '("\\.csv\\'" . csv-mode)) +# (autoload 'csv-mode "csv-mode" "Major mode for csv files." t) +# @CODE +# +# If your Emacs support files are installed in a subdirectory of +# /usr/share/emacs/site-lisp/ (which is strongly recommended), you need +# to extend Emacs' load-path as shown in the first non-comment line. +# The elisp-site-file-install() function of this eclass will replace +# "@SITELISP@" and "@SITEETC@" by the actual paths. +# +# The next line tells Emacs to load the mode opening a file ending +# with ".csv" and load functions depending on the context and needed +# features. Be careful though. Commands as "load-library" or "require" +# bloat the editor as they are loaded on every startup. When having +# many Emacs support files, users may be annoyed by the start-up time. +# Also avoid keybindings as they might interfere with the user's +# settings. Give a hint in pkg_postinst(), which should be enough. +# The guiding principle is that emerging your package should not by +# itself cause a change of standard Emacs behaviour. +# +# The naming scheme for this site-init file matches the shell pattern +# "[1-8][0-9]*-gentoo*.el", where the two digits at the beginning define +# the loading order (numbers below 10 or above 89 are reserved for +# internal use). So if your initialisation depends on another Emacs +# package, your site file's number must be higher! If there are no such +# interdependencies then the number should be 50. Otherwise, numbers +# divisible by 10 are preferred. +# +# Best practice is to define a SITEFILE variable in the global scope of +# your ebuild (e.g., right after S or RDEPEND): +# +# @CODE +# SITEFILE="50${PN}-gentoo.el" +# @CODE +# +# Which is then installed by +# +# @CODE +# elisp-site-file-install "${FILESDIR}/${SITEFILE}" +# @CODE +# +# in src_install(). Any characters after the "-gentoo" part and before +# the extension will be stripped from the destination file's name. +# For example, a file "50${PN}-gentoo-${PV}.el" will be installed as +# "50${PN}-gentoo.el". If your subdirectory is not named ${PN}, give +# the differing name as second argument. +# +# @SUBSECTION pkg_setup() usage: +# +# If your ebuild uses the elisp-compile eclass function to compile +# its elisp files (see above), then you don't need a pkg_setup phase, +# because elisp-compile and elisp-make-autoload-file do their own sanity +# checks. On the other hand, if the elisp files are compiled by the +# package's build system, then there is often no check for the Emacs +# version. In this case, you can add an explicit check in pkg_setup: +# +# @CODE +# elisp-check-emacs-version +# @CODE +# +# When having optional Emacs support, you should prepend "use emacs &&" +# to above call of elisp-check-emacs-version(). +# +# @SUBSECTION pkg_postinst() / pkg_postrm() usage: +# +# After that you need to recreate the start-up file of Emacs after +# emerging and unmerging by using +# +# @CODE +# pkg_postinst() { +# elisp-site-regen +# } +# +# pkg_postrm() { +# elisp-site-regen +# } +# @CODE +# +# Again, with optional Emacs support, you should prepend "use emacs &&" +# to above calls of elisp-site-regen(). + +case ${EAPI:-0} in + 4|5|6) inherit eapi7-ver ;; + 7) ;; + *) die "${ECLASS}: EAPI ${EAPI:-0} not supported" ;; +esac + +# @ECLASS-VARIABLE: SITELISP +# @DESCRIPTION: +# Directory where packages install Emacs Lisp files. +SITELISP=/usr/share/emacs/site-lisp + +# @ECLASS-VARIABLE: SITEETC +# @DESCRIPTION: +# Directory where packages install miscellaneous (not Lisp) files. +SITEETC=/usr/share/emacs/etc + +# @ECLASS-VARIABLE: EMACSMODULES +# @DESCRIPTION: +# Directory where packages install dynamically loaded modules. +# May contain a @libdir@ token which will be replaced by $(get_libdir). +EMACSMODULES=/usr/@libdir@/emacs/modules + +# @ECLASS-VARIABLE: EMACS +# @DESCRIPTION: +# Path of Emacs executable. +EMACS=${EPREFIX}/usr/bin/emacs + +# @ECLASS-VARIABLE: EMACSFLAGS +# @DESCRIPTION: +# Flags for executing Emacs in batch mode. +# These work for Emacs versions 18-24, so don't change them. +EMACSFLAGS="-batch -q --no-site-file" + +# @ECLASS-VARIABLE: BYTECOMPFLAGS +# @DESCRIPTION: +# Emacs flags used for byte-compilation in elisp-compile(). +BYTECOMPFLAGS="-L ." + +# @ECLASS-VARIABLE: NEED_EMACS +# @DESCRIPTION: +# The minimum Emacs version required for the package. +: ${NEED_EMACS:=23.1} + +# @ECLASS-VARIABLE: _ELISP_EMACS_VERSION +# @INTERNAL +# @DESCRIPTION: +# Cached value of Emacs version detected in elisp-check-emacs-version(). +_ELISP_EMACS_VERSION="" + +# @FUNCTION: elisp-emacs-version +# @RETURN: exit status of Emacs +# @DESCRIPTION: +# Output version of currently active Emacs. + +elisp-emacs-version() { + local version ret + # The following will work for at least versions 18-24. + echo "(princ emacs-version)" >"${T}"/emacs-version.el + version=$( + # EMACS could be a microemacs variant that ignores the -batch + # option and would therefore hang, waiting for user interaction. + # Redirecting stdin and unsetting TERM and DISPLAY will cause + # most of them to exit with an error. + unset TERM DISPLAY + ${EMACS} ${EMACSFLAGS} -l "${T}"/emacs-version.el </dev/null + ) + ret=$? + rm -f "${T}"/emacs-version.el + if [[ ${ret} -ne 0 ]]; then + eerror "elisp-emacs-version: Failed to run ${EMACS}" + return ${ret} + fi + if [[ -z ${version} ]]; then + eerror "elisp-emacs-version: Could not determine Emacs version" + return 1 + fi + echo "${version}" +} + +# @FUNCTION: elisp-check-emacs-version +# @USAGE: [version] +# @DESCRIPTION: +# Test if the eselected Emacs version is at least the version of +# GNU Emacs specified in the NEED_EMACS variable, or die otherwise. + +elisp-check-emacs-version() { + if [[ -z ${_ELISP_EMACS_VERSION} ]]; then + local have_emacs + have_emacs=$(elisp-emacs-version) \ + || die "Could not determine Emacs version" + einfo "Emacs version: ${have_emacs}" + if [[ ${have_emacs} =~ XEmacs|Lucid ]]; then + die "XEmacs detected. This package needs GNU Emacs." + fi + # GNU Emacs versions have only numeric components. + if ! [[ ${have_emacs} =~ ^[0-9]+(\.[0-9]+)*$ ]]; then + die "Malformed version string: ${have_emacs}" + fi + _ELISP_EMACS_VERSION=${have_emacs} + fi + + if ! ver_test "${_ELISP_EMACS_VERSION}" -ge "${NEED_EMACS}"; then + eerror "This package needs at least Emacs ${NEED_EMACS}." + eerror "Use \"eselect emacs\" to select the active version." + die "Emacs version too low" + fi +} + +# Test if the eselected Emacs version is at least the major version +# of GNU Emacs specified as argument. +# Return 0 if true, 1 if false, 2 if trouble. +# Deprecated, use elisp-check-emacs-version instead. + +elisp-need-emacs() { + local need_emacs=$1 have_emacs + have_emacs=$(elisp-emacs-version) || return 2 + einfo "Emacs version: ${have_emacs}" + if [[ ${have_emacs} =~ XEmacs|Lucid ]]; then + eerror "This package needs GNU Emacs." + return 1 + fi + if ! [[ ${have_emacs%%.*} -ge ${need_emacs%%.*} ]]; then + eerror "This package needs at least Emacs ${need_emacs%%.*}." + eerror "Use \"eselect emacs\" to select the active version." + return 1 + fi + return 0 +} + +# @FUNCTION: elisp-compile +# @USAGE: <list of elisp files> +# @DESCRIPTION: +# Byte-compile Emacs Lisp files. +# +# This function uses GNU Emacs to byte-compile all ".el" specified by +# its arguments. The resulting byte-code (".elc") files are placed in +# the same directory as their corresponding source file. +# +# The current directory is added to the load-path. This will ensure +# that interdependent Emacs Lisp files are visible between themselves, +# in case they require or load one another. + +elisp-compile() { + elisp-check-emacs-version + + ebegin "Compiling GNU Emacs Elisp files" + ${EMACS} ${EMACSFLAGS} ${BYTECOMPFLAGS} -f batch-byte-compile "$@" + eend $? "elisp-compile: batch-byte-compile failed" || die +} + +# @FUNCTION: elisp-make-autoload-file +# @USAGE: [output file] [list of directories] +# @DESCRIPTION: +# Generate a file with autoload definitions for the lisp functions. + +elisp-make-autoload-file() { + local f="${1:-${PN}-autoloads.el}" null="" page=$'\f' + shift + elisp-check-emacs-version + + ebegin "Generating autoload file for GNU Emacs" + + cat >"${f}" <<-EOF + ;;; ${f##*/} --- autoloads for ${PN} + + ;;; Commentary: + ;; Automatically generated by elisp-common.eclass + ;; DO NOT EDIT THIS FILE + + ;;; Code: + ${page} + ;; Local ${null}Variables: + ;; version-control: never + ;; no-byte-compile: t + ;; no-update-autoloads: t + ;; End: + + ;;; ${f##*/} ends here + EOF + + ${EMACS} ${EMACSFLAGS} \ + --eval "(setq make-backup-files nil)" \ + --eval "(setq generated-autoload-file (expand-file-name \"${f}\"))" \ + -f batch-update-autoloads "${@-.}" + + eend $? "elisp-make-autoload-file: batch-update-autoloads failed" || die +} + +# @FUNCTION: elisp-install +# @USAGE: <subdirectory> <list of files> +# @DESCRIPTION: +# Install files in SITELISP directory. + +elisp-install() { + local subdir="$1" + shift + ebegin "Installing Elisp files for GNU Emacs support" + ( # subshell to avoid pollution of calling environment + insinto "${SITELISP}/${subdir}" + doins "$@" + ) + eend $? "elisp-install: doins failed" || die +} + +# @FUNCTION: elisp-modules-install +# @USAGE: <subdirectory> <list of files> +# @DESCRIPTION: +# Install dynamic modules in EMACSMODULES directory. + +elisp-modules-install() { + local subdir="$1" + shift + # Don't bother inheriting multilib.eclass for get_libdir(), but + # error out in old EAPIs that don't support it natively. + [[ ${EAPI} == [45] ]] \ + && die "${ECLASS}: Dynamic modules not supported in EAPI ${EAPI}" + ebegin "Installing dynamic modules for GNU Emacs support" + ( # subshell to avoid pollution of calling environment + exeinto "${EMACSMODULES//@libdir@/$(get_libdir)}/${subdir}" + doexe "$@" + ) + eend $? "elisp-modules-install: doins failed" || die +} + +# @FUNCTION: elisp-site-file-install +# @USAGE: <site-init file> [subdirectory] +# @DESCRIPTION: +# Install Emacs site-init file in SITELISP directory. Automatically +# inserts a standard comment header with the name of the package +# (unless it is already present). Tokens @SITELISP@, @SITEETC@, +# and @EMACSMODULES@ are replaced by the path to the package's +# subdirectory in SITELISP, SITEETC, and EMACSMODULES, respectively. + +elisp-site-file-install() { + local sf="${1##*/}" my_pn="${2:-${PN}}" modules ret + local header=";;; ${PN} site-lisp configuration" + + [[ ${sf} == [0-9][0-9]*-gentoo*.el ]] \ + || ewarn "elisp-site-file-install: bad name of site-init file" + [[ ${sf%-gentoo*.el} != "${sf}" ]] && sf="${sf%-gentoo*.el}-gentoo.el" + sf="${T}/${sf}" + ebegin "Installing site initialisation file for GNU Emacs" + [[ $1 = "${sf}" ]] || cp "$1" "${sf}" + if [[ ${EAPI} == [45] ]]; then + grep -q "@EMACSMODULES@" "${sf}" \ + && die "${ECLASS}: Dynamic modules not supported in EAPI ${EAPI}" + else + modules=${EMACSMODULES//@libdir@/$(get_libdir)} + fi + sed -i -e "1{:x;/^\$/{n;bx;};/^;.*${PN}/I!s:^:${header}\n\n:;1s:^:\n:;}" \ + -e "s:@SITELISP@:${EPREFIX}${SITELISP}/${my_pn}:g" \ + -e "s:@SITEETC@:${EPREFIX}${SITEETC}/${my_pn}:g" \ + -e "s:@EMACSMODULES@:${EPREFIX}${modules}/${my_pn}:g;\$q" "${sf}" + ( # subshell to avoid pollution of calling environment + insinto "${SITELISP}/site-gentoo.d" + doins "${sf}" + ) + ret=$? + rm -f "${sf}" + eend ${ret} "elisp-site-file-install: doins failed" || die +} + +# @FUNCTION: elisp-site-regen +# @DESCRIPTION: +# Regenerate the site-gentoo.el file, based on packages' site +# initialisation files in the /usr/share/emacs/site-lisp/site-gentoo.d/ +# directory. + +elisp-site-regen() { + local sitelisp=${ROOT%/}${EPREFIX}${SITELISP} + local sf i ret=0 null="" page=$'\f' + local -a sflist + + if [[ ${EBUILD_PHASE} = *rm && ! -e ${sitelisp}/site-gentoo.el ]]; then + ewarn "Refusing to create site-gentoo.el in ${EBUILD_PHASE} phase." + return 0 + fi + + [[ -d ${sitelisp} ]] \ + || die "elisp-site-regen: Directory ${sitelisp} does not exist" + + [[ -d ${T} ]] \ + || die "elisp-site-regen: Temporary directory ${T} does not exist" + + ebegin "Regenerating site-gentoo.el for GNU Emacs (${EBUILD_PHASE})" + + for sf in "${sitelisp}"/site-gentoo.d/[0-9][0-9]*.el; do + [[ -r ${sf} ]] && sflist+=("${sf}") + done + + cat <<-EOF >"${T}"/site-gentoo.el || ret=$? + ;;; site-gentoo.el --- site initialisation for Gentoo-installed packages + + ;;; Commentary: + ;; Automatically generated by elisp-common.eclass + ;; DO NOT EDIT THIS FILE + + ;;; Code: + EOF + # Use sed instead of cat here, since files may miss a trailing newline. + sed '$q' "${sflist[@]}" </dev/null >>"${T}"/site-gentoo.el || ret=$? + cat <<-EOF >>"${T}"/site-gentoo.el || ret=$? + + ${page} + (provide 'site-gentoo) + + ;; Local ${null}Variables: + ;; no-byte-compile: t + ;; buffer-read-only: t + ;; End: + + ;;; site-gentoo.el ends here + EOF + + if [[ ${ret} -ne 0 ]]; then + eend ${ret} "elisp-site-regen: Writing site-gentoo.el failed." + die + elif cmp -s "${sitelisp}"/site-gentoo.el "${T}"/site-gentoo.el; then + # This prevents outputting unnecessary text when there + # was actually no change. + # A case is a remerge where we have doubled output. + rm -f "${T}"/site-gentoo.el + eend 0 + einfo "... no changes." + else + mv "${T}"/site-gentoo.el "${sitelisp}"/site-gentoo.el + eend $? "elisp-site-regen: Replacing site-gentoo.el failed" || die + case ${#sflist[@]} in + 0) [[ ${PN} = emacs-common-gentoo ]] \ + || ewarn "... Huh? No site initialisation files found." ;; + 1) einfo "... ${#sflist[@]} site initialisation file included." ;; + *) einfo "... ${#sflist[@]} site initialisation files included." ;; + esac + fi + + return 0 +} diff --git a/eclass/elisp.eclass b/eclass/elisp.eclass new file mode 100644 index 0000000..7876928 --- /dev/null +++ b/eclass/elisp.eclass @@ -0,0 +1,202 @@ +# Copyright 2002-2020 Gentoo Authors +# Distributed under the terms of the GNU General Public License v2 + +# @ECLASS: elisp.eclass +# @MAINTAINER: +# Gentoo GNU Emacs project <gnu-emacs@gentoo.org> +# @AUTHOR: +# Matthew Kennedy <mkennedy@gentoo.org> +# Jeremy Maitin-Shepard <jbms@attbi.com> +# Christian Faulhammer <fauli@gentoo.org> +# Ulrich Müller <ulm@gentoo.org> +# @SUPPORTED_EAPIS: 4 5 6 7 +# @BLURB: Eclass for Emacs Lisp packages +# @DESCRIPTION: +# +# This eclass is designed to install elisp files of Emacs related +# packages into the site-lisp directory. The majority of elisp packages +# will only need to define the standard ebuild variables (like SRC_URI) +# and optionally SITEFILE for successful installation. +# +# Emacs support for other than pure elisp packages is handled by +# elisp-common.eclass where you won't have a dependency on Emacs itself. +# All elisp-* functions are documented there. +# +# If the package's source is a single (in whatever way) compressed elisp +# file with the file name ${P}.el, then this eclass will move ${P}.el to +# ${PN}.el in src_unpack(). + +# @ECLASS-VARIABLE: NEED_EMACS +# @DEFAULT_UNSET +# @DESCRIPTION: +# If you need anything different from Emacs 23, use the NEED_EMACS +# variable before inheriting elisp.eclass. Set it to the version your +# package uses and the dependency will be adjusted. + +# @ECLASS-VARIABLE: ELISP_PATCHES +# @DEFAULT_UNSET +# @DESCRIPTION: +# Space separated list of patches to apply after unpacking the sources. +# Patch files are searched for in the current working dir, WORKDIR, and +# FILESDIR. This variable is semi-deprecated, preferably use the +# PATCHES array instead if the EAPI supports it. + +# @ECLASS-VARIABLE: ELISP_REMOVE +# @DEFAULT_UNSET +# @DESCRIPTION: +# Space separated list of files to remove after unpacking the sources. + +# @ECLASS-VARIABLE: SITEFILE +# @DEFAULT_UNSET +# @DESCRIPTION: +# Name of package's site-init file. The filename must match the shell +# pattern "[1-8][0-9]*-gentoo.el"; numbers below 10 and above 89 are +# reserved for internal use. "50${PN}-gentoo.el" is a reasonable choice +# in most cases. + +# @ECLASS-VARIABLE: ELISP_TEXINFO +# @DEFAULT_UNSET +# @DESCRIPTION: +# Space separated list of Texinfo sources. Respective GNU Info files +# will be generated in src_compile() and installed in src_install(). + +inherit elisp-common +case ${EAPI:-0} in + 4|5) inherit epatch ;; + 6|7) ;; + *) die "${ECLASS}: EAPI ${EAPI:-0} not supported" ;; +esac + +EXPORT_FUNCTIONS src_{unpack,prepare,configure,compile,install} \ + pkg_{setup,postinst,postrm} + +RDEPEND=">=app-editors/emacs-${NEED_EMACS}:*" +case ${EAPI} in + 4) RDEPEND="${RDEPEND%:*}"; DEPEND="${RDEPEND}" ;; + 5|6) DEPEND="${RDEPEND}" ;; + *) BDEPEND="${RDEPEND}" ;; +esac + +# @FUNCTION: elisp_pkg_setup +# @DESCRIPTION: +# Test if the eselected Emacs version is sufficient to fulfil the +# version requirement of the NEED_EMACS variable. + +elisp_pkg_setup() { + elisp-check-emacs-version +} + +# @FUNCTION: elisp_src_unpack +# @DESCRIPTION: +# Unpack the sources; also handle the case of a single *.el file in +# WORKDIR for packages distributed that way. + +elisp_src_unpack() { + default + if [[ -f ${P}.el ]]; then + # the "simple elisp" case with a single *.el file in WORKDIR + mv ${P}.el ${PN}.el || die + [[ -d ${S} ]] || S=${WORKDIR} + fi +} + +# @FUNCTION: elisp_src_prepare +# @DESCRIPTION: +# Apply any patches listed in ELISP_PATCHES. Patch files are searched +# for in the current working dir, WORKDIR, and FILESDIR. + +elisp_src_prepare() { + local patch file + for patch in ${ELISP_PATCHES}; do + if [[ -f ${patch} ]]; then + file="${patch}" + elif [[ -f ${WORKDIR}/${patch} ]]; then + file="${WORKDIR}/${patch}" + elif [[ -f ${FILESDIR}/${patch} ]]; then + file="${FILESDIR}/${patch}" + else + die "Cannot find ${patch}" + fi + case ${EAPI} in + 4|5) epatch "${file}" ;; + *) eapply "${file}" ;; + esac + done + + # apply PATCHES (if supported in EAPI), and any user patches + case ${EAPI} in + 4|5) epatch_user ;; + *) default ;; + esac + + if [[ -n ${ELISP_REMOVE} ]]; then + rm ${ELISP_REMOVE} || die + fi +} + +# @FUNCTION: elisp_src_configure +# @DESCRIPTION: +# Do nothing, because Emacs packages seldomly bring a full build system. + +elisp_src_configure() { :; } + +# @FUNCTION: elisp_src_compile +# @DESCRIPTION: +# Call elisp-compile to byte-compile all Emacs Lisp (*.el) files. +# If ELISP_TEXINFO lists any Texinfo sources, call makeinfo to generate +# GNU Info files from them. + +elisp_src_compile() { + elisp-compile *.el + if [[ -n ${ELISP_TEXINFO} ]]; then + makeinfo ${ELISP_TEXINFO} || die + fi +} + +# @FUNCTION: elisp_src_install +# @DESCRIPTION: +# Call elisp-install to install all Emacs Lisp (*.el and *.elc) files. +# If the SITEFILE variable specifies a site-init file, install it with +# elisp-site-file-install. Also install any GNU Info files listed in +# ELISP_TEXINFO and documentation listed in the DOCS variable. + +elisp_src_install() { + elisp-install ${PN} *.el *.elc + if [[ -n ${SITEFILE} ]]; then + elisp-site-file-install "${FILESDIR}/${SITEFILE}" + fi + if [[ -n ${ELISP_TEXINFO} ]]; then + set -- ${ELISP_TEXINFO} + set -- ${@##*/} + doinfo ${@/%.*/.info*} + fi + # install documentation only when explicitly requested + case ${EAPI} in + 4|5) [[ -n ${DOCS} ]] && dodoc ${DOCS} ;; + *) [[ $(declare -p DOCS 2>/dev/null) == *=* ]] && einstalldocs ;; + esac + if declare -f readme.gentoo_create_doc >/dev/null; then + readme.gentoo_create_doc + fi +} + +# @FUNCTION: elisp_pkg_postinst +# @DESCRIPTION: +# Call elisp-site-regen, in order to collect the site initialisation for +# all installed Emacs Lisp packages in the site-gentoo.el file. + +elisp_pkg_postinst() { + elisp-site-regen + if declare -f readme.gentoo_print_elog >/dev/null; then + readme.gentoo_print_elog + fi +} + +# @FUNCTION: elisp_pkg_postrm +# @DESCRIPTION: +# Call elisp-site-regen, in order to collect the site initialisation for +# all installed Emacs Lisp packages in the site-gentoo.el file. + +elisp_pkg_postrm() { + elisp-site-regen +} diff --git a/eclass/emboss-r2.eclass b/eclass/emboss-r2.eclass new file mode 100644 index 0000000..7d13f19 --- /dev/null +++ b/eclass/emboss-r2.eclass @@ -0,0 +1,163 @@ +# Copyright 1999-2020 Gentoo Authors +# Distributed under the terms of the GNU General Public License v2 + +# @ECLASS: emboss-r2.eclass +# @MAINTAINER: +# sci-biology@gentoo.org +# ted.tanberry@gmail.com +# @AUTHOR: +# Original author: Author Olivier Fisette <ofisette@gmail.com> +# Next gen author: Justin Lecher <jlec@gentoo.org> +# Next gen author: Ted Tanberry <ted.tanberry@gmail.com> +# @SUPPORTED_EAPIS: 6 +# @BLURB: Use this to easy install EMBOSS and EMBASSY programs (EMBOSS add-ons). +# @DESCRIPTION: +# The inheriting ebuild must set at least EAPI=6 and provide EBO_DESCRIPTION before the inherit line. +# KEYWORDS should be set. Additionally "(R|P)DEPEND"encies and other standard +# ebuild variables can be extended (FOO+=" bar"). +# +# Example: +# +# EAPI=6 +# +# EBO_DESCRIPTION="applications from the CBS group" +# +# inherit emboss-r2 + +# @ECLASS-VARIABLE: EBO_DESCRIPTION +# @DEFAULT_UNSET +# @DESCRIPTION: +# Should be set. Completes the generic description of the embassy module as follows: +# +# EMBOSS integrated version of ${EBO_DESCRIPTION}, e.g. +# +# "EMBOSS integrated version of applications from the CBS group" +# +# Defaults to the upstream name of the module. + +if [[ ! ${_EMBOSS_R2} ]]; then + +case ${EAPI:-0} in + 6) ;; + *) die "EAPI=${EAPI} is not supported" ;; +esac + +inherit autotools flag-o-matic + +EXPORT_FUNCTIONS src_prepare src_configure src_install + +HOMEPAGE="http://emboss.sourceforge.net/" +LICENSE="LGPL-2 GPL-2" + +SLOT="0" +IUSE="mysql pdf png postgres static-libs X" + +RDEPEND=" + dev-libs/expat + dev-libs/libpcre:3 + sci-libs/plplot:= + sys-libs/zlib + mysql? ( dev-db/mysql-connector-c:0= ) + pdf? ( media-libs/libharu:= ) + png? ( media-libs/gd:2=[png] ) + postgres? ( dev-db/postgresql:= ) + X? ( x11-libs/libXt )" + +if [[ ${PN} == embassy-* ]]; then + EMBASSY_PACKAGE=yes + # The EMBASSY package name, retrieved from the inheriting ebuild's name + EN=${PN:8} + # The full name and version of the EMBASSY package (excluding the Gentoo + # revision number) + EF="${EN^^}-${PV}" + + [[ ${EBO_DESCRIPTION} ]] || die "EBO_DESCRIPTION was not set before inheriting emboss-r2.eclass" + + DESCRIPTION="EMBOSS integrated version of ${EBO_DESCRIPTION}" + SRC_URI="ftp://emboss.open-bio.org/pub/EMBOSS/${EF}.tar.gz -> embassy-${EN}-${PV}.tar.gz" + RDEPEND+=" >=sci-biology/emboss-6.6.0-r1[mysql=,pdf=,png=,postgres=,static-libs=,X=]" + + S="${WORKDIR}/${EF}" +fi + +DEPEND="${RDEPEND}" + +# @ECLASS-VARIABLE: EBO_EAUTORECONF +# @DEFAULT_UNSET +# @DESCRIPTION: +# If set, run eautoreconf from autotools.eclass after applying patches +# in emboss-r2_src_prepare. + +# @FUNCTION: emboss-r2_src_prepare +# @DESCRIPTION: +# Does the following things +# +# 1. Renames configure.in to configure.ac, if possible +# 2. Calls default_src_prepare (i.e. +# applies Gentoo and user patches in EAPI>=6) +# 3. If EBO_EAUTORECONF is set, run eautoreconf +# + +emboss-r2_src_prepare() { + if [[ -e configure.in ]]; then + mv configure.{in,ac} || die + fi + + default + [[ ${EBO_EAUTORECONF} ]] && eautoreconf +} + +# @FUNCTION: emboss-r2_src_configure +# @DESCRIPTION: +# runs econf with following options. +# +# --enable-shared +# $(use_enable static-libs static) +# $(use_with X x) +# $(use_with png pngdriver) +# $(use_with pdf hpdf) +# $(use_with mysql mysql) +# $(use_with postgres postgresql) +# --enable-large +# --without-java +# --enable-systemlibs +# +# can be appended to like econf, e.g. +# emboss-r2_src_configure --disable-shared + +emboss-r2_src_configure() { + local myconf=( + --enable-shared + $(use_enable static-libs static) + $(use_with X x) + $(use_with png pngdriver "${EPREFIX}/usr") + $(use_with pdf hpdf "${EPREFIX}/usr") + $(use_with mysql mysql "${EPREFIX}/usr/bin/mysql_config") + $(use_with postgres postgresql "${EPREFIX}/usr/bin/pg_config") + --enable-large + --without-java + --enable-systemlibs + ) + + [[ ${EMBASSY_PACKAGE} == yes ]] && \ + append-cppflags "-I${EPREFIX}/usr/include/emboss" + + econf "${myconf[@]}" "$@" +} + +# @FUNCTION: emboss-r2_src_install +# @DESCRIPTION: +# Installs the package into the staging area and removes +# extraneous .la files, if USE="-static-libs" + +emboss-r2_src_install() { + default + + # delete .la files + if ! use static-libs; then + find "${D}" -name '*.la' -delete || die + fi +} + +_EMBOSS_R2=1 +fi diff --git a/eclass/epatch.eclass b/eclass/epatch.eclass new file mode 100644 index 0000000..fbb4f0b --- /dev/null +++ b/eclass/epatch.eclass @@ -0,0 +1,469 @@ +# Copyright 1999-2020 Gentoo Authors +# Distributed under the terms of the GNU General Public License v2 + +# @ECLASS: epatch.eclass +# @MAINTAINER: +# base-system@gentoo.org +# @SUPPORTED_EAPIS: 0 1 2 3 4 5 6 +# @BLURB: easy patch application functions +# @DEPRECATED: eapply from EAPI 7 +# @DESCRIPTION: +# An eclass providing epatch and epatch_user functions to easily apply +# patches to ebuilds. Mostly superseded by eapply* in EAPI 6. + +if [[ -z ${_EPATCH_ECLASS} ]]; then + +case ${EAPI:-0} in + 0|1|2|3|4|5|6) + ;; + *) + die "${ECLASS}: banned in EAPI=${EAPI}; use eapply* instead";; +esac + +inherit estack + +# @VARIABLE: EPATCH_SOURCE +# @DESCRIPTION: +# Default directory to search for patches. +EPATCH_SOURCE="${WORKDIR}/patch" +# @VARIABLE: EPATCH_SUFFIX +# @DESCRIPTION: +# Default extension for patches (do not prefix the period yourself). +EPATCH_SUFFIX="patch.bz2" +# @VARIABLE: EPATCH_OPTS +# @DESCRIPTION: +# Options to pass to patch. Meant for ebuild/package-specific tweaking +# such as forcing the patch level (-p#) or fuzz (-F#) factor. Note that +# for single patch tweaking, you can also pass flags directly to epatch. +EPATCH_OPTS="" +# @VARIABLE: EPATCH_COMMON_OPTS +# @DESCRIPTION: +# Common options to pass to `patch`. You probably should never need to +# change these. If you do, please discuss it with base-system first to +# be sure. +# @CODE +# -g0 - keep RCS, ClearCase, Perforce and SCCS happy #24571 +# --no-backup-if-mismatch - do not leave .orig files behind +# -E - automatically remove empty files +# @CODE +EPATCH_COMMON_OPTS="-g0 -E --no-backup-if-mismatch" +# @VARIABLE: EPATCH_EXCLUDE +# @DESCRIPTION: +# List of patches not to apply. Note this is only file names, +# and not the full path. Globs accepted. +EPATCH_EXCLUDE="" +# @VARIABLE: EPATCH_SINGLE_MSG +# @DESCRIPTION: +# Change the printed message for a single patch. +EPATCH_SINGLE_MSG="" +# @VARIABLE: EPATCH_MULTI_MSG +# @DESCRIPTION: +# Change the printed message for multiple patches. +EPATCH_MULTI_MSG="Applying various patches (bugfixes/updates) ..." +# @VARIABLE: EPATCH_FORCE +# @DESCRIPTION: +# Only require patches to match EPATCH_SUFFIX rather than the extended +# arch naming style. +EPATCH_FORCE="no" +# @VARIABLE: EPATCH_USER_EXCLUDE +# @DEFAULT_UNSET +# @DESCRIPTION: +# List of patches not to apply. Note this is only file names, +# and not the full path. Globs accepted. + +# @FUNCTION: epatch +# @USAGE: [options] [patches] [dirs of patches] +# @DESCRIPTION: +# epatch is designed to greatly simplify the application of patches. It can +# process patch files directly, or directories of patches. The patches may be +# compressed (bzip/gzip/etc...) or plain text. You generally need not specify +# the -p option as epatch will automatically attempt -p0 to -p4 until things +# apply successfully. +# +# If you do not specify any patches/dirs, then epatch will default to the +# directory specified by EPATCH_SOURCE. +# +# Any options specified that start with a dash will be passed down to patch +# for this specific invocation. As soon as an arg w/out a dash is found, then +# arg processing stops. +# +# When processing directories, epatch will apply all patches that match: +# @CODE +# if ${EPATCH_FORCE} != "yes" +# ??_${ARCH}_foo.${EPATCH_SUFFIX} +# else +# *.${EPATCH_SUFFIX} +# @CODE +# The leading ?? are typically numbers used to force consistent patch ordering. +# The arch field is used to apply patches only for the host architecture with +# the special value of "all" means apply for everyone. Note that using values +# other than "all" is highly discouraged -- you should apply patches all the +# time and let architecture details be detected at configure/compile time. +# +# If EPATCH_SUFFIX is empty, then no period before it is implied when searching +# for patches to apply. +# +# Refer to the other EPATCH_xxx variables for more customization of behavior. +epatch() { + _epatch_draw_line() { + # create a line of same length as input string + [[ -z $1 ]] && set "$(printf "%65s" '')" + echo "${1//?/=}" + } + + unset P4CONFIG P4PORT P4USER # keep perforce at bay #56402 + + # First process options. We localize the EPATCH_OPTS setting + # from above so that we can pass it on in the loop below with + # any additional values the user has specified. + local EPATCH_OPTS=( ${EPATCH_OPTS[*]} ) + while [[ $# -gt 0 ]] ; do + case $1 in + -*) EPATCH_OPTS+=( "$1" ) ;; + *) break ;; + esac + shift + done + + # Let the rest of the code process one user arg at a time -- + # each arg may expand into multiple patches, and each arg may + # need to start off with the default global EPATCH_xxx values + if [[ $# -gt 1 ]] ; then + local m + for m in "$@" ; do + epatch "${m}" + done + return 0 + fi + + local SINGLE_PATCH="no" + # no args means process ${EPATCH_SOURCE} + [[ $# -eq 0 ]] && set -- "${EPATCH_SOURCE}" + + if [[ -f $1 ]] ; then + SINGLE_PATCH="yes" + set -- "$1" + # Use the suffix from the single patch (localize it); the code + # below will find the suffix for us + local EPATCH_SUFFIX=$1 + + elif [[ -d $1 ]] ; then + # We have to force sorting to C so that the wildcard expansion is consistent #471666. + evar_push_set LC_COLLATE C + # Some people like to make dirs of patches w/out suffixes (vim). + set -- "$1"/*${EPATCH_SUFFIX:+."${EPATCH_SUFFIX}"} + evar_pop + + elif [[ -f ${EPATCH_SOURCE}/$1 ]] ; then + # Re-use EPATCH_SOURCE as a search dir + epatch "${EPATCH_SOURCE}/$1" + return $? + + else + # sanity check ... if it isn't a dir or file, wtf man ? + [[ $# -ne 0 ]] && EPATCH_SOURCE=$1 + echo + eerror "Cannot find \$EPATCH_SOURCE! Value for \$EPATCH_SOURCE is:" + eerror + eerror " ${EPATCH_SOURCE}" + eerror " ( ${EPATCH_SOURCE##*/} )" + echo + die "Cannot find \$EPATCH_SOURCE!" + fi + + # Now that we know we're actually going to apply something, merge + # all of the patch options back in to a single variable for below. + EPATCH_OPTS="${EPATCH_COMMON_OPTS} ${EPATCH_OPTS[*]}" + + local PIPE_CMD + case ${EPATCH_SUFFIX##*\.} in + xz) PIPE_CMD="xz -dc" ;; + lzma) PIPE_CMD="lzma -dc" ;; + bz2) PIPE_CMD="bzip2 -dc" ;; + gz|Z|z) PIPE_CMD="gzip -dc" ;; + ZIP|zip) PIPE_CMD="unzip -p" ;; + *) ;; + esac + + [[ ${SINGLE_PATCH} == "no" ]] && einfo "${EPATCH_MULTI_MSG}" + + local x + for x in "$@" ; do + # If the patch dir given contains subdirs, or our EPATCH_SUFFIX + # didn't match anything, ignore continue on + [[ ! -f ${x} ]] && continue + + local patchname=${x##*/} + + # Apply single patches, or forced sets of patches, or + # patches with ARCH dependant names. + # ???_arch_foo.patch + # Else, skip this input altogether + local a=${patchname#*_} # strip the ???_ + a=${a%%_*} # strip the _foo.patch + if ! [[ ${SINGLE_PATCH} == "yes" || \ + ${EPATCH_FORCE} == "yes" || \ + ${a} == all || \ + ${a} == ${ARCH} ]] + then + continue + fi + + # Let people filter things dynamically + if [[ -n ${EPATCH_EXCLUDE}${EPATCH_USER_EXCLUDE} ]] ; then + # let people use globs in the exclude + eshopts_push -o noglob + + local ex + for ex in ${EPATCH_EXCLUDE} ; do + if [[ ${patchname} == ${ex} ]] ; then + einfo " Skipping ${patchname} due to EPATCH_EXCLUDE ..." + eshopts_pop + continue 2 + fi + done + + for ex in ${EPATCH_USER_EXCLUDE} ; do + if [[ ${patchname} == ${ex} ]] ; then + einfo " Skipping ${patchname} due to EPATCH_USER_EXCLUDE ..." + eshopts_pop + continue 2 + fi + done + + eshopts_pop + fi + + if [[ ${SINGLE_PATCH} == "yes" ]] ; then + if [[ -n ${EPATCH_SINGLE_MSG} ]] ; then + einfo "${EPATCH_SINGLE_MSG}" + else + einfo "Applying ${patchname} ..." + fi + else + einfo " ${patchname} ..." + fi + + # Handle aliased patch command #404447 #461568 + local patch="patch" + eval $(alias patch 2>/dev/null | sed 's:^alias ::') + + # most of the time, there will only be one run per unique name, + # but if there are more, make sure we get unique log filenames + local STDERR_TARGET="${T}/${patchname}.out" + if [[ -e ${STDERR_TARGET} ]] ; then + STDERR_TARGET="${T}/${patchname}-$$.out" + fi + + printf "***** %s *****\nPWD: %s\nPATCH TOOL: %s -> %s\nVERSION INFO:\n%s\n\n" \ + "${patchname}" \ + "${PWD}" \ + "${patch}" \ + "$(type -P "${patch}")" \ + "$(${patch} --version)" \ + > "${STDERR_TARGET}" + + # Decompress the patch if need be + local count=0 + local PATCH_TARGET + if [[ -n ${PIPE_CMD} ]] ; then + PATCH_TARGET="${T}/$$.patch" + echo "PIPE_COMMAND: ${PIPE_CMD} ${x} > ${PATCH_TARGET}" >> "${STDERR_TARGET}" + + if ! (${PIPE_CMD} "${x}" > "${PATCH_TARGET}") >> "${STDERR_TARGET}" 2>&1 ; then + echo + eerror "Could not extract patch!" + #die "Could not extract patch!" + count=5 + break + fi + else + PATCH_TARGET=${x} + fi + + # Check for absolute paths in patches. If sandbox is disabled, + # people could (accidently) patch files in the root filesystem. + # Or trigger other unpleasantries #237667. So disallow -p0 on + # such patches. + local abs_paths=$(egrep -n '^[-+]{3} /' "${PATCH_TARGET}" | awk '$2 != "/dev/null" { print }') + if [[ -n ${abs_paths} ]] ; then + count=1 + printf "NOTE: skipping -p0 due to absolute paths in patch:\n%s\n" "${abs_paths}" >> "${STDERR_TARGET}" + fi + # Similar reason, but with relative paths. + local rel_paths=$(egrep -n '^[-+]{3} [^ ]*[.][.]/' "${PATCH_TARGET}") + if [[ -n ${rel_paths} ]] ; then + echo + eerror "Rejected Patch: ${patchname} !" + eerror " ( ${PATCH_TARGET} )" + eerror + eerror "Your patch uses relative paths '../':" + eerror "${rel_paths}" + echo + die "you need to fix the relative paths in patch" + fi + + # Dynamically detect the correct -p# ... i'm lazy, so shoot me :/ + local patch_cmd + while [[ ${count} -lt 5 ]] ; do + patch_cmd="${patch} -p${count} ${EPATCH_OPTS}" + + # Generate some useful debug info ... + ( + _epatch_draw_line "***** ${patchname} *****" + echo + echo "PATCH COMMAND: ${patch_cmd} --dry-run -f < '${PATCH_TARGET}'" + echo + _epatch_draw_line "***** ${patchname} *****" + ${patch_cmd} --dry-run -f < "${PATCH_TARGET}" 2>&1 + ret=$? + echo + echo "patch program exited with status ${ret}" + exit ${ret} + ) >> "${STDERR_TARGET}" + + if [ $? -eq 0 ] ; then + ( + _epatch_draw_line "***** ${patchname} *****" + echo + echo "ACTUALLY APPLYING ${patchname} ..." + echo "PATCH COMMAND: ${patch_cmd} < '${PATCH_TARGET}'" + echo + _epatch_draw_line "***** ${patchname} *****" + ${patch_cmd} < "${PATCH_TARGET}" 2>&1 + ret=$? + echo + echo "patch program exited with status ${ret}" + exit ${ret} + ) >> "${STDERR_TARGET}" + + if [ $? -ne 0 ] ; then + echo + eerror "A dry-run of patch command succeeded, but actually" + eerror "applying the patch failed!" + #die "Real world sux compared to the dreamworld!" + count=5 + fi + break + fi + + : $(( count++ )) + done + + (( EPATCH_N_APPLIED_PATCHES++ )) + + # if we had to decompress the patch, delete the temp one + if [[ -n ${PIPE_CMD} ]] ; then + rm -f "${PATCH_TARGET}" + fi + + if [[ ${count} -ge 5 ]] ; then + echo + eerror "Failed Patch: ${patchname} !" + eerror " ( ${PATCH_TARGET} )" + eerror + eerror "Include in your bugreport the contents of:" + eerror + eerror " ${STDERR_TARGET}" + echo + die "Failed Patch: ${patchname}!" + fi + + # if everything worked, delete the full debug patch log + rm -f "${STDERR_TARGET}" + + # then log away the exact stuff for people to review later + cat <<-EOF >> "${T}/epatch.log" + PATCH: ${x} + CMD: ${patch_cmd} + PWD: ${PWD} + + EOF + eend 0 + done + + [[ ${SINGLE_PATCH} == "no" ]] && einfo "Done with patching" + : # everything worked +} + +case ${EAPI:-0} in +0|1|2|3|4|5) + +# @VARIABLE: EPATCH_USER_SOURCE +# @DESCRIPTION: +# Location for user patches, see the epatch_user function. +# Should be set by the user. Don't set this in ebuilds. +: ${EPATCH_USER_SOURCE:=${PORTAGE_CONFIGROOT%/}/etc/portage/patches} + +# @FUNCTION: epatch_user +# @USAGE: +# @DESCRIPTION: +# Applies user-provided patches to the source tree. The patches are +# taken from /etc/portage/patches/<CATEGORY>/<P-PR|P|PN>[:SLOT]/, where the first +# of these three directories to exist will be the one to use, ignoring +# any more general directories which might exist as well. They must end +# in ".patch" to be applied. +# +# User patches are intended for quick testing of patches without ebuild +# modifications, as well as for permanent customizations a user might +# desire. Obviously, there can be no official support for arbitrarily +# patched ebuilds. So whenever a build log in a bug report mentions that +# user patches were applied, the user should be asked to reproduce the +# problem without these. +# +# Not all ebuilds do call this function, so placing patches in the +# stated directory might or might not work, depending on the package and +# the eclasses it inherits and uses. It is safe to call the function +# repeatedly, so it is always possible to add a call at the ebuild +# level. The first call is the time when the patches will be +# applied. +# +# Ideally, this function should be called after gentoo-specific patches +# have been applied, so that their code can be modified as well, but +# before calls to e.g. eautoreconf, as the user patches might affect +# autotool input files as well. +epatch_user() { + [[ $# -ne 0 ]] && die "epatch_user takes no options" + + # Allow multiple calls to this function; ignore all but the first + local applied="${T}/epatch_user.log" + [[ -e ${applied} ]] && return 2 + + # don't clobber any EPATCH vars that the parent might want + local EPATCH_SOURCE check + for check in ${CATEGORY}/{${P}-${PR},${P},${PN}}{,:${SLOT%/*}}; do + EPATCH_SOURCE=${EPATCH_USER_SOURCE}/${CTARGET}/${check} + [[ -r ${EPATCH_SOURCE} ]] || EPATCH_SOURCE=${EPATCH_USER_SOURCE}/${CHOST}/${check} + [[ -r ${EPATCH_SOURCE} ]] || EPATCH_SOURCE=${EPATCH_USER_SOURCE}/${check} + if [[ -d ${EPATCH_SOURCE} ]] ; then + local old_n_applied_patches=${EPATCH_N_APPLIED_PATCHES:-0} + EPATCH_SOURCE=${EPATCH_SOURCE} \ + EPATCH_SUFFIX="patch" \ + EPATCH_FORCE="yes" \ + EPATCH_MULTI_MSG="Applying user patches from ${EPATCH_SOURCE} ..." \ + epatch + echo "${EPATCH_SOURCE}" > "${applied}" + if [[ ${old_n_applied_patches} -lt ${EPATCH_N_APPLIED_PATCHES} ]]; then + has epatch_user_death_notice ${EBUILD_DEATH_HOOKS} || \ + EBUILD_DEATH_HOOKS+=" epatch_user_death_notice" + fi + return 0 + fi + done + echo "none" > "${applied}" + return 1 +} + +# @FUNCTION: epatch_user_death_notice +# @INTERNAL +# @DESCRIPTION: +# Include an explicit notice in the die message itself that user patches were +# applied to this build. +epatch_user_death_notice() { + ewarn "!!! User patches were applied to this build!" +} + +esac + +_EPATCH_ECLASS=1 +fi #_EPATCH_ECLASS diff --git a/eclass/estack.eclass b/eclass/estack.eclass new file mode 100644 index 0000000..c0823ad --- /dev/null +++ b/eclass/estack.eclass @@ -0,0 +1,202 @@ +# Copyright 1999-2020 Gentoo Authors +# Distributed under the terms of the GNU General Public License v2 + +# @ECLASS: estack.eclass +# @MAINTAINER: +# base-system@gentoo.org +# @BLURB: stack-like value storage support +# @DESCRIPTION: +# Support for storing values on stack-like variables. + +if [[ -z ${_ESTACK_ECLASS} ]]; then + +# @FUNCTION: estack_push +# @USAGE: <stack> [items to push] +# @DESCRIPTION: +# Push any number of items onto the specified stack. Pick a name that +# is a valid variable (i.e. stick to alphanumerics), and push as many +# items as you like onto the stack at once. +# +# The following code snippet will echo 5, then 4, then 3, then ... +# @CODE +# estack_push mystack 1 2 3 4 5 +# while estack_pop mystack i ; do +# echo "${i}" +# done +# @CODE +estack_push() { + [[ $# -eq 0 ]] && die "estack_push: incorrect # of arguments" + local stack_name="_ESTACK_$1_" ; shift + eval ${stack_name}+=\( \"\$@\" \) +} + +# @FUNCTION: estack_pop +# @USAGE: <stack> [variable] +# @DESCRIPTION: +# Pop a single item off the specified stack. If a variable is specified, +# the popped item is stored there. If no more items are available, return +# 1, else return 0. See estack_push for more info. +estack_pop() { + [[ $# -eq 0 || $# -gt 2 ]] && die "estack_pop: incorrect # of arguments" + + # We use the fugly _estack_xxx var names to avoid collision with + # passing back the return value. If we used "local i" and the + # caller ran `estack_pop ... i`, we'd end up setting the local + # copy of "i" rather than the caller's copy. The _estack_xxx + # garbage is preferable to using $1/$2 everywhere as that is a + # bit harder to read. + local _estack_name="_ESTACK_$1_" ; shift + local _estack_retvar=$1 ; shift + eval local _estack_i=\${#${_estack_name}\[@\]} + # Don't warn -- let the caller interpret this as a failure + # or as normal behavior (akin to `shift`) + [[ $(( --_estack_i )) -eq -1 ]] && return 1 + + if [[ -n ${_estack_retvar} ]] ; then + eval ${_estack_retvar}=\"\${${_estack_name}\[${_estack_i}\]}\" + fi + eval unset \"${_estack_name}\[${_estack_i}\]\" +} + +# @FUNCTION: evar_push +# @USAGE: <variable to save> [more vars to save] +# @DESCRIPTION: +# This let's you temporarily modify a variable and then restore it (including +# set vs unset semantics). Arrays are not supported at this time. +# +# This is meant for variables where using `local` does not work (such as +# exported variables, or only temporarily changing things in a func). +# +# For example: +# @CODE +# evar_push LC_ALL +# export LC_ALL=C +# ... do some stuff that needs LC_ALL=C set ... +# evar_pop +# +# # You can also save/restore more than one var at a time +# evar_push BUTTERFLY IN THE SKY +# ... do stuff with the vars ... +# evar_pop # This restores just one var, SKY +# ... do more stuff ... +# evar_pop 3 # This pops the remaining 3 vars +# @CODE +evar_push() { + local var val + for var ; do + [[ ${!var+set} == "set" ]] \ + && val=${!var} \ + || val="unset_76fc3c462065bb4ca959f939e6793f94" + estack_push evar "${var}" "${val}" + done +} + +# @FUNCTION: evar_push_set +# @USAGE: <variable to save> [new value to store] +# @DESCRIPTION: +# This is a handy shortcut to save and temporarily set a variable. If a value +# is not specified, the var will be unset. +evar_push_set() { + local var=$1 + evar_push ${var} + case $# in + 1) unset ${var} ;; + 2) printf -v "${var}" '%s' "$2" ;; + *) die "${FUNCNAME}: incorrect # of args: $*" ;; + esac +} + +# @FUNCTION: evar_pop +# @USAGE: [number of vars to restore] +# @DESCRIPTION: +# Restore the variables to the state saved with the corresponding +# evar_push call. See that function for more details. +evar_pop() { + local cnt=${1:-bad} + case $# in + 0) cnt=1 ;; + 1) [[ -z ${cnt//[0-9]} ]] \ + || die "${FUNCNAME}: first arg must be a number: $*" ;; + *) die "${FUNCNAME}: only accepts one arg: $*" ;; + esac + + local var val + while (( cnt-- )) ; do + estack_pop evar val || die "${FUNCNAME}: unbalanced push" + estack_pop evar var || die "${FUNCNAME}: unbalanced push" + [[ ${val} == "unset_76fc3c462065bb4ca959f939e6793f94" ]] \ + && unset ${var} \ + || printf -v "${var}" '%s' "${val}" + done +} + +# @FUNCTION: eshopts_push +# @USAGE: [options to `set` or `shopt`] +# @DESCRIPTION: +# Often times code will want to enable a shell option to change code behavior. +# Since changing shell options can easily break other pieces of code (which +# assume the default state), eshopts_push is used to (1) push the current shell +# options onto a stack and (2) pass the specified arguments to set. +# +# If the first argument is '-s' or '-u', we assume you want to call `shopt` +# rather than `set` as there are some options only available via that. +# +# A common example is to disable shell globbing so that special meaning/care +# may be used with variables/arguments to custom functions. That would be: +# @CODE +# eshopts_push -o noglob +# for x in ${foo} ; do +# if ...some check... ; then +# eshopts_pop +# return 0 +# fi +# done +# eshopts_pop +# @CODE +eshopts_push() { + # Save both "shopt" and "set -o" option sets, because otherwise + # restoring posix would disable expand_aliases by side effect. #662586 + estack_push eshopts "$(shopt -p -o) $(shopt -p)" + if [[ $1 == -[su] ]] ; then + [[ $# -le 1 ]] && return 0 + shopt "$@" || die "${FUNCNAME}: bad options to shopt: $*" + else + [[ $# -eq 0 ]] && return 0 + set "$@" || die "${FUNCNAME}: bad options to set: $*" + fi +} + +# @FUNCTION: eshopts_pop +# @USAGE: +# @DESCRIPTION: +# Restore the shell options to the state saved with the corresponding +# eshopts_push call. See that function for more details. +eshopts_pop() { + local s + estack_pop eshopts s || die "${FUNCNAME}: unbalanced push" + eval "${s}" || die "${FUNCNAME}: sanity: invalid shopt options: ${s}" +} + +# @FUNCTION: eumask_push +# @USAGE: <new umask> +# @DESCRIPTION: +# Set the umask to the new value specified while saving the previous +# value onto a stack. Useful for temporarily changing the umask. +eumask_push() { + estack_push eumask "$(umask)" + umask "$@" || die "${FUNCNAME}: bad options to umask: $*" +} + +# @FUNCTION: eumask_pop +# @USAGE: +# @DESCRIPTION: +# Restore the previous umask state. +eumask_pop() { + [[ $# -eq 0 ]] || die "${FUNCNAME}: we take no options" + local s + estack_pop eumask s || die "${FUNCNAME}: unbalanced push" + umask ${s} || die "${FUNCNAME}: sanity: could not restore umask: ${s}" +} + +_ESTACK_ECLASS=1 +fi #_ESTACK_ECLASS diff --git a/eclass/eutils.eclass b/eclass/eutils.eclass new file mode 100644 index 0000000..20ebe31 --- /dev/null +++ b/eclass/eutils.eclass @@ -0,0 +1,214 @@ +# Copyright 1999-2020 Gentoo Authors +# Distributed under the terms of the GNU General Public License v2 + +# @ECLASS: eutils.eclass +# @MAINTAINER: +# base-system@gentoo.org +# @SUPPORTED_EAPIS: 0 1 2 3 4 5 6 7 +# @BLURB: many extra (but common) functions that are used in ebuilds +# @DESCRIPTION: +# The eutils eclass contains a suite of functions that complement +# the ones that ebuild.sh already contain. The idea is that the functions +# are not required in all ebuilds but enough utilize them to have a common +# home rather than having multiple ebuilds implementing the same thing. +# +# Due to the nature of this eclass, some functions may have maintainers +# different from the overall eclass! +# +# This eclass is DEPRECATED and must not be inherited by any new ebuilds +# or eclasses. Use the more specific split eclasses instead, or native +# package manager functions when available. + +if [[ -z ${_EUTILS_ECLASS} ]]; then +_EUTILS_ECLASS=1 + +# implicitly inherited (now split) eclasses +case ${EAPI:-0} in + 0|1|2|3|4|5|6) + inherit desktop edos2unix epatch estack l10n ltprune multilib \ + preserve-libs toolchain-funcs vcs-clean wrapper + ;; + 7) inherit edos2unix l10n wrapper ;; + *) die "${ECLASS} is banned in EAPI ${EAPI}" ;; +esac + +# @FUNCTION: emktemp +# @USAGE: [temp dir] +# @DESCRIPTION: +# Cheap replacement for when coreutils (and thus mktemp) does not exist +# on the user's system. +emktemp() { + eqawarn "emktemp is deprecated. Create a temporary file in \${T} instead." + + local exe="touch" + [[ $1 == -d ]] && exe="mkdir" && shift + local topdir=$1 + + if [[ -z ${topdir} ]] ; then + [[ -z ${T} ]] \ + && topdir="/tmp" \ + || topdir=${T} + fi + + if ! type -P mktemp > /dev/null ; then + # system lacks `mktemp` so we have to fake it + local tmp=/ + while [[ -e ${tmp} ]] ; do + tmp=${topdir}/tmp.${RANDOM}.${RANDOM}.${RANDOM} + done + ${exe} "${tmp}" || ${exe} -p "${tmp}" + echo "${tmp}" + else + # the args here will give slightly wierd names on BSD, + # but should produce a usable file on all userlands + if [[ ${exe} == "touch" ]] ; then + TMPDIR="${topdir}" mktemp -t tmp.XXXXXXXXXX + else + TMPDIR="${topdir}" mktemp -dt tmp.XXXXXXXXXX + fi + fi +} + +path_exists() { + eerror "path_exists has been removed. Please see the following post" + eerror "for a replacement snippet:" + eerror "https://blogs.gentoo.org/mgorny/2018/08/09/inlining-path_exists/" + die "path_exists is banned" +} + +# @FUNCTION: use_if_iuse +# @USAGE: <flag> +# @DESCRIPTION: +# Return true if the given flag is in USE and IUSE. +# +# Note that this function should not be used in the global scope. +use_if_iuse() { + eqawarn "use_if_iuse is deprecated." + eqawarn "Define it as a local function, or inline it:" + eqawarn " in_iuse foo && use foo" + in_iuse $1 || return 1 + use $1 +} + +case ${EAPI:-0} in +0|1|2|3|4) + +# @FUNCTION: usex +# @USAGE: <USE flag> [true output] [false output] [true suffix] [false suffix] +# @DESCRIPTION: +# Proxy to declare usex for package managers or EAPIs that do not provide it +# and use the package manager implementation when available (i.e. EAPI >= 5). +# If USE flag is set, echo [true output][true suffix] (defaults to "yes"), +# otherwise echo [false output][false suffix] (defaults to "no"). +usex() { use "$1" && echo "${2-yes}$4" || echo "${3-no}$5" ; } #382963 + +;; +esac + +case ${EAPI:-0} in +0|1|2|3|4|5) + +# @FUNCTION: einstalldocs +# @DESCRIPTION: +# Install documentation using DOCS and HTML_DOCS, in EAPIs that do not +# provide this function. When available (i.e., in EAPI 6 or later), +# the package manager implementation should be used instead. +# +# If DOCS is declared and non-empty, all files listed in it are +# installed. The files must exist, otherwise the function will fail. +# In EAPI 4 and 5, DOCS may specify directories as well; in earlier +# EAPIs using directories is unsupported. +# +# If DOCS is not declared, the files matching patterns given +# in the default EAPI implementation of src_install will be installed. +# If this is undesired, DOCS can be set to empty value to prevent any +# documentation from being installed. +# +# If HTML_DOCS is declared and non-empty, all files and/or directories +# listed in it are installed as HTML docs (using dohtml). +# +# Both DOCS and HTML_DOCS can either be an array or a whitespace- +# separated list. Whenever directories are allowed, '<directory>/.' may +# be specified in order to install all files within the directory +# without creating a sub-directory in docdir. +# +# Passing additional options to dodoc and dohtml is not supported. +# If you needed such a thing, you need to call those helpers explicitly. +einstalldocs() { + debug-print-function ${FUNCNAME} "${@}" + + local dodoc_opts=-r + has ${EAPI} 0 1 2 3 && dodoc_opts= + + if ! declare -p DOCS &>/dev/null ; then + local d + for d in README* ChangeLog AUTHORS NEWS TODO CHANGES \ + THANKS BUGS FAQ CREDITS CHANGELOG ; do + if [[ -s ${d} ]] ; then + dodoc "${d}" || die + fi + done + elif [[ $(declare -p DOCS) == "declare -a"* ]] ; then + if [[ ${DOCS[@]} ]] ; then + dodoc ${dodoc_opts} "${DOCS[@]}" || die + fi + else + if [[ ${DOCS} ]] ; then + dodoc ${dodoc_opts} ${DOCS} || die + fi + fi + + if [[ $(declare -p HTML_DOCS 2>/dev/null) == "declare -a"* ]] ; then + if [[ ${HTML_DOCS[@]} ]] ; then + dohtml -r "${HTML_DOCS[@]}" || die + fi + else + if [[ ${HTML_DOCS} ]] ; then + dohtml -r ${HTML_DOCS} || die + fi + fi + + return 0 +} + +# @FUNCTION: in_iuse +# @USAGE: <flag> +# @DESCRIPTION: +# Determines whether the given flag is in IUSE. Strips IUSE default +# prefixes as necessary. In EAPIs where it is available (i.e., EAPI 6 +# or later), the package manager implementation should be used instead. +# +# Note that this function must not be used in the global scope. +in_iuse() { + debug-print-function ${FUNCNAME} "${@}" + [[ ${#} -eq 1 ]] || die "Invalid args to ${FUNCNAME}()" + + local flag=${1} + local liuse=( ${IUSE} ) + + has "${flag}" "${liuse[@]#[+-]}" +} + +;; +esac + +case ${EAPI:-0} in +0|1|2|3|4|5|6) + +# @FUNCTION: eqawarn +# @USAGE: [message] +# @DESCRIPTION: +# Proxy to ewarn for package managers that don't provide eqawarn and use the PM +# implementation if available. Reuses PORTAGE_ELOG_CLASSES as set by the dev +# profile. +if ! declare -F eqawarn >/dev/null ; then + eqawarn() { + has qa ${PORTAGE_ELOG_CLASSES} && ewarn "$@" + : + } +fi + +;; +esac + +fi diff --git a/eclass/fcaps.eclass b/eclass/fcaps.eclass new file mode 100644 index 0000000..4bef00d --- /dev/null +++ b/eclass/fcaps.eclass @@ -0,0 +1,194 @@ +# Copyright 1999-2020 Gentoo Authors +# Distributed under the terms of the GNU General Public License v2 + +# @ECLASS: fcaps.eclass +# @MAINTAINER: +# base-system@gentoo.org +# @BLURB: function to set POSIX file-based capabilities +# @DESCRIPTION: +# This eclass provides a function to set file-based capabilities on binaries. +# This is not the same as USE=caps which controls runtime capability changes, +# often via packages like libcap. +# +# Due to probable capability-loss on moving or copying, this happens in +# pkg_postinst phase (at least for now). +# +# @EXAMPLE: +# You can manually set the caps on ping and ping6 by doing: +# @CODE +# pkg_postinst() { +# fcaps cap_net_raw bin/ping bin/ping6 +# } +# @CODE +# +# Or set it via the global ebuild var FILECAPS: +# @CODE +# FILECAPS=( +# cap_net_raw bin/ping bin/ping6 +# ) +# @CODE + +if [[ -z ${_FCAPS_ECLASS} ]]; then +_FCAPS_ECLASS=1 + +IUSE="+filecaps" + +# Since it is needed in pkg_postinst() it must be in RDEPEND +case "${EAPI:-0}" in + [0-6]) + RDEPEND="filecaps? ( sys-libs/libcap )" + ;; + *) + BDEPEND="filecaps? ( sys-libs/libcap )" + RDEPEND="${BDEPEND}" + ;; +esac + +# @ECLASS-VARIABLE: FILECAPS +# @DEFAULT_UNSET +# @DESCRIPTION: +# An array of fcap arguments to use to automatically execute fcaps. See that +# function for more details. +# +# All args are consumed until the '--' marker is found. So if you have: +# @CODE +# FILECAPS=( moo cow -- fat cat -- chubby penguin ) +# @CODE +# +# This will end up executing: +# @CODE +# fcaps moo cow +# fcaps fat cat +# fcaps chubby penguin +# @CODE +# +# Note: If you override pkg_postinst, you must call fcaps_pkg_postinst yourself. + +# @FUNCTION: fcaps +# @USAGE: [-o <owner>] [-g <group>] [-m <mode>] [-M <caps mode>] <capabilities> <file[s]> +# @DESCRIPTION: +# Sets the specified capabilities on the specified files. +# +# The caps option takes the form as expected by the cap_from_text(3) man page. +# If no action is specified, then "=ep" will be used as a default. +# +# If the file is a relative path (e.g. bin/foo rather than /bin/foo), then the +# appropriate path var ($D/$ROOT/etc...) will be prefixed based on the current +# ebuild phase. +# +# The caps mode (default 711) is used to set the permission on the file if +# capabilities were properly set on the file. +# +# If the system is unable to set capabilities, it will use the specified user, +# group, and mode (presumably to make the binary set*id). The defaults there +# are root:0 and 4711. Otherwise, the ownership and permissions will be +# unchanged. +fcaps() { + debug-print-function ${FUNCNAME} "$@" + + if [[ ${EUID} != 0 ]] ; then + einfo "Insufficient privileges to execute ${FUNCNAME}, skipping." + return 0 + fi + + # Process the user options first. + local owner='root' + local group='0' + local mode='4711' + local caps_mode='711' + + while [[ $# -gt 0 ]] ; do + case $1 in + -o) owner=$2; shift;; + -g) group=$2; shift;; + -m) mode=$2; shift;; + -M) caps_mode=$2; shift;; + *) break;; + esac + shift + done + + [[ $# -lt 2 ]] && die "${FUNCNAME}: wrong arg count" + + local caps=$1 + [[ ${caps} == *[-=+]* ]] || caps+="=ep" + shift + + local root + case ${EBUILD_PHASE} in + compile|install|preinst) + root=${ED:-${D}} + ;; + postinst) + root=${EROOT:-${ROOT}} + ;; + esac + root=${root%/} + + # Process every file! + local file + for file ; do + [[ ${file} != /* ]] && file="${root}/${file}" + + if use filecaps ; then + # Try to set capabilities. Ignore errors when the + # fs doesn't support it, but abort on all others. + debug-print "${FUNCNAME}: setting caps '${caps}' on '${file}'" + + # If everything goes well, we don't want the file to be readable + # by people. + chmod ${caps_mode} "${file}" || die + + if ! out=$(LC_ALL=C setcap "${caps}" "${file}" 2>&1) ; then + case ${out} in + # ENOTSUP and EOPNOTSUPP might be the same value which means + # strerror() on them is unstable -- we can get both. #559608 + *"Not supported"*|\ + *"Operation not supported"*) + local fstype=$(stat -f -c %T "${file}") + ewarn "Could not set caps on '${file}' due to missing filesystem support:" + ewarn "* enable XATTR support for '${fstype}' in your kernel (if configurable)" + ewarn "* mount the fs with the user_xattr option (if not the default)" + ewarn "* enable the relevant FS_SECURITY option (if configurable)" + ;; + *) + eerror "Setting caps '${caps}' on file '${file}' failed:" + eerror "${out}" + die "could not set caps" + ;; + esac + else + # Sanity check that everything took. + setcap -v "${caps}" "${file}" >/dev/null \ + || die "Checking caps '${caps}' on '${file}' failed" + + # Everything worked. Move on to the next file. + continue + fi + fi + + # If we're still here, setcaps failed. + debug-print "${FUNCNAME}: setting owner/mode on '${file}'" + chown "${owner}:${group}" "${file}" || die + chmod ${mode} "${file}" || die + done +} + +# @FUNCTION: fcaps_pkg_postinst +# @DESCRIPTION: +# Process the FILECAPS array. +fcaps_pkg_postinst() { + local arg args=() + for arg in "${FILECAPS[@]}" "--" ; do + if [[ ${arg} == "--" ]] ; then + fcaps "${args[@]}" + args=() + else + args+=( "${arg}" ) + fi + done +} + +EXPORT_FUNCTIONS pkg_postinst + +fi diff --git a/eclass/findlib.eclass b/eclass/findlib.eclass new file mode 100644 index 0000000..8090d6c --- /dev/null +++ b/eclass/findlib.eclass @@ -0,0 +1,59 @@ +# Copyright 1999-2020 Gentoo Authors +# Distributed under the terms of the GNU General Public License v2 + +# @ECLASS: findlib.eclass +# @MAINTAINER: +# maintainer-needed@gentoo.org +# @AUTHOR: +# Original author: Matthieu Sozeau <mattam@gentoo.org> (retired) +# @BLURB: ocamlfind (a.k.a. findlib) eclass +# @DESCRIPTION: +# ocamlfind (a.k.a. findlib) eclass + +# Do not complain about CFLAGS etc since ml projects do not use them. +QA_FLAGS_IGNORED='.*' + +# From this findlib version there is proper stublibs support. +DEPEND=">=dev-ml/findlib-1.0.4-r1" +[[ ${FINDLIB_USE} ]] && DEPEND="${FINDLIB_USE}? ( ${DEPEND} )" + +check_ocamlfind() { + if [ ! -x "${EPREFIX}"/usr/bin/ocamlfind ] + then + eerror "In findlib.eclass: could not find the ocamlfind executable" + eerror "Please report this bug on gentoo's bugzilla, assigning to ml@gentoo.org" + die "ocamlfind executabled not found" + fi +} + +# @FUNCTION: findlib_src_preinst +# @DESCRIPTION: +# Prepare the image for a findlib installation. +# We use the stublibs style, so no ld.conf needs to be +# updated when a package installs C shared libraries. +findlib_src_preinst() { + has "${EAPI:-0}" 0 1 2 && ! use prefix && EPREFIX= + has "${EAPI:-0}" 0 1 2 && use !prefix && ED="${D}" + check_ocamlfind + + # destdir is the ocaml sitelib + local destdir=`ocamlfind printconf destdir` + + # strip off prefix + destdir=${destdir#${EPREFIX}} + + dodir ${destdir} || die "dodir failed" + export OCAMLFIND_DESTDIR=${ED}${destdir} + + # stublibs style + dodir ${destdir}/stublibs || die "dodir failed" + export OCAMLFIND_LDCONF=ignore +} + +# @FUNCTION: findlib_src_install +# @DESCRIPTION: +# Install with a properly setup findlib +findlib_src_install() { + findlib_src_preinst + make DESTDIR="${D}" "$@" install || die "make failed" +} diff --git a/eclass/fixheadtails.eclass b/eclass/fixheadtails.eclass new file mode 100644 index 0000000..475b182 --- /dev/null +++ b/eclass/fixheadtails.eclass @@ -0,0 +1,41 @@ +# Copyright 1999-2020 Gentoo Authors +# Distributed under the terms of the GNU General Public License v2 + +# @ECLASS: fixheadtails.eclass +# @MAINTAINER: +# base-system@gentoo.org +# @AUTHOR: +# Original author John Mylchreest <johnm@gentoo.org> +# @BLURB: functions to replace obsolete head/tail with POSIX compliant ones + +_do_sed_fix() { + einfo " - fixed $1" + sed -i \ + -e 's/head \+-\([0-9]\)/head -n \1/g' \ + -e 's/tail \+\([-+][0-9]\+\)c/tail -c \1/g' \ + -e 's/tail \+\([-+][0-9]\)/tail -n \1/g' ${1} || \ + die "sed ${1} failed" +} + +# @FUNCTION: ht_fix_file +# @USAGE: <files> +# @DESCRIPTION: +# Fix all the specified files. +ht_fix_file() { + local i + einfo "Replacing obsolete head/tail with POSIX compliant ones" + for i in "$@" ; do + _do_sed_fix "$i" + done +} + +# @FUNCTION: ht_fix_all +# @DESCRIPTION: +# Find and fix all files in the current directory as needed. +ht_fix_all() { + local MATCHES + MATCHES=$(grep -l -s -i -R -e "head -[ 0-9]" -e "tail [+-][ 0-9]" * | sort -u) + [[ -n ${MATCHES} ]] \ + && ht_fix_file ${MATCHES} \ + || einfo "No need for ht_fix_all anymore !" +} diff --git a/eclass/flag-o-matic.eclass b/eclass/flag-o-matic.eclass new file mode 100644 index 0000000..20ee39d --- /dev/null +++ b/eclass/flag-o-matic.eclass @@ -0,0 +1,776 @@ +# Copyright 1999-2020 Gentoo Authors +# Distributed under the terms of the GNU General Public License v2 + +# @ECLASS: flag-o-matic.eclass +# @MAINTAINER: +# toolchain@gentoo.org +# @BLURB: common functions to manipulate and query toolchain flags +# @DESCRIPTION: +# This eclass contains a suite of functions to help developers sanely +# and safely manage toolchain flags in their builds. + +if [[ -z ${_FLAG_O_MATIC_ECLASS} ]]; then +_FLAG_O_MATIC_ECLASS=1 + +inherit eutils toolchain-funcs multilib + +# Return all the flag variables that our high level funcs operate on. +all-flag-vars() { + echo {ADA,C,CPP,CXX,CCAS,F,FC,LD}FLAGS +} + +# {C,CPP,CXX,CCAS,F,FC,LD}FLAGS that we allow in strip-flags +# Note: shell globs and character lists are allowed +setup-allowed-flags() { + ALLOWED_FLAGS=( + -pipe -O '-O[12sg]' -mcpu -march -mtune + '-fstack-protector*' '-fsanitize*' '-fstack-check*' -fno-stack-check + -fbounds-check -fbounds-checking -fno-strict-overflow + -fno-PIE -fno-pie -nopie -no-pie -fno-unit-at-a-time + + # debugging symbols should generally be very safe to add + -g '-g[0-9]' + -ggdb '-ggdb[0-9]' + -gdwarf '-gdwarf-*' + -gstabs -gstabs+ + -gz + + -fno-ident -fpermissive -frecord-gcc-switches + '-fdiagnostics*' '-fplugin*' + '-W*' -w + + # CPPFLAGS and LDFLAGS + '-[DUILR]*' '-Wl,*' + + # Linker choice flag + '-fuse-ld' + ) + + # allow a bunch of flags that negate features / control ABI + ALLOWED_FLAGS+=( + '-fno-stack-protector*' '-fabi-version=*' + -fno-strict-aliasing -fno-bounds-check -fno-bounds-checking -fstrict-overflow + -fno-omit-frame-pointer '-fno-builtin*' + ) + ALLOWED_FLAGS+=( + -mregparm -mno-app-regs -mapp-regs -mno-mmx -mno-sse + -mno-sse2 -mno-sse3 -mno-ssse3 -mno-sse4 -mno-sse4.1 -mno-sse4.2 + -mno-avx -mno-aes -mno-pclmul -mno-sse4a -mno-3dnow -mno-popcnt + -mno-abm -mips1 -mips2 -mips3 -mips4 -mips32 -mips64 -mips16 -mplt + -msoft-float -mno-soft-float -mhard-float -mno-hard-float -mfpu + -mieee -mieee-with-inexact -mschedule -mfloat-gprs -mspe -mno-spe + -mtls-direct-seg-refs -mno-tls-direct-seg-refs -mflat -mno-flat + -mno-faster-structs -mfaster-structs -m32 -m64 -mx32 -mabi + -mlittle-endian -mbig-endian -EL -EB -fPIC -mlive-g0 -mcmodel + -mstack-bias -mno-stack-bias -msecure-plt '-m*-toc' -mfloat-abi + -mfix-r4000 -mno-fix-r4000 -mfix-r4400 -mno-fix-r4400 + -mfix-rm7000 -mno-fix-rm7000 -mfix-r10000 -mno-fix-r10000 + -mr10k-cache-barrier -mthumb -marm + + # gcc 4.5 + -mno-fma4 -mno-movbe -mno-xop -mno-lwp + # gcc 4.6 + -mno-fsgsbase -mno-rdrnd -mno-f16c -mno-bmi -mno-tbm + # gcc 4.7 + -mno-avx2 -mno-bmi2 -mno-fma -mno-lzcnt + # gcc 4.8 + -mno-fxsr -mno-hle -mno-rtm -mno-xsave -mno-xsaveopt + # gcc 4.9 + -mno-avx512cd -mno-avx512er -mno-avx512f -mno-avx512pf -mno-sha + ) + + # Allow some safe individual flags. Should come along with the bug reference. + ALLOWED_FLAGS+=( + # Allow explicit stack realignment to run non-conformant + # binaries: bug #677852 + -mstackrealign + ) +} + +# inverted filters for hardened compiler. This is trying to unpick +# the hardened compiler defaults. +_filter-hardened() { + local f + for f in "$@" ; do + case "${f}" in + # Ideally we should only concern ourselves with PIE flags, + # not -fPIC or -fpic, but too many places filter -fPIC without + # thinking about -fPIE. + -fPIC|-fpic|-fPIE|-fpie|-Wl,pie|-pie) + gcc-specs-pie || continue + if ! is-flagq -nopie && ! is-flagq -no-pie ; then + # Support older Gentoo form first (-nopie) before falling + # back to the official gcc-6+ form (-no-pie). + if test-flags -nopie >/dev/null ; then + append-flags -nopie + else + append-flags -no-pie + fi + fi + ;; + -fstack-protector) + gcc-specs-ssp || continue + is-flagq -fno-stack-protector || append-flags $(test-flags -fno-stack-protector);; + -fstack-protector-all) + gcc-specs-ssp-to-all || continue + is-flagq -fno-stack-protector-all || append-flags $(test-flags -fno-stack-protector-all);; + -fno-strict-overflow) + gcc-specs-nostrict || continue + is-flagq -fstrict-overflow || append-flags $(test-flags -fstrict-overflow);; + esac + done +} + +# Remove occurrences of strings from variable given in $1 +# Strings removed are matched as globs, so for example +# '-O*' would remove -O1, -O2 etc. +_filter-var() { + local f x var=$1 new=() + shift + + for f in ${!var} ; do + for x in "$@" ; do + # Note this should work with globs like -O* + [[ ${f} == ${x} ]] && continue 2 + done + new+=( "${f}" ) + done + export ${var}="${new[*]}" +} + +# @FUNCTION: filter-flags +# @USAGE: <flags> +# @DESCRIPTION: +# Remove particular <flags> from {C,CPP,CXX,CCAS,F,FC,LD}FLAGS. Accepts shell globs. +filter-flags() { + _filter-hardened "$@" + local v + for v in $(all-flag-vars) ; do + _filter-var ${v} "$@" + done + return 0 +} + +# @FUNCTION: filter-lfs-flags +# @DESCRIPTION: +# Remove flags that enable Large File Support. +filter-lfs-flags() { + [[ $# -ne 0 ]] && die "filter-lfs-flags takes no arguments" + # http://www.gnu.org/s/libc/manual/html_node/Feature-Test-Macros.html + # _LARGEFILE_SOURCE: enable support for new LFS funcs (ftello/etc...) + # _LARGEFILE64_SOURCE: enable support for 64bit variants (off64_t/fseeko64/etc...) + # _FILE_OFFSET_BITS: default to 64bit variants (off_t is defined as off64_t) + filter-flags -D_FILE_OFFSET_BITS=64 -D_LARGEFILE_SOURCE -D_LARGEFILE64_SOURCE +} + +# @FUNCTION: filter-ldflags +# @USAGE: <flags> +# @DESCRIPTION: +# Remove particular <flags> from LDFLAGS. Accepts shell globs. +filter-ldflags() { + _filter-var LDFLAGS "$@" + return 0 +} + +# @FUNCTION: append-cppflags +# @USAGE: <flags> +# @DESCRIPTION: +# Add extra <flags> to the current CPPFLAGS. +append-cppflags() { + [[ $# -eq 0 ]] && return 0 + export CPPFLAGS+=" $*" + return 0 +} + +# @FUNCTION: append-cflags +# @USAGE: <flags> +# @DESCRIPTION: +# Add extra <flags> to the current CFLAGS. If a flag might not be supported +# with different compilers (or versions), then use test-flags-CC like so: +# @CODE +# append-cflags $(test-flags-CC -funky-flag) +# @CODE +append-cflags() { + [[ $# -eq 0 ]] && return 0 + # Do not do automatic flag testing ourselves. #417047 + export CFLAGS+=" $*" + return 0 +} + +# @FUNCTION: append-cxxflags +# @USAGE: <flags> +# @DESCRIPTION: +# Add extra <flags> to the current CXXFLAGS. If a flag might not be supported +# with different compilers (or versions), then use test-flags-CXX like so: +# @CODE +# append-cxxflags $(test-flags-CXX -funky-flag) +# @CODE +append-cxxflags() { + [[ $# -eq 0 ]] && return 0 + # Do not do automatic flag testing ourselves. #417047 + export CXXFLAGS+=" $*" + return 0 +} + +# @FUNCTION: append-fflags +# @USAGE: <flags> +# @DESCRIPTION: +# Add extra <flags> to the current {F,FC}FLAGS. If a flag might not be supported +# with different compilers (or versions), then use test-flags-F77 like so: +# @CODE +# append-fflags $(test-flags-F77 -funky-flag) +# @CODE +append-fflags() { + [[ $# -eq 0 ]] && return 0 + # Do not do automatic flag testing ourselves. #417047 + export FFLAGS+=" $*" + export FCFLAGS+=" $*" + return 0 +} + +# @FUNCTION: append-lfs-flags +# @DESCRIPTION: +# Add flags that enable Large File Support. +append-lfs-flags() { + [[ $# -ne 0 ]] && die "append-lfs-flags takes no arguments" + # see comments in filter-lfs-flags func for meaning of these + append-cppflags -D_FILE_OFFSET_BITS=64 -D_LARGEFILE_SOURCE -D_LARGEFILE64_SOURCE +} + +# @FUNCTION: append-ldflags +# @USAGE: <flags> +# @DESCRIPTION: +# Add extra <flags> to the current LDFLAGS. +append-ldflags() { + [[ $# -eq 0 ]] && return 0 + local flag + for flag in "$@"; do + [[ ${flag} == -l* ]] && \ + eqawarn "Appending a library link instruction (${flag}); libraries to link to should not be passed through LDFLAGS" + done + + export LDFLAGS="${LDFLAGS} $*" + return 0 +} + +# @FUNCTION: append-flags +# @USAGE: <flags> +# @DESCRIPTION: +# Add extra <flags> to your current {C,CXX,F,FC}FLAGS. +append-flags() { + [[ $# -eq 0 ]] && return 0 + case " $* " in + *' '-[DIU]*) eqawarn 'please use append-cppflags for preprocessor flags' ;; + *' '-L*|\ + *' '-Wl,*) eqawarn 'please use append-ldflags for linker flags' ;; + esac + append-cflags "$@" + append-cxxflags "$@" + append-fflags "$@" + return 0 +} + +# @FUNCTION: replace-flags +# @USAGE: <old> <new> +# @DESCRIPTION: +# Replace the <old> flag with <new>. Accepts shell globs for <old>. +replace-flags() { + [[ $# != 2 ]] && die "Usage: replace-flags <old flag> <new flag>" + + local f var new + for var in $(all-flag-vars) ; do + # Looping over the flags instead of using a global + # substitution ensures that we're working with flag atoms. + # Otherwise globs like -O* have the potential to wipe out the + # list of flags. + new=() + for f in ${!var} ; do + # Note this should work with globs like -O* + [[ ${f} == ${1} ]] && f=${2} + new+=( "${f}" ) + done + export ${var}="${new[*]}" + done + + return 0 +} + +# @FUNCTION: replace-cpu-flags +# @USAGE: <old> <new> +# @DESCRIPTION: +# Replace cpu flags (like -march/-mcpu/-mtune) that select the <old> cpu +# with flags that select the <new> cpu. Accepts shell globs for <old>. +replace-cpu-flags() { + local newcpu="$#" ; newcpu="${!newcpu}" + while [ $# -gt 1 ] ; do + # quote to make sure that no globbing is done (particularly on + # ${oldcpu}) prior to calling replace-flags + replace-flags "-march=${1}" "-march=${newcpu}" + replace-flags "-mcpu=${1}" "-mcpu=${newcpu}" + replace-flags "-mtune=${1}" "-mtune=${newcpu}" + shift + done + return 0 +} + +_is_flagq() { + local x var="$1[*]" + for x in ${!var} ; do + [[ ${x} == $2 ]] && return 0 + done + return 1 +} + +# @FUNCTION: is-flagq +# @USAGE: <flag> +# @DESCRIPTION: +# Returns shell true if <flag> is in {C,CXX,F,FC}FLAGS, else returns shell false. Accepts shell globs. +is-flagq() { + [[ -n $2 ]] && die "Usage: is-flag <flag>" + + local var + for var in $(all-flag-vars) ; do + _is_flagq ${var} "$1" && return 0 + done + return 1 +} + +# @FUNCTION: is-flag +# @USAGE: <flag> +# @DESCRIPTION: +# Echo's "true" if flag is set in {C,CXX,F,FC}FLAGS. Accepts shell globs. +is-flag() { + is-flagq "$@" && echo true +} + +# @FUNCTION: is-ldflagq +# @USAGE: <flag> +# @DESCRIPTION: +# Returns shell true if <flag> is in LDFLAGS, else returns shell false. Accepts shell globs. +is-ldflagq() { + [[ -n $2 ]] && die "Usage: is-ldflag <flag>" + _is_flagq LDFLAGS $1 +} + +# @FUNCTION: is-ldflag +# @USAGE: <flag> +# @DESCRIPTION: +# Echo's "true" if flag is set in LDFLAGS. Accepts shell globs. +is-ldflag() { + is-ldflagq "$@" && echo true +} + +# @FUNCTION: filter-mfpmath +# @USAGE: <math types> +# @DESCRIPTION: +# Remove specified math types from the fpmath flag. For example, if the user +# has -mfpmath=sse,386, running `filter-mfpmath sse` will leave the user with +# -mfpmath=386. +filter-mfpmath() { + local orig_mfpmath new_math prune_math + + # save the original -mfpmath flag + orig_mfpmath=$(get-flag -mfpmath) + # get the value of the current -mfpmath flag + new_math=$(get-flag mfpmath) + # convert "both" to something we can filter + new_math=${new_math/both/387,sse} + new_math=" ${new_math//[,+]/ } " + # figure out which math values are to be removed + prune_math="" + for prune_math in "$@" ; do + new_math=${new_math/ ${prune_math} / } + done + new_math=$(echo ${new_math}) + new_math=${new_math// /,} + + if [[ -z ${new_math} ]] ; then + # if we're removing all user specified math values are + # slated for removal, then we just filter the flag + filter-flags ${orig_mfpmath} + else + # if we only want to filter some of the user specified + # math values, then we replace the current flag + replace-flags ${orig_mfpmath} -mfpmath=${new_math} + fi + return 0 +} + +# @FUNCTION: strip-flags +# @DESCRIPTION: +# Strip *FLAGS of everything except known good/safe flags. This runs over all +# flags returned by all_flag_vars(). +strip-flags() { + [[ $# -ne 0 ]] && die "strip-flags takes no arguments" + local x y var + + local ALLOWED_FLAGS + setup-allowed-flags + + set -f # disable pathname expansion + + for var in $(all-flag-vars) ; do + local new=() + + for x in ${!var} ; do + local flag=${x%%=*} + for y in "${ALLOWED_FLAGS[@]}" ; do + if [[ -z ${flag%%${y}} ]] ; then + new+=( "${x}" ) + break + fi + done + done + + # In case we filtered out all optimization flags fallback to -O2 + if _is_flagq ${var} "-O*" && ! _is_flagq new "-O*" ; then + new+=( -O2 ) + fi + + if [[ ${!var} != "${new[*]}" ]] ; then + einfo "strip-flags: ${var}: changed '${!var}' to '${new[*]}'" + fi + export ${var}="${new[*]}" + done + + set +f # re-enable pathname expansion + + return 0 +} + +test-flag-PROG() { + local comp=$1 + local lang=$2 + shift 2 + + if [[ -z ${comp} ]]; then + return 1 + fi + if [[ -z $1 ]]; then + return 1 + fi + + # verify selected compiler exists before using it + comp=($(tc-get${comp})) + # 'comp' can already contain compiler options. + # 'type' needs a binary name + if ! type -p ${comp[0]} >/dev/null; then + return 1 + fi + + # Set up test file. + local in_src in_ext cmdline_extra=() + case "${lang}" in + # compiler/assembler only + c) + in_ext='c' + in_src='int main(void) { return 0; }' + cmdline_extra+=(-xc -c) + ;; + c++) + in_ext='cc' + in_src='int main(void) { return 0; }' + cmdline_extra+=(-xc++ -c) + ;; + f77) + in_ext='f' + # fixed source form + in_src=' end' + cmdline_extra+=(-xf77 -c) + ;; + f95) + in_ext='f90' + in_src='end' + cmdline_extra+=(-xf95 -c) + ;; + + # C compiler/assembler/linker + c+ld) + in_ext='c' + in_src='int main(void) { return 0; }' + cmdline_extra+=(-xc) + ;; + esac + local test_in=${T}/test-flag.${in_ext} + local test_out=${T}/test-flag.exe + + printf "%s\n" "${in_src}" > "${test_in}" || die "Failed to create '${test_in}'" + + # Currently we rely on warning-free output of a compiler + # before the flag to see if a flag prduces any warnings. + # This has a few drawbacks: + # - if compiler already generates warnings we filter out + # every single flag: bug #712488 + # - if user actually wants to see warnings we just strip + # them regardless of warnings type. + # + # We can add more selective detection of no-op flags via + # '-Werror=ignored-optimization-argument' and similar error options + # similar to what we are doing with '-Qunused-arguments'. + local cmdline=( + "${comp[@]}" + # Clang will warn about unknown gcc flags but exit 0. + # Need -Werror to force it to exit non-zero. + -Werror + "$@" + # -x<lang> options need to go before first source file + "${cmdline_extra[@]}" + + "${test_in}" -o "${test_out}" + ) + + if ! "${cmdline[@]}" &>/dev/null; then + # -Werror makes clang bail out on unused arguments as well; + # try to add -Qunused-arguments to work-around that + # other compilers don't support it but then, it's failure like + # any other + cmdline+=( -Qunused-arguments ) + "${cmdline[@]}" &>/dev/null + fi +} + +# @FUNCTION: test-flag-CC +# @USAGE: <flag> +# @DESCRIPTION: +# Returns shell true if <flag> is supported by the C compiler, else returns shell false. +test-flag-CC() { test-flag-PROG "CC" c "$@"; } + +# @FUNCTION: test-flag-CXX +# @USAGE: <flag> +# @DESCRIPTION: +# Returns shell true if <flag> is supported by the C++ compiler, else returns shell false. +test-flag-CXX() { test-flag-PROG "CXX" c++ "$@"; } + +# @FUNCTION: test-flag-F77 +# @USAGE: <flag> +# @DESCRIPTION: +# Returns shell true if <flag> is supported by the Fortran 77 compiler, else returns shell false. +test-flag-F77() { test-flag-PROG "F77" f77 "$@"; } + +# @FUNCTION: test-flag-FC +# @USAGE: <flag> +# @DESCRIPTION: +# Returns shell true if <flag> is supported by the Fortran 90 compiler, else returns shell false. +test-flag-FC() { test-flag-PROG "FC" f95 "$@"; } + +# @FUNCTION: test-flag-CCLD +# @USAGE: <flag> +# @DESCRIPTION: +# Returns shell true if <flag> is supported by the C compiler and linker, else returns shell false. +test-flag-CCLD() { test-flag-PROG "CC" c+ld "$@"; } + +test-flags-PROG() { + local comp=$1 + local flags=() + local x + + shift + + [[ -z ${comp} ]] && return 1 + + while (( $# )); do + case "$1" in + # '-B /foo': bug # 687198 + --param|-B) + if test-flag-${comp} "$1" "$2"; then + flags+=( "$1" "$2" ) + fi + shift 2 + ;; + *) + if test-flag-${comp} "$1"; then + flags+=( "$1" ) + fi + shift 1 + ;; + esac + done + + echo "${flags[*]}" + + # Just bail if we dont have any flags + [[ ${#flags[@]} -gt 0 ]] +} + +# @FUNCTION: test-flags-CC +# @USAGE: <flags> +# @DESCRIPTION: +# Returns shell true if <flags> are supported by the C compiler, else returns shell false. +test-flags-CC() { test-flags-PROG "CC" "$@"; } + +# @FUNCTION: test-flags-CXX +# @USAGE: <flags> +# @DESCRIPTION: +# Returns shell true if <flags> are supported by the C++ compiler, else returns shell false. +test-flags-CXX() { test-flags-PROG "CXX" "$@"; } + +# @FUNCTION: test-flags-F77 +# @USAGE: <flags> +# @DESCRIPTION: +# Returns shell true if <flags> are supported by the Fortran 77 compiler, else returns shell false. +test-flags-F77() { test-flags-PROG "F77" "$@"; } + +# @FUNCTION: test-flags-FC +# @USAGE: <flags> +# @DESCRIPTION: +# Returns shell true if <flags> are supported by the Fortran 90 compiler, else returns shell false. +test-flags-FC() { test-flags-PROG "FC" "$@"; } + +# @FUNCTION: test-flags-CCLD +# @USAGE: <flags> +# @DESCRIPTION: +# Returns shell true if <flags> are supported by the C compiler and default linker, else returns shell false. +test-flags-CCLD() { test-flags-PROG "CCLD" "$@"; } + +# @FUNCTION: test-flags +# @USAGE: <flags> +# @DESCRIPTION: +# Short-hand that should hopefully work for both C and C++ compiler, but +# its really only present due to the append-flags() abomination. +test-flags() { test-flags-CC "$@"; } + +# @FUNCTION: test_version_info +# @USAGE: <version> +# @DESCRIPTION: +# Returns shell true if the current C compiler version matches <version>, else returns shell false. +# Accepts shell globs. +test_version_info() { + if [[ $($(tc-getCC) --version 2>&1) == *$1* ]]; then + return 0 + else + return 1 + fi +} + +# @FUNCTION: strip-unsupported-flags +# @DESCRIPTION: +# Strip {C,CXX,F,FC}FLAGS of any flags not supported by the active toolchain. +strip-unsupported-flags() { + [[ $# -ne 0 ]] && die "strip-unsupported-flags takes no arguments" + export CFLAGS=$(test-flags-CC ${CFLAGS}) + export CXXFLAGS=$(test-flags-CXX ${CXXFLAGS}) + export FFLAGS=$(test-flags-F77 ${FFLAGS}) + export FCFLAGS=$(test-flags-FC ${FCFLAGS}) + export LDFLAGS=$(test-flags-CCLD ${LDFLAGS}) +} + +# @FUNCTION: get-flag +# @USAGE: <flag> +# @DESCRIPTION: +# Find and echo the value for a particular flag. Accepts shell globs. +get-flag() { + [[ $# -ne 1 ]] && die "usage: <flag>" + local f var findflag="$1" + + # this code looks a little flaky but seems to work for + # everything we want ... + # for example, if CFLAGS="-march=i686": + # `get-flag -march` == "-march=i686" + # `get-flag march` == "i686" + for var in $(all-flag-vars) ; do + for f in ${!var} ; do + if [ "${f/${findflag}}" != "${f}" ] ; then + printf "%s\n" "${f/-${findflag}=}" + return 0 + fi + done + done + return 1 +} + +# @FUNCTION: replace-sparc64-flags +# @DESCRIPTION: +# Sets mcpu to v8 and uses the original value as mtune if none specified. +replace-sparc64-flags() { + [[ $# -ne 0 ]] && die "replace-sparc64-flags takes no arguments" + local SPARC64_CPUS="ultrasparc3 ultrasparc v9" + + if [ "${CFLAGS/mtune}" != "${CFLAGS}" ]; then + for x in ${SPARC64_CPUS}; do + CFLAGS="${CFLAGS/-mcpu=${x}/-mcpu=v8}" + done + else + for x in ${SPARC64_CPUS}; do + CFLAGS="${CFLAGS/-mcpu=${x}/-mcpu=v8 -mtune=${x}}" + done + fi + + if [ "${CXXFLAGS/mtune}" != "${CXXFLAGS}" ]; then + for x in ${SPARC64_CPUS}; do + CXXFLAGS="${CXXFLAGS/-mcpu=${x}/-mcpu=v8}" + done + else + for x in ${SPARC64_CPUS}; do + CXXFLAGS="${CXXFLAGS/-mcpu=${x}/-mcpu=v8 -mtune=${x}}" + done + fi + + export CFLAGS CXXFLAGS +} + +# @FUNCTION: append-libs +# @USAGE: <libs> +# @DESCRIPTION: +# Add extra <libs> to the current LIBS. All arguments should be prefixed with +# either -l or -L. For compatibility, if arguments are not prefixed as +# options, they are given a -l prefix automatically. +append-libs() { + [[ $# -eq 0 ]] && return 0 + local flag + for flag in "$@"; do + if [[ -z "${flag// }" ]]; then + eqawarn "Appending an empty argument to LIBS is invalid! Skipping." + continue + fi + case $flag in + -[lL]*) + export LIBS="${LIBS} ${flag}" + ;; + -*) + eqawarn "Appending non-library to LIBS (${flag}); Other linker flags should be passed via LDFLAGS" + export LIBS="${LIBS} ${flag}" + ;; + *) + export LIBS="${LIBS} -l${flag}" + esac + done + + return 0 +} + +# @FUNCTION: raw-ldflags +# @USAGE: [flags] +# @DESCRIPTION: +# Turn C style ldflags (-Wl,-foo) into straight ldflags - the results +# are suitable for passing directly to 'ld'; note LDFLAGS is usually passed +# to gcc where it needs the '-Wl,'. +# +# If no flags are specified, then default to ${LDFLAGS}. +raw-ldflags() { + local x input="$@" + [[ -z ${input} ]] && input=${LDFLAGS} + set -- + for x in ${input} ; do + case ${x} in + -Wl,*) + x=${x#-Wl,} + set -- "$@" ${x//,/ } + ;; + *) # Assume it's a compiler driver flag, so throw it away #441808 + ;; + esac + done + echo "$@" +} + +# @FUNCTION: no-as-needed +# @RETURN: Flag to disable asneeded behavior for use with append-ldflags. +no-as-needed() { + [[ $# -ne 0 ]] && die "no-as-needed takes no arguments" + case $($(tc-getLD) -v 2>&1 </dev/null) in + *GNU*) # GNU ld + echo "-Wl,--no-as-needed" ;; + esac +} + +fi diff --git a/eclass/font-ebdftopcf.eclass b/eclass/font-ebdftopcf.eclass new file mode 100644 index 0000000..29568e5 --- /dev/null +++ b/eclass/font-ebdftopcf.eclass @@ -0,0 +1,45 @@ +# Copyright 1999-2020 Gentoo Authors +# Distributed under the terms of the GNU General Public License v2 + +# Author: Robin H. Johnson <robbat2@gentoo.org> + +# font-ebdftopcf.eclass +# Eclass to make PCF font generator from BDF uniform and optimal +# The manpage for this eclass is in media-gfx/ebdftopcf. + +# inherit this eclass after font.eclass + +# if USE="-X", this eclass is basically a no-op, since bdftopcf requires Xorg. +IUSE="X" + +# Variable declarations +DEPEND="X? ( media-gfx/ebdftopcf )" +RDEPEND="" + +# +# Public functions +# +ebdftopcf() { + local bdffiles + bdffiles="$@" + [ -z "$bdffiles" ] && die "No BDF files specified." + emake -f "${EPREFIX}"/usr/share/ebdftopcf/Makefile.ebdftopcf \ + BDFFILES="${bdffiles}" \ + BDFTOPCF_PARAMS="${BDFTOPCF_PARAMS}" \ + || die "Failed to build PCF files" +} + +# +# Public inheritable functions +# +font-ebdftopcf_src_compile() { + use X && FONT_SUFFIX="pcf.gz" + use X || FONT_SUFFIX="bdf" + + if use X; then + [ -z "${BDFFILES}" ] && BDFFILES="$(find . -name '*.bdf')" + ebdftopcf ${BDFFILES} + fi +} + +EXPORT_FUNCTIONS src_compile diff --git a/eclass/font.eclass b/eclass/font.eclass new file mode 100644 index 0000000..e9e448a --- /dev/null +++ b/eclass/font.eclass @@ -0,0 +1,258 @@ +# Copyright 1999-2020 Gentoo Authors +# Distributed under the terms of the GNU General Public License v2 + +# @ECLASS: font.eclass +# @MAINTAINER: +# fonts@gentoo.org +# @SUPPORTED_EAPIS: 5 6 7 +# @BLURB: Eclass to make font installation uniform + +case ${EAPI:-0} in + [56]) inherit eutils ;; + 7) ;; + *) die "EAPI ${EAPI} is not supported by font.eclass." ;; +esac + +if [[ ! ${_FONT_ECLASS} ]]; then + +EXPORT_FUNCTIONS pkg_setup src_install pkg_postinst pkg_postrm + +# @ECLASS-VARIABLE: FONT_SUFFIX +# @DEFAULT_UNSET +# @REQUIRED +# @DESCRIPTION: +# Space delimited list of font suffixes to install. +FONT_SUFFIX=${FONT_SUFFIX:-} + +# @ECLASS-VARIABLE: FONT_S +# @DEFAULT_UNSET +# @DESCRIPTION: +# Directory containing the fonts. If unset, ${S} is used instead. +# Can also be an array of several directories. + +# @ECLASS-VARIABLE: FONT_PN +# @DESCRIPTION: +# Font name (ie. last part of FONTDIR). +FONT_PN=${FONT_PN:-${PN}} + +# @ECLASS-VARIABLE: FONTDIR +# @DESCRIPTION: +# Full path to installation directory. +FONTDIR=${FONTDIR:-/usr/share/fonts/${FONT_PN}} + +# @ECLASS-VARIABLE: FONT_CONF +# @DEFAULT_UNSET +# @DESCRIPTION: +# Array containing fontconfig conf files to install. +FONT_CONF=( "" ) + +# @ECLASS-VARIABLE: DOCS +# @DEFAULT_UNSET +# @DESCRIPTION: +# Space delimited list of docs to install. +# We always install these: +# COPYRIGHT README{,.txt} NEWS AUTHORS BUGS ChangeLog FONTLOG.txt +DOCS=${DOCS:-} + +if [[ ${CATEGORY}/${PN} != media-fonts/encodings ]]; then + IUSE="X" + DEPEND="X? ( + >=x11-apps/mkfontscale-1.2.0 + media-fonts/encodings + )" + RDEPEND="" +fi + +# @FUNCTION: font_xfont_config +# @DESCRIPTION: +# Generate Xorg font files (mkfontscale/mkfontdir). +font_xfont_config() { + local dir_name + if in_iuse X && use X ; then + dir_name="${1:-${FONT_PN}}" + rm -f "${ED%/}/${FONTDIR}/${1//${S}/}"/{fonts.{dir,scale},encodings.dir} \ + || die "failed to prepare ${FONTDIR}/${1//${S}/}" + einfo "Creating fonts.scale & fonts.dir in ${dir_name##*/}" + mkfontscale "${ED%/}/${FONTDIR}/${1//${S}/}" || eerror "failed to create fonts.scale" + mkfontdir \ + -e ${EPREFIX}/usr/share/fonts/encodings \ + -e ${EPREFIX}/usr/share/fonts/encodings/large \ + "${ED%/}/${FONTDIR}/${1//${S}/}" || eerror "failed to create fonts.dir" + [[ -e fonts.alias ]] && doins fonts.alias + fi +} + +# @FUNCTION: font_fontconfig +# @DESCRIPTION: +# Install fontconfig conf files given in FONT_CONF. +font_fontconfig() { + local conffile + if [[ -n ${FONT_CONF[@]} ]]; then + insinto /etc/fonts/conf.avail/ + for conffile in "${FONT_CONF[@]}"; do + [[ -e ${conffile} ]] && doins "${conffile}" + done + fi +} + +# @FUNCTION: font_cleanup_dirs +# @DESCRIPTION: +# Remove font directories containing only generated files. +font_cleanup_dirs() { + local genfiles="encodings.dir fonts.alias fonts.cache-1 fonts.dir fonts.scale" + # fonts.alias isn't generated but it's a special case (see below). + local d f g generated candidate otherfile + + ebegin "Cleaning up font directories" + while read -d $'\0' -r; do + candidate=false + otherfile=false + for f in "${d}"/*; do + generated=false + # make sure this is a file and not a subdir + [[ -e ${f} || -L ${f} ]] || continue + if has ${f##*/} ${genfiles}; then + # this is a generated file + generated=true + break + fi + # if the file is a generated file then we know this is a font dir (as + # opposed to something like encodings or util) and a candidate for + # removal. if it's not generated then it's an "otherfile". + ${generated} && candidate=true || otherfile=true + # if the directory is both a candidate for removal and contains at + # least one "otherfile" then don't remove it. + [[ ${candidate} == ${otherfile} ]] && break + done + # if in the end we only have generated files, purge the directory. + if [[ ${candidate} == true && ${otherfile} == false ]]; then + # we don't want to remove fonts.alias files that were installed by + # media-fonts/font-alias. any other fonts.alias files will have + # already been unmerged with their packages. + for g in ${genfiles}; do + if [[ ${g} != fonts.alias && ( -e ${d}/${g} || -L ${d}/${g} ) ]] ; then + rm "${d}"/${g} || eerror "failed to remove ${d}/${g}" + fi + done + # if there's nothing left remove the directory + find "${d}" -maxdepth 0 -type d -empty -delete || eerror "failed to purge ${d}" + fi + done < <(find -L "${EROOT%/}"/usr/share/fonts/ -type d -print0) + eend 0 +} + +# @FUNCTION: font_pkg_setup +# @DESCRIPTION: +# The font pkg_setup function. +# Collision protection +font_pkg_setup() { + # make sure we get no collisions + # setup is not the nicest place, but preinst doesn't cut it + if [[ -e "${EROOT%/}/${FONTDIR}/fonts.cache-1" ]] ; then + rm "${EROOT%/}/${FONTDIR}/fonts.cache-1" || die "failed to remove fonts.cache-1" + fi +} + +# @FUNCTION: font_src_install +# @DESCRIPTION: +# The font src_install function. +font_src_install() { + local dir suffix commondoc + + if [[ $(declare -p FONT_S 2>/dev/null) == "declare -a"* ]]; then + # recreate the directory structure if FONT_S is an array + for dir in "${FONT_S[@]}"; do + pushd "${dir}" > /dev/null || die "pushd ${dir} failed" + insinto "${FONTDIR}/${dir#"${S}"}" + for suffix in ${FONT_SUFFIX}; do + doins *.${suffix} + done + font_xfont_config "${dir}" + popd > /dev/null || die + done + elif [[ ${FONT_S/[[:space:]]} != "${FONT_S}" ]]; then + # backwards compatibility code, can be removed after 2021-02-14 + eqawarn "Using a space-separated list for FONT_S is deprecated." + eqawarn "Use a bash array instead if there are multiple directories." + for dir in ${FONT_S}; do + pushd "${dir}" > /dev/null || die "pushd ${dir} failed" + insinto "${FONTDIR}/${dir//${S}/}" + for suffix in ${FONT_SUFFIX}; do + doins *.${suffix} + done + font_xfont_config "${dir}" + popd > /dev/null || die + done + else + pushd "${FONT_S:-${S}}" > /dev/null \ + || die "pushd ${FONT_S:-${S}} failed" + insinto "${FONTDIR}" + for suffix in ${FONT_SUFFIX}; do + doins *.${suffix} + done + font_xfont_config + popd > /dev/null || die + fi + + font_fontconfig + + einstalldocs + + # install common docs + for commondoc in COPYRIGHT FONTLOG.txt; do + [[ -s ${commondoc} ]] && dodoc ${commondoc} + done +} + +# @FUNCTION: _update_fontcache +# @DESCRIPTION: +# Updates fontcache if !prefix and media-libs/fontconfig installed +_update_fontcache() { + # unreadable font files = fontconfig segfaults + find "${EROOT%/}"/usr/share/fonts/ -type f '!' -perm 0644 \ + -exec chmod -v 0644 2>/dev/null {} + || die "failed to fix font files perms" + + if [[ -z ${ROOT%/} ]] ; then + if has_version media-libs/fontconfig ; then + ebegin "Updating global fontcache" + fc-cache -fs + if ! eend $? ; then + die "failed to update global fontcache" + fi + else + einfo "Skipping fontcache update (media-libs/fontconfig not installed)" + fi + else + einfo "Skipping fontcache update (ROOT != /)" + fi +} + +# @FUNCTION: font_pkg_postinst +# @DESCRIPTION: +# The font pkg_postinst function. +font_pkg_postinst() { + if [[ -n ${FONT_CONF[@]} ]]; then + local conffile + elog "The following fontconfig configuration files have been installed:" + elog + for conffile in "${FONT_CONF[@]}"; do + [[ -e "${EROOT%/}"/etc/fonts/conf.avail/${conffile##*/} ]] && + elog " ${conffile##*/}" + done + elog + elog "Use \`eselect fontconfig\` to enable/disable them." + fi + + _update_fontcache +} + +# @FUNCTION: font_pkg_postrm +# @DESCRIPTION: +# The font pkg_postrm function. +font_pkg_postrm() { + font_cleanup_dirs + _update_fontcache +} + +_FONT_ECLASS=1 +fi diff --git a/eclass/fortran-2.eclass b/eclass/fortran-2.eclass new file mode 100644 index 0000000..6049b03 --- /dev/null +++ b/eclass/fortran-2.eclass @@ -0,0 +1,286 @@ +# Copyright 1999-2020 Gentoo Authors +# Distributed under the terms of the GNU General Public License v2 + +# @ECLASS: fortran-2.eclass +# @MAINTAINER: +# sci@gentoo.org +# @AUTHOR: +# Author Justin Lecher <jlec@gentoo.org> +# Test functions provided by Sebastien Fabbro and Kacper Kowalik +# @SUPPORTED_EAPIS: 4 5 6 7 +# @BLURB: Simplify fortran compiler management +# @DESCRIPTION: +# If you need a fortran compiler, then you should be inheriting this eclass. +# In case you only need optional support, please export FORTRAN_NEEDED before +# inheriting the eclass. +# +# The eclass tests for working fortran compilers +# and exports the variables FC and F77. +# Optionally, it checks for extended capabilities based on +# the variable options selected in the ebuild +# The only phase function exported is fortran-2_pkg_setup. +# @EXAMPLE: +# FORTRAN_NEEDED="lapack fortran" +# +# inherit fortran-2 +# +# FORTRAN_NEED_OPENMP=1 + +inherit toolchain-funcs +case ${EAPI:-0} in + # not used in the eclass, but left for backward compatibility with legacy users + 4|5|6) inherit eutils ;; + 7) ;; + *) die "EAPI=${EAPI} is not supported" ;; +esac + +EXPORT_FUNCTIONS pkg_setup + +if [[ ! ${_FORTRAN_2_CLASS} ]]; then + +# @ECLASS-VARIABLE: FORTRAN_NEED_OPENMP +# @DESCRIPTION: +# Set to "1" in order to automatically have the eclass abort if the fortran +# compiler lacks openmp support. +: ${FORTRAN_NEED_OPENMP:=0} + +# @ECLASS-VARIABLE: FORTRAN_STANDARD +# @DESCRIPTION: +# Set this, if a special dialect needs to be supported. +# Generally not needed as default is sufficient. +# +# Valid settings are any combination of: 77 90 95 2003 +: ${FORTRAN_STANDARD:=77} + +# @ECLASS-VARIABLE: FORTRAN_NEEDED +# @DESCRIPTION: +# If your package has an optional fortran support, set this variable +# to the space separated list of USE triggering the fortran +# dependency. +# +# e.g. FORTRAN_NEEDED=lapack would result in +# +# DEPEND="lapack? ( virtual/fortran )" +# +# If unset, we always depend on virtual/fortran. +: ${FORTRAN_NEEDED:=always} + +for _f_use in ${FORTRAN_NEEDED}; do + case ${_f_use} in + always) + DEPEND+=" virtual/fortran" + RDEPEND+=" virtual/fortran" + break + ;; + no) + break + ;; + test) + DEPEND+=" ${_f_use}? ( virtual/fortran )" + ;; + *) + DEPEND+=" ${_f_use}? ( virtual/fortran )" + RDEPEND+=" ${_f_use}? ( virtual/fortran )" + ;; + esac +done +unset _f_use + +# @FUNCTION: fortran_int64_abi_fflags +# @DESCRIPTION: +# Return the Fortran compiler flag to enable 64 bit integers for +# array indices +fortran_int64_abi_fflags() { + debug-print-function ${FUNCNAME} "${@}" + + local _FC=$(tc-getFC) + if [[ ${_FC} == *gfortran* ]]; then + echo "-fdefault-integer-8" + elif [[ ${_FC} == ifort ]]; then + echo "-integer-size 64" + else + die "Compiler flag for 64bit interger for ${_FC} unknown" + fi +} + +# @FUNCTION: _fortran_write_testsuite +# @INTERNAL +# @DESCRIPTION: +# writes fortran test code +_fortran_write_testsuite() { + debug-print-function ${FUNCNAME} "${@}" + + local filebase=${T}/test-fortran + + # f77 code + cat <<- EOF > "${filebase}.f" || die + end + EOF + + # f90/95 code + cat <<- EOF > "${filebase}.f90" || die + end + EOF + + # f2003 code + cat <<- EOF > "${filebase}.f03" || die + procedure(), pointer :: p + end + EOF +} + +# @FUNCTION: _fortran_compile_test +# @USAGE: <compiler> [dialect] +# @INTERNAL +# @DESCRIPTION: +# Takes fortran compiler as first argument and dialect as second. +# Checks whether the passed fortran compiler speaks the fortran dialect +_fortran_compile_test() { + debug-print-function ${FUNCNAME} "${@}" + + local filebase=${T}/test-fortran + local fcomp=${1} + local fdia=${2} + local fcode=${filebase}.f${fdia} + local ret + + [[ $# -lt 1 ]] && \ + die "_fortran_compile_test() needs at least one argument" + + [[ -f ${fcode} ]] || _fortran_write_testsuite + + ${fcomp} "${fcode}" -o "${fcode}.x" \ + >> "${T}"/_fortran_compile_test.log 2>&1 + ret=$? + + rm -f "${fcode}.x" + return ${ret} +} + +# @FUNCTION: _fortran-has-openmp +# @RETURN: return code of the compiler +# @INTERNAL +# @DESCRIPTION: +# See if the fortran supports OpenMP. +_fortran-has-openmp() { + debug-print-function ${FUNCNAME} "${@}" + + local flag + local filebase=${T}/test-fc-openmp + local fcode=${filebase}.f + local ret + local _fc=$(tc-getFC) + + cat <<- EOF > "${fcode}" || die + call omp_get_num_threads + end + EOF + + for flag in -fopenmp -xopenmp -openmp -mp -omp -qsmp=omp; do + ${_fc} ${flag} "${fcode}" -o "${fcode}.x" \ + &>> "${T}"/_fortran_compile_test.log + ret=$? + [[ ${ret} == 0 ]] && break + done + + rm -f "${fcode}.x" + return ${ret} +} + +# @FUNCTION: _fortran_die_msg +# @INTERNAL +# @DESCRIPTION: +# Detailed description how to handle fortran support +_fortran_die_msg() { + debug-print-function ${FUNCNAME} "${@}" + + eerror + eerror "Please install currently selected gcc version with USE=fortran." + eerror "If you intend to use a different compiler then gfortran, please" + eerror "set FC variable accordingly and take care that the necessary" + eerror "fortran dialects are supported." + eerror + die "Currently no working fortran compiler is available (see ${T}/_fortran_compile_test.log for information)" +} + +# @FUNCTION: _fortran_test_function +# @INTERNAL +# @DESCRIPTION: +# Internal test function for working fortran compiler. +# It is called in fortran-2_pkg_setup. +_fortran_test_function() { + debug-print-function ${FUNCNAME} "${@}" + + local dialect + + : ${F77:=$(tc-getFC)} + + : ${FORTRAN_STANDARD:=77} + for dialect in ${FORTRAN_STANDARD}; do + case ${dialect} in + 77) _fortran_compile_test $(tc-getF77) || \ + _fortran_die_msg ;; + 90|95) _fortran_compile_test $(tc-getFC) 90 || \ + _fortran_die_msg ;; + 2003) _fortran_compile_test $(tc-getFC) 03 || \ + _fortran_die_msg ;; + 2008) die "Future" ;; + *) die "${dialect} is not a Fortran dialect." ;; + esac + done + + tc-export F77 FC + einfo "Using following Fortran compiler:" + einfo " F77: ${F77}" + einfo " FC: ${FC}" + + if [[ ${FORTRAN_NEED_OPENMP} == 1 ]]; then + if _fortran-has-openmp; then + einfo "${FC} has OPENMP support" + else + die "Please install current gcc with USE=openmp or set the FC variable to a compiler that supports OpenMP" + fi + fi +} + +# @FUNCTION: _fortran-2_pkg_setup +# @INTERNAL +# @DESCRIPTION: +# _The_ fortran-2_pkg_setup() code +_fortran-2_pkg_setup() { + for _f_use in ${FORTRAN_NEEDED}; do + case ${_f_use} in + always) + _fortran_test_function && break 2 + ;; + no) + einfo "Forcing fortran support off" + break + ;; + *) + if use ${_f_use}; then + _fortran_test_function && break 2 + else + unset FC + unset F77 + fi + ;; + esac + done +} + + +# @FUNCTION: fortran-2_pkg_setup +# @DESCRIPTION: +# Setup functionality, +# checks for a valid fortran compiler and optionally for its openmp support. +fortran-2_pkg_setup() { + debug-print-function ${FUNCNAME} "${@}" + + if [[ ${MERGE_TYPE} != binary ]]; then + _fortran-2_pkg_setup + fi +} + +_FORTRAN_2_ECLASS=1 +fi diff --git a/eclass/freedict.eclass b/eclass/freedict.eclass new file mode 100644 index 0000000..c1b32d1 --- /dev/null +++ b/eclass/freedict.eclass @@ -0,0 +1,52 @@ +# Copyright 1999-2018 Gentoo Foundation +# Distributed under the terms of the GNU General Public License v2 + +# @ECLASS: freedict.eclass +# @MAINTAINER: +# maintainer-needed@gentoo.org +# @AUTHOR: +# Original author: Seemant Kulleen +# @SUPPORTED_EAPIS: 6 +# @BLURB: Ease the installation of freedict translation dictionaries +# @DESCRIPTION: +# This eclass exists to ease the installation of freedict translation +# dictionaries. The only variables which need to be defined in the actual +# ebuilds are FORLANG and TOLANG for the source and target languages, +# respectively. + +# @ECLASS-VARIABLE: FORLANG +# @DESCRIPTION: +# Please see above for a description. + +# @ECLASS-VARIABLE: TOLANG +# @DESCRIPTION: +# Please see above for a description. + +case ${EAPI:-0} in + 6) ;; + *) die "${ECLASS}.eclass is banned in EAPI=${EAPI}" ;; +esac + +MY_P=${PN/freedict-/} + +DESCRIPTION="Freedict for language translation from ${FORLANG} to ${TOLANG}" +HOMEPAGE="http://freedict.sourceforge.net/" +SRC_URI="http://freedict.sourceforge.net/download/linux/${MY_P}.tar.gz" + +LICENSE="GPL-2+" +SLOT="0" + +RDEPEND="app-text/dictd" + +S="${WORKDIR}" + +# @FUNCTION: freedict_src_install +# @DESCRIPTION: +# The freedict src_install function, which is exported +freedict_src_install() { + insinto /usr/$(get_libdir)/dict + doins ${MY_P}.dict.dz + doins ${MY_P}.index +} + +EXPORT_FUNCTIONS src_install diff --git a/eclass/games.eclass b/eclass/games.eclass new file mode 100644 index 0000000..a2a5ce0 --- /dev/null +++ b/eclass/games.eclass @@ -0,0 +1,397 @@ +# Copyright 1999-2020 Gentoo Authors +# Distributed under the terms of the GNU General Public License v2 + +# @ECLASS: games.eclass +# @MAINTAINER: +# Games team <games@gentoo.org> +# @SUPPORTED_EAPIS: 0 1 2 3 4 5 +# @BLURB: Standardizing the install of games. +# @DEPRECATED: none +# @DESCRIPTION: +# This eclass makes sure that games are consistently handled in gentoo. +# It installs game files by default in FHS-compatible directories +# like /usr/share/games and sets more restrictive permissions in order +# to avoid some security bugs. +# +# The installation directories as well as the user and group files are +# installed as can be controlled by the user. See the variables like +# GAMES_BINDIR, GAMES_USER etc. below. These are NOT supposed to be set +# by ebuilds! +# +# For a general guide on writing games ebuilds, see: +# https://wiki.gentoo.org/wiki/Project:Games/Ebuild_howto +# +# WARNING: This eclass is DEPRECATED and must not be used by new games +# ebuilds, bug #574082. When writing game ebuilds, no specific eclass +# is needed. For more details, see the QA team policies page: +# https://wiki.gentoo.org/wiki/Project:Quality_Assurance/Policies#Games + + +if [[ -z ${_GAMES_ECLASS} ]]; then +_GAMES_ECLASS=1 + +inherit base multilib toolchain-funcs eutils user + +case ${EAPI:-0} in + 0|1) EXPORT_FUNCTIONS pkg_setup src_compile pkg_preinst pkg_postinst ;; + 2|3|4|5) EXPORT_FUNCTIONS pkg_setup src_configure src_compile pkg_preinst pkg_postinst ;; + *) die "games.eclass is banned in EAPI=${EAPI}, see https://wiki.gentoo.org/wiki/Project:Quality_Assurance/Policies#Games" ;; +esac + +if [[ ${CATEGORY}/${PN} != "games-misc/games-envd" ]] ; then + # environment file + RDEPEND="games-misc/games-envd" +fi + +# @ECLASS-VARIABLE: GAMES_PREFIX +# @DESCRIPTION: +# Prefix where to install games, mostly used by GAMES_BINDIR. Games data should +# still go into GAMES_DATADIR. May be set by the user. +GAMES_PREFIX=${GAMES_PREFIX:-/usr/games} + +# @ECLASS-VARIABLE: GAMES_PREFIX_OPT +# @DESCRIPTION: +# Prefix where to install precompiled/blob games, usually followed by +# package name. May be set by the user. +GAMES_PREFIX_OPT=${GAMES_PREFIX_OPT:-/opt} + +# @ECLASS-VARIABLE: GAMES_DATADIR +# @DESCRIPTION: +# Base directory where to install game data files, usually followed by +# package name. May be set by the user. +GAMES_DATADIR=${GAMES_DATADIR:-/usr/share/games} + +# @ECLASS-VARIABLE: GAMES_DATADIR_BASE +# @DESCRIPTION: +# Similar to GAMES_DATADIR, but only used when a package auto appends 'games' +# to the path. May be set by the user. +GAMES_DATADIR_BASE=${GAMES_DATADIR_BASE:-/usr/share} + +# @ECLASS-VARIABLE: GAMES_SYSCONFDIR +# @DESCRIPTION: +# Where to install global games configuration files, usually followed by +# package name. May be set by the user. +GAMES_SYSCONFDIR=${GAMES_SYSCONFDIR:-/etc/games} + +# @ECLASS-VARIABLE: GAMES_STATEDIR +# @DESCRIPTION: +# Where to install/store global variable game data, usually followed by +# package name. May be set by the user. +GAMES_STATEDIR=${GAMES_STATEDIR:-/var/games} + +# @ECLASS-VARIABLE: GAMES_LOGDIR +# @DESCRIPTION: +# Where to store global game log files, usually followed by +# package name. May be set by the user. +GAMES_LOGDIR=${GAMES_LOGDIR:-/var/log/games} + +# @ECLASS-VARIABLE: GAMES_BINDIR +# @DESCRIPTION: +# Where to install the game binaries. May be set by the user. This is in PATH. +GAMES_BINDIR=${GAMES_BINDIR:-${GAMES_PREFIX}/bin} + +# @ECLASS-VARIABLE: GAMES_ENVD +# @INTERNAL +# @DESCRIPTION: +# The games environment file name which sets games specific LDPATH and PATH. +GAMES_ENVD="90games" + +# @ECLASS-VARIABLE: GAMES_USER +# @DESCRIPTION: +# The USER who owns all game files and usually has write permissions. +# May be set by the user. +GAMES_USER=${GAMES_USER:-root} + +# @ECLASS-VARIABLE: GAMES_USER_DED +# @DESCRIPTION: +# The USER who owns all game files related to the dedicated server part +# of a package. May be set by the user. +GAMES_USER_DED=${GAMES_USER_DED:-games} + +# @ECLASS-VARIABLE: GAMES_GROUP +# @DESCRIPTION: +# The GROUP that owns all game files and usually does not have +# write permissions. May be set by the user. +# If you want games world-executable, then you can at least set this variable +# to 'users' which is almost the same. +GAMES_GROUP=${GAMES_GROUP:-games} + +# @FUNCTION: games_get_libdir +# @DESCRIPTION: +# Gets the directory where to install games libraries. This is in LDPATH. +games_get_libdir() { + echo ${GAMES_PREFIX}/$(get_libdir) +} + +# @FUNCTION: egamesconf +# @USAGE: [<args>...] +# @DESCRIPTION: +# Games equivalent to 'econf' for autotools based build systems. It passes +# the necessary games specific directories automatically. +egamesconf() { + # handle verbose build log pre-EAPI5 + local _gamesconf + if has "${EAPI:-0}" 0 1 2 3 4 ; then + if grep -q -s disable-silent-rules "${ECONF_SOURCE:-.}"/configure ; then + _gamesconf="--disable-silent-rules" + fi + fi + + # bug 493954 + if grep -q -s datarootdir "${ECONF_SOURCE:-.}"/configure ; then + _gamesconf="${_gamesconf} --datarootdir=/usr/share" + fi + + econf \ + --prefix="${GAMES_PREFIX}" \ + --libdir="$(games_get_libdir)" \ + --datadir="${GAMES_DATADIR}" \ + --sysconfdir="${GAMES_SYSCONFDIR}" \ + --localstatedir="${GAMES_STATEDIR}" \ + ${_gamesconf} \ + "$@" +} + +# @FUNCTION: gameswrapper +# @USAGE: <command> [<args>...] +# @INTERNAL +# @DESCRIPTION: +# Wraps an install command like dobin, dolib etc, so that +# it has GAMES_PREFIX as prefix. +gameswrapper() { + # dont want to pollute calling env + ( + into "${GAMES_PREFIX}" + cmd=$1 + shift + ${cmd} "$@" + ) +} + +# @FUNCTION: dogamesbin +# @USAGE: <path>... +# @DESCRIPTION: +# Install one or more games binaries. +dogamesbin() { gameswrapper ${FUNCNAME/games} "$@"; } + +# @FUNCTION: dogamessbin +# @USAGE: <path>... +# @DESCRIPTION: +# Install one or more games system binaries. +dogamessbin() { gameswrapper ${FUNCNAME/games} "$@"; } + +# @FUNCTION: dogameslib +# @USAGE: <path>... +# @DESCRIPTION: +# Install one or more games libraries. +dogameslib() { gameswrapper ${FUNCNAME/games} "$@"; } + +# @FUNCTION: dogameslib.a +# @USAGE: <path>... +# @DESCRIPTION: +# Install one or more static games libraries. +dogameslib.a() { gameswrapper ${FUNCNAME/games} "$@"; } + +# @FUNCTION: dogameslib.so +# @USAGE: <path>... +# @DESCRIPTION: +# Install one or more shared games libraries. +dogameslib.so() { gameswrapper ${FUNCNAME/games} "$@"; } + +# @FUNCTION: newgamesbin +# @USAGE: <path> <newname> +# @DESCRIPTION: +# Install one games binary with a new name. +newgamesbin() { gameswrapper ${FUNCNAME/games} "$@"; } + +# @FUNCTION: newgamessbin +# @USAGE: <path> <newname> +# @DESCRIPTION: +# Install one system games binary with a new name. +newgamessbin() { gameswrapper ${FUNCNAME/games} "$@"; } + +# @FUNCTION: games_make_wrapper +# @USAGE: <wrapper> <target> [chdir] [libpaths] [installpath] +# @DESCRIPTION: +# Create a shell wrapper script named wrapper in installpath +# (defaults to the games bindir) to execute target (default of wrapper) by +# first optionally setting LD_LIBRARY_PATH to the colon-delimited +# libpaths followed by optionally changing directory to chdir. +games_make_wrapper() { gameswrapper ${FUNCNAME/games_} "$@"; } + +# @FUNCTION: gamesowners +# @USAGE: [<args excluding owner/group>...] <path>... +# @DESCRIPTION: +# Run 'chown' with the given args on the given files. Owner and +# group are GAMES_USER and GAMES_GROUP and must not be passed +# as args. +gamesowners() { chown ${GAMES_USER}:${GAMES_GROUP} "$@"; } + +# @FUNCTION: gamesperms +# @USAGE: <path>... +# @DESCRIPTION: +# Run 'chmod' with games specific permissions on the given files. +gamesperms() { chmod u+rw,g+r-w,o-rwx "$@"; } + +# @FUNCTION: prepgamesdirs +# @DESCRIPTION: +# Fix all permissions/owners of files in games related directories, +# usually called at the end of src_install(). +prepgamesdirs() { + local dir f mode + for dir in \ + "${GAMES_PREFIX}" "${GAMES_PREFIX_OPT}" "${GAMES_DATADIR}" \ + "${GAMES_SYSCONFDIR}" "${GAMES_STATEDIR}" "$(games_get_libdir)" \ + "${GAMES_BINDIR}" "$@" + do + [[ ! -d ${D}/${dir} ]] && continue + ( + gamesowners -R "${D}/${dir}" + find "${D}/${dir}" -type d -print0 | xargs -0 chmod 750 + mode=o-rwx,g+r,g-w + [[ ${dir} = ${GAMES_STATEDIR} ]] && mode=o-rwx,g+r + find "${D}/${dir}" -type f -print0 | xargs -0 chmod $mode + + # common trees should not be games owned #264872 #537580 + fowners root:0 "${dir}" + fperms 755 "${dir}" + if [[ ${dir} == "${GAMES_PREFIX}" \ + || ${dir} == "${GAMES_PREFIX_OPT}" ]] ; then + for d in $(get_libdir) bin ; do + # check if dirs exist to avoid "nonfatal" option + if [[ -e ${D}/${dir}/${d} ]] ; then + fowners root:0 "${dir}/${d}" + fperms 755 "${dir}/${d}" + fi + done + fi + ) &>/dev/null + + f=$(find "${D}/${dir}" -perm +4000 -a -uid 0 2>/dev/null) + if [[ -n ${f} ]] ; then + eerror "A game was detected that is setuid root!" + eerror "${f}" + die "refusing to merge a setuid root game" + fi + done + [[ -d ${D}/${GAMES_BINDIR} ]] || return 0 + find "${D}/${GAMES_BINDIR}" -maxdepth 1 -type f -exec chmod 750 '{}' \; +} + +# @FUNCTION: games_pkg_setup +# @DESCRIPTION: +# Export some toolchain specific variables and create games related groups +# and users. This function is exported as pkg_setup(). +games_pkg_setup() { + tc-export CC CXX LD AR RANLIB + + enewgroup "${GAMES_GROUP}" 35 + [[ ${GAMES_USER} != "root" ]] \ + && enewuser "${GAMES_USER}" 35 -1 "${GAMES_PREFIX}" "${GAMES_GROUP}" + [[ ${GAMES_USER_DED} != "root" ]] \ + && enewuser "${GAMES_USER_DED}" 36 /bin/bash "${GAMES_PREFIX}" "${GAMES_GROUP}" + + # Dear portage team, we are so sorry. Lots of love, games team. + # See Bug #61680 + [[ ${USERLAND} != "GNU" ]] && return 0 + [[ $(egetshell "${GAMES_USER_DED}") == "/bin/false" ]] \ + && usermod -s /bin/bash "${GAMES_USER_DED}" +} + +# @FUNCTION: games_src_configure +# @DESCRIPTION: +# Runs egamesconf if there is a configure file. +# This function is exported as src_configure(). +games_src_configure() { + [[ -x "${ECONF_SOURCE:-.}"/configure ]] && egamesconf +} + +# @FUNCTION: games_src_compile +# @DESCRIPTION: +# Runs base_src_make(). This function is exported as src_compile(). +games_src_compile() { + case ${EAPI:-0} in + 0|1) games_src_configure ;; + esac + base_src_make +} + +# @FUNCTION: games_pkg_preinst +# @DESCRIPTION: +# Synchronizes GAMES_STATEDIR of the ebuild image with the live filesystem. +games_pkg_preinst() { + local f + + while read f ; do + if [[ -e ${ROOT}/${GAMES_STATEDIR}/${f} ]] ; then + cp -p \ + "${ROOT}/${GAMES_STATEDIR}/${f}" \ + "${D}/${GAMES_STATEDIR}/${f}" \ + || die "cp failed" + # make the date match the rest of the install + touch "${D}/${GAMES_STATEDIR}/${f}" + fi + done < <(find "${D}/${GAMES_STATEDIR}" -type f -printf '%P\n' 2>/dev/null) +} + +# @FUNCTION: games_pkg_postinst +# @DESCRIPTION: +# Prints some warnings and infos, also related to games groups. +games_pkg_postinst() { + if [[ -z "${GAMES_SHOW_WARNING}" ]] ; then + ewarn "Remember, in order to play games, you have to" + ewarn "be in the '${GAMES_GROUP}' group." + echo + case ${CHOST} in + *-darwin*) ewarn "Just run 'niutil -appendprop / /groups/games users <USER>'";; + *-freebsd*|*-dragonfly*) ewarn "Just run 'pw groupmod ${GAMES_GROUP} -m <USER>'";; + *) ewarn "Just run 'gpasswd -a <USER> ${GAMES_GROUP}', then have <USER> re-login.";; + esac + echo + einfo "For more info about Gentoo gaming in general, see our website:" + einfo " https://games.gentoo.org/" + echo + fi +} + +# @FUNCTION: games_ut_unpack +# @USAGE: <directory or file to unpack> +# @DESCRIPTION: +# Unpack .uz2 files for UT2003/UT2004. +games_ut_unpack() { + local ut_unpack="$1" + local f= + + if [[ -z ${ut_unpack} ]] ; then + die "You must provide an argument to games_ut_unpack" + fi + if [[ -f ${ut_unpack} ]] ; then + uz2unpack "${ut_unpack}" "${ut_unpack%.uz2}" \ + || die "uncompressing file ${ut_unpack}" + fi + if [[ -d ${ut_unpack} ]] ; then + while read f ; do + uz2unpack "${ut_unpack}/${f}" "${ut_unpack}/${f%.uz2}" \ + || die "uncompressing file ${f}" + rm -f "${ut_unpack}/${f}" || die "deleting compressed file ${f}" + done < <(find "${ut_unpack}" -maxdepth 1 -name '*.uz2' -printf '%f\n' 2>/dev/null) + fi +} + +# @FUNCTION: games_umod_unpack +# @USAGE: <file to unpack> +# @DESCRIPTION: +# Unpacks .umod/.ut2mod/.ut4mod files for UT/UT2003/UT2004. +# Don't forget to set 'dir' and 'Ddir'. +games_umod_unpack() { + local umod=$1 + mkdir -p "${Ddir}"/System + cp "${dir}"/System/{ucc-bin,{Manifest,Def{ault,User}}.ini,{Engine,Core,zlib,ogg,vorbis}.so,{Engine,Core}.int} "${Ddir}"/System + cd "${Ddir}"/System + UT_DATA_PATH=${Ddir}/System ./ucc-bin umodunpack -x "${S}/${umod}" -nohomedir &> /dev/null \ + || die "uncompressing file ${umod}" + rm -f "${Ddir}"/System/{ucc-bin,{Manifest,Def{ault,User},User,UT200{3,4}}.ini,{Engine,Core,zlib,ogg,vorbis}.so,{Engine,Core}.int,ucc.log} &>/dev/null \ + || die "Removing temporary files" +} + +fi diff --git a/eclass/ghc-package.eclass b/eclass/ghc-package.eclass new file mode 100644 index 0000000..72d668c --- /dev/null +++ b/eclass/ghc-package.eclass @@ -0,0 +1,368 @@ +# Copyright 1999-2020 Gentoo Authors +# Distributed under the terms of the GNU General Public License v2 + +# @ECLASS: ghc-package.eclass +# @MAINTAINER: +# "Gentoo's Haskell Language team" <haskell@gentoo.org> +# @AUTHOR: +# Original Author: Andres Loeh <kosmikus@gentoo.org> +# @BLURB: This eclass helps with the Glasgow Haskell Compiler's package configuration utility. +# @DESCRIPTION: +# Helper eclass to handle ghc installation/upgrade/deinstallation process. + +inherit multiprocessing + +# Maintain version-testing compatibility with ebuilds not using EAPI 7. +case "${EAPI:-0}" in + 4|5|6) inherit eapi7-ver ;; + *) ;; +esac + +# GHC uses it's own native code generator. Portage's +# QA check generates false positive because it assumes +# presence of GCC-specific sections. +# +# Workaround false positiove by disabling the check completely. +# bug #722078, bug #677600 +QA_FLAGS_IGNORED='.*' + +# @FUNCTION: ghc-getghc +# @DESCRIPTION: +# returns the name of the ghc executable +ghc-getghc() { + if ! type -P ${HC:-ghc}; then + ewarn "ghc not found" + type -P false + fi +} + +# @FUNCTION: ghc-getghcpkg +# @DESCRIPTION: +# Internal function determines returns the name of the ghc-pkg executable +ghc-getghcpkg() { + if ! type -P ${HC_PKG:-ghc-pkg}; then + ewarn "ghc-pkg not found" + type -P false + fi +} + +# @FUNCTION: ghc-getghcpkgbin +# @DESCRIPTION: +# returns the name of the ghc-pkg binary (ghc-pkg +# itself usually is a shell script, and we have to +# bypass the script under certain circumstances); +# for Cabal, we add an empty global package config file, +# because for some reason the global package file +# must be specified +ghc-getghcpkgbin() { + if ver_test "$(ghc-version)" -ge "7.9.20141222"; then + # ghc-7.10 stopped supporting single-file database + local empty_db="${T}/empty.conf.d" ghc_pkg="$(ghc-libdir)/bin/ghc-pkg" + if [[ ! -d ${empty_db} ]]; then + "${ghc_pkg}" init "${empty_db}" || die "Failed to initialize empty global db" + fi + echo "$(ghc-libdir)/bin/ghc-pkg" "--global-package-db=${empty_db}" + + elif ver_test "$(ghc-version)" -ge "7.7.20121101"; then + # the ghc-pkg executable changed name in ghc 6.10, as it no longer needs + # the wrapper script with the static flags + # was moved to bin/ subtree by: + # http://www.haskell.org/pipermail/cvs-ghc/2012-September/076546.html + echo '[]' > "${T}/empty.conf" + echo "$(ghc-libdir)/bin/ghc-pkg" "--global-package-db=${T}/empty.conf" + + elif ver_test "$(ghc-version)" -ge "7.5.20120516"; then + echo '[]' > "${T}/empty.conf" + echo "$(ghc-libdir)/ghc-pkg" "--global-package-db=${T}/empty.conf" + + else + echo '[]' > "${T}/empty.conf" + echo "$(ghc-libdir)/ghc-pkg" "--global-conf=${T}/empty.conf" + fi +} + +# @FUNCTION: ghc-version +# @DESCRIPTION: +# returns upstream version of ghc +# as reported by '--numeric-version' +# Examples: "7.10.2", "7.9.20141222" +_GHC_VERSION_CACHE="" +ghc-version() { + if [[ -z "${_GHC_VERSION_CACHE}" ]]; then + _GHC_VERSION_CACHE="$($(ghc-getghc) --numeric-version)" + fi + echo "${_GHC_VERSION_CACHE}" +} + +# @FUNCTION: ghc-pm-version +# @DESCRIPTION: +# returns package manager(PM) version of ghc +# as reported by '$(best_version)' +# Examples: "PM:7.10.2", "PM:7.10.2_rc1", "PM:7.8.4-r4" +_GHC_PM_VERSION_CACHE="" +ghc-pm-version() { + local pm_ghc_p + + if [[ -z "${_GHC_PM_VERSION_CACHE}" ]]; then + pm_ghc_p=$(best_version dev-lang/ghc) + _GHC_PM_VERSION_CACHE="PM:${pm_ghc_p#dev-lang/ghc-}" + fi + echo "${_GHC_PM_VERSION_CACHE}" +} + +# @FUNCTION: ghc-cabal-version +# @DESCRIPTION: +# return version of the Cabal library bundled with ghc +ghc-cabal-version() { + if ver_test "$(ghc-version)" -ge "7.9.20141222"; then + # outputs in format: 'version: 1.18.1.5' + set -- `$(ghc-getghcpkg) --package-db=$(ghc-libdir)/package.conf.d.initial field Cabal version` + echo "$2" + else + local cabal_package=`echo "$(ghc-libdir)"/Cabal-*` + # /path/to/ghc/Cabal-${VER} -> ${VER} + echo "${cabal_package/*Cabal-/}" + fi +} + +# @FUNCTION: ghc-is-dynamic +# @DESCRIPTION: +# checks if ghc is built against dynamic libraries +# binaries linked against GHC library (and using plugin loading) +# have to be linked the same way: +# https://ghc.haskell.org/trac/ghc/ticket/10301 +ghc-is-dynamic() { + $(ghc-getghc) --info | grep "GHC Dynamic" | grep -q "YES" +} + +# @FUNCTION: ghc-supports-shared-libraries +# @DESCRIPTION: +# checks if ghc is built with support for building +# shared libraries (aka '-dynamic' option) +ghc-supports-shared-libraries() { + $(ghc-getghc) --info | grep "RTS ways" | grep -q "dyn" +} + +# @FUNCTION: ghc-supports-threaded-runtime +# @DESCRIPTION: +# checks if ghc is built with support for threaded +# runtime (aka '-threaded' option) +ghc-supports-threaded-runtime() { + $(ghc-getghc) --info | grep "RTS ways" | grep -q "thr" +} + +# @FUNCTION: ghc-supports-smp +# @DESCRIPTION: +# checks if ghc is built with support for multiple cores runtime +ghc-supports-smp() { + $(ghc-getghc) --info | grep "Support SMP" | grep -q "YES" +} + +# @FUNCTION: ghc-supports-interpreter +# @DESCRIPTION: +# checks if ghc has interpreter mode (aka GHCi) +# It usually means that ghc supports for template haskell. +ghc-supports-interpreter() { + $(ghc-getghc) --info | grep "Have interpreter" | grep -q "YES" +} + +# @FUNCTION: ghc-supports-parallel-make +# @DESCRIPTION: +# checks if ghc has support for '--make -j' mode +# The option was introduced in ghc-7.8-rc1. +ghc-supports-parallel-make() { + $(ghc-getghc) --info | grep "Support parallel --make" | grep -q "YES" +} + +# @FUNCTION: ghc-extractportageversion +# @DESCRIPTION: +# extract the version of a portage-installed package +ghc-extractportageversion() { + local pkg + local version + pkg="$(best_version $1)" + version="${pkg#$1-}" + version="${version%-r*}" + version="${version%_pre*}" + echo "${version}" +} + +# @FUNCTION: ghc-libdir +# @DESCRIPTION: +# returns the library directory +_GHC_LIBDIR_CACHE="" +ghc-libdir() { + if [[ -z "${_GHC_LIBDIR_CACHE}" ]]; then + _GHC_LIBDIR_CACHE="$($(ghc-getghc) --print-libdir)" + fi + echo "${_GHC_LIBDIR_CACHE}" +} + +# @FUNCTION: ghc-make-args +# @DESCRIPTION: +# Returns default arguments passed along 'ghc --make' +# build mode. Used mainly to enable parallel build mode. +ghc-make-args() { + local ghc_make_args=() + # parallel on all available cores + if ghc-supports-smp && ghc-supports-parallel-make; then + # It should have been just -j$(makeopts_jobs) + # but GHC does not yet have nice defaults: + # https://ghc.haskell.org/trac/ghc/ticket/9221#comment:57 + # SMP is a requirement for parallel GC's gen0 + # 'qb' balancing. + echo "-j$(makeopts_jobs) +RTS -A256M -qb0 -RTS" + ghc_make_args=() + fi + echo "${ghc_make_args[@]}" +} + +# @FUNCTION: ghc-confdir +# @DESCRIPTION: +# returns the (Gentoo) library configuration directory, we +# store here a hint for 'haskell-updater' about packages +# installed for old ghc versions and current ones. +ghc-confdir() { + echo "$(ghc-libdir)/gentoo" +} + +# @FUNCTION: ghc-package-db +# @DESCRIPTION: +# returns the global package database directory +ghc-package-db() { + echo "$(ghc-libdir)/package.conf.d" +} + +# @FUNCTION: ghc-localpkgconfd +# @DESCRIPTION: +# returns the name of the local (package-specific) +# package configuration file +ghc-localpkgconfd() { + echo "${PF}.conf.d" +} + +# @FUNCTION: ghc-package-exists +# @DESCRIPTION: +# tests if a ghc package exists +ghc-package-exists() { + $(ghc-getghcpkg) describe "$1" > /dev/null 2>&1 +} + +# @FUNCTION: check-for-collisions +# @DESCRIPTION: +# makes sure no packages +# have the same version as initial package setup +check-for-collisions() { + local localpkgconf=$1 + local checked_pkg + local initial_pkg_db="$(ghc-libdir)/package.conf.d.initial" + + for checked_pkg in `$(ghc-getghcpkgbin) -f "${localpkgconf}" list --simple-output` + do + # should return empty output + local collided=`$(ghc-getghcpkgbin) -f ${initial_pkg_db} list --simple-output "${checked_pkg}"` + + if [[ -n ${collided} ]]; then + eerror "Cabal package '${checked_pkg}' is shipped with '$(ghc-pm-version)' ('$(ghc-version)')." + eerror "Ebuild author forgot an entry in CABAL_CORE_LIB_GHC_PV='${CABAL_CORE_LIB_GHC_PV}'." + eerror "Found in ${initial_pkg_db}." + die + fi + done +} + +# @FUNCTION: ghc-install-pkg +# @DESCRIPTION: +# moves the local (package-specific) package configuration +# file to its final destination +ghc-install-pkg() { + local localpkgconf="${T}/$(ghc-localpkgconfd)" + local pkg_path pkg pkg_db="${D}/$(ghc-package-db)" hint_db="${D}/$(ghc-confdir)" + + $(ghc-getghcpkgbin) init "${localpkgconf}" || die "Failed to initialize empty local db" + for pkg_config_file in "$@"; do + $(ghc-getghcpkgbin) -f "${localpkgconf}" update - --force \ + < "${pkg_config_file}" || die "failed to register ${pkg}" + done + + check-for-collisions "${localpkgconf}" + + mkdir -p "${pkg_db}" || die + for pkg_path in "${localpkgconf}"/*.conf; do + pkg=$(basename "${pkg_path}") + cp "${pkg_path}" "${pkg_db}/${pkg}" || die + done + + mkdir -p "${hint_db}" || die + for pkg_config_file in "$@"; do + local pkg_name="gentoo-${CATEGORY}-${PF}-"$(basename "${pkg_config_file}") + cp "${pkg_config_file}" "${hint_db}/${pkg_name}" || die + chmod 0644 "${hint_db}/${pkg_name}" || die + done +} + +# @FUNCTION: ghc-recache-db +# @DESCRIPTION: +# updates 'package.cache' binary cacne for registered '*.conf' +# packages +ghc-recache-db() { + einfo "Recaching GHC package DB" + $(ghc-getghcpkg) recache +} + +# @FUNCTION: ghc-register-pkg +# @DESCRIPTION: +# registers all packages in the local (package-specific) +# package configuration file +ghc-register-pkg() { + ghc-recache-db +} + +# @FUNCTION: ghc-reregister +# @DESCRIPTION: +# re-adds all available .conf files to the global +# package conf file, to be used on a ghc reinstallation +ghc-reregister() { + ghc-recache-db +} + +# @FUNCTION: ghc-unregister-pkg +# @DESCRIPTION: +# unregisters a package configuration file +ghc-unregister-pkg() { + ghc-recache-db +} + +# @FUNCTION: ghc-pkgdeps +# @DESCRIPTION: +# exported function: loads a package dependency in a form +# cabal_package version +ghc-pkgdeps() { + echo $($(ghc-getghcpkg) describe "${1}") \ + | sed \ + -e '/depends/,/^.*:/ !d' \ + -e 's/\(.*\)-\(.*\)-\(.*\)/\1 \2/' \ + -e 's/^.*://g' +} + +# @FUNCTION: ghc-package_pkg_postinst +# @DESCRIPTION: +# updates package.cache after package install +ghc-package_pkg_postinst() { + ghc-recache-db +} + +# @FUNCTION: ghc-package_pkg_prerm +# @DESCRIPTION: +# updates package.cache after package deinstall +ghc-package_pkg_prerm() { + ewarn "ghc-package.eclass: 'ghc-package_pkg_prerm()' is a noop" + ewarn "ghc-package.eclass: consider 'haskell-cabal_pkg_postrm()' instead" +} + +# @FUNCTION: ghc-package_pkg_postrm +# @DESCRIPTION: +# updates package.cache after package deinstall +ghc-package_pkg_postrm() { + ghc-recache-db +} diff --git a/eclass/git-r3.eclass b/eclass/git-r3.eclass new file mode 100644 index 0000000..cda7ac1 --- /dev/null +++ b/eclass/git-r3.eclass @@ -0,0 +1,1129 @@ +# Copyright 1999-2020 Gentoo Authors +# Distributed under the terms of the GNU General Public License v2 + +# @ECLASS: git-r3.eclass +# @MAINTAINER: +# Michał Górny <mgorny@gentoo.org> +# @SUPPORTED_EAPIS: 4 5 6 7 +# @BLURB: Eclass for fetching and unpacking git repositories. +# @DESCRIPTION: +# Third generation eclass for easing maintenance of live ebuilds using +# git as remote repository. + +case "${EAPI:-0}" in + 0|1|2|3) + die "Unsupported EAPI=${EAPI} (obsolete) for ${ECLASS}" + ;; + 4|5|6|7) + ;; + *) + die "Unsupported EAPI=${EAPI} (unknown) for ${ECLASS}" + ;; +esac + +EXPORT_FUNCTIONS src_unpack + +if [[ ! ${_GIT_R3} ]]; then + +PROPERTIES+=" live" + +if [[ ! ${_INHERITED_BY_GIT_2} ]]; then + if [[ ${EAPI:-0} != [0123456] ]]; then + BDEPEND=">=dev-vcs/git-1.8.2.1[curl]" + else + DEPEND=">=dev-vcs/git-1.8.2.1[curl]" + fi +fi + +# @ECLASS-VARIABLE: EGIT_CLONE_TYPE +# @DESCRIPTION: +# Type of clone that should be used against the remote repository. +# This can be either of: 'mirror', 'single', 'shallow'. +# +# This is intended to be set by user in make.conf. Ebuilds are supposed +# to set EGIT_MIN_CLONE_TYPE if necessary instead. +# +# The 'mirror' type clones all remote branches and tags with complete +# history and all notes. EGIT_COMMIT can specify any commit hash. +# Upstream-removed branches and tags are purged from the local clone +# while fetching. This mode is suitable for cloning the local copy +# for development or hosting a local git mirror. However, clones +# of repositories with large diverged branches may quickly grow large. +# +# The 'single+tags' type clones the requested branch and all tags +# in the repository. All notes are fetched as well. EGIT_COMMIT +# can safely specify hashes throughout the current branch and all tags. +# No purging of old references is done (if you often switch branches, +# you may need to remove stale branches yourself). This mode is intended +# mostly for use with broken git servers such as Google Code that fail +# to fetch tags along with the branch in 'single' mode. +# +# The 'single' type clones only the requested branch or tag. Tags +# referencing commits throughout the branch history are fetched as well, +# and all notes. EGIT_COMMIT can safely specify only hashes +# in the current branch. No purging of old references is done (if you +# often switch branches, you may need to remove stale branches +# yourself). This mode is suitable for general use. +# +# The 'shallow' type clones only the newest commit on requested branch +# or tag. EGIT_COMMIT can only specify tags, and since the history is +# unavailable calls like 'git describe' will not reference prior tags. +# No purging of old references is done. This mode is intended mostly for +# embedded systems with limited disk space. +: ${EGIT_CLONE_TYPE:=single} + +# @ECLASS-VARIABLE: EGIT_MIN_CLONE_TYPE +# @DESCRIPTION: +# 'Minimum' clone type supported by the ebuild. Takes same values +# as EGIT_CLONE_TYPE. When user sets a type that's 'lower' (that is, +# later on the list) than EGIT_MIN_CLONE_TYPE, the eclass uses +# EGIT_MIN_CLONE_TYPE instead. +# +# This variable is intended to be used by ebuilds only. Users are +# supposed to set EGIT_CLONE_TYPE instead. +# +# A common case is to use 'single' whenever the build system requires +# access to full branch history, or 'single+tags' when Google Code +# or a similar remote is used that does not support shallow clones +# and fetching tags along with commits. Please use sparingly, and to fix +# fatal errors rather than 'non-pretty versions'. +: ${EGIT_MIN_CLONE_TYPE:=shallow} + +# @ECLASS-VARIABLE: EGIT3_STORE_DIR +# @USER_VARIABLE +# @DEFAULT_UNSET +# @DESCRIPTION: +# Storage directory for git sources. +# +# This is intended to be set by user in make.conf. Ebuilds must not set +# it. +# +# EGIT3_STORE_DIR=${DISTDIR}/git3-src + +# @ECLASS-VARIABLE: EGIT_MIRROR_URI +# @DEFAULT_UNSET +# @DESCRIPTION: +# 'Top' URI to a local git mirror. If specified, the eclass will try +# to fetch from the local mirror instead of using the remote repository. +# +# The mirror needs to follow EGIT3_STORE_DIR structure. The directory +# created by eclass can be used for that purpose. +# +# Example: +# @CODE +# EGIT_MIRROR_URI="git://mirror.lan/" +# @CODE + +# @ECLASS-VARIABLE: EGIT_REPO_URI +# @REQUIRED +# @DESCRIPTION: +# URIs to the repository, e.g. https://foo. If multiple URIs are +# provided, the eclass will consider the remaining URIs as fallbacks +# to try if the first URI does not work. For supported URI syntaxes, +# read the manpage for git-clone(1). +# +# URIs should be using https:// whenever possible. http:// and git:// +# URIs are completely unsecured and their use (even if only as +# a fallback) renders the ebuild completely vulnerable to MITM attacks. +# +# Can be a whitespace-separated list or an array. +# +# Example: +# @CODE +# EGIT_REPO_URI="https://a/b.git https://c/d.git" +# @CODE + +# @ECLASS-VARIABLE: EVCS_OFFLINE +# @DEFAULT_UNSET +# @DESCRIPTION: +# If non-empty, this variable prevents any online operations. + +# @ECLASS-VARIABLE: EVCS_UMASK +# @DEFAULT_UNSET +# @DESCRIPTION: +# Set this variable to a custom umask. This is intended to be set by +# users. By setting this to something like 002, it can make life easier +# for people who do development as non-root (but are in the portage +# group), and then switch over to building with FEATURES=userpriv. +# Or vice-versa. Shouldn't be a security issue here as anyone who has +# portage group write access already can screw the system over in more +# creative ways. + +# @ECLASS-VARIABLE: EGIT_BRANCH +# @DEFAULT_UNSET +# @DESCRIPTION: +# The branch name to check out. If unset, the upstream default (HEAD) +# will be used. + +# @ECLASS-VARIABLE: EGIT_COMMIT +# @DEFAULT_UNSET +# @DESCRIPTION: +# The tag name or commit identifier to check out. If unset, newest +# commit from the branch will be used. Note that if set to a commit +# not on HEAD branch, EGIT_BRANCH needs to be set to a branch on which +# the commit is available. + +# @ECLASS-VARIABLE: EGIT_COMMIT_DATE +# @DEFAULT_UNSET +# @DESCRIPTION: +# Attempt to check out the repository state for the specified timestamp. +# The date should be in format understood by 'git rev-list'. The commits +# on EGIT_BRANCH will be considered. +# +# The eclass will select the last commit with commit date preceding +# the specified date. When merge commits are found, only first parents +# will be considered in order to avoid switching into external branches +# (assuming that merges are done correctly). In other words, each merge +# will be considered alike a single commit with date corresponding +# to the merge commit date. + +# @ECLASS-VARIABLE: EGIT_CHECKOUT_DIR +# @DEFAULT_UNSET +# @DESCRIPTION: +# The directory to check the git sources out to. +# +# EGIT_CHECKOUT_DIR=${WORKDIR}/${P} + +# @ECLASS-VARIABLE: EGIT_SUBMODULES +# @DEFAULT_UNSET +# @DESCRIPTION: +# An array of inclusive and exclusive wildcards on submodule names, +# stating which submodules are fetched and checked out. Exclusions +# start with '-', and exclude previously matched submodules. +# +# If unset, all submodules are enabled. Empty list disables all +# submodules. In order to use an exclude-only list, start the array +# with '*'. +# +# Remember that wildcards need to be quoted in order to prevent filename +# expansion. +# +# Examples: +# @CODE +# # Disable all submodules +# EGIT_SUBMODULES=() +# +# # Include only foo and bar +# EGIT_SUBMODULES=( foo bar ) +# +# # Use all submodules except for test-* but include test-lib +# EGIT_SUBMODULES=( '*' '-test-*' test-lib ) +# @CODE + +# @FUNCTION: _git-r3_env_setup +# @INTERNAL +# @DESCRIPTION: +# Set the eclass variables as necessary for operation. This can involve +# setting EGIT_* to defaults or ${PN}_LIVE_* variables. +_git-r3_env_setup() { + debug-print-function ${FUNCNAME} "$@" + + # check the clone type + case "${EGIT_CLONE_TYPE}" in + mirror|single+tags|single|shallow) + ;; + *) + die "Invalid EGIT_CLONE_TYPE=${EGIT_CLONE_TYPE}" + esac + case "${EGIT_MIN_CLONE_TYPE}" in + shallow) + ;; + single) + if [[ ${EGIT_CLONE_TYPE} == shallow ]]; then + einfo "git-r3: ebuild needs to be cloned in 'single' mode, adjusting" + EGIT_CLONE_TYPE=single + fi + ;; + single+tags) + if [[ ${EGIT_CLONE_TYPE} == shallow || ${EGIT_CLONE_TYPE} == single ]]; then + einfo "git-r3: ebuild needs to be cloned in 'single+tags' mode, adjusting" + EGIT_CLONE_TYPE=single+tags + fi + ;; + mirror) + if [[ ${EGIT_CLONE_TYPE} != mirror ]]; then + einfo "git-r3: ebuild needs to be cloned in 'mirror' mode, adjusting" + EGIT_CLONE_TYPE=mirror + fi + ;; + *) + die "Invalid EGIT_MIN_CLONE_TYPE=${EGIT_MIN_CLONE_TYPE}" + esac + + if [[ ${EGIT_SUBMODULES[@]+1} && $(declare -p EGIT_SUBMODULES) != "declare -a"* ]] + then + die 'EGIT_SUBMODULES must be an array.' + fi + + local esc_pn livevar + esc_pn=${PN//[-+]/_} + [[ ${esc_pn} == [0-9]* ]] && esc_pn=_${esc_pn} + + # note: deprecated, use EGIT_OVERRIDE_* instead + livevar=${esc_pn}_LIVE_REPO + EGIT_REPO_URI=${!livevar-${EGIT_REPO_URI}} + [[ ${!livevar} ]] \ + && ewarn "Using ${livevar}, no support will be provided" + + livevar=${esc_pn}_LIVE_BRANCH + EGIT_BRANCH=${!livevar-${EGIT_BRANCH}} + [[ ${!livevar} ]] \ + && ewarn "Using ${livevar}, no support will be provided" + + livevar=${esc_pn}_LIVE_COMMIT + EGIT_COMMIT=${!livevar-${EGIT_COMMIT}} + [[ ${!livevar} ]] \ + && ewarn "Using ${livevar}, no support will be provided" + + livevar=${esc_pn}_LIVE_COMMIT_DATE + EGIT_COMMIT_DATE=${!livevar-${EGIT_COMMIT_DATE}} + [[ ${!livevar} ]] \ + && ewarn "Using ${livevar}, no support will be provided" + + if [[ ${EGIT_COMMIT} && ${EGIT_COMMIT_DATE} ]]; then + die "EGIT_COMMIT and EGIT_COMMIT_DATE can not be specified simultaneously" + fi + + # Migration helpers. Remove them when git-2 is removed. + + if [[ ${EGIT_SOURCEDIR} ]]; then + eerror "EGIT_SOURCEDIR has been replaced by EGIT_CHECKOUT_DIR. While updating" + eerror "your ebuild, please check whether the variable is necessary at all" + eerror "since the default has been changed from \${S} to \${WORKDIR}/\${P}." + eerror "Therefore, proper setting of S may be sufficient." + die "EGIT_SOURCEDIR has been replaced by EGIT_CHECKOUT_DIR." + fi + + if [[ ${EGIT_MASTER} ]]; then + eerror "EGIT_MASTER has been removed. Instead, the upstream default (HEAD)" + eerror "is used by the eclass. Please remove the assignment or use EGIT_BRANCH" + eerror "as necessary." + die "EGIT_MASTER has been removed." + fi + + if [[ ${EGIT_HAS_SUBMODULES} ]]; then + eerror "EGIT_HAS_SUBMODULES has been removed. The eclass no longer needs" + eerror "to switch the clone type in order to support submodules and therefore" + eerror "submodules are detected and fetched automatically. If you need to" + eerror "disable or filter submodules, see EGIT_SUBMODULES." + die "EGIT_HAS_SUBMODULES is no longer necessary." + fi + + if [[ ${EGIT_PROJECT} ]]; then + eerror "EGIT_PROJECT has been removed. Instead, the eclass determines" + eerror "the local clone path using path in canonical EGIT_REPO_URI." + eerror "If the current algorithm causes issues for you, please report a bug." + die "EGIT_PROJECT is no longer necessary." + fi + + if [[ ${EGIT_BOOTSTRAP} ]]; then + eerror "EGIT_BOOTSTRAP has been removed. Please create proper src_prepare()" + eerror "instead." + die "EGIT_BOOTSTRAP has been removed." + fi + + if [[ ${EGIT_NOUNPACK} ]]; then + eerror "EGIT_NOUNPACK has been removed. The eclass no longer calls default" + eerror "unpack function. If necessary, please declare proper src_unpack()." + die "EGIT_NOUNPACK has been removed." + fi +} + +# @FUNCTION: _git-r3_set_gitdir +# @USAGE: <repo-uri> +# @INTERNAL +# @DESCRIPTION: +# Obtain the local repository path and set it as GIT_DIR. Creates +# a new repository if necessary. +# +# <repo-uri> may be used to compose the path. It should therefore be +# a canonical URI to the repository. +_git-r3_set_gitdir() { + debug-print-function ${FUNCNAME} "$@" + + local repo_name=${1#*://*/} + + # strip the trailing slash + repo_name=${repo_name%/} + + # strip common prefixes to make paths more likely to match + # e.g. git://X/Y.git vs https://X/git/Y.git + # (but just one of the prefixes) + case "${repo_name}" in + # gnome.org... who else? + browse/*) repo_name=${repo_name#browse/};; + # cgit can proxy requests to git + cgit/*) repo_name=${repo_name#cgit/};; + # pretty common + git/*) repo_name=${repo_name#git/};; + # gentoo.org + gitroot/*) repo_name=${repo_name#gitroot/};; + # sourceforge + p/*) repo_name=${repo_name#p/};; + # kernel.org + pub/scm/*) repo_name=${repo_name#pub/scm/};; + esac + # ensure a .git suffix, same reason + repo_name=${repo_name%.git}.git + # now replace all the slashes + repo_name=${repo_name//\//_} + + local distdir=${PORTAGE_ACTUAL_DISTDIR:-${DISTDIR}} + : ${EGIT3_STORE_DIR:=${distdir}/git3-src} + + GIT_DIR=${EGIT3_STORE_DIR}/${repo_name} + + if [[ ! -d ${EGIT3_STORE_DIR} && ! ${EVCS_OFFLINE} ]]; then + ( + addwrite / + mkdir -p "${EGIT3_STORE_DIR}" + ) || die "Unable to create ${EGIT3_STORE_DIR}" + fi + + addwrite "${EGIT3_STORE_DIR}" + if [[ ! -d ${GIT_DIR} ]]; then + if [[ ${EVCS_OFFLINE} ]]; then + eerror "A clone of the following repository is required to proceed:" + eerror " ${1}" + eerror "However, networking activity has been disabled using EVCS_OFFLINE and there" + eerror "is no local clone available." + die "No local clone of ${1}. Unable to proceed with EVCS_OFFLINE." + fi + + local saved_umask + if [[ ${EVCS_UMASK} ]]; then + saved_umask=$(umask) + umask "${EVCS_UMASK}" || die "Bad options to umask: ${EVCS_UMASK}" + fi + mkdir "${GIT_DIR}" || die + git init --bare || die + if [[ ${saved_umask} ]]; then + umask "${saved_umask}" || die + fi + fi +} + +# @FUNCTION: _git-r3_set_submodules +# @USAGE: <parent-path> <file-contents> +# @INTERNAL +# @DESCRIPTION: +# Parse .gitmodules contents passed as <file-contents> +# as in "$(cat .gitmodules)"). Composes a 'submodules' array that +# contains in order (name, URL, path) for each submodule. +# +# <parent-path> specifies path to current submodule (empty if top repo), +# and is used to support recursively specifying submodules. The path +# must include a trailing slash if it's not empty. +_git-r3_set_submodules() { + debug-print-function ${FUNCNAME} "$@" + + local parent_path=${1} + local data=${2} + [[ -z ${parent_path} || ${parent_path} == */ ]] || die + + # ( name url path ... ) + submodules=() + + local l + while read l; do + # submodule.<path>.path=<path> + # submodule.<path>.url=<url> + [[ ${l} == submodule.*.url=* ]] || continue + + l=${l#submodule.} + local subname=${l%%.url=*} + + # filter out on EGIT_SUBMODULES + if declare -p EGIT_SUBMODULES &>/dev/null; then + local p l_res res= + for p in "${EGIT_SUBMODULES[@]}"; do + if [[ ${p} == -* ]]; then + p=${p#-} + l_res= + else + l_res=1 + fi + + [[ ${parent_path}${subname} == ${p} ]] && res=${l_res} + done + + if [[ ! ${res} ]]; then + einfo "Skipping submodule ${parent_path}${subname}" + continue + else + einfo "Using submodule ${parent_path}${subname}" + fi + fi + + # skip modules that have 'update = none', bug #487262. + local upd=$(echo "${data}" | git config -f /dev/fd/0 \ + submodule."${subname}".update) + [[ ${upd} == none ]] && continue + + # https://github.com/git/git/blob/master/refs.c#L31 + # we are more restrictive than git itself but that should not + # cause any issues, #572312, #606950 + # TODO: check escaped names for collisions + local enc_subname=${subname//[^a-zA-Z0-9-]/_} + + submodules+=( + "${enc_subname}" + "$(echo "${data}" | git config -f /dev/fd/0 \ + submodule."${subname}".url || die)" + "$(echo "${data}" | git config -f /dev/fd/0 \ + submodule."${subname}".path || die)" + ) + done < <(echo "${data}" | git config -f /dev/fd/0 -l || die) +} + +# @FUNCTION: _git-r3_set_subrepos +# @USAGE: <submodule-uri> <parent-repo-uri>... +# @INTERNAL +# @DESCRIPTION: +# Create 'subrepos' array containing absolute (canonical) submodule URIs +# for the given <submodule-uri>. If the URI is relative, URIs will be +# constructed using all <parent-repo-uri>s. Otherwise, this single URI +# will be placed in the array. +_git-r3_set_subrepos() { + debug-print-function ${FUNCNAME} "$@" + + local suburl=${1} + subrepos=( "${@:2}" ) + + if [[ ${suburl} == ./* || ${suburl} == ../* ]]; then + # drop all possible trailing slashes for consistency + subrepos=( "${subrepos[@]%%/}" ) + + while true; do + if [[ ${suburl} == ./* ]]; then + suburl=${suburl:2} + elif [[ ${suburl} == ../* ]]; then + suburl=${suburl:3} + + # XXX: correctness checking + + # drop the last path component + subrepos=( "${subrepos[@]%/*}" ) + # and then the trailing slashes, again + subrepos=( "${subrepos[@]%%/}" ) + else + break + fi + done + + # append the preprocessed path to the preprocessed URIs + subrepos=( "${subrepos[@]/%//${suburl}}") + else + subrepos=( "${suburl}" ) + fi +} + + +# @FUNCTION: _git-r3_is_local_repo +# @USAGE: <repo-uri> +# @INTERNAL +# @DESCRIPTION: +# Determine whether the given URI specifies a local (on-disk) +# repository. +_git-r3_is_local_repo() { + debug-print-function ${FUNCNAME} "$@" + + local uri=${1} + + [[ ${uri} == file://* || ${uri} == /* ]] +} + +# @FUNCTION: git-r3_fetch +# @USAGE: [<repo-uri> [<remote-ref> [<local-id> [<commit-date>]]]] +# @DESCRIPTION: +# Fetch new commits to the local clone of repository. +# +# <repo-uri> specifies the repository URIs to fetch from, as a space- +# -separated list. The first URI will be used as repository group +# identifier and therefore must be used consistently. When not +# specified, defaults to ${EGIT_REPO_URI}. +# +# <remote-ref> specifies the remote ref or commit id to fetch. +# It is preferred to use 'refs/heads/<branch-name>' for branches +# and 'refs/tags/<tag-name>' for tags. Other options are 'HEAD' +# for upstream default branch and hexadecimal commit SHA1. Defaults +# to the first of EGIT_COMMIT, EGIT_BRANCH or literal 'HEAD' that +# is set to a non-null value. +# +# <local-id> specifies the local branch identifier that will be used to +# locally store the fetch result. It should be unique to multiple +# fetches within the repository that can be performed at the same time +# (including parallel merges). It defaults to ${CATEGORY}/${PN}/${SLOT%/*}. +# This default should be fine unless you are fetching multiple trees +# from the same repository in the same ebuild. +# +# <commit-date> requests attempting to use repository state as of specific +# date. For more details, see EGIT_COMMIT_DATE. +# +# The fetch operation will affect the EGIT_STORE only. It will not touch +# the working copy, nor export any environment variables. +# If the repository contains submodules, they will be fetched +# recursively. +git-r3_fetch() { + debug-print-function ${FUNCNAME} "$@" + + # disable password prompts, https://bugs.gentoo.org/701276 + local -x GIT_TERMINAL_PROMPT=0 + + # process repos first since we create repo_name from it + local repos + if [[ ${1} ]]; then + repos=( ${1} ) + elif [[ $(declare -p EGIT_REPO_URI) == "declare -a"* ]]; then + repos=( "${EGIT_REPO_URI[@]}" ) + else + repos=( ${EGIT_REPO_URI} ) + fi + + [[ ${repos[@]} ]] || die "No URI provided and EGIT_REPO_URI unset" + + local r + for r in "${repos[@]}"; do + if [[ ${r} == git:* || ${r} == http:* ]]; then + ewarn "git-r3: ${r%%:*} protocol is completely unsecure and may render the ebuild" + ewarn "easily susceptible to MITM attacks (even if used only as fallback). Please" + ewarn "use https instead." + ewarn "[URI: ${r}]" + fi + done + + local -x GIT_DIR + _git-r3_set_gitdir "${repos[0]}" + + einfo "Repository id: ${GIT_DIR##*/}" + + # prepend the local mirror if applicable + if [[ ${EGIT_MIRROR_URI} ]]; then + repos=( + "${EGIT_MIRROR_URI%/}/${GIT_DIR##*/}" + "${repos[@]}" + ) + fi + + # get the default values for the common variables and override them + local branch_name=${EGIT_BRANCH} + local commit_id=${2:-${EGIT_COMMIT}} + local commit_date=${4:-${EGIT_COMMIT_DATE}} + + # support new override API for EAPI 6+ + if ! has "${EAPI:-0}" 0 1 2 3 4 5; then + # get the name and do some more processing: + # 1) kill .git suffix, + # 2) underscore (remaining) non-variable characters, + # 3) add preceding underscore if it starts with a digit, + # 4) uppercase. + local override_name=${GIT_DIR##*/} + override_name=${override_name%.git} + override_name=${override_name//[^a-zA-Z0-9_]/_} + override_name=${override_name^^} + + local varmap=( + REPO:repos + BRANCH:branch_name + COMMIT:commit_id + COMMIT_DATE:commit_date + ) + + local localvar livevar live_warn= override_vars=() + for localvar in "${varmap[@]}"; do + livevar=EGIT_OVERRIDE_${localvar%:*}_${override_name} + localvar=${localvar#*:} + override_vars+=( "${livevar}" ) + + if [[ -n ${!livevar} ]]; then + [[ ${localvar} == repos ]] && repos=() + live_warn=1 + ewarn "Using ${livevar}=${!livevar}" + declare "${localvar}=${!livevar}" + fi + done + + if [[ ${live_warn} ]]; then + ewarn "No support will be provided." + else + einfo "To override fetched repository properties, use:" + local x + for x in "${override_vars[@]}"; do + einfo " ${x}" + done + einfo + fi + fi + + # set final variables after applying overrides + local branch=${branch_name:+refs/heads/${branch_name}} + local remote_ref=${commit_id:-${branch:-HEAD}} + local local_id=${3:-${CATEGORY}/${PN}/${SLOT%/*}} + local local_ref=refs/git-r3/${local_id}/__main__ + + # try to fetch from the remote + local success saved_umask + if [[ ${EVCS_UMASK} ]]; then + saved_umask=$(umask) + umask "${EVCS_UMASK}" || die "Bad options to umask: ${EVCS_UMASK}" + fi + for r in "${repos[@]}"; do + if [[ ! ${EVCS_OFFLINE} ]]; then + einfo "Fetching ${r} ..." + + local fetch_command=( git fetch "${r}" ) + local clone_type=${EGIT_CLONE_TYPE} + + if [[ ${clone_type} == mirror ]]; then + fetch_command+=( + --prune + # mirror the remote branches as local branches + "+refs/heads/*:refs/heads/*" + # pull tags explicitly in order to prune them properly + "+refs/tags/*:refs/tags/*" + # notes in case something needs them + "+refs/notes/*:refs/notes/*" + # pullrequest refs are useful for testing incoming changes + "+refs/pull/*/head:refs/pull/*" + # and HEAD in case we need the default branch + # (we keep it in refs/git-r3 since otherwise --prune interferes) + "+HEAD:refs/git-r3/HEAD" + ) + else # single or shallow + local fetch_l fetch_r + + if [[ ${remote_ref} == HEAD ]]; then + # HEAD + fetch_l=HEAD + elif [[ ${remote_ref} == refs/* ]]; then + # regular branch, tag or some other explicit ref + fetch_l=${remote_ref} + else + # tag or commit id... + # let ls-remote figure it out + local tagref=$(git ls-remote "${r}" "refs/tags/${remote_ref}") + + # if it was a tag, ls-remote obtained a hash + if [[ ${tagref} ]]; then + # tag + fetch_l=refs/tags/${remote_ref} + else + # commit id + # so we need to fetch the whole branch + if [[ ${branch} ]]; then + fetch_l=${branch} + else + fetch_l=HEAD + fi + + # fetching by commit in shallow mode? can't do. + if [[ ${clone_type} == shallow ]]; then + clone_type=single + fi + fi + fi + + # checkout by date does not make sense in shallow mode + if [[ ${commit_date} && ${clone_type} == shallow ]]; then + clone_type=single + fi + + if [[ ${fetch_l} == HEAD ]]; then + fetch_r=refs/git-r3/HEAD + else + fetch_r=${fetch_l} + fi + + fetch_command+=( + "+${fetch_l}:${fetch_r}" + ) + + if [[ ${clone_type} == single+tags ]]; then + fetch_command+=( + # pull tags explicitly as requested + "+refs/tags/*:refs/tags/*" + ) + fi + fi + + if [[ ${clone_type} == shallow ]]; then + if _git-r3_is_local_repo; then + # '--depth 1' causes sandbox violations with local repos + # bug #491260 + clone_type=single + elif [[ ! $(git rev-parse --quiet --verify "${fetch_r}") ]] + then + # use '--depth 1' when fetching a new branch + fetch_command+=( --depth 1 ) + fi + else # non-shallow mode + if [[ -f ${GIT_DIR}/shallow ]]; then + fetch_command+=( --unshallow ) + fi + fi + + set -- "${fetch_command[@]}" + echo "${@}" >&2 + "${@}" || continue + + if [[ ${clone_type} == mirror || ${fetch_l} == HEAD ]]; then + # update our HEAD to match our remote HEAD ref + git symbolic-ref HEAD refs/git-r3/HEAD \ + || die "Unable to update HEAD" + fi + fi + + # now let's see what the user wants from us + if [[ ${commit_date} ]]; then + local dated_commit_id=$( + git rev-list --first-parent --before="${commit_date}" \ + -n 1 "${remote_ref}" + ) + if [[ ${?} -ne 0 ]]; then + die "Listing ${remote_ref} failed (wrong ref?)." + elif [[ ! ${dated_commit_id} ]]; then + die "Unable to find commit for date ${commit_date}." + else + set -- git update-ref --no-deref "${local_ref}" "${dated_commit_id}" + fi + else + local full_remote_ref=$( + git rev-parse --verify --symbolic-full-name "${remote_ref}" + ) + + if [[ ${full_remote_ref} ]]; then + # when we are given a ref, create a symbolic ref + # so that we preserve the actual argument + set -- git symbolic-ref "${local_ref}" "${full_remote_ref}" + else + # otherwise, we were likely given a commit id + set -- git update-ref --no-deref "${local_ref}" "${remote_ref}" + fi + fi + + echo "${@}" >&2 + if ! "${@}"; then + if [[ ${EVCS_OFFLINE} ]]; then + eerror "A clone of the following repository is required to proceed:" + eerror " ${r}" + eerror "However, networking activity has been disabled using EVCS_OFFLINE and the local" + eerror "clone does not have requested ref:" + eerror " ${remote_ref}" + die "Local clone of ${r} does not have requested ref: ${remote_ref}. Unable to proceed with EVCS_OFFLINE." + else + die "Referencing ${remote_ref} failed (wrong ref?)." + fi + fi + + success=1 + break + done + if [[ ${saved_umask} ]]; then + umask "${saved_umask}" || die + fi + [[ ${success} ]] || die "Unable to fetch from any of EGIT_REPO_URI" + + # submodules can reference commits in any branch + # always use the 'mirror' mode to accomodate that, bug #503332 + local EGIT_CLONE_TYPE=mirror + + # recursively fetch submodules + if git cat-file -e "${local_ref}":.gitmodules &>/dev/null; then + local submodules + _git-r3_set_submodules "${_GIT_SUBMODULE_PATH}" \ + "$(git cat-file -p "${local_ref}":.gitmodules || die)" + + while [[ ${submodules[@]} ]]; do + local subname=${submodules[0]} + local url=${submodules[1]} + local path=${submodules[2]} + + # use only submodules for which path does exist + # (this is in par with 'git submodule'), bug #551100 + # note: git cat-file does not work for submodules + if [[ $(git ls-tree -d "${local_ref}" "${path}") ]] + then + local commit=$(git rev-parse "${local_ref}:${path}" || die) + + if [[ ! ${commit} ]]; then + die "Unable to get commit id for submodule ${subname}" + fi + + local subrepos + _git-r3_set_subrepos "${url}" "${repos[@]}" + + _GIT_SUBMODULE_PATH=${_GIT_SUBMODULE_PATH}${path}/ \ + git-r3_fetch "${subrepos[*]}" "${commit}" \ + "${local_id}/${subname}" "" + fi + + submodules=( "${submodules[@]:3}" ) # shift + done + fi +} + +# @FUNCTION: git-r3_checkout +# @USAGE: [<repo-uri> [<checkout-path> [<local-id> [<checkout-paths>...]]]] +# @DESCRIPTION: +# Check the previously fetched tree to the working copy. +# +# <repo-uri> specifies the repository URIs, as a space-separated list. +# The first URI will be used as repository group identifier +# and therefore must be used consistently with git-r3_fetch. +# The remaining URIs are not used and therefore may be omitted. +# When not specified, defaults to ${EGIT_REPO_URI}. +# +# <checkout-path> specifies the path to place the checkout. It defaults +# to ${EGIT_CHECKOUT_DIR} if set, otherwise to ${WORKDIR}/${P}. +# +# <local-id> needs to specify the local identifier that was used +# for respective git-r3_fetch. +# +# If <checkout-paths> are specified, then the specified paths are passed +# to 'git checkout' to effect a partial checkout. Please note that such +# checkout will not cause the repository to switch branches, +# and submodules will be skipped at the moment. The submodules matching +# those paths might be checked out in a future version of the eclass. +# +# The checkout operation will write to the working copy, and export +# the repository state into the environment. If the repository contains +# submodules, they will be checked out recursively. +git-r3_checkout() { + debug-print-function ${FUNCNAME} "$@" + + local repos + if [[ ${1} ]]; then + repos=( ${1} ) + elif [[ $(declare -p EGIT_REPO_URI) == "declare -a"* ]]; then + repos=( "${EGIT_REPO_URI[@]}" ) + else + repos=( ${EGIT_REPO_URI} ) + fi + + local out_dir=${2:-${EGIT_CHECKOUT_DIR:-${WORKDIR}/${P}}} + local local_id=${3:-${CATEGORY}/${PN}/${SLOT%/*}} + local checkout_paths=( "${@:4}" ) + + local -x GIT_DIR + _git-r3_set_gitdir "${repos[0]}" + + einfo "Checking out ${repos[0]} to ${out_dir} ..." + + if ! git cat-file -e refs/git-r3/"${local_id}"/__main__; then + die "Logic error: no local clone of ${repos[0]}. git-r3_fetch not used?" + fi + local remote_ref=$( + git symbolic-ref --quiet refs/git-r3/"${local_id}"/__main__ + ) + local new_commit_id=$( + git rev-parse --verify refs/git-r3/"${local_id}"/__main__ + ) + + git-r3_sub_checkout() { + local orig_repo=${GIT_DIR} + local -x GIT_DIR=${out_dir}/.git + local -x GIT_WORK_TREE=${out_dir} + + mkdir -p "${out_dir}" || die + + # use git init+fetch instead of clone since the latter doesn't like + # non-empty directories. + + git init --quiet || die + # setup 'alternates' to avoid copying objects + echo "${orig_repo}/objects" > "${GIT_DIR}"/objects/info/alternates || die + # now copy the refs + cp -R "${orig_repo}"/refs/* "${GIT_DIR}"/refs/ || die + if [[ -f ${orig_repo}/packed-refs ]]; then + cp "${orig_repo}"/packed-refs "${GIT_DIR}"/packed-refs || die + fi + + # (no need to copy HEAD, we will set it via checkout) + + if [[ -f ${orig_repo}/shallow ]]; then + cp "${orig_repo}"/shallow "${GIT_DIR}"/ || die + fi + + set -- git checkout --quiet + if [[ ${remote_ref} ]]; then + set -- "${@}" "${remote_ref#refs/heads/}" + else + set -- "${@}" "${new_commit_id}" + fi + if [[ ${checkout_paths[@]} ]]; then + set -- "${@}" -- "${checkout_paths[@]}" + fi + echo "${@}" >&2 + "${@}" || die "git checkout ${remote_ref:-${new_commit_id}} failed" + } + git-r3_sub_checkout + unset -f git-r3_sub_checkout + + local old_commit_id=$( + git rev-parse --quiet --verify refs/git-r3/"${local_id}"/__old__ + ) + if [[ ! ${old_commit_id} ]]; then + echo "GIT NEW branch -->" + echo " repository: ${repos[0]}" + echo " at the commit: ${new_commit_id}" + else + # diff against previous revision + echo "GIT update -->" + echo " repository: ${repos[0]}" + # write out message based on the revisions + if [[ "${old_commit_id}" != "${new_commit_id}" ]]; then + echo " updating from commit: ${old_commit_id}" + echo " to commit: ${new_commit_id}" + + set -- git --no-pager diff --stat \ + ${old_commit_id}..${new_commit_id} + if [[ ${checkout_paths[@]} ]]; then + set -- "${@}" -- "${checkout_paths[@]}" + fi + "${@}" + else + echo " at the commit: ${new_commit_id}" + fi + fi + git update-ref --no-deref refs/git-r3/"${local_id}"/{__old__,__main__} || die + + # recursively checkout submodules + if [[ -f ${out_dir}/.gitmodules && ! ${checkout_paths} ]]; then + local submodules + _git-r3_set_submodules "${_GIT_SUBMODULE_PATH}" \ + "$(<"${out_dir}"/.gitmodules)" + + while [[ ${submodules[@]} ]]; do + local subname=${submodules[0]} + local url=${submodules[1]} + local path=${submodules[2]} + + # use only submodules for which path does exist + # (this is in par with 'git submodule'), bug #551100 + if [[ -d ${out_dir}/${path} ]]; then + local subrepos + _git-r3_set_subrepos "${url}" "${repos[@]}" + + _GIT_SUBMODULE_PATH=${_GIT_SUBMODULE_PATH}${path}/ \ + git-r3_checkout "${subrepos[*]}" "${out_dir}/${path}" \ + "${local_id}/${subname}" + fi + + submodules=( "${submodules[@]:3}" ) # shift + done + fi + + # keep this *after* submodules + export EGIT_DIR=${GIT_DIR} + export EGIT_VERSION=${new_commit_id} +} + +# @FUNCTION: git-r3_peek_remote_ref +# @USAGE: [<repo-uri> [<remote-ref>]] +# @DESCRIPTION: +# Peek the reference in the remote repository and print the matching +# (newest) commit SHA1. +# +# <repo-uri> specifies the repository URIs to fetch from, as a space- +# -separated list. When not specified, defaults to ${EGIT_REPO_URI}. +# +# <remote-ref> specifies the remote ref to peek. It is preferred to use +# 'refs/heads/<branch-name>' for branches and 'refs/tags/<tag-name>' +# for tags. Alternatively, 'HEAD' may be used for upstream default +# branch. Defaults to the first of EGIT_COMMIT, EGIT_BRANCH or literal +# 'HEAD' that is set to a non-null value. +# +# The operation will be done purely on the remote, without using local +# storage. If commit SHA1 is provided as <remote-ref>, the function will +# fail due to limitations of git protocol. +# +# On success, the function returns 0 and writes hexadecimal commit SHA1 +# to stdout. On failure, the function returns 1. +git-r3_peek_remote_ref() { + debug-print-function ${FUNCNAME} "$@" + + local repos + if [[ ${1} ]]; then + repos=( ${1} ) + elif [[ $(declare -p EGIT_REPO_URI) == "declare -a"* ]]; then + repos=( "${EGIT_REPO_URI[@]}" ) + else + repos=( ${EGIT_REPO_URI} ) + fi + + local branch=${EGIT_BRANCH:+refs/heads/${EGIT_BRANCH}} + local remote_ref=${2:-${EGIT_COMMIT:-${branch:-HEAD}}} + + [[ ${repos[@]} ]] || die "No URI provided and EGIT_REPO_URI unset" + + local r success + for r in "${repos[@]}"; do + einfo "Peeking ${remote_ref} on ${r} ..." >&2 + + local lookup_ref + if [[ ${remote_ref} == refs/* || ${remote_ref} == HEAD ]] + then + lookup_ref=${remote_ref} + else + # ls-remote by commit is going to fail anyway, + # so we may as well pass refs/tags/ABCDEF... + lookup_ref=refs/tags/${remote_ref} + fi + + # split on whitespace + local ref=( + $(git ls-remote "${r}" "${lookup_ref}") + ) + + if [[ ${ref[0]} ]]; then + echo "${ref[0]}" + return 0 + fi + done + + return 1 +} + +git-r3_src_fetch() { + debug-print-function ${FUNCNAME} "$@" + + if [[ ! ${EGIT3_STORE_DIR} && ${EGIT_STORE_DIR} ]]; then + ewarn "You have set EGIT_STORE_DIR but not EGIT3_STORE_DIR. Please consider" + ewarn "setting EGIT3_STORE_DIR for git-r3.eclass. It is recommended to use" + ewarn "a different directory than EGIT_STORE_DIR to ease removing old clones" + ewarn "when git-2 eclass becomes deprecated." + fi + + _git-r3_env_setup + git-r3_fetch +} + +git-r3_src_unpack() { + debug-print-function ${FUNCNAME} "$@" + + _git-r3_env_setup + git-r3_src_fetch + git-r3_checkout +} + +# https://bugs.gentoo.org/show_bug.cgi?id=482666 +git-r3_pkg_needrebuild() { + debug-print-function ${FUNCNAME} "$@" + + local new_commit_id=$(git-r3_peek_remote_ref) + [[ ${new_commit_id} && ${EGIT_VERSION} ]] || die "Lookup failed" + + if [[ ${EGIT_VERSION} != ${new_commit_id} ]]; then + einfo "Update from ${EGIT_VERSION} to ${new_commit_id}" + else + einfo "Local and remote at ${EGIT_VERSION}" + fi + + [[ ${EGIT_VERSION} != ${new_commit_id} ]] +} + +# 'export' locally until this gets into EAPI +pkg_needrebuild() { git-r3_pkg_needrebuild; } + +_GIT_R3=1 +fi diff --git a/eclass/gkrellm-plugin.eclass b/eclass/gkrellm-plugin.eclass new file mode 100644 index 0000000..d6eb57a --- /dev/null +++ b/eclass/gkrellm-plugin.eclass @@ -0,0 +1,100 @@ +# Copyright 1999-2018 Gentoo Foundation +# Distributed under the terms of the GNU General Public License v2 + +# @ECLASS: gkrellm-plugin.eclass +# @MAINTAINER: +# maintainer-needed@gentoo.org +# @AUTHOR: +# Original author: Jim Ramsay +# EAPI 6 author: David Seifert +# @SUPPORTED_EAPIS: 6 +# @BLURB: Provides src_install used by (almost) all gkrellm plugins +# @DESCRIPTION: +# - Sets up default dependencies +# - Provides a common src_install method to avoid code duplication +# +# Changelog: +# 03 January 2018: David Seifert <soap@gentoo.org> +# - Port to EAPI 6, remove built_with_use, simplify a lot +# 12 March 2007: Jim Ramsay <lack@gentoo.org> +# - Added server plugin support +# 09 March 2007: Jim Ramsay <lack@gentoo.org> +# - Initial commit +# + +# @ECLASS-VARIABLE: PLUGIN_SO +# @DESCRIPTION: +# The name of the plugin's .so file which will be installed in +# the plugin dir. Defaults to "${PN}$(get_modname)". Has to be a bash array. + +# @ECLASS-VARIABLE: PLUGIN_SERVER_SO +# @DESCRIPTION: +# The name of the plugin's server plugin $(get_modname) portion. +# Unset by default. Has to be a bash array. + +# @ECLASS-VARIABLE: PLUGIN_DOCS +# @DESCRIPTION: +# An optional list of docs to be installed, in addition to the default +# DOCS variable which is respected too. Has to be a bash array. + +case ${EAPI:-0} in + [0-5]) + die "${ECLASS} is banned in EAPI ${EAPI:-0}" + ;; + 6) + ;; + *) + die "Unknown EAPI ${EAPI:-0}" + ;; +esac + +inherit multilib + +EXPORT_FUNCTIONS src_install + +if [[ ! ${_GKRELLM_PLUGIN_R1} ]]; then + +DEPEND="virtual/pkgconfig" + +# @FUNCTION: gkrellm-plugin_src_install +# @DESCRIPTION: +# Install the plugins and call einstalldocs +gkrellm-plugin_src_install() { + exeinto /usr/$(get_libdir)/gkrellm2/plugins + + if ! declare -p PLUGIN_SO >/dev/null 2>&1 ; then + doexe ${PN}$(get_modname) + elif declare -p PLUGIN_SO | grep -q "^declare -a " ; then + doexe "${PLUGIN_SO[@]}" + else + die "PLUGIN_SO has to be a bash array!" + fi + + + if [[ -n ${PLUGIN_SERVER_SO} ]]; then + exeinto /usr/$(get_libdir)/gkrellm2/plugins-gkrellmd + + if declare -p PLUGIN_SERVER_SO | grep -q "^declare -a " ; then + doexe "${PLUGIN_SERVER_SO[@]}" + else + die "PLUGIN_SERVER_SO has to be a bash array!" + fi + fi + + einstalldocs + local d + for d in Changelog* ChangeLog*; do + [[ -s "${d}" ]] && dodoc "${d}" + done + + if [[ -n ${PLUGIN_DOCS} ]]; then + if declare -p PLUGIN_DOCS | grep -q "^declare -a " ; then + dodoc "${PLUGIN_DOCS[@]}" + else + die "PLUGIN_DOCS has to be a bash array!" + fi + fi +} + +_GKRELLM_PLUGIN_R1=1 +fi diff --git a/eclass/gnome.org.eclass b/eclass/gnome.org.eclass new file mode 100644 index 0000000..fd6077e --- /dev/null +++ b/eclass/gnome.org.eclass @@ -0,0 +1,53 @@ +# Copyright 1999-2019 Gentoo Authors +# Distributed under the terms of the GNU General Public License v2 + +# @ECLASS: gnome.org.eclass +# @MAINTAINER: +# gnome@gentoo.org +# @AUTHOR: +# Authors: Spidler <spidler@gentoo.org> with help of carparski. +# eclass variable additions and documentation: Gilles Dartiguelongue <eva@gentoo.org> +# @BLURB: Helper eclass for gnome.org hosted archives +# @DESCRIPTION: +# Provide a default SRC_URI for tarball hosted on gnome.org mirrors. + +# versionator inherit kept for older EAPIs due to ebuilds (potentially) relying on it +[[ ${EAPI} == [0123456] ]] && inherit eapi7-ver versionator + +# @ECLASS-VARIABLE: GNOME_TARBALL_SUFFIX +# @DESCRIPTION: +# Most projects hosted on gnome.org mirrors provide tarballs as tar.bz2 or +# tar.xz. This eclass defaults to bz2 for EAPI 0, 1, 2, 3 and defaults to xz for +# everything else. This is because the gnome mirrors are moving to only have xz +# tarballs for new releases. +if has "${EAPI:-0}" 0 1 2 3; then + : ${GNOME_TARBALL_SUFFIX:="bz2"} +else + : ${GNOME_TARBALL_SUFFIX:="xz"} +fi + +# Even though xz-utils are in @system, they must still be added to DEPEND; see +# https://archives.gentoo.org/gentoo-dev/msg_a0d4833eb314d1be5d5802a3b710e0a4.xml +if [[ ${GNOME_TARBALL_SUFFIX} == "xz" ]]; then + if [[ ${EAPI:-0} != [0123456] ]]; then + BDEPEND="app-arch/xz-utils" + else + DEPEND="app-arch/xz-utils" + fi +fi + +# @ECLASS-VARIABLE: GNOME_ORG_MODULE +# @DESCRIPTION: +# Name of the module as hosted on gnome.org mirrors. +# Leave unset if package name matches module name. +: ${GNOME_ORG_MODULE:=$PN} + +# @ECLASS-VARIABLE: GNOME_ORG_PVP +# @INTERNAL +# @DESCRIPTION: +# Major and minor numbers of the version number. +: ${GNOME_ORG_PVP:=$(ver_cut 1-2)} + +SRC_URI="mirror://gnome/sources/${GNOME_ORG_MODULE}/${GNOME_ORG_PVP}/${GNOME_ORG_MODULE}-${PV}.tar.${GNOME_TARBALL_SUFFIX}" + +S="${WORKDIR}/${GNOME_ORG_MODULE}-${PV}" diff --git a/eclass/gnome2-utils.eclass b/eclass/gnome2-utils.eclass new file mode 100644 index 0000000..8513de0 --- /dev/null +++ b/eclass/gnome2-utils.eclass @@ -0,0 +1,516 @@ +# Copyright 1999-2020 Gentoo Authors +# Distributed under the terms of the GNU General Public License v2 + +# @ECLASS: gnome2-utils.eclass +# @MAINTAINER: +# gnome@gentoo.org +# @SUPPORTED_EAPIS: 5 6 7 +# @BLURB: Auxiliary functions commonly used by Gnome packages. +# @DESCRIPTION: +# This eclass provides a set of auxiliary functions needed by most Gnome +# packages. It may be used by non-Gnome packages as needed for handling various +# Gnome stack related functions such as: +# * GSettings schemas management +# * GConf schemas management +# * scrollkeeper (old Gnome help system) management + +[[ ${EAPI} == 5 ]] && inherit multilib +# eutils.eclass: emktemp +# toolchain-funs.eclass: tc-is-cross-compiler +# xdg-utils.eclass: xdg_environment_reset, xdg_icon_cache_update +inherit eutils toolchain-funcs xdg-utils + +case ${EAPI} in + 5|6|7) ;; + *) die "EAPI=${EAPI} is not supported" ;; +esac + +# @ECLASS-VARIABLE: GCONFTOOL_BIN +# @INTERNAL +# @DESCRIPTION: +# Path to gconftool-2 +: ${GCONFTOOL_BIN:="/usr/bin/gconftool-2"} + +# @ECLASS-VARIABLE: SCROLLKEEPER_DIR +# @INTERNAL +# @DESCRIPTION: +# Directory where scrollkeeper-update should do its work +: ${SCROLLKEEPER_DIR:="/var/lib/scrollkeeper"} + +# @ECLASS-VARIABLE: SCROLLKEEPER_UPDATE_BIN +# @INTERNAL +# @DESCRIPTION: +# Path to scrollkeeper-update +: ${SCROLLKEEPER_UPDATE_BIN:="/usr/bin/scrollkeeper-update"} + +# @ECLASS-VARIABLE: GLIB_COMPILE_SCHEMAS +# @INTERNAL +# @DESCRIPTION: +# Path to glib-compile-schemas +: ${GLIB_COMPILE_SCHEMAS:="/usr/bin/glib-compile-schemas"} + +# @ECLASS-VARIABLE: GNOME2_ECLASS_SCHEMAS +# @INTERNAL +# @DEFAULT_UNSET +# @DESCRIPTION: +# List of GConf schemas provided by the package + +# @ECLASS-VARIABLE: GNOME2_ECLASS_ICONS +# @INTERNAL +# @DEFAULT_UNSET +# @DESCRIPTION: +# List of icons provided by the package + +# @ECLASS-VARIABLE: GNOME2_ECLASS_SCROLLS +# @INTERNAL +# @DEFAULT_UNSET +# @DESCRIPTION: +# List of scrolls (documentation files) provided by the package + +# @ECLASS-VARIABLE: GNOME2_ECLASS_GLIB_SCHEMAS +# @INTERNAL +# @DEFAULT_UNSET +# @DESCRIPTION: +# List of GSettings schemas provided by the package + +# @ECLASS-VARIABLE: GNOME2_ECLASS_GDK_PIXBUF_LOADERS +# @INTERNAL +# @DEFAULT_UNSET +# @DESCRIPTION: +# List of gdk-pixbuf loaders provided by the package + + +# @FUNCTION: gnome2_environment_reset +# @DESCRIPTION: +# Reset various variables inherited from root's evironment to a reasonable +# default for ebuilds to help avoid access violations and test failures. +gnome2_environment_reset() { + xdg_environment_reset + + # Respected by >=glib-2.30.1-r1 + export G_HOME="${T}" + + # GST_REGISTRY is to work around gst utilities trying to read/write /root + export GST_REGISTRY="${T}/registry.xml" + + # Ensure we don't rely on dconf/gconf while building, bug #511946 + export GSETTINGS_BACKEND="memory" + + if has ${EAPI} 6 7; then + # Try to cover the packages honoring this variable, bug #508124 + export GST_INSPECT="$(type -P true)" + + # Stop relying on random DISPLAY variable values, bug #534312 + unset DISPLAY + fi +} + +# @FUNCTION: gnome2_gconf_savelist +# @DESCRIPTION: +# Find the GConf schemas that are about to be installed and save their location +# in the GNOME2_ECLASS_SCHEMAS environment variable. +# This function should be called from pkg_preinst. +gnome2_gconf_savelist() { + pushd "${ED}" > /dev/null || die + export GNOME2_ECLASS_SCHEMAS=$(find 'etc/gconf/schemas/' -name '*.schemas' 2> /dev/null) + popd > /dev/null || die +} + +# @FUNCTION: gnome2_gconf_install +# @DESCRIPTION: +# Applies any schema files installed by the current ebuild to Gconf's database +# using gconftool-2. +# This function should be called from pkg_postinst. +gnome2_gconf_install() { + local updater="${EROOT%/}${GCONFTOOL_BIN}" + + if [[ -z "${GNOME2_ECLASS_SCHEMAS}" ]]; then + debug-print "No GNOME 2 GConf schemas found" + return + fi + + if tc-is-cross-compiler ; then + ewarn "Updating of GNOME 2 GConf schemas skipped due to cross-compilation." + ewarn "You might want to run gconftool-2 manually on the target for" + ewarn "your final image and re-run it when packages installing" + ewarn "GNOME 2 GConf schemas get upgraded or added to the image." + return + fi + + if [[ ! -x "${updater}" ]]; then + debug-print "${updater} is not executable" + return + fi + + # We are ready to install the GCONF Scheme now + unset GCONF_DISABLE_MAKEFILE_SCHEMA_INSTALL + export GCONF_CONFIG_SOURCE="$("${updater}" --get-default-source | sed "s;:/;:${ROOT%/}/;")" + + einfo "Installing GNOME 2 GConf schemas" + + local F + for F in ${GNOME2_ECLASS_SCHEMAS}; do + if [[ -e "${EROOT%/}/${F}" ]]; then + debug-print "Installing schema: ${F}" + "${updater}" --makefile-install-rule "${EROOT%/}/${F}" 1>/dev/null + fi + done + + # have gconf reload the new schemas + pids=$(pgrep -x gconfd-2) + if [[ $? == 0 ]] ; then + ebegin "Reloading GConf schemas" + kill -HUP ${pids} + eend $? + fi +} + +# @FUNCTION: gnome2_gconf_uninstall +# @DESCRIPTION: +# Removes schema files previously installed by the current ebuild from Gconf's +# database. +gnome2_gconf_uninstall() { + local updater="${EROOT%/}${GCONFTOOL_BIN}" + + if [[ -z "${GNOME2_ECLASS_SCHEMAS}" ]]; then + debug-print "No GNOME 2 GConf schemas found" + return + fi + + if tc-is-cross-compiler ; then + ewarn "Removal of GNOME 2 GConf schemas skipped due to cross-compilation." + ewarn "You might want to run gconftool-2 manually on the target for" + ewarn "your final image to uninstall this package's schemas." + return + fi + + if [[ ! -x "${updater}" ]]; then + debug-print "${updater} is not executable" + return + fi + + unset GCONF_DISABLE_MAKEFILE_SCHEMA_INSTALL + export GCONF_CONFIG_SOURCE="$("${updater}" --get-default-source | sed "s;:/;:${ROOT%/}/;")" + + einfo "Uninstalling GNOME 2 GConf schemas" + + local F + for F in ${GNOME2_ECLASS_SCHEMAS}; do + if [[ -e "${EROOT%/}/${F}" ]]; then + debug-print "Uninstalling gconf schema: ${F}" + "${updater}" --makefile-uninstall-rule "${EROOT%/}/${F}" 1>/dev/null + fi + done + + # have gconf reload the new schemas + pids=$(pgrep -x gconfd-2) + if [[ $? == 0 ]] ; then + ebegin "Reloading GConf schemas" + kill -HUP ${pids} + eend $? + fi +} + +# @FUNCTION: gnome2_omf_fix +# @DESCRIPTION: +# Workaround applied to Makefile rules in order to remove redundant +# calls to scrollkeeper-update and sandbox violations. +# This function should be called from src_prepare. +gnome2_omf_fix() { + local omf_makefiles filename + + omf_makefiles="$@" + + if [[ -f ${S}/omf.make ]] ; then + omf_makefiles="${omf_makefiles} ${S}/omf.make" + fi + + if [[ -f ${S}/gnome-doc-utils.make ]] ; then + omf_makefiles="${omf_makefiles} ${S}/gnome-doc-utils.make" + fi + + # testing fixing of all makefiles found + # The sort is important to ensure .am is listed before the respective .in for + # maintainer mode regeneration not kicking in due to .am being newer than .in + for filename in $(find "${S}" -name "Makefile.in" -o -name "Makefile.am" |sort) ; do + omf_makefiles="${omf_makefiles} ${filename}" + done + + ebegin "Fixing OMF Makefiles" + + local retval=0 + local fails=( ) + + for omf in ${omf_makefiles} ; do + sed -i -e 's:scrollkeeper-update:true:' "${omf}" + retval=$? + + if [[ $retval -ne 0 ]] ; then + debug-print "updating of ${omf} failed" + + # Add to the list of failures + fails[$(( ${#fails[@]} + 1 ))]=$omf + + retval=2 + fi + done + + eend $retval + + for f in "${fails[@]}" ; do + eerror "Failed to update OMF Makefile $f" + done +} + +# @FUNCTION: gnome2_scrollkeeper_savelist +# @DESCRIPTION: +# Find the scrolls that are about to be installed and save their location +# in the GNOME2_ECLASS_SCROLLS environment variable. +# This function should be called from pkg_preinst. +gnome2_scrollkeeper_savelist() { + pushd "${ED}" > /dev/null || die + export GNOME2_ECLASS_SCROLLS=$(find 'usr/share/omf' -type f -name "*.omf" 2> /dev/null) + popd > /dev/null || die +} + +# @FUNCTION: gnome2_scrollkeeper_update +# @DESCRIPTION: +# Updates the global scrollkeeper database. +# This function should be called from pkg_postinst and pkg_postrm. +gnome2_scrollkeeper_update() { + local updater="${EROOT%/}${SCROLLKEEPER_UPDATE_BIN}" + + if [[ -z "${GNOME2_ECLASS_SCROLLS}" ]]; then + debug-print "No scroll cache to update" + return + fi + + if tc-is-cross-compiler ; then + ewarn "Updating of scrollkeeper database skipped due to cross-compilation." + ewarn "You might want to run scrollkeeper-update manually on the target" + ewarn "for your final image and re-run it when packages installing" + ewarn "scrollkeeper OMF files get upgraded or added to the image." + return + fi + + if [[ ! -x "${updater}" ]] ; then + debug-print "${updater} is not executable" + return + fi + + ebegin "Updating scrollkeeper database ..." + "${updater}" -q -p "${EROOT%/}${SCROLLKEEPER_DIR}" + eend $? +} + +# @FUNCTION: gnome2_schemas_savelist +# @DESCRIPTION: +# Find if there is any GSettings schema to install and save the list in +# GNOME2_ECLASS_GLIB_SCHEMAS variable. This is only necessary for eclass +# implementations that call gnome2_schemas_update conditionally. +# This function should be called from pkg_preinst. +gnome2_schemas_savelist() { + pushd "${ED}" > /dev/null || die + export GNOME2_ECLASS_GLIB_SCHEMAS=$(find 'usr/share/glib-2.0/schemas' -name '*.gschema.xml' 2>/dev/null) + popd > /dev/null || die +} + +# @FUNCTION: gnome2_schemas_update +# @DESCRIPTION: +# Updates GSettings schemas. +# This function should be called from pkg_postinst and pkg_postrm. +gnome2_schemas_update() { + local updater="${EROOT%/}${GLIB_COMPILE_SCHEMAS}" + + if tc-is-cross-compiler ; then + ewarn "Updating of GSettings schemas skipped due to cross-compilation." + ewarn "You might want to run glib-compile-schemas manually on the target" + ewarn "for your final image and re-run it when packages installing" + ewarn "GSettings schemas get upgraded or added to the image." + return + fi + + if [[ ! -x ${updater} ]]; then + debug-print "${updater} is not executable" + return + fi + + ebegin "Updating GSettings schemas" + ${updater} --allow-any-name "$@" "${EROOT%/}/usr/share/glib-2.0/schemas" &>/dev/null + eend $? +} + +# @FUNCTION: gnome2_gdk_pixbuf_savelist +# @DESCRIPTION: +# Find if there is any gdk-pixbuf loader to install and save the list in +# GNOME2_ECLASS_GDK_PIXBUF_LOADERS variable. +# This function should be called from pkg_preinst. +gnome2_gdk_pixbuf_savelist() { + pushd "${ED}" > /dev/null || die + export GNOME2_ECLASS_GDK_PIXBUF_LOADERS=$(find usr/lib*/gdk-pixbuf-2.0 -type f 2>/dev/null) + popd > /dev/null || die +} + +# @FUNCTION: gnome2_gdk_pixbuf_update +# @DESCRIPTION: +# Updates gdk-pixbuf loader cache if GNOME2_ECLASS_GDK_PIXBUF_LOADERS has some. +# This function should be called from pkg_postinst and pkg_postrm. +gnome2_gdk_pixbuf_update() { + local updater="${EROOT%/}/usr/bin/${CHOST}-gdk-pixbuf-query-loaders" + [[ -x ${updater} ]] || updater="${EROOT%/}/usr/bin/gdk-pixbuf-query-loaders" + + if [[ -z ${GNOME2_ECLASS_GDK_PIXBUF_LOADERS} ]]; then + debug-print "gdk-pixbuf loader cache does not need an update" + return + fi + + if tc-is-cross-compiler ; then + ewarn "Updating of gdk-pixbuf loader cache skipped due to cross-compilation." + ewarn "You might want to run gdk-pixbuf-query-loaders manually on the target" + ewarn "for your final image and re-run it when packages installing" + ewarn "gdk-pixbuf loaders get upgraded or added to the image." + return + fi + + if [[ ! -x ${updater} ]]; then + debug-print "${updater} is not executable" + return + fi + + ebegin "Updating gdk-pixbuf loader cache" + local tmp_file=$(emktemp) + ${updater} 1> "${tmp_file}" && + chmod 0644 "${tmp_file}" && + cp -f "${tmp_file}" "${EROOT%/}/usr/$(get_libdir)/gdk-pixbuf-2.0/2.10.0/loaders.cache" && + rm "${tmp_file}" # don't replace this with mv, required for SELinux support + eend $? +} + +# @FUNCTION: gnome2_query_immodules_gtk2 +# @DESCRIPTION: +# Updates gtk2 immodules/gdk-pixbuf loaders listing. +gnome2_query_immodules_gtk2() { + local updater=${EPREFIX}/usr/bin/${CHOST}-gtk-query-immodules-2.0 + [[ -x ${updater} ]] || updater=${EPREFIX}/usr/bin/gtk-query-immodules-2.0 + + if [[ ! -x ${updater} ]]; then + debug-print "${updater} is not executable" + return + fi + + ebegin "Updating gtk2 input method module cache" + GTK_IM_MODULE_FILE="${EROOT%/}/usr/$(get_libdir)/gtk-2.0/2.10.0/immodules.cache" \ + "${updater}" --update-cache + eend $? +} + +# @FUNCTION: gnome2_query_immodules_gtk3 +# @DESCRIPTION: +# Updates gtk3 immodules/gdk-pixbuf loaders listing. +gnome2_query_immodules_gtk3() { + local updater=${EPREFIX}/usr/bin/${CHOST}-gtk-query-immodules-3.0 + [[ -x ${updater} ]] || updater=${EPREFIX}/usr/bin/gtk-query-immodules-3.0 + + if [[ ! -x ${updater} ]]; then + debug-print "${updater} is not executable" + return + fi + + ebegin "Updating gtk3 input method module cache" + GTK_IM_MODULE_FILE="${EROOT%/}/usr/$(get_libdir)/gtk-3.0/3.0.0/immodules.cache" \ + "${updater}" --update-cache + eend $? +} + +# @FUNCTION: gnome2_giomodule_cache_update +# @DESCRIPTION: +# Updates glib's gio modules cache. +# This function should be called from pkg_postinst and pkg_postrm. +gnome2_giomodule_cache_update() { + local updater="${EROOT%/}/usr/bin/${CHOST}-gio-querymodules" + [[ -x ${updater} ]] || updater="${EROOT%/}/usr/bin/gio-querymodules" + + if tc-is-cross-compiler ; then + ewarn "Updating of GIO modules cache skipped due to cross-compilation." + ewarn "You might want to run gio-querymodules manually on the target for" + ewarn "your final image for performance reasons and re-run it when packages" + ewarn "installing GIO modules get upgraded or added to the image." + return + fi + + if [[ ! -x ${updater} ]]; then + debug-print "${updater} is not executable" + return + fi + + ebegin "Updating GIO modules cache" + ${updater} "${EROOT%/}"/usr/$(get_libdir)/gio/modules + eend $? +} + +# @FUNCTION: gnome2_disable_deprecation_warning +# @DESCRIPTION: +# Disable deprecation warnings commonly found in glib based packages. +# Should be called from src_prepare. +gnome2_disable_deprecation_warning() { + local retval=0 + local fails=( ) + local makefile + + ebegin "Disabling deprecation warnings" + # The sort is important to ensure .am is listed before the respective .in for + # maintainer mode regeneration not kicking in due to .am being newer than .in + while read makefile ; do + if ! grep -qE "(DISABLE_DEPRECATED|GSEAL_ENABLE)" "${makefile}"; then + continue + fi + + LC_ALL=C sed -r -i \ + -e 's:-D[A-Z_]+_DISABLE_DEPRECATED:$(/bin/true):g' \ + -e 's:-DGSEAL_ENABLE(=[A-Za-z0-9_]*)?:$(/bin/true):g' \ + -i "${makefile}" + + if [[ $? -ne 0 ]]; then + # Add to the list of failures + fails+=( "${makefile}" ) + retval=2 + fi + done < <(find "${S}" -name "Makefile.in" \ + -o -name "Makefile.am" -o -name "Makefile.decl" \ + | sort; [[ -f "${S}"/configure ]] && echo configure) +# TODO: sedding configure.ac can trigger maintainer mode; bug #439602 +# -o -name "configure.ac" -o -name "configure.in" \ +# | sort; echo configure) + eend ${retval} + + for makefile in "${fails[@]}" ; do + ewarn "Failed to disable deprecation warnings in ${makefile}" + done +} + +case ${EAPI} in +5|6) + +# @FUNCTION: gnome2_icon_savelist +# @DESCRIPTION: +# Find the icons that are about to be installed and save their location +# in the GNOME2_ECLASS_ICONS environment variable. This is only +# necessary for eclass implementations that call +# gnome2_icon_cache_update conditionally. +# This function should be called from pkg_preinst. +gnome2_icon_savelist() { + pushd "${ED}" > /dev/null || die + export GNOME2_ECLASS_ICONS=$(find 'usr/share/icons' -maxdepth 1 -mindepth 1 -type d 2> /dev/null) + popd > /dev/null || die +} + +# @FUNCTION: gnome2_icon_cache_update +# @DESCRIPTION: +# Updates Gtk+ icon cache files under /usr/share/icons. +# Deprecated. Please use xdg_icon_cache_update from xdg-utils.eclass +gnome2_icon_cache_update() { + xdg_icon_cache_update +} + +;; +esac diff --git a/eclass/gnome2.eclass b/eclass/gnome2.eclass new file mode 100644 index 0000000..27ea9f9 --- /dev/null +++ b/eclass/gnome2.eclass @@ -0,0 +1,337 @@ +# Copyright 1999-2020 Gentoo Authors +# Distributed under the terms of the GNU General Public License v2 + +# @ECLASS: gnome2.eclass +# @MAINTAINER: +# gnome@gentoo.org +# @SUPPORTED_EAPIS: 5 6 7 +# @BLURB: Provides phases for Gnome/Gtk+ based packages. +# @DESCRIPTION: +# Exports portage base functions used by ebuilds written for packages using the +# GNOME framework. For additional functions, see gnome2-utils.eclass. + +# @ECLASS-VARIABLE: GNOME2_EAUTORECONF +# @DEFAULT_UNSET +# @DESCRIPTION: +# Run eautoreconf instead of only elibtoolize +GNOME2_EAUTORECONF=${GNOME2_EAUTORECONF:-""} + +[[ ${GNOME2_EAUTORECONF} == 'yes' ]] && inherit autotools +[[ ${EAPI} == [56] ]] && inherit eutils ltprune +inherit libtool gnome.org gnome2-utils xdg + +case ${EAPI:-0} in + 5) + EXPORT_FUNCTIONS src_unpack src_prepare src_configure src_compile src_install pkg_preinst pkg_postinst pkg_postrm + ;; + 6|7) + EXPORT_FUNCTIONS src_prepare src_configure src_compile src_install pkg_preinst pkg_postinst pkg_postrm + ;; + *) die "EAPI=${EAPI} is not supported" ;; +esac + +# @ECLASS-VARIABLE: ELTCONF +# @DEFAULT_UNSET +# @DESCRIPTION: +# Extra options passed to elibtoolize +ELTCONF=${ELTCONF:-""} + +# @ECLASS-VARIABLE: G2CONF +# @DEFAULT_UNSET +# @DESCRIPTION: +# Extra configure opts passed to econf. +# Deprecated, pass extra arguments to gnome2_src_configure. +# Banned in eapi6 and newer. +if has ${EAPI} 5; then + G2CONF=${G2CONF:-""} +fi + +# @ECLASS-VARIABLE: GCONF_DEBUG +# @DEFAULT_UNSET +# @DESCRIPTION: +# Whether to handle debug or not. +# Some gnome applications support various levels of debugging (yes, no, minimum, +# etc), but using --disable-debug also removes g_assert which makes debugging +# harder. This variable should be set to yes for such packages for the eclass +# to handle it properly. It will enable minimal debug with USE=-debug. +# Note that this is most commonly found in configure.ac as GNOME_DEBUG_CHECK. +# +# Banned since eapi6 as upstream is moving away from this obsolete macro in favor +# of autoconf-archive macros, that do not expose this issue (bug #270919) +if has ${EAPI} 5; then + if [[ ${GCONF_DEBUG} != "no" ]]; then + IUSE="debug" + fi +fi + +# @ECLASS-VARIABLE: GNOME2_ECLASS_GIO_MODULES +# @INTERNAL +# @DESCRIPTION: +# Array containing glib GIO modules + +# @ECLASS-VARIABLE: GNOME2_LA_PUNT +# @DESCRIPTION: +# In EAPIs 5 and 6, it relies on prune_libtool_files (from ltprune.eclass) for +# this. Later EAPIs use find ... -delete. Available values for GNOME2_LA_PUNT: +# - "no": will not clean any .la files +# - "yes": will run prune_libtool_files --modules +# - If it is not set, it will run prune_libtool_files +GNOME2_LA_PUNT=${GNOME2_LA_PUNT:-""} + +# @FUNCTION: gnome2_src_unpack +# @DESCRIPTION: +# Stub function for old EAPI. +gnome2_src_unpack() { + if has ${EAPI} 5; then + unpack ${A} + cd "${S}" + else + die "gnome2_src_unpack is banned since eapi6" + fi +} + +# @FUNCTION: gnome2_src_prepare +# @DESCRIPTION: +# Prepare environment for build, fix build of scrollkeeper documentation, +# run elibtoolize. +gnome2_src_prepare() { + xdg_src_prepare + + # Prevent assorted access violations and test failures + gnome2_environment_reset + + # Prevent scrollkeeper access violations + # We stop to run it from eapi6 as scrollkeeper helpers from + # rarian are not running anything and, then, access violations + # shouldn't occur. + has ${EAPI} 5 && gnome2_omf_fix + + # Disable all deprecation warnings + gnome2_disable_deprecation_warning + + # Run libtoolize or eautoreconf, bug #591584 + # https://bugzilla.gnome.org/show_bug.cgi?id=655517 + if [[ ${GNOME2_EAUTORECONF} == 'yes' ]]; then + eautoreconf + else + elibtoolize ${ELTCONF} + fi +} + +# @FUNCTION: gnome2_src_configure +# @DESCRIPTION: +# Gnome specific configure handling +gnome2_src_configure() { + # Deprecated for a long time now and banned since eapi6, see Gnome team policies + if [[ -n ${G2CONF} ]] ; then + if has ${EAPI} 5; then + eqawarn "G2CONF set, please review documentation at https://wiki.gentoo.org/wiki/Project:GNOME/Gnome_Team_Ebuild_Policies#G2CONF_and_src_configure" + else + die "G2CONF set, please review documentation at https://wiki.gentoo.org/wiki/Project:GNOME/Gnome_Team_Ebuild_Policies#G2CONF_and_src_configure" + fi + fi + + local g2conf=() + + if has ${EAPI} 5; then + if [[ ${GCONF_DEBUG} != 'no' ]] ; then + if use debug ; then + g2conf+=( --enable-debug=yes ) + fi + fi + else + if [[ -n ${GCONF_DEBUG} ]] ; then + die "GCONF_DEBUG is banned since eapi6 in favor of each ebuild taking care of the proper handling of debug configure option" + fi + fi + + # We consider packages installing gtk-doc to be handled by adding + # DEPEND="dev-util/gtk-doc-am" which provides tools to relink URLs in + # documentation to already installed documentation. This decision also + # greatly helps with constantly broken doc generation. + # Remember to drop 'doc' USE flag from your package if it was only used to + # rebuild docs. + if grep -q "enable-gtk-doc" "${ECONF_SOURCE:-.}"/configure ; then + g2conf+=( --disable-gtk-doc ) + fi + + # Pass --disable-maintainer-mode when needed + if grep -q "^[[:space:]]*AM_MAINTAINER_MODE(\[enable\])" \ + "${ECONF_SOURCE:-.}"/configure.*; then + g2conf+=( --disable-maintainer-mode ) + fi + + # Pass --disable-scrollkeeper when possible + if grep -q "disable-scrollkeeper" "${ECONF_SOURCE:-.}"/configure; then + g2conf+=( --disable-scrollkeeper ) + fi + + # Pass --disable-schemas-install when possible + if grep -q "disable-schemas-install" "${ECONF_SOURCE:-.}"/configure; then + g2conf+=( --disable-schemas-install ) + fi + + # Pass --disable-schemas-compile when possible + if grep -q "disable-schemas-compile" "${ECONF_SOURCE:-.}"/configure; then + g2conf+=( --disable-schemas-compile ) + fi + + # Pass --disable-update-mimedb when possible + if grep -q "disable-update-mimedb" "${ECONF_SOURCE:-.}"/configure; then + g2conf+=( --disable-update-mimedb ) + fi + + # Pass --enable-compile-warnings=minimum as we don't want -Werror* flags, bug #471336 + if grep -q "enable-compile-warnings" "${ECONF_SOURCE:-.}"/configure; then + g2conf+=( --enable-compile-warnings=minimum ) + fi + + # Pass --docdir with proper directory, bug #482646 (not needed since eapi6) + if has ${EAPI} 5; then + if grep -q "^ *--docdir=" "${ECONF_SOURCE:-.}"/configure; then + g2conf+=( --docdir="${EPREFIX}"/usr/share/doc/${PF} ) + fi + fi + + # Avoid sandbox violations caused by gnome-vfs (bug #128289 and #345659) + if has ${EAPI} 5; then + addwrite "$(unset HOME; echo ~)/.gnome2" + else + addpredict "$(unset HOME; echo ~)/.gnome2" + fi + + if has ${EAPI} 5; then + econf ${g2conf[@]} ${G2CONF} "$@" + else + econf ${g2conf[@]} "$@" + fi +} + +# @FUNCTION: gnome2_src_compile +# @DESCRIPTION: +# Only default src_compile for now +gnome2_src_compile() { + if has ${EAPI} 5; then + emake + else + default + fi +} + +# @FUNCTION: gnome2_src_install +# @DESCRIPTION: +# Gnome specific install. Handles typical GConf and scrollkeeper setup +# in packages and removal of .la files if requested +gnome2_src_install() { + # we must delay gconf schema installation due to sandbox + export GCONF_DISABLE_MAKEFILE_SCHEMA_INSTALL="1" + + local sk_tmp_dir="/var/lib/scrollkeeper" + # scrollkeeper-update from rarian doesn't do anything. Then, since eapi6 + # we stop taking care of it + # + # if this is not present, scrollkeeper-update may segfault and + # create bogus directories in /var/lib/ + if has ${EAPI} 5; then + dodir "${sk_tmp_dir}" || die "dodir failed" + emake DESTDIR="${D}" "scrollkeeper_localstate_dir=${ED}${sk_tmp_dir} " "$@" install || die "install failed" + else + default + fi + + unset GCONF_DISABLE_MAKEFILE_SCHEMA_INSTALL + + # Handle documentation as 'default' for eapi5, bug #373131 + # Since eapi6 this is handled by default on its own plus MAINTAINERS and HACKING + # files that are really common in gnome packages (bug #573390) + if has ${EAPI} 5; then + einstalldocs + else + local d + for d in HACKING MAINTAINERS; do + [[ -s "${d}" ]] && dodoc "${d}" + done + fi + + # Do not keep /var/lib/scrollkeeper because: + # 1. The scrollkeeper database is regenerated at pkg_postinst() + # 2. ${ED}/var/lib/scrollkeeper contains only indexes for the current pkg + # thus it makes no sense if pkg_postinst ISN'T run for some reason. + rm -rf "${ED}${sk_tmp_dir}" + rmdir "${ED}/var/lib" 2>/dev/null + rmdir "${ED}/var" 2>/dev/null + + # Make sure this one doesn't get in the portage db + rm -fr "${ED}/usr/share/applications/mimeinfo.cache" + + # Delete all .la files + if has ${EAPI} 5 6; then + case "${GNOME2_LA_PUNT}" in + yes) prune_libtool_files --modules;; + no) ;; + *) prune_libtool_files;; + esac + else + if [[ ${GNOME2_LA_PUNT} != 'no' ]]; then + find "${ED}" -name '*.la' -delete || die + fi + fi +} + +# @FUNCTION: gnome2_pkg_preinst +# @DESCRIPTION: +# Finds Icons, GConf and GSettings schemas for later handling in pkg_postinst +gnome2_pkg_preinst() { + xdg_pkg_preinst + gnome2_gconf_savelist + gnome2_schemas_savelist + gnome2_scrollkeeper_savelist + gnome2_gdk_pixbuf_savelist + + local f + + GNOME2_ECLASS_GIO_MODULES=() + while IFS= read -r -d '' f; do + GNOME2_ECLASS_GIO_MODULES+=( ${f} ) + done < <(cd "${D}" && find usr/$(get_libdir)/gio/modules -type f -print0 2>/dev/null) + + export GNOME2_ECLASS_GIO_MODULES +} + +# @FUNCTION: gnome2_pkg_postinst +# @DESCRIPTION: +# Handle scrollkeeper, GConf, GSettings, Icons, desktop and mime +# database updates. +gnome2_pkg_postinst() { + xdg_pkg_postinst + gnome2_gconf_install + if [[ -n ${GNOME2_ECLASS_GLIB_SCHEMAS} ]]; then + gnome2_schemas_update + fi + gnome2_scrollkeeper_update + gnome2_gdk_pixbuf_update + + if [[ ${#GNOME2_ECLASS_GIO_MODULES[@]} -gt 0 ]]; then + gnome2_giomodule_cache_update + fi +} + +# # FIXME Handle GConf schemas removal +#gnome2_pkg_prerm() { +# gnome2_gconf_uninstall +#} + +# @FUNCTION: gnome2_pkg_postrm +# @DESCRIPTION: +# Handle scrollkeeper, GSettings, Icons, desktop and mime database updates. +gnome2_pkg_postrm() { + xdg_pkg_postrm + if [[ -n ${GNOME2_ECLASS_GLIB_SCHEMAS} ]]; then + gnome2_schemas_update + fi + gnome2_scrollkeeper_update + + if [[ ${#GNOME2_ECLASS_GIO_MODULES[@]} -gt 0 ]]; then + gnome2_giomodule_cache_update + fi +} diff --git a/eclass/gnuconfig.eclass b/eclass/gnuconfig.eclass new file mode 100644 index 0000000..3433837 --- /dev/null +++ b/eclass/gnuconfig.eclass @@ -0,0 +1,90 @@ +# Copyright 1999-2020 Gentoo Authors +# Distributed under the terms of the GNU General Public License v2 +# +# Author: Will Woods <wwoods@gentoo.org> +# +# This eclass is used to automatically update files that typically come with +# automake to the newest version available on the system. The most common use +# of this is to update config.guess and config.sub when configure dies from +# misguessing your canonical system name (CHOST). It can also be used to update +# other files that come with automake, e.g. depcomp, mkinstalldirs, etc. +# +# usage: gnuconfig_update [file1 file2 ...] +# if called without arguments, config.guess and config.sub will be updated. +# All files in the source tree ($S) with the given name(s) will be replaced +# with the newest available versions chosen from the list of locations in +# gnuconfig_findnewest(), below. +# +# gnuconfig_update should generally be called from src_unpack() + + +DEPEND="sys-devel/gnuconfig" + +# Wrapper function for gnuconfig_do_update. If no arguments are given, update +# config.sub and config.guess (old default behavior), otherwise update the +# named files. +gnuconfig_update() { + local startdir # declared here ... used in gnuconfig_do_update + + if [[ $1 == /* ]] ; then + startdir=$1 + shift + else + startdir=${S} + fi + + if [[ $# -gt 0 ]] ; then + gnuconfig_do_update "$@" + else + gnuconfig_do_update config.sub config.guess + fi + + return $? +} + +# Copy the newest available version of specified files over any old ones in the +# source dir. This function shouldn't be called directly - use gnuconfig_update +# +# Note that since bash using dynamic scoping, startdir is available here from +# the gnuconfig_update function +gnuconfig_do_update() { + local configsubs_dir target targetlist file + + [[ $# -eq 0 ]] && die "do not call gnuconfig_do_update; use gnuconfig_update" + + configsubs_dir=$(gnuconfig_findnewest) + einfo "Using GNU config files from ${configsubs_dir}" + for file in "$@" ; do + if [[ ! -r ${configsubs_dir}/${file} ]] ; then + eerror "Can't read ${configsubs_dir}/${file}, skipping.." + continue + fi + targetlist=$(find "${startdir}" -name "${file}") + if [[ -n ${targetlist} ]] ; then + for target in ${targetlist} ; do + [[ -L ${target} ]] && rm -f "${target}" + einfo " Updating ${target/$startdir\//}" + cp -f "${configsubs_dir}/${file}" "${target}" + eend $? + done + else + ewarn " No ${file} found in ${startdir}, skipping ..." + fi + done + + return 0 +} + +# this searches the standard locations for the newest config.{sub|guess}, and +# returns the directory where they can be found. +gnuconfig_findnewest() { + local locations=( + "${EPREFIX}"/usr/share/misc/config.sub + "${EPREFIX}"/usr/share/gnuconfig/config.sub + "${EPREFIX}"/usr/share/automake*/config.sub + "${EPREFIX}"/usr/share/libtool/config.sub + ) + grep -s '^timestamp' "${locations[@]}" | \ + sort -r -n -t\' -k2 | \ + sed -n '1{s,/config.sub:.*$,,;p;q}' +} diff --git a/eclass/gnustep-2.eclass b/eclass/gnustep-2.eclass new file mode 100644 index 0000000..d1acdc1 --- /dev/null +++ b/eclass/gnustep-2.eclass @@ -0,0 +1,26 @@ +# Copyright 1999-2019 Gentoo Authors +# Distributed under the terms of the GNU General Public License v2 + +# @ECLASS: gnustep-2.eclass +# @MAINTAINER: +# GNUstep Herd <gnustep@gentoo.org> +# @SUPPORTED_EAPIS: 0 1 2 3 4 5 6 7 +# @BLURB: eclass for GNUstep Apps, Frameworks, and Bundles build +# @DESCRIPTION: +# This eclass sets up GNUstep environment to properly install +# GNUstep packages + +inherit gnustep-base + +DEPEND=">=gnustep-base/gnustep-make-2.0 + virtual/gnustep-back" +RDEPEND="${DEPEND}" + +# The following gnustep-based EXPORT_FUNCTIONS are available: +# * gnustep-base_pkg_setup +# * gnustep-base_src_unpack (EAPI 0|1 only) +# * gnustep-base_src_prepare (EAPI>=2 only) +# * gnustep-base_src_configure (EAPI>=2 only) +# * gnustep-base_src_compile +# * gnustep-base_src_install +# * gnustep-base_pkg_postinst diff --git a/eclass/gnustep-base.eclass b/eclass/gnustep-base.eclass new file mode 100644 index 0000000..6cd9f53 --- /dev/null +++ b/eclass/gnustep-base.eclass @@ -0,0 +1,269 @@ +# Copyright 1999-2018 Gentoo Foundation +# Distributed under the terms of the GNU General Public License v2 + +# @ECLASS: gnustep-base.eclass +# @MAINTAINER: +# GNUstep Herd <gnustep@gentoo.org> +# @SUPPORTED_EAPIS: 0 1 2 3 4 5 6 7 +# @BLURB: Internal handling of GNUstep pacakges +# @DESCRIPTION: +# Inner gnustep eclass, should only be inherited directly by gnustep-base +# packages + +inherit eutils flag-o-matic + +# IUSE variables across all GNUstep packages +# "debug": enable code for debugging +# "doc": build and install documentation, if available +IUSE="debug doc" + +# packages needed to build any base gnustep package +GNUSTEP_CORE_DEPEND="doc? ( virtual/texi2dvi dev-tex/latex2html app-text/texi2html )" + +# New layout is used when ${EPREFIX}/usr/share/GNUstep/Makefiles exists +# Where to install GNUstep (with old layout) +GNUSTEP_PREFIX="${EPREFIX}/usr/GNUstep" + +# GNUstep environment array +typeset -a GS_ENV + +# Ebuild function overrides +gnustep-base_pkg_setup() { + if test_version_info 3.3 ; then + strip-unsupported-flags + elif test_version_info 3.4 ; then + # strict-aliasing is known to break obj-c stuff in gcc-3.4* + filter-flags -fstrict-aliasing + fi + + # known to break ObjC (bug 86089) + filter-flags -fomit-frame-pointer +} + +gnustep-base_src_unpack() { + unpack ${A} + cd "${S}" + + gnustep-base_src_prepare +} + +gnustep-base_src_prepare() { + if [[ -f ./GNUmakefile ]] ; then + # Kill stupid includes that are simply overdone or useless on normal + # Gentoo, but (may) cause major headaches on Prefixed Gentoo. If this + # only removes a part of a path it's good that it bails out, as we want + # to know when they use some direct include. + ebegin "Cleaning paths from GNUmakefile" + sed -i \ + -e 's|-I/usr/X11R6/include/\?||g' \ + -e 's|-I/usr/include/\?||g' \ + -e 's|-L/usr/X11R6/lib/\?||g' \ + -e 's|-L/usr/lib/\?||g' \ + GNUmakefile + eend $? + fi + + ! has ${EAPI:-0} 0 1 2 3 4 5 && default +} + +gnustep-base_src_configure() { + egnustep_env + if [[ -x ./configure ]] ; then + econf || die "configure failed" + fi +} + +gnustep-base_src_compile() { + egnustep_env + case ${EAPI:-0} in + 0|1) gnustep-base_src_configure ;; + esac + + egnustep_make +} + +gnustep-base_src_install() { + egnustep_env + egnustep_install + if use doc ; then + egnustep_env + egnustep_doc + fi + egnustep_install_config +} + +gnustep-base_pkg_postinst() { + [[ $(type -t gnustep_config_script) != "function" ]] && return 0 + + local SCRIPT_PATH + if [[ -d ${EPREFIX}/usr/share/GNUstep/Makefiles ]]; then + SCRIPT_PATH="/usr/bin" + else + SCRIPT_PATH=${GNUSTEP_SYSTEM_TOOLS}/Gentoo + fi + elog "To use this package, as *user* you should run:" + elog " ${SCRIPT_PATH}/config-${PN}.sh" +} + +# Clean/reset an ebuild to the installed GNUstep environment +egnustep_env() { + # Get additional variables + GNUSTEP_SH_EXPORT_ALL_VARIABLES="true" + + # Makefiles path + local GS_MAKEFILES + if [[ -d ${EPREFIX}/usr/share/GNUstep/Makefiles ]]; then + GS_MAKEFILES=${EPREFIX}/usr/share/GNUstep/Makefiles + else + GS_MAKEFILES=${GNUSTEP_PREFIX}/System/Library/Makefiles + fi + if [[ -f ${GS_MAKEFILES}/GNUstep.sh ]] ; then + # Reset GNUstep variables + source "${GS_MAKEFILES}"/GNUstep-reset.sh + source "${GS_MAKEFILES}"/GNUstep.sh + + # Create compilation GNUstep.conf if it does not exist yet + if [[ ! -f ${WORKDIR}/GNUstep.conf ]]; then + cp "${EPREFIX}"/etc/GNUstep/GNUstep.conf "${WORKDIR}" \ + || die "GNUstep.conf copy failed" + sed -e "s#\(GNUSTEP_USER_.*DIR.*=\)#\1${WORKDIR}/#" \ + -i "${WORKDIR}"/GNUstep.conf || die "GNUstep.conf sed failed" + fi + + + if [[ ! -d ${EPREFIX}/usr/share/GNUstep/Makefiles ]]; then + # Set rpath in ldflags when available + case ${CHOST} in + *-linux-gnu|*-solaris*) + is-ldflagq -Wl,-rpath="${GNUSTEP_SYSTEM_LIBRARIES}" \ + || append-ldflags \ + -Wl,-rpath="${GNUSTEP_SYSTEM_LIBRARIES}" + ;; + esac + fi + + # Set up env vars for make operations + GS_ENV=( AUXILIARY_LDFLAGS="${LDFLAGS}" \ + ADDITIONAL_NATIVE_LIB_DIRS="${GNUSTEP_SYSTEM_LIBRARIES}" \ + DESTDIR="${D}" \ + HOME="${T}" \ + GNUSTEP_CONFIG_FILE="${WORKDIR}"/GNUstep.conf \ + GNUSTEP_INSTALLATION_DOMAIN=SYSTEM \ + TAR_OPTIONS="${TAR_OPTIONS} --no-same-owner" \ + messages=yes ) + + use doc \ + && GS_ENV=( "${GS_ENV[@]}" VARTEXFONTS="${T}"/fonts ) + + use debug \ + && GS_ENV=( "${GS_ENV[@]}" "debug=yes" ) \ + || GS_ENV=( "${GS_ENV[@]}" "debug=no" ) + + if has_version "gnustep-base/gnustep-make[libobjc2]"; + then + # Set clang for packages that do not respect gnustep-make + # settings (gnustep-base's configure for example) + export CC=clang CXX=clang CPP="clang -E" LD="clang" + fi + + return 0 + fi + die "gnustep-make not installed!" +} + +# Make utilizing GNUstep Makefiles +egnustep_make() { + if [[ -f ./Makefile || -f ./makefile || -f ./GNUmakefile ]] ; then + emake ${*} "${GS_ENV[@]}" all || die "package make failed" + return 0 + fi + die "no Makefile found" +} + +# Make-install utilizing GNUstep Makefiles +egnustep_install() { + if [[ ! -d ${EPREFIX}/usr/share/GNUstep/Makefiles ]]; then + # avoid problems due to our "weird" prefix, make sure it exists + mkdir -p "${D}"${GNUSTEP_SYSTEM_TOOLS} + fi + if [[ -f ./[mM]akefile || -f ./GNUmakefile ]] ; then + emake ${*} "${GS_ENV[@]}" install || die "package install failed" + return 0 + fi + die "no Makefile found" +} + +# Make and install docs using GNUstep Makefiles +egnustep_doc() { + if [[ -d "${S}"/Documentation ]] ; then + # Check documentation presence + pushd "${S}"/Documentation || die + if [[ -f ./[mM]akefile || -f ./GNUmakefile ]] ; then + emake "${GS_ENV[@]}" all || die "doc make failed" + emake "${GS_ENV[@]}" install || die "doc install failed" + fi + popd || die + fi +} + +egnustep_install_config() { + [[ $(type -t gnustep_config_script) != "function" ]] && return 0 + + local cfile=config-${PN}.sh + + cat << 'EOF' > "${T}"/${cfile} +#!/usr/bin/env bash +gnustep_append_default() { + if [[ -z $1 || -z $2 || -z $3 ]]; then + echo "warning: invalid script invocation" + return + fi + dom=$1 + key=$2 + val=$3 + cur=$(defaults read ${dom} ${key}) 2> /dev/null + if [[ -z $cur ]] ; then + echo " * setting ${dom} ${key}" + defaults write ${dom} ${key} "( ${val} )" + elif [[ ${cur} != *${val}* ]] ; then + echo " * adding ${val} to ${dom} ${key}" + echo "${cur%)\'}, \"${val}\" )'" | defaults write + else + echo " * ${val} already present in ${dom} ${key}" + fi +} + +gnustep_set_default() { + if [[ -z $1 || -z $2 || -z $3 ]]; then + echo "warning: invalid script invocation" + return + fi + dom=$1 + key=$2 + val=$3 + echo " * setting ${dom} ${key}" + defaults write ${dom} ${key} ${val} +} + +EOF + + echo "echo \"Applying ${P} default configuration ...\"" >> "${T}"/${cfile} + + gnustep_config_script | \ + while read line ; do + echo "${line}" >> "${T}"/${cfile} + done + echo 'echo "done"' >> "${T}"/${cfile} + + if [[ -d ${EPREFIX}/usr/share/GNUstep/Makefiles ]]; then + exeinto /usr/bin + else + exeinto ${GNUSTEP_SYSTEM_TOOLS#${EPREFIX}}/Gentoo + fi + doexe "${T}"/${cfile} +} + +case ${EAPI:-0} in + 0|1) EXPORT_FUNCTIONS pkg_setup src_unpack src_compile src_install pkg_postinst ;; + *) EXPORT_FUNCTIONS pkg_setup src_prepare src_configure src_compile src_install pkg_postinst ;; +esac diff --git a/eclass/go-module.eclass b/eclass/go-module.eclass new file mode 100644 index 0000000..c9a7ab1 --- /dev/null +++ b/eclass/go-module.eclass @@ -0,0 +1,418 @@ +# Copyright 2019-2020 Gentoo Authors +# Distributed under the terms of the GNU General Public License v2 + +# @ECLASS: go-module.eclass +# @MAINTAINER: +# William Hubbs <williamh@gentoo.org> +# @AUTHOR: +# William Hubbs <williamh@gentoo.org> +# Robin H. Johnson <robbat2@gentoo.org> +# @SUPPORTED_EAPIS: 7 +# @BLURB: basic eclass for building software written as go modules +# @DESCRIPTION: +# This eclass provides basic settings and functions needed by all software +# written in the go programming language that uses modules. +# +# If the software you are packaging has a file named go.mod in its top +# level directory, it uses modules and your ebuild should inherit this +# eclass. If it does not, your ebuild should use the golang-* eclasses. +# +# If, besides go.mod, your software has a directory named vendor in its +# top level directory, the only thing you need to do is inherit the +# eclass. If there is no vendor directory, you need to also populate +# EGO_SUM and call go-module_set_globals as discussed below. +# +# Since Go programs are statically linked, it is important that your ebuild's +# LICENSE= setting includes the licenses of all statically linked +# dependencies. So please make sure it is accurate. +# You can use a utility like dev-util/golicense (network connectivity is +# required) to extract this information from the compiled binary. +# +# @EXAMPLE: +# +# @CODE +# +# inherit go-module +# +# EGO_SUM=( +# "github.com/aybabtme/rgbterm v0.0.0-20170906152045-cc83f3b3ce59/go.mod" +# "github.com/aybabtme/rgbterm v0.0.0-20170906152045-cc83f3b3ce59" +# ) +# +# go-module_set_globals +# +# SRC_URI="https://github.com/example/${PN}/archive/v${PV}.tar.gz -> ${P}.tar.gz +# ${EGO_SUM_SRC_URI}" +# +# @CODE + +case ${EAPI:-0} in + 7) ;; + *) die "${ECLASS} EAPI ${EAPI} is not supported." +esac + +if [[ -z ${_GO_MODULE} ]]; then + +_GO_MODULE=1 + +BDEPEND=">=dev-lang/go-1.12" + +# Workaround for pkgcheck false positive: https://github.com/pkgcore/pkgcheck/issues/214 +# MissingUnpackerDep: version ...: missing BDEPEND="app-arch/unzip" +# Added here rather than to each affected package, so it can be cleaned up just +# once when pkgcheck is improved. +BDEPEND+=" app-arch/unzip" + +# Force go to build in module mode. +# In this mode the GOPATH environment variable is ignored. +# this will become the default in the future. +export GO111MODULE=on + +# Set the default for the go build cache +# See "go help environment" for information on this setting +export GOCACHE="${T}/go-build" + +# The following go flags should be used for all builds. +# -v prints the names of packages as they are compiled +# -x prints commands as they are executed +# -mod=readonly do not update go.mod/go.sum but fail if updates are needed +# -mod=vendor use the vendor directory instead of downloading dependencies +export GOFLAGS="-v -x -mod=readonly" + +# Do not complain about CFLAGS etc since go projects do not use them. +QA_FLAGS_IGNORED='.*' + +# Go packages should not be stripped with strip(1). +RESTRICT+=" strip" + +EXPORT_FUNCTIONS src_unpack pkg_postinst + +# @ECLASS-VARIABLE: EGO_SUM +# @DESCRIPTION: +# This is an array based on the go.sum content from inside the target package. +# Each array entry must be quoted and contain information from a single +# line from go.sum. +# +# The format of go.sum is described upstream here: +# https://tip.golang.org/cmd/go/#hdr-Module_authentication_using_go_sum +# +# For inclusion in EGO_SUM, the h1: value and other future extensions SHOULD be +# omitted at this time. The EGO_SUM parser will accept them for ease of ebuild +# creation. +# +# h1:<hash> is the Hash1 structure used by upstream Go +# The Hash1 is MORE stable than Gentoo distfile hashing, and upstream warns +# that it's conceptually possible for the Hash1 value to remain stable while +# the upstream zipfiles change. Here are examples that do NOT change the h1: +# hash, but do change a regular checksum over all bytes of the file: +# - Differing mtimes within zipfile +# - Differing filename ordering with the zipfile +# - Differing zipfile compression parameters +# - Differing zipfile extra fields +# +# For Gentoo usage, the authors of this eclass feel that the h1: hash should +# NOT be included in the EGO_SUM at this time in order to reduce size of the +# ebuilds. This position will be reconsidered in future when a Go module +# distfile collision comes to light, where the Hash1 value of two distfiles is +# the same, but checksums over the file as a byte stream consider the files to +# be different. +# +# This decision does NOT weaken Go module security, as Go will verify the +# go.sum copy of the Hash1 values during building of the package. + +# @ECLASS-VARIABLE: _GOMODULE_GOPROXY_BASEURI +# @DESCRIPTION: +# Golang module proxy service to fetch module files from. Note that the module +# proxy generally verifies modules via the Hash1 code. +# +# Users in China may find some mirrors in the default list blocked, and should +# explicitly set an entry in /etc/portage/mirrors for goproxy to +# https://goproxy.cn/ or another mirror that is not blocked in China. +# See https://arslan.io/2019/08/02/why-you-should-use-a-go-module-proxy/ for +# further details +# +# This variable is NOT intended for user-level configuration of mirrors, but +# rather to cover go modules that might exist only on specific Goproxy +# servers for non-technical reasons. +# +# This variable should NOT be present in user-level configuration e.g. +# /etc/portage/make.conf, as it will violate metadata immutability! +# +# I am considering removing this and just hard coding mirror://goproxy +# below, so please do not rely on it. +: "${_GOMODULE_GOPROXY_BASEURI:=mirror://goproxy/}" + +# @ECLASS-VARIABLE: _GOMODULE_GOSUM_REVERSE_MAP +# @DESCRIPTION: +# Mapping back from Gentoo distfile name to upstream distfile path. +# Associative array to avoid O(N*M) performance when populating the GOPROXY +# directory structure. +declare -A -g _GOMODULE_GOSUM_REVERSE_MAP + +# @FUNCTION: go-module_set_globals +# @DESCRIPTION: +# Convert the information in EGO_SUM for other usage in the ebuild. +# - Populates EGO_SUM_SRC_URI that can be added to SRC_URI +# - Exports _GOMODULE_GOSUM_REVERSE_MAP which provides reverse mapping from +# distfile back to the relative part of SRC_URI, as needed for +# GOPROXY=file:///... +go-module_set_globals() { + local line exts + # for tracking go.sum errors + local error_in_gosum=0 + local -a gosum_errorlines + # used make SRC_URI easier to read + local newline=$'\n' + + # Now parse EGO_SUM + for line in "${EGO_SUM[@]}"; do + local module version modfile version_modfile kvs x + read -r module version_modfile kvs <<< "${line}" + # kvs contains the hash and may contain other data from + # upstream in the future. We do not currently use any of this data. + + # Split 'v0.3.0/go.mod' into 'v0.3.0' and '/go.mod' + # It might NOT have the trailing /go.mod + IFS=/ read -r version modfile x <<<"${version_modfile}" + # Reject multiple slashes + if [[ -n ${x} ]]; then + error_in_gosum=1 + gosum_errorlines+=( "Bad version: ${version_modfile}" ) + continue + fi + + # The modfile variable should be either empty or '/go.mod' + # There is a chance that upstream Go might add something else here in + # the future, and we should be prepared to capture it. + # The .info files do not need to be downloaded, they will be created + # based on the .mod file. + # See https://github.com/golang/go/issues/35922#issuecomment-584824275 + exts=() + local errormsg='' + case "${modfile}" in + '') exts=( zip ) ;; + 'go.mod'|'/go.mod') exts=( mod ) ;; + *) errormsg="Unknown modfile: line='${line}', modfile='${modfile}'" ;; + esac + + # If it was a bad entry, restart the loop + if [[ -n ${errormsg} ]]; then + error_in_gosum=1 + gosum_errorlines+=( "${errormsg} line='${line}', modfile='${modfile}'" ) + continue + fi + + _dir=$(_go-module_gomod_encode "${module}") + + for _ext in "${exts[@]}" ; do + # Relative URI within a GOPROXY for a file + _reluri="${_dir}/@v/${version}.${_ext}" + # SRC_URI: LHS entry + _uri="${_GOMODULE_GOPROXY_BASEURI}/${_reluri}" +# _uri="mirror://goproxy/${_reluri}" + # SRC_URI: RHS entry, encode any slash in the path as + # %2F in the filename + _distfile="${_reluri//\//%2F}" + + EGO_SUM_SRC_URI+=" ${_uri} -> ${_distfile}${newline}" + _GOMODULE_GOSUM_REVERSE_MAP["${_distfile}"]="${_reluri}" + done + done + + if [[ ${error_in_gosum} != 0 ]]; then + eerror "Trailing information in EGO_SUM in ${P}.ebuild" + for line in "${gosum_errorlines[@]}" ; do + eerror "${line}" + done + die "Invalid EGO_SUM format" + fi + + # Ensure these variables are not changed past this point + readonly EGO_SUM + readonly EGO_SUM_SRC_URI + readonly _GOMODULE_GOSUM_REVERSE_MAP + + # Set the guard that we are safe + _GO_MODULE_SET_GLOBALS_CALLED=1 +} + +# @FUNCTION: go-module_src_unpack +# @DESCRIPTION: +# If EGO_SUM is set, unpack the base tarball(s) and set up the +# local go proxy. +# - Otherwise, if EGO_VENDOR is set, bail out. +# - Otherwise do a normal unpack. +go-module_src_unpack() { + if [[ "${#EGO_SUM[@]}" -gt 0 ]]; then + _go-module_src_unpack_gosum + elif [[ "${#EGO_VENDOR[@]}" -gt 0 ]]; then + eerror "${EBUILD} is using EGO_VENDOR which is no longer supported" + die "Please update this ebuild" + else + default + fi +} + +# @FUNCTION: _go-module_src_unpack_gosum +# @DESCRIPTION: +# Populate a GOPROXY directory hierarchy with distfiles from EGO_SUM and +# unpack the base distfiles. +# +# Exports GOPROXY environment variable so that Go calls will source the +# directory correctly. +_go-module_src_unpack_gosum() { + # shellcheck disable=SC2120 + debug-print-function "${FUNCNAME}" "$@" + + if [[ ! ${_GO_MODULE_SET_GLOBALS_CALLED} ]]; then + die "go-module_set_globals must be called in global scope" + fi + + local goproxy_dir="${T}/go-proxy" + mkdir -p "${goproxy_dir}" || die + + # For each Golang module distfile, look up where it's supposed to go, and + # symlink into place. + local f + local goproxy_mod_dir + for f in ${A}; do + goproxy_mod_path="${_GOMODULE_GOSUM_REVERSE_MAP["${f}"]}" + if [[ -n "${goproxy_mod_path}" ]]; then + debug-print-function "Populating go proxy for ${goproxy_mod_path}" + # Build symlink hierarchy + goproxy_mod_dir=$( dirname "${goproxy_dir}"/"${goproxy_mod_path}" ) + mkdir -p "${goproxy_mod_dir}" || die + ln -sf "${DISTDIR}"/"${f}" "${goproxy_dir}/${goproxy_mod_path}" || + die "Failed to ln" + local v=${goproxy_mod_path} + v="${v%.mod}" + v="${v%.zip}" + v="${v//*\/}" + _go-module_gosum_synthesize_files "${goproxy_mod_dir}" "${v}" + else + unpack "$f" + fi + done + export GOPROXY="file://${goproxy_dir}" + + # Validate the gosum now + _go-module_src_unpack_verify_gosum +} + +# @FUNCTION: _go-module_gosum_synthesize_files +# @DESCRIPTION: +# Given a path & version, populate all Goproxy metadata files which aren't +# needed to be downloaded directly. +# - .../@v/${version}.info +# - .../@v/list +_go-module_gosum_synthesize_files() { + local target=$1 + local version=$2 + # 'go get' doesn't care about the hash of the .info files, they + # just need a 'version' element! + # This saves a download of a tiny file + # The .time key is omitted, because that is the time a module was added + # to the upstream goproxy, and not metadata about the module itself. + cat >"${target}/${version}.info" <<-EOF + { + "Version": "${version}", + "shortName": "${version}", + "Name": "${version}" + } + EOF + listfile="${target}"/list + if ! grep -sq -x -e "${version}" "${listfile}" 2>/dev/null; then + echo "${version}" >>"${listfile}" + fi +} + +# @FUNCTION: _go-module_src_unpack_verify_gosum +# @DESCRIPTION: +# Validate the Go modules declared by EGO_SUM are sufficient to cover building +# the package, without actually building it yet. +_go-module_src_unpack_verify_gosum() { + # shellcheck disable=SC2120 + debug-print-function "${FUNCNAME}" "$@" + + if [[ ! ${_GO_MODULE_SET_GLOBALS_CALLED} ]]; then + die "go-module_set_globals must be called in global scope" + fi + + cd "${S}" || die "cd failed" + + # Cleanup the modules before starting anything else + # This will print 'downloading' messages, but it's accessing content from + # the $GOPROXY file:/// URL! + einfo "Tidying go.mod/go.sum" + go mod tidy >/dev/null + + # This used to call 'go get' to verify by fetching everything from the main + # go.mod. However 'go get' also turns out to recursively try to fetch + # everything in dependencies, even materials that are used only for tests + # of the dependencies, or code generation. + # If EGO_SUM is missing an entry now, it will fail during the build process + # rather than this helper function. +} + +# @FUNCTION: go-module_live_vendor +# @DESCRIPTION: +# This function is used in live ebuilds to vendor the dependencies when +# upstream doesn't vendor them. +go-module_live_vendor() { + debug-print-function "${FUNCNAME}" "$@" + + # shellcheck disable=SC2086 + has live ${PROPERTIES} || + die "${FUNCNAME} only allowed in live ebuilds" + [[ "${EBUILD_PHASE}" == unpack ]] || + die "${FUNCNAME} only allowed in src_unpack" + [[ -d "${S}"/vendor ]] && + die "${FUNCNAME} only allowed when upstream isn't vendoring" + + pushd "${S}" >& /dev/null || die + go mod vendor || die + popd >& /dev/null || die +} + +# @FUNCTION: go-module_pkg_postinst +# @DESCRIPTION: +# Display a warning about security updates for Go programs. +go-module_pkg_postinst() { + debug-print-function "${FUNCNAME}" "$@" + [[ -n ${REPLACING_VERSIONS} ]] && return 0 + ewarn "${PN} is written in the Go programming language." + ewarn "Since this language is statically linked, security" + ewarn "updates will be handled in individual packages and will be" + ewarn "difficult for us to track as a distribution." + ewarn "For this reason, please update any go packages asap when new" + ewarn "versions enter the tree or go stable if you are running the" + ewarn "stable tree." +} + +# @FUNCTION: _go-module_gomod_encode +# @DESCRIPTION: +# Encode the name(path) of a Golang module in the format expected by Goproxy. +# +# Upper letters are replaced by their lowercase version with a '!' prefix. +# +_go-module_gomod_encode() { + ## Python: + # return re.sub('([A-Z]{1})', r'!\1', s).lower() + + ## Sed: + ## This uses GNU Sed extension \l to downcase the match + #echo "${module}" |sed 's,[A-Z],!\l&,g' + # + # Bash variant: + debug-print-function "${FUNCNAME}" "$@" + #local re input lower + re='(.*)([A-Z])(.*)' + input="${1}" + while [[ ${input} =~ ${re} ]]; do + lower='!'"${BASH_REMATCH[2],}" + input="${BASH_REMATCH[1]}${lower}${BASH_REMATCH[3]}" + done + echo "${input}" +} + +fi diff --git a/eclass/golang-base.eclass b/eclass/golang-base.eclass new file mode 100644 index 0000000..45603d7 --- /dev/null +++ b/eclass/golang-base.eclass @@ -0,0 +1,88 @@ +# Copyright 1999-2019 Gentoo Authors +# Distributed under the terms of the GNU General Public License v2 + +# @ECLASS: golang-base.eclass +# @MAINTAINER: +# William Hubbs <williamh@gentoo.org> +# @SUPPORTED_EAPIS: 5 6 7 +# @BLURB: Eclass that provides base functions for Go packages. +# @DESCRIPTION: +# This eclass provides base functions for software written in the Go +# programming language; it also provides the build-time dependency on +# dev-lang/go. + +case "${EAPI:-0}" in + 5|6|7) + ;; + *) + die "${ECLASS}: Unsupported eapi (EAPI=${EAPI})" + ;; +esac + +if [[ -z ${_GOLANG_BASE} ]]; then + +_GOLANG_BASE=1 + +GO_DEPEND=">=dev-lang/go-1.10" +if [[ ${EAPI:-0} == [56] ]]; then + DEPEND="${GO_DEPEND}" +else + BDEPEND="${GO_DEPEND}" +fi + +# Do not complain about CFLAGS etc since go projects do not use them. +QA_FLAGS_IGNORED='.*' + +# Upstream does not support stripping go packages +RESTRICT="strip" + +# @ECLASS-VARIABLE: EGO_PN +# @REQUIRED +# @DESCRIPTION: +# This is the import path for the go package to build. Please emerge +# dev-lang/go and read "go help importpath" for syntax. +# +# Example: +# @CODE +# EGO_PN=github.com/user/package +# @CODE + +# @FUNCTION: ego_pn_check +# @DESCRIPTION: +# Make sure EGO_PN has a value. +ego_pn_check() { + [[ -z "${EGO_PN}" ]] && + die "${ECLASS}.eclass: EGO_PN is not set" + return 0 +} + +# @FUNCTION: get_golibdir +# @DESCRIPTION: +# Return the non-prefixed library directory where Go packages +# should be installed +get_golibdir() { + echo /usr/lib/go-gentoo +} + +# @FUNCTION: get_golibdir_gopath +# @DESCRIPTION: +# Return the library directory where Go packages should be installed +# This is the prefixed version which should be included in GOPATH +get_golibdir_gopath() { + echo "${EPREFIX}$(get_golibdir)" +} + +# @FUNCTION: golang_install_pkgs +# @DESCRIPTION: +# Install Go packages. +# This function assumes that $cwd is a Go workspace. +golang_install_pkgs() { + debug-print-function ${FUNCNAME} "$@" + + ego_pn_check + insinto "$(get_golibdir)" + insopts -m0644 -p # preserve timestamps for bug 551486 + doins -r pkg src +} + +fi diff --git a/eclass/golang-build.eclass b/eclass/golang-build.eclass new file mode 100644 index 0000000..d106a30 --- /dev/null +++ b/eclass/golang-build.eclass @@ -0,0 +1,85 @@ +# Copyright 1999-2019 Gentoo Authors +# Distributed under the terms of the GNU General Public License v2 + +# @ECLASS: golang-build.eclass +# @MAINTAINER: +# William Hubbs <williamh@gentoo.org> +# @SUPPORTED_EAPIS: 5 6 7 +# @BLURB: Eclass for compiling go packages. +# @DESCRIPTION: +# This eclass provides default src_compile, src_test and src_install +# functions for software written in the Go programming language. + +inherit golang-base + +case "${EAPI:-0}" in + 5|6|7) + ;; + *) + die "${ECLASS}: Unsupported eapi (EAPI=${EAPI})" + ;; +esac + +EXPORT_FUNCTIONS src_compile src_install src_test + +if [[ -z ${_GOLANG_BUILD} ]]; then + +_GOLANG_BUILD=1 + +# @ECLASS-VARIABLE: EGO_BUILD_FLAGS +# @DEFAULT_UNSET +# @DESCRIPTION: +# This allows you to pass build flags to the Go compiler. These flags +# are common to the "go build" and "go install" commands used below. +# Please emerge dev-lang/go and run "go help build" for the +# documentation for these flags. +# +# Example: +# @CODE +# EGO_BUILD_FLAGS="-ldflags \"-X main.version ${PV}\"" +# @CODE + +# @ECLASS-VARIABLE: EGO_PN +# @REQUIRED +# @DESCRIPTION: +# This is the import path for the go package(s) to build. Please emerge +# dev-lang/go and read "go help importpath" for syntax. +# +# Example: +# @CODE +# EGO_PN=github.com/user/package +# @CODE + +golang-build_src_compile() { + debug-print-function ${FUNCNAME} "$@" + + ego_pn_check + set -- env GOPATH="${WORKDIR}/${P}:$(get_golibdir_gopath)" \ + GOCACHE="${T}/go-cache" \ + go build -v -work -x ${EGO_BUILD_FLAGS} "${EGO_PN}" + echo "$@" + "$@" || die +} + +golang-build_src_install() { + debug-print-function ${FUNCNAME} "$@" + + ego_pn_check + set -- env GOPATH="${WORKDIR}/${P}:$(get_golibdir_gopath)" \ + go install -v -work -x ${EGO_BUILD_FLAGS} "${EGO_PN}" + echo "$@" + "$@" || die + golang_install_pkgs +} + +golang-build_src_test() { + debug-print-function ${FUNCNAME} "$@" + + ego_pn_check + set -- env GOPATH="${WORKDIR}/${P}:$(get_golibdir_gopath)" \ + go test -v -work -x "${EGO_PN}" + echo "$@" + "$@" || die +} + +fi diff --git a/eclass/golang-vcs-snapshot.eclass b/eclass/golang-vcs-snapshot.eclass new file mode 100644 index 0000000..306db1f --- /dev/null +++ b/eclass/golang-vcs-snapshot.eclass @@ -0,0 +1,118 @@ +# Copyright 1999-2020 Gentoo Authors +# Distributed under the terms of the GNU General Public License v2 + +# @ECLASS: golang-vcs-snapshot.eclass +# @MAINTAINER: +# William Hubbs <williamh@gentoo.org> +# @SUPPORTED_EAPIS: 5 6 7 +# @BLURB: support eclass for unpacking VCS snapshot tarballs for +# software written in the Go programming language +# @DESCRIPTION: +# This eclass provides a convenience src_unpack() which unpacks the +# first tarball mentioned in SRC_URI to its appropriate location in +# ${WORKDIR}/${P}, treating ${WORKDIR}/${P} as a go workspace. +# Also, it provides a downstream method of vendoring packages. +# +# The location where the tarball is extracted is defined as +# ${WORKDIR}/${P}/src/${EGO_PN}. The location of vendored packages is +# defined as ${WORKDIR}/${P}/src/${EGO_PN%/*}/vendor to match Go's +# vendoring setup. +# +# The typical use case is VCS snapshots coming from github, bitbucket +# and similar services. +# +# Please note that this eclass currently handles only tarballs +# (.tar.gz), but support for more formats may be added in the future. +# +# @EXAMPLE: +# +# @CODE +# EGO_PN=github.com/user/package +# EGO_VENDOR=( +# "github.com/xenolf/lego 6cac0ea7d8b28c889f709ec7fa92e92b82f490dd" +# "golang.org/x/crypto 453249f01cfeb54c3d549ddb75ff152ca243f9d8 github.com/golang/crypto" +# ) +# +# inherit golang-vcs-snapshot +# +# SRC_URI="https://github.com/example/${PN}/tarball/v${PV} -> ${P}.tar.gz +# ${EGO_VENDOR_URI}" +# @CODE +# +# The above example will extract the tarball to +# ${WORKDIR}/${P}/src/github.com/user/package +# and add the vendored tarballs to ${WORKDIR}/src/${EGO_PN}/vendor + +inherit golang-base + +case ${EAPI:-0} in + 5|6|7) ;; + *) die "${ECLASS} API in EAPI ${EAPI} not yet established." +esac + +EXPORT_FUNCTIONS src_unpack + +# @ECLASS-VARIABLE: EGO_VENDOR +# @DESCRIPTION: +# This variable contains a list of vendored packages. +# The items of this array are strings that contain the +# import path and the git commit hash for a vendored package. +# If the import path does not start with github.com, the third argument +# can be used to point to a github repository. + +declare -arg EGO_VENDOR + +_golang-vcs-snapshot_set_vendor_uri() { + EGO_VENDOR_URI= + local lib + for lib in "${EGO_VENDOR[@]}"; do + lib=(${lib}) + if [[ -n ${lib[2]} ]]; then + EGO_VENDOR_URI+=" https://${lib[2]}/archive/${lib[1]}.tar.gz -> ${lib[2]//\//-}-${lib[1]}.tar.gz" + else + EGO_VENDOR_URI+=" https://${lib[0]}/archive/${lib[1]}.tar.gz -> ${lib[0]//\//-}-${lib[1]}.tar.gz" + fi + done + readonly EGO_VENDOR_URI +} + +_golang-vcs-snapshot_set_vendor_uri +unset -f _golang-vcs-snapshot_set_vendor_uri + +_golang-vcs-snapshot_dovendor() { + local VENDOR_PATH=$1 VENDORPN=$2 TARBALL=$3 + rm -fr "${VENDOR_PATH}/${VENDORPN}" || die + mkdir -p "${VENDOR_PATH}/${VENDORPN}" || die + tar -C "${VENDOR_PATH}/${VENDORPN}" -x --strip-components 1\ + -f "${DISTDIR}"/${TARBALL} || die +} + +# @FUNCTION: golang-vcs-snapshot_src_unpack +# @DESCRIPTION: +# Extract the first archive from ${A} to the appropriate location for GOPATH. +golang-vcs-snapshot_src_unpack() { + local lib vendor_path x + ego_pn_check + set -- ${A} + x="$1" + mkdir -p "${WORKDIR}/${P}/src/${EGO_PN%/...}" || die + tar -C "${WORKDIR}/${P}/src/${EGO_PN%/...}" -x --strip-components 1 \ + -f "${DISTDIR}/${x}" || die + + if [[ -n "${EGO_VENDOR}" ]]; then + vendor_path="${WORKDIR}/${P}/src/${EGO_PN%/...}/vendor" + mkdir -p "${vendor_path}" || die + for lib in "${EGO_VENDOR[@]}"; do + lib=(${lib}) + if [[ -n ${lib[2]} ]]; then + einfo "Vendoring ${lib[0]} ${lib[2]//\//-}-${lib[1]}.tar.gz" + _golang-vcs-snapshot_dovendor "${vendor_path}" ${lib[0]} \ + ${lib[2]//\//-}-${lib[1]}.tar.gz + else + einfo "Vendoring ${lib[0]} ${lib[0]//\//-}-${lib[1]}.tar.gz" + _golang-vcs-snapshot_dovendor "${vendor_path}" ${lib[0]} \ + ${lib[0]//\//-}-${lib[1]}.tar.gz + fi + done + fi +} diff --git a/eclass/golang-vcs.eclass b/eclass/golang-vcs.eclass new file mode 100644 index 0000000..159b32f --- /dev/null +++ b/eclass/golang-vcs.eclass @@ -0,0 +1,138 @@ +# Copyright 1999-2020 Gentoo Authors +# Distributed under the terms of the GNU General Public License v2 + +# @ECLASS: golang-vcs.eclass +# @MAINTAINER: +# William Hubbs <williamh@gentoo.org> +# @SUPPORTED_EAPIS: 5 6 7 +# @BLURB: Eclass for fetching and unpacking go repositories. +# @DESCRIPTION: +# This eclass is written to ease the maintenance of live ebuilds +# of software written in the Go programming language. + +inherit estack eutils golang-base + +case "${EAPI:-0}" in + 5|6|7) + ;; + *) + die "${ECLASS}: Unsupported eapi (EAPI=${EAPI})" + ;; +esac + +EXPORT_FUNCTIONS src_unpack + +if [[ -z ${_GOLANG_VCS} ]]; then + +_GOLANG_VCS=1 + +PROPERTIES+=" live" + +# @ECLASS-VARIABLE: EGO_PN +# @REQUIRED +# @DESCRIPTION: +# This is the import path for the go package(s). Please emerge dev-lang/go +# and read "go help importpath" for syntax. +# +# Example: +# @CODE +# EGO_PN="github.com/user/package" +# EGO_PN="github.com/user1/package1 github.com/user2/package2" +# @CODE + +# @ECLASS-VARIABLE: EGO_STORE_DIR +# @DESCRIPTION: +# Storage directory for Go sources. +# +# This is intended to be set by the user in make.conf. Ebuilds must not set +# it. +# +# EGO_STORE_DIR=${DISTDIR}/go-src + +# @ECLASS-VARIABLE: EVCS_OFFLINE +# @DEFAULT_UNSET +# @DESCRIPTION: +# If non-empty, this variable prevents any online operations. + +# @ECLASS-VARIABLE: EVCS_UMASK +# @DEFAULT_UNSET +# @DESCRIPTION: +# Set this variable to a custom umask. This is intended to be set by +# users. By setting this to something like 002, it can make life easier +# for people who do development as non-root (but are in the portage +# group) and use FEATURES=userpriv. + +# @FUNCTION: _golang-vcs_env_setup +# @INTERNAL +# @DESCRIPTION: +# Create EGO_STORE_DIR if necessary. +_golang-vcs_env_setup() { + debug-print-function ${FUNCNAME} "$@" + + local distdir=${PORTAGE_ACTUAL_DISTDIR:-${DISTDIR}} + : ${EGO_STORE_DIR:=${distdir}/go-src} + + [[ -n ${EVCS_UMASK} ]] && eumask_push $EVCS_UMASK + + if [[ ! -d ${EGO_STORE_DIR} ]]; then + ( + addwrite / + mkdir -p "${EGO_STORE_DIR}" + ) || die "${ECLASS}: unable to create ${EGO_STORE_DIR}" + fi + + addwrite "${EGO_STORE_DIR}" + + [[ -n ${EVCS_UMASK} ]] && eumask_pop + mkdir -p "${WORKDIR}/${P}/src" || + die "${ECLASS}: unable to create ${WORKDIR}/${P}" + return 0 +} + +# @FUNCTION: _golang-vcs_fetch +# @INTERNAL +# @DESCRIPTION: +# Retrieve the EGO_PN go package along with its dependencies. +_golang-vcs_fetch() { + debug-print-function ${FUNCNAME} "$@" + + ego_pn_check + + if [[ -z ${EVCS_OFFLINE} ]]; then + [[ -n ${EVCS_UMASK} ]] && eumask_push ${EVCS_UMASK} + + set -- env GOPATH="${EGO_STORE_DIR}" go get -d -t -u -v -x "${EGO_PN}" + echo "$@" + "$@" || die + # The above dies if you pass repositories in EGO_PN instead of + # packages, e.g. golang.org/x/tools instead of golang.org/x/tools/cmd/vet. + # This is being discussed in the following upstream issue: + # https://github.com/golang/go/issues/11090 + + [[ -n ${EVCS_UMASK} ]] && eumask_pop + fi + local go_srcpath="${WORKDIR}/${P}/src/${EGO_PN%/...}" + set -- mkdir -p "${go_srcpath}" + echo "$@" + "$@" || die "Unable to create ${go_srcpath}" + set -- cp -r "${EGO_STORE_DIR}/src/${EGO_PN%/...}" \ + "${go_srcpath}/.." + echo "$@" + "$@" || die "Unable to copy sources to ${go_srcpath}" + return 0 +} + +golang-vcs_src_fetch() { + debug-print-function ${FUNCNAME} "$@" + + _golang-vcs_env_setup + _golang-vcs_fetch +} + +golang-vcs_src_unpack() { + debug-print-function ${FUNCNAME} "$@" + + golang-vcs_src_fetch +} + +fi diff --git a/eclass/gstreamer.eclass b/eclass/gstreamer.eclass new file mode 100644 index 0000000..301d087 --- /dev/null +++ b/eclass/gstreamer.eclass @@ -0,0 +1,268 @@ +# Copyright 1999-2020 Gentoo Authors +# Distributed under the terms of the GNU General Public License v2 + +# @ECLASS: gstreamer.eclass +# @MAINTAINER: +# gstreamer@gentoo.org +# @AUTHOR: +# Michał Górny <mgorny@gentoo.org> +# Gilles Dartiguelongue <eva@gentoo.org> +# Saleem Abdulrasool <compnerd@gentoo.org> +# foser <foser@gentoo.org> +# zaheerm <zaheerm@gentoo.org> +# @SUPPORTED_EAPIS: 5 6 +# @BLURB: Helps building core & split gstreamer plugins. +# @DESCRIPTION: +# Eclass to make external gst-plugins emergable on a per-plugin basis +# and to solve the problem with gst-plugins generating far too much +# unneeded dependencies. +# +# GStreamer consuming applications should depend on the specific plugins +# they need as defined in their source code. Usually you can find that +# out by grepping the source tree for 'factory_make'. If it uses playbin +# plugin, consider adding media-plugins/gst-plugins-meta dependency, but +# also list any packages that provide explicitly requested plugins. + +inherit eutils ltprune multilib multilib-minimal toolchain-funcs versionator xdg-utils + +case "${EAPI:-0}" in + 5|6) + ;; + 0|1|2|3|4) + die "EAPI=\"${EAPI:-0}\" is not supported anymore" + ;; + *) + die "EAPI=\"${EAPI}\" is not supported yet" + ;; +esac + +# @ECLASS-VARIABLE: GST_PLUGINS_BUILD +# @DESCRIPTION: +# Defines the plugins to be built. +# May be set by an ebuild and contain more than one indentifier, space +# seperated (only src_configure can handle mutiple plugins at this time). +: ${GST_PLUGINS_BUILD:=${PN/gst-plugins-/}} + +# @ECLASS-VARIABLE: GST_PLUGINS_BUILD_DIR +# @DESCRIPTION: +# Actual build directory of the plugin. +# Most often the same as the configure switch name. +: ${GST_PLUGINS_BUILD_DIR:=${PN/gst-plugins-/}} + +# @ECLASS-VARIABLE: GST_TARBALL_SUFFIX +# @DESCRIPTION: +# Most projects hosted on gstreamer.freedesktop.org mirrors provide +# tarballs as tar.bz2 or tar.xz. This eclass defaults to xz. This is +# because the gstreamer mirrors are moving to only have xz tarballs for +# new releases. +: ${GST_TARBALL_SUFFIX:="xz"} + +# Even though xz-utils are in @system, they must still be added to DEPEND; see +# https://archives.gentoo.org/gentoo-dev/msg_a0d4833eb314d1be5d5802a3b710e0a4.xml +if [[ ${GST_TARBALL_SUFFIX} == "xz" ]]; then + DEPEND="${DEPEND} app-arch/xz-utils" +fi + +# @ECLASS-VARIABLE: GST_ORG_MODULE +# @DESCRIPTION: +# Name of the module as hosted on gstreamer.freedesktop.org mirrors. +# Leave unset if package name matches module name. +: ${GST_ORG_MODULE:=$PN} + +# @ECLASS-VARIABLE: GST_ORG_PVP +# @INTERNAL +# @DESCRIPTION: +# Major and minor numbers of the version number. +: ${GST_ORG_PVP:=$(get_version_component_range 1-2)} + + +DESCRIPTION="${BUILD_GST_PLUGINS} plugin for gstreamer" +HOMEPAGE="https://gstreamer.freedesktop.org/" +SRC_URI="https://gstreamer.freedesktop.org/src/${GST_ORG_MODULE}/${GST_ORG_MODULE}-${PV}.tar.${GST_TARBALL_SUFFIX}" + +LICENSE="GPL-2" +case ${GST_ORG_PVP} in + 0.10) SLOT="0.10"; GST_MIN_PV="0.10.36-r2" ;; + 1.*) SLOT="1.0"; GST_MIN_PV="1.2.4-r1" ;; + *) die "Unkown gstreamer release." +esac + +S="${WORKDIR}/${GST_ORG_MODULE}-${PV}" + +RDEPEND=" + >=dev-libs/glib-2.38.2-r1:2[${MULTILIB_USEDEP}] + >=media-libs/gstreamer-${GST_MIN_PV}:${SLOT}[${MULTILIB_USEDEP}] +" +DEPEND=" + >=sys-apps/sed-4 + virtual/pkgconfig +" + +# Export common multilib phases. +multilib_src_configure() { gstreamer_multilib_src_configure; } + +if [[ ${PN} != ${GST_ORG_MODULE} ]]; then + # Do not run test phase for invididual plugin ebuilds. + RESTRICT="test" + RDEPEND="${RDEPEND} + >=media-libs/${GST_ORG_MODULE}-${PV}:${SLOT}[${MULTILIB_USEDEP}]" + + # Export multilib phases used for split builds. + multilib_src_compile() { gstreamer_multilib_src_compile; } + multilib_src_install() { gstreamer_multilib_src_install; } + multilib_src_install_all() { gstreamer_multilib_src_install_all; } +else + IUSE="nls" + DEPEND="${DEPEND} nls? ( >=sys-devel/gettext-0.17 )" +fi + +DEPEND="${DEPEND} ${RDEPEND}" + +# @FUNCTION: gstreamer_environment_reset +# @INTERNAL +# @DESCRIPTION: +# Clean up environment for clean builds. +# >=dev-lang/orc-0.4.23 rely on environment variables to find a place to +# allocate files to mmap. +gstreamer_environment_reset() { + xdg_environment_reset +} + +# @FUNCTION: gstreamer_get_plugins +# @INTERNAL +# @DESCRIPTION: +# Get the list of plugins requiring external dependencies. +gstreamer_get_plugins() { + # Must be called from src_prepare/src_configure + GST_PLUGINS_LIST=$(sed -rn 's/^AG_GST_CHECK_FEATURE\((\w+),.*/ \1 /p' \ + "${ECONF_SOURCE:-${S}}"/configure.* | LC_ALL='C' tr '[:upper:]' '[:lower:]') +} + +# @FUNCTION: gstreamer_get_plugin_dir +# @USAGE: [build_dir] +# @INTERNAL +# @DESCRIPTION: +# Finds plugin build directory and output it. +# Defaults to ${GST_PLUGINS_BUILD_DIR} if argument is not provided +gstreamer_get_plugin_dir() { + local build_dir=${1:-${GST_PLUGINS_BUILD_DIR}} + + if [[ ! -d ${S}/ext/${build_dir} ]]; then + if [[ ! -d ${S}/sys/${build_dir} ]]; then + ewarn "No such plugin directory" + die + fi + einfo "Building system plugin in ${build_dir}..." >&2 + echo sys/${build_dir} + else + einfo "Building external plugin in ${build_dir}..." >&2 + echo ext/${build_dir} + fi +} + +# @FUNCTION: gstreamer_system_link +# @USAGE: <gst-libs/gst/audio:gstreamer-audio> [...] +# @DESCRIPTION: +# Walks through makefiles in order to make sure build will link against system +# libraries. +# Takes a list of path fragments and corresponding pkgconfig libraries +# separated by colon (:). Will replace the path fragment by the output of +# pkgconfig. +gstreamer_system_link() { + local pdir directory libs pkgconfig pc tuple + pkgconfig=$(tc-getPKG_CONFIG) + + for plugin_dir in ${GST_PLUGINS_BUILD_DIR} ; do + pdir=$(gstreamer_get_plugin_dir ${plugin_dir}) + + for tuple in $@ ; do + directory=${tuple%:*} + pc=${tuple#*:}-${SLOT} + libs="$(${pkgconfig} --libs-only-l ${pc} || die)" + sed -e "s:\$(top_builddir)/${directory}/.*\.la:${libs}:" \ + -i "${pdir}"/Makefile.{am,in} || die + done + done +} + +# @FUNCTION: gstreamer_multilib_src_configure +# @DESCRIPTION: +# Handles logic common to configuring gstreamer plugins +gstreamer_multilib_src_configure() { + local plugin gst_conf=() ECONF_SOURCE=${ECONF_SOURCE:-${S}} + + gstreamer_get_plugins + gstreamer_environment_reset + + for plugin in ${GST_PLUGINS_LIST} ; do + if has ${plugin} ${GST_PLUGINS_BUILD} ; then + gst_conf+=( --enable-${plugin} ) + else + gst_conf+=( --disable-${plugin} ) + fi + done + + if grep -q "ORC_CHECK" "${ECONF_SOURCE}"/configure.* ; then + if in_iuse orc ; then + gst_conf+=( $(use_enable orc) ) + else + gst_conf+=( --disable-orc ) + fi + fi + + if grep -q "AM_MAINTAINER_MODE" "${ECONF_SOURCE}"/configure.* ; then + gst_conf+=( --disable-maintainer-mode ) + fi + + if grep -q "disable-schemas-compile" "${ECONF_SOURCE}"/configure ; then + gst_conf+=( --disable-schemas-compile ) + fi + + if [[ ${PN} == ${GST_ORG_MODULE} ]]; then + gst_conf+=( $(use_enable nls) ) + fi + + einfo "Configuring to build ${GST_PLUGINS_BUILD} plugin(s) ..." + econf \ + --with-package-name="Gentoo GStreamer ebuild" \ + --with-package-origin="https://www.gentoo.org" \ + "${gst_conf[@]}" "${@}" +} + +# @FUNCTION: gstreamer_multilib_src_compile +# @DESCRIPTION: +# Compiles requested gstreamer plugin. +gstreamer_multilib_src_compile() { + local plugin_dir + + for plugin_dir in ${GST_PLUGINS_BUILD_DIR} ; do + emake -C "$(gstreamer_get_plugin_dir ${plugin_dir})" + done +} + +# @FUNCTION: gstreamer_multilib_src_install +# @DESCRIPTION: +# Installs requested gstreamer plugin. +gstreamer_multilib_src_install() { + local plugin_dir + + for plugin_dir in ${GST_PLUGINS_BUILD_DIR} ; do + emake -C "$(gstreamer_get_plugin_dir ${plugin_dir})" \ + DESTDIR="${D}" install + done +} + +# @FUNCTION: gstreamer_multilib_src_install_all +# @DESCRIPTION: +# Installs documentation for requested gstreamer plugin, and removes .la +# files. +gstreamer_multilib_src_install_all() { + local plugin_dir + + for plugin_dir in ${GST_PLUGINS_BUILD_DIR} ; do + local dir=$(gstreamer_get_plugin_dir ${plugin_dir}) + [[ -e ${dir}/README ]] && dodoc "${dir}"/README + done + + prune_libtool_files --modules +} diff --git a/eclass/haskell-cabal.eclass b/eclass/haskell-cabal.eclass new file mode 100644 index 0000000..6099363 --- /dev/null +++ b/eclass/haskell-cabal.eclass @@ -0,0 +1,771 @@ +# Copyright 1999-2019 Gentoo Authors +# Distributed under the terms of the GNU General Public License v2 + +# @ECLASS: haskell-cabal.eclass +# @MAINTAINER: +# Haskell herd <haskell@gentoo.org> +# @AUTHOR: +# Original author: Andres Loeh <kosmikus@gentoo.org> +# Original author: Duncan Coutts <dcoutts@gentoo.org> +# @BLURB: for packages that make use of the Haskell Common Architecture for Building Applications and Libraries (cabal) +# @DESCRIPTION: +# Basic instructions: +# +# Before inheriting the eclass, set CABAL_FEATURES to +# reflect the tools and features that the package makes +# use of. +# +# Currently supported features: +# haddock -- for documentation generation +# hscolour -- generation of colourised sources +# hoogle -- generation of documentation search index +# profile -- if package supports to build profiling-enabled libraries +# bootstrap -- only used for the cabal package itself +# lib -- the package installs libraries +# nocabaldep -- don't add dependency on cabal. +# only used for packages that _must_ not pull the dependency +# on cabal, but still use this eclass (e.g. haskell-updater). +# ghcdeps -- constraint dependency on package to ghc onces +# only used for packages that use libghc internally and _must_ +# not pull upper versions +# test-suite -- add support for cabal test-suites (introduced in Cabal-1.8) +# rebuild-after-doc-workaround -- enable doctest test failue workaround. +# Symptom: when `./setup haddock` is run in a `build-type: Custom` +# package it might cause cause the test-suite to fail with +# errors like: +# > <command line>: cannot satisfy -package-id singletons-2.7-3Z7pnljD8tU1NrslJodXmr +# Workaround re-reginsters the package to avoid the failure +# (and rebuilds changes). +# FEATURE can be removed once https://github.com/haskell/cabal/issues/7213 +# is fixed. + +inherit eutils ghc-package multilib toolchain-funcs + +# @ECLASS-VARIABLE: CABAL_EXTRA_CONFIGURE_FLAGS +# @DESCRIPTION: +# User-specified additional parameters passed to 'setup configure'. +# example: /etc/portage/make.conf: +# CABAL_EXTRA_CONFIGURE_FLAGS="--enable-shared --enable-executable-dynamic" +: ${CABAL_EXTRA_CONFIGURE_FLAGS:=} + +# @ECLASS-VARIABLE: CABAL_EXTRA_BUILD_FLAGS +# @DESCRIPTION: +# User-specified additional parameters passed to 'setup build'. +# example: /etc/portage/make.conf: CABAL_EXTRA_BUILD_FLAGS=-v +: ${CABAL_EXTRA_BUILD_FLAGS:=} + +# @ECLASS-VARIABLE: GHC_BOOTSTRAP_FLAGS +# @DESCRIPTION: +# User-specified additional parameters for ghc when building +# _only_ 'setup' binary bootstrap. +# example: /etc/portage/make.conf: GHC_BOOTSTRAP_FLAGS=-dynamic to make +# linking 'setup' faster. +: ${GHC_BOOTSTRAP_FLAGS:=} + +# @ECLASS-VARIABLE: CABAL_EXTRA_HADDOCK_FLAGS +# @DESCRIPTION: +# User-specified additional parameters passed to 'setup haddock'. +# example: /etc/portage/make.conf: +# CABAL_EXTRA_HADDOCK_FLAGS="--haddock-options=--latex --haddock-options=--pretty-html" +: ${CABAL_EXTRA_HADDOCK_FLAGS:=} + +# @ECLASS-VARIABLE: CABAL_EXTRA_HOOGLE_FLAGS +# @DESCRIPTION: +# User-specified additional parameters passed to 'setup haddock --hoogle'. +# example: /etc/portage/make.conf: +# CABAL_EXTRA_HOOGLE_FLAGS="--haddock-options=--show-all" +: ${CABAL_EXTRA_HOOGLE_FLAGS:=} + +# @ECLASS-VARIABLE: CABAL_EXTRA_HSCOLOUR_FLAGS +# @DESCRIPTION: +# User-specified additional parameters passed to 'setup hscolour'. +# example: /etc/portage/make.conf: +# CABAL_EXTRA_HSCOLOUR_FLAGS="--executables --tests" +: ${CABAL_EXTRA_HSCOLOUR_FLAGS:=} + + +# @ECLASS-VARIABLE: CABAL_EXTRA_TEST_FLAGS +# @DESCRIPTION: +# User-specified additional parameters passed to 'setup test'. +# example: /etc/portage/make.conf: +# CABAL_EXTRA_TEST_FLAGS="-v3 --show-details=streaming" +: ${CABAL_EXTRA_TEST_FLAGS:=} + +# @ECLASS-VARIABLE: CABAL_DEBUG_LOOSENING +# @DESCRIPTION: +# Show debug output for 'cabal_chdeps' function if set. +# Needs working 'diff'. +: ${CABAL_DEBUG_LOOSENING:=} + +# @ECLASS-VARIABLE: CABAL_REPORT_OTHER_BROKEN_PACKAGES +# @DESCRIPTION: +# Show other broken packages if 'cabal configure' fails. +# It should be normally enabled unless you know you are about +# to try to compile a lot of broken packages. Default value: 'yes' +# Set to anything else to disable. +: ${CABAL_REPORT_OTHER_BROKEN_PACKAGES:=yes} + +HASKELL_CABAL_EXPF="pkg_setup src_compile src_test src_install pkg_postinst pkg_postrm" + +# 'dev-haskell/cabal' passes those options with ./configure-based +# configuration, but most packages don't need/don't accept it: +# #515362, #515362 +QA_CONFIGURE_OPTIONS+=" --with-compiler --with-hc --with-hc-pkg --with-gcc" + +case "${EAPI:-0}" in + 2|3|4|5|6|7) HASKELL_CABAL_EXPF+=" src_configure" ;; + *) ;; +esac + +EXPORT_FUNCTIONS ${HASKELL_CABAL_EXPF} + +for feature in ${CABAL_FEATURES}; do + case ${feature} in + haddock) CABAL_USE_HADDOCK=yes;; + hscolour) CABAL_USE_HSCOLOUR=yes;; + hoogle) CABAL_USE_HOOGLE=yes;; + profile) CABAL_USE_PROFILE=yes;; + bootstrap) CABAL_BOOTSTRAP=yes;; + lib) CABAL_HAS_LIBRARIES=yes;; + nocabaldep) CABAL_FROM_GHC=yes;; + ghcdeps) CABAL_GHC_CONSTRAINT=yes;; + test-suite) CABAL_TEST_SUITE=yes;; + rebuild-after-doc-workaround) CABAL_REBUILD_AFTER_DOC_WORKAROUND=yes;; + + # does nothing, removed 2016-09-04 + bin) ;; + + *) CABAL_UNKNOWN="${CABAL_UNKNOWN} ${feature}";; + esac +done + +if [[ -n "${CABAL_USE_HADDOCK}" ]]; then + IUSE="${IUSE} doc" +fi + +if [[ -n "${CABAL_USE_HSCOLOUR}" ]]; then + IUSE="${IUSE} hscolour" + DEPEND="${DEPEND} hscolour? ( dev-haskell/hscolour )" +fi + +if [[ -n "${CABAL_USE_HOOGLE}" ]]; then + # enabled only in ::haskell + #IUSE="${IUSE} hoogle" + CABAL_USE_HOOGLE= +fi + +if [[ -n "${CABAL_USE_PROFILE}" ]]; then + IUSE="${IUSE} profile" +fi + +if [[ -n "${CABAL_TEST_SUITE}" ]]; then + IUSE="${IUSE} test" + RESTRICT+=" !test? ( test )" +fi + +# returns the version of cabal currently in use. +# Rarely it's handy to pin cabal version from outside. +: ${_CABAL_VERSION_CACHE:=""} +cabal-version() { + if [[ -z "${_CABAL_VERSION_CACHE}" ]]; then + if [[ "${CABAL_BOOTSTRAP}" ]]; then + # We're bootstrapping cabal, so the cabal version is the version + # of this package itself. + _CABAL_VERSION_CACHE="${PV}" + elif [[ "${CABAL_FROM_GHC}" ]]; then + _CABAL_VERSION_CACHE="$(ghc-cabal-version)" + else + # We ask portage, not ghc, so that we only pick up + # portage-installed cabal versions. + _CABAL_VERSION_CACHE="$(ghc-extractportageversion dev-haskell/cabal)" + fi + fi + echo "${_CABAL_VERSION_CACHE}" +} + +cabal-bootstrap() { + local setupmodule + local cabalpackage + local setup_bootstrap_args=() + + if [[ -f "${S}/Setup.lhs" ]]; then + setupmodule="${S}/Setup.lhs" + elif [[ -f "${S}/Setup.hs" ]]; then + setupmodule="${S}/Setup.hs" + else + eqawarn "No Setup.lhs or Setup.hs found. Either add Setup.hs to package or call cabal-mksetup from ebuild" + cabal-mksetup + setupmodule="${S}/Setup.hs" + fi + + # We build the setup program using the latest version of + # cabal that we have installed + cabalpackage=Cabal-$(cabal-version) + einfo "Using cabal-$(cabal-version)." + + if $(ghc-supports-threaded-runtime); then + # Cabal has a bug that deadlocks non-threaded RTS: + # https://bugs.gentoo.org/537500 + # https://github.com/haskell/cabal/issues/2398 + setup_bootstrap_args+=(-threaded) + fi + + make_setup() { + set -- -package "${cabalpackage}" --make "${setupmodule}" \ + $(ghc-make-args) \ + "${setup_bootstrap_args[@]}" \ + ${HCFLAGS} \ + ${GHC_BOOTSTRAP_FLAGS} \ + "$@" \ + -o setup + echo $(ghc-getghc) "$@" + $(ghc-getghc) "$@" + } + if $(ghc-supports-shared-libraries); then + # # some custom build systems might use external libraries, + # # for which we don't have shared libs, so keep static fallback + # bug #411789, http://hackage.haskell.org/trac/ghc/ticket/5743#comment:3 + # http://hackage.haskell.org/trac/ghc/ticket/7062 + # http://hackage.haskell.org/trac/ghc/ticket/3072 + # ghc does not set RPATH for extralibs, thus we do it ourselves by hands + einfo "Prepending $(ghc-libdir) to LD_LIBRARY_PATH" + if [[ ${CHOST} != *-darwin* ]]; then + LD_LIBRARY_PATH="$(ghc-libdir)${LD_LIBRARY_PATH:+:}${LD_LIBRARY_PATH}" + export LD_LIBRARY_PATH + else + DYLD_LIBRARY_PATH="$(ghc-libdir)${DYLD_LIBRARY_PATH:+:}${DYLD_LIBRARY_PATH}" + export DYLD_LIBRARY_PATH + fi + { make_setup -dynamic "$@" && ./setup --help >/dev/null; } || + make_setup "$@" || die "compiling ${setupmodule} failed" + else + make_setup "$@" || die "compiling ${setupmodule} failed" + fi +} + +cabal-mksetup() { + local setupdir=${1:-${S}} + local setup_src=${setupdir}/Setup.hs + + rm -vf "${setupdir}"/Setup.{lhs,hs} + elog "Creating 'Setup.hs' for 'Simple' build type." + + echo 'import Distribution.Simple; main = defaultMain' \ + > "${setup_src}" || die "failed to create default Setup.hs" +} + +haskell-cabal-run_verbose() { + echo "$@" + "$@" || die "failed: $@" +} + +cabal-hscolour() { + haskell-cabal-run_verbose ./setup hscolour "$@" +} + +cabal-haddock() { + haskell-cabal-run_verbose ./setup haddock "$@" +} + +cabal-die-if-nonempty() { + local breakage_type=$1 + shift + + [[ "${#@}" == 0 ]] && return 0 + eerror "Detected ${breakage_type} packages: ${@}" + die "//==-- Please, run 'haskell-updater' to fix ${breakage_type} packages --==//" +} + +cabal-show-brokens() { + [[ ${CABAL_REPORT_OTHER_BROKEN_PACKAGES} != yes ]] && return 0 + + elog "ghc-pkg check: 'checking for other broken packages:'" + # pretty-printer + $(ghc-getghcpkg) check 2>&1 \ + | egrep -v '^Warning: haddock-(html|interfaces): ' \ + | egrep -v '^Warning: include-dirs: ' \ + | head -n 20 + + cabal-die-if-nonempty 'broken' \ + $($(ghc-getghcpkg) check --simple-output) +} + +cabal-show-old() { + [[ ${CABAL_REPORT_OTHER_BROKEN_PACKAGES} != yes ]] && return 0 + + cabal-die-if-nonempty 'outdated' \ + $("${EPREFIX}"/usr/sbin/haskell-updater --quiet --upgrade --list-only) +} + +cabal-show-brokens-and-die() { + cabal-show-brokens + cabal-show-old + + die "$@" +} + +cabal-configure() { + local cabalconf=() + has "${EAPI:-0}" 0 1 2 && ! use prefix && EPREFIX= + + if [[ -n "${CABAL_USE_HADDOCK}" ]] && use doc; then + # We use the bundled with GHC version if exists + # Haddock is very picky about index files + # it generates for ghc's base and other packages. + local p=${EPREFIX}/usr/bin/haddock-ghc-$(ghc-version) + if [[ -f $p ]]; then + cabalconf+=(--with-haddock="${p}") + else + cabalconf+=(--with-haddock=${EPREFIX}/usr/bin/haddock) + fi + fi + if [[ -n "${CABAL_USE_PROFILE}" ]] && use profile; then + cabalconf+=(--enable-library-profiling) + fi + + if [[ -n "${CABAL_TEST_SUITE}" ]]; then + cabalconf+=($(use_enable test tests)) + fi + + if [[ -n "${CABAL_GHC_CONSTRAINT}" ]]; then + cabalconf+=($(cabal-constraint "ghc")) + fi + + cabalconf+=(--ghc-options="$(ghc-make-args)") + + local option + for option in ${HCFLAGS} + do + cabalconf+=(--ghc-option="$option") + done + + # toolchain + cabalconf+=(--with-ar="$(tc-getAR)") + + # Building GHCi libs on ppc64 causes "TOC overflow". + if use ppc64; then + cabalconf+=(--disable-library-for-ghci) + fi + + # currently cabal does not respect CFLAGS and LDFLAGS on it's own (bug #333217) + # so translate LDFLAGS to ghc parameters (with mild filtering). + local flag + for flag in $CFLAGS; do + case "${flag}" in + -flto|-flto=*) + # binutils does not support partial linking yet: + # https://github.com/gentoo-haskell/gentoo-haskell/issues/1110 + # https://sourceware.org/PR12291 + einfo "Filter '${flag}' out of CFLAGS (avoid lto partial linking)" + continue + ;; + esac + + cabalconf+=(--ghc-option="-optc$flag") + done + for flag in $LDFLAGS; do + case "${flag}" in + -flto|-flto=*) + # binutils does not support partial linking yet: + # https://github.com/gentoo-haskell/gentoo-haskell/issues/1110 + # https://sourceware.org/PR12291 + einfo "Filter '${flag}' out of LDFLAGS (avoid lto partial linking)" + continue + ;; + esac + + cabalconf+=(--ghc-option="-optl$flag") + done + + # disable executable stripping for the executables, as portage will + # strip by itself, and pre-stripping gives a QA warning. + # cabal versions previous to 1.4 does not strip executables, and does + # not accept the flag. + # this fixes numerous bugs, amongst them; + # bug #251881, bug #251882, bug #251884, bug #251886, bug #299494 + cabalconf+=(--disable-executable-stripping) + + cabalconf+=(--docdir="${EPREFIX}"/usr/share/doc/${PF}) + # As of Cabal 1.2, configure is quite quiet. For diagnostic purposes + # it's better if the configure chatter is in the build logs: + cabalconf+=(--verbose) + + # We build shared version of our Cabal where ghc ships it's shared + # version of it. We will link ./setup as dynamic binary againt Cabal later. + [[ ${CATEGORY}/${PN} == "dev-haskell/cabal" ]] && \ + $(ghc-supports-shared-libraries) && \ + cabalconf+=(--enable-shared) + + if $(ghc-supports-shared-libraries); then + # Experimental support for dynamically linked binaries. + # We are enabling it since 7.10.1_rc3 + if ver_test "$(ghc-version)" -ge "7.10.0.20150316"; then + # we didn't enable it before as it was not stable on all arches + cabalconf+=(--enable-shared) + # Known to break on ghc-7.8/Cabal-1.18 + # https://ghc.haskell.org/trac/ghc/ticket/9625 + cabalconf+=(--enable-executable-dynamic) + fi + fi + + # --sysconfdir appeared in Cabal-1.18+ + if ./setup configure --help | grep -q -- --sysconfdir; then + cabalconf+=(--sysconfdir="${EPREFIX}"/etc) + fi + + # appeared in Cabal-1.18+ (see '--disable-executable-stripping') + if ./setup configure --help | grep -q -- --disable-library-stripping; then + cabalconf+=(--disable-library-stripping) + fi + + set -- configure \ + --ghc --prefix="${EPREFIX}"/usr \ + --with-compiler="$(ghc-getghc)" \ + --with-hc-pkg="$(ghc-getghcpkg)" \ + --prefix="${EPREFIX}"/usr \ + --libdir="${EPREFIX}"/usr/$(get_libdir) \ + --libsubdir=${P}/ghc-$(ghc-version) \ + --datadir="${EPREFIX}"/usr/share/ \ + --datasubdir=${P}/ghc-$(ghc-version) \ + "${cabalconf[@]}" \ + ${CABAL_CONFIGURE_FLAGS} \ + "$@" \ + ${CABAL_EXTRA_CONFIGURE_FLAGS} + echo ./setup "$@" + ./setup "$@" || cabal-show-brokens-and-die "setup configure failed" +} + +cabal-build() { + set -- build "$@" ${CABAL_EXTRA_BUILD_FLAGS} + echo ./setup "$@" + ./setup "$@" \ + || die "setup build failed" +} + +cabal-copy() { + has "${EAPI:-0}" 0 1 2 && ! use prefix && ED=${D} + + set -- copy --destdir="${D}" "$@" + echo ./setup "$@" + ./setup "$@" || die "setup copy failed" + + # cabal is a bit eager about creating dirs, + # so remove them if they are empty + rmdir "${ED}/usr/bin" 2> /dev/null +} + +cabal-pkg() { + # This does not actually register since we're using true instead + # of ghc-pkg. So it just leaves the .conf file and we can + # register that ourselves (if it exists). + + if [[ -n ${CABAL_HAS_LIBRARIES} ]]; then + # Newer cabal can generate a package conf for us: + ./setup register --gen-pkg-config="${T}/${P}.conf" + if [[ -d "${T}/${P}.conf" ]]; then + ghc-install-pkg "${T}/${P}.conf"/* + else + ghc-install-pkg "${T}/${P}.conf" + fi + fi +} + +# Some cabal libs are bundled along with some versions of ghc +# eg filepath-1.0 comes with ghc-6.6.1 +# by putting CABAL_CORE_LIB_GHC_PV="6.6.1" in an ebuild we are declaring that +# when building with this version of ghc, the ebuild is a dummy that is it will +# install no files since the package is already included with ghc. +# However portage still records the dependency and we can upgrade the package +# to a later one that's not included with ghc. +# You can also put a space separated list, eg CABAL_CORE_LIB_GHC_PV="6.6 6.6.1". +# Those versions are taken as-is from ghc `--numeric-version`. +# Package manager versions are also supported: +# CABAL_CORE_LIB_GHC_PV="7.10.* PM:7.8.4-r1". +cabal-is-dummy-lib() { + local bin_ghc_version=$(ghc-version) + local pm_ghc_version=$(ghc-pm-version) + + for version in ${CABAL_CORE_LIB_GHC_PV}; do + [[ "${bin_ghc_version}" == ${version} ]] && return 0 + [[ "${pm_ghc_version}" == ${version} ]] && return 0 + done + + return 1 +} + +# exported function: check if cabal is correctly installed for +# the currently active ghc (we cannot guarantee this with portage) +haskell-cabal_pkg_setup() { + if [[ -n ${CABAL_HAS_LIBRARIES} ]]; then + [[ ${RDEPEND} == *dev-lang/ghc* ]] || eqawarn "QA Notice: A library does not have runtime dependency on dev-lang/ghc." + fi + if [[ -n "${CABAL_UNKNOWN}" ]]; then + eqawarn "QA Notice: Unknown entry in CABAL_FEATURES: ${CABAL_UNKNOWN}" + fi + if cabal-is-dummy-lib; then + einfo "${P} is included in ghc-${CABAL_CORE_LIB_GHC_PV}, nothing to install." + fi +} + +haskell-cabal_src_configure() { + cabal-is-dummy-lib && return + + pushd "${S}" > /dev/null || die + + cabal-bootstrap + + cabal-configure "$@" + + popd > /dev/null || die +} + +# exported function: nice alias +cabal_src_configure() { + haskell-cabal_src_configure "$@" +} + +# exported function: cabal-style bootstrap configure and compile +cabal_src_compile() { + # it's a common mistake when one bumps ebuild to EAPI="2" (and upper) + # and forgets to separate src_compile() to src_configure()/src_compile(). + # Such error leads to default src_configure and we lose all passed flags. + if ! has "${EAPI:-0}" 0 1; then + local passed_flag + for passed_flag in "$@"; do + [[ ${passed_flag} == --flags=* ]] && \ + eqawarn "QA Notice: Cabal option '${passed_flag}' has effect only in src_configure()" + done + fi + + cabal-is-dummy-lib && return + + has src_configure ${HASKELL_CABAL_EXPF} || haskell-cabal_src_configure "$@" + cabal-build + + if [[ -n "$CABAL_USE_HADDOCK" ]] && use doc; then + if [[ -n "$CABAL_USE_HSCOLOUR" ]] && use hscolour; then + # --hyperlink-source implies calling 'setup hscolour' + haddock_args+=(--hyperlink-source) + fi + + cabal-haddock "${haddock_args[@]}" $CABAL_EXTRA_HADDOCK_FLAGS + + if [[ -n "$CABAL_USE_HOOGLE" ]] && use hoogle; then + cabal-haddock --hoogle $CABAL_EXTRA_HOOGLE_FLAGS + fi + if [[ -n "${CABAL_REBUILD_AFTER_DOC_WORKAROUND}" ]]; then + ewarn "rebuild-after-doc-workaround is enabled. This is a" + ewarn "temporary worakround to deal with https://github.com/haskell/cabal/issues/7213" + ewarn "until the upstream issue can be resolved." + cabal-build + fi + else + if [[ -n "$CABAL_USE_HSCOLOUR" ]] && use hscolour; then + cabal-hscolour $CABAL_EXTRA_HSCOLOUR_FLAGS + fi + + if [[ -n "$CABAL_USE_HOOGLE" ]] && use hoogle; then + ewarn "hoogle USE flag requires doc USE flag, building without hoogle" + fi + fi +} + +haskell-cabal_src_compile() { + pushd "${S}" > /dev/null || die + + cabal_src_compile "$@" + + popd > /dev/null || die +} + +haskell-cabal_src_test() { + local cabaltest=() + + pushd "${S}" > /dev/null || die + + if cabal-is-dummy-lib; then + einfo ">>> No tests for dummy library: ${CATEGORY}/${PF}" + else + einfo ">>> Test phase [cabal test]: ${CATEGORY}/${PF}" + + # '--show-details=streaming' appeared in Cabal-1.20 + if ./setup test --help | grep -q -- "'streaming'"; then + cabaltest+=(--show-details=streaming) + fi + + set -- test \ + "${cabaltest[@]}" \ + ${CABAL_TEST_FLAGS} \ + "$@" \ + ${CABAL_EXTRA_TEST_FLAGS} + echo ./setup "$@" + ./setup "$@" || die "cabal test failed" + fi + + popd > /dev/null || die +} + +# exported function: cabal-style copy and register +cabal_src_install() { + has "${EAPI:-0}" 0 1 2 && ! use prefix && EPREFIX= + + if ! cabal-is-dummy-lib; then + cabal-copy + cabal-pkg + fi + + # create a dummy local package conf file for haskell-updater + # if it does not exist (dummy libraries and binaries w/o libraries) + local ghc_confdir_with_prefix="$(ghc-confdir)" + # remove EPREFIX + dodir ${ghc_confdir_with_prefix#${EPREFIX}} + local hint_db="${D}/$(ghc-confdir)" + local hint_file="${hint_db}/gentoo-empty-${CATEGORY}-${PF}.conf" + mkdir -p "${hint_db}" || die + touch "${hint_file}" || die +} + +haskell-cabal_src_install() { + pushd "${S}" > /dev/null || die + + cabal_src_install + + popd > /dev/null || die +} + +haskell-cabal_pkg_postinst() { + ghc-package_pkg_postinst +} + +haskell-cabal_pkg_postrm() { + ghc-package_pkg_postrm +} + +# @FUNCTION: cabal_flag +# @DESCRIPTION: +# ebuild.sh:use_enable() taken as base +# +# Usage examples: +# +# CABAL_CONFIGURE_FLAGS=$(cabal_flag gui) +# leads to "--flags=gui" or "--flags=-gui" (useflag 'gui') +# +# CABAL_CONFIGURE_FLAGS=$(cabal_flag gtk gui) +# also leads to "--flags=gui" or " --flags=-gui" (useflag 'gtk') +# +cabal_flag() { + if [[ -z "$1" ]]; then + echo "!!! cabal_flag() called without a parameter." >&2 + echo "!!! cabal_flag() <USEFLAG> [<cabal_flagname>]" >&2 + return 1 + fi + + local UWORD=${2:-$1} + + if use "$1"; then + echo "--flags=${UWORD}" + else + echo "--flags=-${UWORD}" + fi + + return 0 +} + +# @FUNCTION: cabal_chdeps +# @DESCRIPTION: +# Allows easier patching of $CABAL_FILE (${S}/${PN}.cabal by default) +# depends +# +# Accepts argument list as pairs of substitutions: <from-string> <to-string>... +# +# Dies on error. +# +# Usage examples: +# +# src_prepare() { +# cabal_chdeps \ +# 'base >= 4.2 && < 4.6' 'base >= 4.2 && < 4.7' \ +# 'containers ==0.4.*' 'containers >= 0.4 && < 0.6' +#} +# or +# src_prepare() { +# CABAL_FILE=${S}/${MY_PN}.cabal cabal_chdeps \ +# 'base >= 4.2 && < 4.6' 'base >= 4.2 && < 4.7' +# CABAL_FILE=${S}/${MY_PN}-tools.cabal cabal_chdeps \ +# 'base == 3.*' 'base >= 4.2 && < 4.7' +#} +# +cabal_chdeps() { + local cabal_fn=${MY_PN:-${PN}}.cabal + local cf=${CABAL_FILE:-${S}/${cabal_fn}} + local from_ss # ss - substring + local to_ss + local orig_c # c - contents + local new_c + + [[ -f $cf ]] || die "cabal file '$cf' does not exist" + + orig_c=$(< "$cf") + + while :; do + from_pat=$1 + to_str=$2 + + [[ -n ${from_pat} ]] || break + [[ -n ${to_str} ]] || die "'${from_str}' does not have 'to' part" + + einfo "CHDEP: '${from_pat}' -> '${to_str}'" + + # escape pattern-like symbols + from_pat=${from_pat//\*/\\*} + from_pat=${from_pat//\[/\\[} + + new_c=${orig_c//${from_pat}/${to_str}} + + if [[ -n $CABAL_DEBUG_LOOSENING ]]; then + echo "${orig_c}" >"${T}/${cf}".pre + echo "${new_c}" >"${T}/${cf}".post + diff -u "${T}/${cf}".{pre,post} + fi + + [[ "${orig_c}" == "${new_c}" ]] && die "no trigger for '${from_pat}'" + orig_c=${new_c} + shift + shift + done + + echo "${new_c}" > "$cf" || + die "failed to update" +} + +# @FUNCTION: cabal-constraint +# @DESCRIPTION: +# Allowes to set contraint to the libraries that are +# used by specified package +cabal-constraint() { + while read p v ; do + echo "--constraint \"$p == $v\"" + done < $(ghc-pkgdeps ${1}) +} + +# @FUNCTION: replace-hcflags +# @USAGE: <old> <new> +# @DESCRIPTION: +# Replace the <old> flag with <new> in HCFLAGS. Accepts shell globs for <old>. +# The implementation is picked from flag-o-matic.eclass:replace-flags() +replace-hcflags() { + [[ $# != 2 ]] && die "Usage: replace-hcflags <old flag> <new flag>" + + local f new=() + for f in ${HCFLAGS} ; do + # Note this should work with globs like -O* + if [[ ${f} == ${1} ]]; then + einfo "HCFLAGS: replacing '${f}' to '${2}'" + f=${2} + fi + new+=( "${f}" ) + done + export HCFLAGS="${new[*]}" + + return 0 +} diff --git a/eclass/java-ant-2.eclass b/eclass/java-ant-2.eclass new file mode 100644 index 0000000..733d1d1 --- /dev/null +++ b/eclass/java-ant-2.eclass @@ -0,0 +1,431 @@ +# Copyright 2004-2019 Gentoo Authors +# Distributed under the terms of the GNU General Public License v2 + +# @ECLASS: java-ant-2.eclass +# @MAINTAINER: +# java@gentoo.org +# @AUTHOR: +# kiorky (kiorky@cryptelium.net), Petteri Räty (betelgeuse@gentoo.org) +# @BLURB: eclass for ant based Java packages +# @DESCRIPTION: +# Eclass for Ant-based Java packages. Provides support for both automatic and +# manual manipulation of build.xml files. Should be inherited after java-pkg-2 +# or java-pkg-opt-2 eclass. + +inherit java-utils-2 multilib + +# This eclass provides functionality for Java packages which use +# ant to build. In particular, it will attempt to fix build.xml files, so that +# they use the appropriate 'target' and 'source' attributes. + +# @ECLASS-VARIABLE: WANT_ANT_TASKS +# @DEFAULT_UNSET +# @DESCRIPTION: +# An $IFS separated list of ant tasks. +# Ebuild can specify this variable before inheriting java-ant-2 eclass to +# determine ANT_TASKS it needs. They will be automatically translated to +# DEPEND variable and ANT_TASKS variable. JAVA_PKG_FORCE_ANT_TASKS can override +# ANT_TASKS set by WANT_ANT_TASKS, but not the DEPEND due to caching. +# Ebuilds that need to depend conditionally on certain tasks and specify them +# differently for different eant calls can't use this simplified approach. +# You also cannot specify version or anything else than ant-*. +# +# @CODE +# WANT_ANT_TASKS="ant-junit ant-trax" +# @CODE + +#The implementation of dependencies is handled by java-utils-2.eclass +#WANT_ANT_TASKS + +# @ECLASS-VARIABLE: JAVA_ANT_DISABLE_ANT_CORE_DEP +# @DEFAULT_UNSET +# @DESCRIPTION: +# Setting this variable non-empty before inheriting java-ant-2 disables adding +# dev-java/ant-core into DEPEND. +if [[ -z "${JAVA_ANT_DISABLE_ANT_CORE_DEP}" ]]; then + JAVA_ANT_E_DEPEND+=" >=dev-java/ant-core-1.8.2" + [[ "${EAPI:-0}" != 0 ]] && JAVA_ANT_E_DEPEND+=":0" +fi + +# add ant tasks specified in WANT_ANT_TASKS to DEPEND +local ANT_TASKS_DEPEND; +ANT_TASKS_DEPEND="$(java-pkg_ant-tasks-depend)" +# check that java-pkg_ant-tasks-depend didn't fail +if [[ $? != 0 ]]; then + eerror "${ANT_TASKS_DEPEND}" + die "java-pkg_ant-tasks-depend() failed" +fi + +# We need some tools from javatoolkit. We also need ant dependencies +# constructed above. +JAVA_ANT_E_DEPEND="${JAVA_ANT_E_DEPEND} + ${ANT_TASKS_DEPEND} + >=dev-java/javatoolkit-0.3.0-r2" + +# this eclass must be inherited after java-pkg-2 or java-pkg-opt-2 +# if it's java-pkg-opt-2, ant dependencies are pulled based on USE flag +if has java-pkg-opt-2 ${INHERITED}; then + JAVA_ANT_E_DEPEND="${JAVA_PKG_OPT_USE}? ( ${JAVA_ANT_E_DEPEND} )" +elif ! has java-pkg-2 ${INHERITED}; then + eerror "java-ant-2 eclass can only be inherited AFTER java-pkg-2 or java-pkg-opt-2" +fi + +DEPEND="${JAVA_ANT_E_DEPEND}" + +# @ECLASS-VARIABLE: JAVA_PKG_BSFIX +# @DESCRIPTION: +# Should we attempt to 'fix' ant build files to include the source/target +# attributes when calling javac? +JAVA_PKG_BSFIX=${JAVA_PKG_BSFIX:-"on"} + +# @ECLASS-VARIABLE: JAVA_PKG_BSFIX_ALL +# @DESCRIPTION: +# If we're fixing build files, should we try to fix all the ones we can find? +JAVA_PKG_BSFIX_ALL=${JAVA_PKG_BSFIX_ALL:-"yes"} + +# @ECLASS-VARIABLE: JAVA_PKG_BSFIX_NAME +# @DESCRIPTION: +# Filename of build files to fix/search for +JAVA_PKG_BSFIX_NAME=${JAVA_PKG_BSFIX_NAME:-"build.xml"} + +# @ECLASS-VARIABLE: JAVA_PKG_BSFIX_TARGET_TAGS +# @DESCRIPTION: +# Targets to fix the 'source' attribute in +JAVA_PKG_BSFIX_TARGET_TAGS=${JAVA_PKG_BSFIX_TARGET_TAGS:-"javac xjavac javac.preset"} + +# @ECLASS-VARIABLE: JAVA_PKG_BSFIX_SOURCE_TAGS +# @DESCRIPTION: +# Targets to fix the 'target' attribute in +JAVA_PKG_BSFIX_SOURCE_TAGS=${JAVA_PKG_BSFIX_SOURCE_TAGS:-"javadoc javac xjavac javac.preset"} + +# @ECLASS-VARIABLE: JAVA_ANT_CLASSPATH_TAGS +# @DESCRIPTION: +# Targets to add the classpath attribute to +JAVA_ANT_CLASSPATH_TAGS="javac xjavac" + +# @ECLASS-VARIABLE: JAVA_ANT_IGNORE_SYSTEM_CLASSES +# @DEFAULT_UNSET +# @DESCRIPTION: +# When set, <available> Ant tasks are rewritten to ignore Ant's runtime classpath. + +case "${EAPI:-0}" in + 0|1) : ;; + *) EXPORT_FUNCTIONS src_configure ;; +esac + +# @FUNCTION: java-ant-2_src_configure +# @DESCRIPTION: +# src_configure rewrites the build.xml files automatically, unless EAPI is undefined, 0 or 1. +java-ant-2_src_configure() { + # if java support is optional, don't perform this when the USE flag is off + if has java-pkg-opt-2 ${INHERITED}; then + use ${JAVA_PKG_OPT_USE} || return + fi + + # eant will call us unless called by Portage + [[ -e "${T}/java-ant-2_src_configure-run" ]] && return + + [[ "${JAVA_ANT_IGNORE_SYSTEM_CLASSES}" ]] \ + && java-ant_ignore-system-classes "${S}/build.xml" + + java-ant_bsfix + touch "${T}/java-ant-2_src_configure-run" +} + +# @FUNCTION: java-ant_bsfix +# @INTERNAL +# @DESCRIPTION: +# Attempts to fix build files. +# +# @CODE +# Affected by variables: +# JAVA_PKG_BSFIX +# JAVA_PKG_BSFIX_ALL +# JAVA_PKG_BSFIX_NAME, +# @CODE +java-ant_bsfix() { + debug-print-function ${FUNCNAME} $* + + [[ "${JAVA_PKG_BSFIX}" != "on" ]] && return + if ! java-pkg_needs-vm; then + echo "QA Notice: Package is using java-ant, but doesn't depend on a Java VM" + fi + + pushd "${S}" >/dev/null || die + + local find_args="" + [[ "${JAVA_PKG_BSFIX_ALL}" == "yes" ]] || find_args="-maxdepth 1" + + find_args="${find_args} -type f ( -name ${JAVA_PKG_BSFIX_NAME// / -o -name } )" + + local bsfix_these=() line + while IFS= read -r -d $'\0' line; do + bsfix_these+=( "${line}" ) + done < <(find . ${find_args} -print0) + + [[ "${bsfix_these[@]}" ]] && java-ant_bsfix_files "${bsfix_these[@]}" + + popd > /dev/null || die +} + +# @FUNCTION: java-ant_bsfix_files +# @USAGE: <path/to/first/build.xml> [path/to/second.build.xml ...] +# @DESCRIPTION: +# Attempts to fix named build files. +# +# @CODE +# Affected by variables: +# JAVA_PKG_BSFIX_SOURCE_TAGS +# JAVA_PKG_BSFIX_TARGET_TAGS +# JAVA_ANT_REWRITE_CLASSPATH +# JAVA_ANT_JAVADOC_INPUT_DIRS: Where we can find java sources for javadoc +# input. Can be a space separated list of +# directories +# JAVA_ANT_BSFIX_EXTRA_ARGS: You can use this to pass extra variables to the +# rewriter if you know what you are doing. +# @CODE +# +# If JAVA_ANT_JAVADOC_INPUT_DIRS is set, we will turn on the adding of a basic +# javadoc target to the ant's build.xml with the javadoc xml-rewriter feature. +# Then we will set EANT DOC TARGET to the added javadoc target +# NOTE: the variable JAVA_ANT_JAVADOC_OUTPUT_DIR points where we will +# generate the javadocs. This is a read-only variable, dont change it. + +# When changing this function, make sure that it works with paths with spaces in +# them. +java-ant_bsfix_files() { + debug-print-function ${FUNCNAME} $* + + [[ ${#} = 0 ]] && die "${FUNCNAME} called without arguments" + + local want_source="$(java-pkg_get-source)" + local want_target="$(java-pkg_get-target)" + + debug-print "${FUNCNAME}: target: ${want_target} source: ${want_source}" + + if [ -z "${want_source}" -o -z "${want_target}" ]; then + eerror "Could not find valid -source/-target values" + eerror "Please file a bug about this on bugs.gentoo.org" + die "Could not find valid -source/-target values" + else + local files=() + + for file in "${@}"; do + debug-print "${FUNCNAME}: ${file}" + + if [[ -n "${JAVA_PKG_DEBUG}" ]]; then + cp "${file}" "${file}.orig" || die "failed to copy ${file}" + fi + + if [[ ! -w "${file}" ]]; then + chmod u+w "${file}" || die "chmod u+w ${file} failed" + fi + + files+=( -f "${file}" ) + done + + if [ -e "${EPREFIX}/usr/libexec/javatoolkit" ]; then + local rewriter3="${EPREFIX}/usr/libexec/javatoolkit/xml-rewrite-3.py" + local rewriter4="${EPREFIX}/usr/libexec/javatoolkit/build-xml-rewrite" + else + local rewriter3="${EPREFIX}/usr/$(get_libdir)/javatoolkit/bin/xml-rewrite-3.py" + local rewriter4="${EPREFIX}/usr/$(get_libdir)/javatoolkit/bin/build-xml-rewrite" + fi + + if [[ -x ${rewriter4} && ${JAVA_ANT_ENCODING} ]]; then + [[ ${JAVA_ANT_REWRITE_CLASSPATH} ]] && local gcp="-g" + [[ ${JAVA_ANT_ENCODING} ]] && local enc="-e ${JAVA_ANT_ENCODING}" + echo "cElementTree rewriter" + debug-print "${rewriter4} extra args: ${gcp} ${enc}" + ${rewriter4} ${gcp} ${enc} \ + -c "${JAVA_PKG_BSFIX_SOURCE_TAGS}" source ${want_source} \ + -c "${JAVA_PKG_BSFIX_TARGET_TAGS}" target ${want_target} \ + "${@}" || die "build-xml-rewrite failed" + else + debug-print "Using third generation rewriter" + echo "Rewriting attributes" + local bsfix_extra_args=() + # WARNING KEEP THE ORDER, ESPECIALLY FOR CHANGED ATTRIBUTES! + if [[ -n ${JAVA_ANT_REWRITE_CLASSPATH} ]]; then + local cp_tags="${JAVA_ANT_CLASSPATH_TAGS// / -e }" + bsfix_extra_args+=( -g -e ${cp_tags} ) + bsfix_extra_args+=( -a classpath -v '${gentoo.classpath}' ) + fi + if [[ -n ${JAVA_ANT_JAVADOC_INPUT_DIRS} ]]; then + if [[ -n ${JAVA_ANT_JAVADOC_OUTPUT_DIR} ]]; then + die "Do not define JAVA_ANT_JAVADOC_OUTPUT_DIR!" + fi + # Where will our generated javadoc go. + readonly JAVA_ANT_JAVADOC_OUTPUT_DIR="${WORKDIR}/gentoo_javadoc" + mkdir -p "${JAVA_ANT_JAVADOC_OUTPUT_DIR}" || die + + if has doc ${IUSE}; then + if use doc; then + if [[ -z ${EANT_DOC_TARGET} ]]; then + EANT_DOC_TARGET="gentoojavadoc" + else + die "You can't use javadoc adding and set EANT_DOC_TARGET too." + fi + + for dir in ${JAVA_ANT_JAVADOC_INPUT_DIRS};do + if [[ ! -d ${dir} ]]; then + eerror "This dir: ${dir} doesnt' exists" + die "You must specify directories for javadoc input/output dirs." + fi + done + bsfix_extra_args+=( --javadoc --source-directory ) + # filter third/double spaces + JAVA_ANT_JAVADOC_INPUT_DIRS=${JAVA_ANT_JAVADOC_INPUT_DIRS// /} + JAVA_ANT_JAVADOC_INPUT_DIRS=${JAVA_ANT_JAVADOC_INPUT_DIRS// /} + bsfix_extra_args+=( ${JAVA_ANT_JAVADOC_INPUT_DIRS// / --source-directory } ) + bsfix_extra_args+=( --output-directory "${JAVA_ANT_JAVADOC_OUTPUT_DIR}" ) + fi + else + die "You need to have doc in IUSE when using JAVA_ANT_JAVADOC_INPUT_DIRS" + fi + fi + + [[ -n ${JAVA_ANT_BSFIX_EXTRA_ARGS} ]] \ + && bsfix_extra_args+=( ${JAVA_ANT_BSFIX_EXTRA_ARGS} ) + + debug-print "bsfix_extra_args: ${bsfix_extra_args[*]}" + + ${rewriter3} "${files[@]}" \ + -c --source-element ${JAVA_PKG_BSFIX_SOURCE_TAGS// / --source-element } \ + --source-attribute source --source-value ${want_source} \ + --target-element ${JAVA_PKG_BSFIX_TARGET_TAGS// / --target-element } \ + --target-attribute target --target-value ${want_target} \ + --target-attribute nowarn --target-value yes \ + "${bsfix_extra_args[@]}" \ + || die "xml-rewrite-3 failed: ${file}" + fi + + if [[ -n "${JAVA_PKG_DEBUG}" ]]; then + for file in "${@}"; do + diff -NurbB "${file}.orig" "${file}" + done + fi + fi + return 0 # so that the 1 for diff doesn't get reported +} + + +# @FUNCTION: java-ant_bsfix_one +# @USAGE: <path/to/build.xml> +# @DESCRIPTION: +# Attempts to fix named build file. +# +# @CODE +# Affected by variables: +# JAVA_PKG_BSFIX_SOURCE_TAGS +# JAVA_PKG_BSFIX_TARGET_TAGS +# @CODE +java-ant_bsfix_one() { + debug-print-function ${FUNCNAME} $* + + if [ -z "${1}" ]; then + eerror "${FUNCNAME} needs one argument" + die "${FUNCNAME} needs one argument" + fi + + java-ant_bsfix_files "${1}" +} + +# @FUNCTION: java-ant_rewrite-classpath +# @USAGE: [path/to/build.xml] +# @DESCRIPTION: +# Adds 'classpath="${gentoo.classpath}"' to specified build file. +# +# Affected by: +# JAVA_ANT_CLASSPATH_TAGS +# +# Parameter defaults to build.xml when not specified +java-ant_rewrite-classpath() { + debug-print-function ${FUNCNAME} $* + + local file="${1}" + [[ -z "${1}" ]] && file=build.xml + [[ ${#} -gt 1 ]] && die "${FUNCNAME} currently can only rewrite one file." + + echo "Adding gentoo.classpath to ${file}" + debug-print "java-ant_rewrite-classpath: ${file}" + + cp "${file}" "${file}.orig" || die "failed to copy ${file}" + + chmod u+w "${file}" + + java-ant_xml-rewrite -f "${file}" --change \ + -e ${JAVA_ANT_CLASSPATH_TAGS// / -e } -a classpath -v '${gentoo.classpath}' + + if [[ -n "${JAVA_PKG_DEBUG}" ]]; then + diff -NurbB "${file}.orig" "${file}" + fi +} + +# @FUNCTION: java-ant_ignore-system-classes +# @USAGE: [path/to/build.xml] +# @DESCRIPTION: +# Makes the available task ignore classes in the system classpath +# Parameter defaults to build.xml when not specified +java-ant_ignore-system-classes() { + debug-print-function ${FUNCNAME} $* + local file=${1:-build.xml} + echo "Changing ignoresystemclasses to true for available tasks in ${file}" + java-ant_xml-rewrite -f "${file}" --change \ + -e available -a ignoresystemclasses -v "true" +} + +# @FUNCTION: java-ant_xml-rewrite +# @USAGE: <xml rewriter arguments> +# @DESCRIPTION: +# Run the right xml-rewrite binary with the given arguments +java-ant_xml-rewrite() { + local gen2_1="${EPREFIX}/usr/$(get_libdir)/javatoolkit/bin/xml-rewrite-2.py" + local gen2_2="${EPREFIX}/usr/libexec/javatoolkit/xml-rewrite-2.py" + # gen1 is deprecated + if [[ -x "${gen2_2}" ]]; then + ${gen2_2} "${@}" || die "${gen2_2} failed" + elif [[ -x "${gen2_1}" ]]; then + ${gen2_1} "${@}" || die "${gen2_1} failed" + else + eerror "No binary for rewriting found." + eerror "Do you have dev-java/javatoolkit installed?" + die "xml-rewrite not found" + fi +} + +# @FUNCTION: java-ant_rewrite-bootclasspath +# @USAGE: <version> [path/to/build.xml] [prepend] [append] +# @DESCRIPTION: +# Adds bootclasspath to javac-like tasks in build.xml filled with jars of a +# bootclasspath package of given version. +# +# @CODE +# Affected by: +# JAVA_PKG_BSFIX_TARGET_TAGS - the tags of javac tasks +# +# Parameters: +# $1 - the version of bootclasspath (e.g. 1.5), 'auto' for bootclasspath +# of the current JDK +# $2 - path to desired build.xml file, defaults to 'build.xml' +# $3 - (optional) what to prepend the bootclasspath with (to override) +# $4 - (optional) what to append to the bootclasspath +# @CODE +java-ant_rewrite-bootclasspath() { + local version="${1}" + local file="${2-build.xml}" + local extra_before="${3}" + local extra_after="${4}" + + local bcp="$(java-pkg_get-bootclasspath "${version}")" + + if [[ -n "${extra_before}" ]]; then + bcp="${extra_before}:${bcp}" + fi + if [[ -n "${extra_after}" ]]; then + bcp="${bcp}:${extra_after}" + fi + + java-ant_xml-rewrite -f "${file}" -c -e ${JAVA_PKG_BSFIX_TARGET_TAGS// / -e } \ + -a bootclasspath -v "${bcp}" +} diff --git a/eclass/java-osgi.eclass b/eclass/java-osgi.eclass new file mode 100644 index 0000000..bb8c1d8 --- /dev/null +++ b/eclass/java-osgi.eclass @@ -0,0 +1,277 @@ +# Copyright 2007-2015 Gentoo Foundation +# Distributed under the terms of the GNU General Public License v2 + +# @ECLASS: java-osgi.eclass +# @MAINTAINER: +# java@gentoo.org +# @AUTHOR: +# Java maintainers (java@gentoo.org) +# @BLURB: Java OSGi eclass +# @DESCRIPTION: +# This eclass provides functionality which is used by packages that need to be +# OSGi compliant. This means that the generated jars will have special headers +# in their manifests. Currently this is used only by Eclipse-3.3 - later we +# could extend this so that Gentoo Java system would be fully OSGi compliant. + +inherit java-utils-2 + +# @ECLASS-VARIABLE: _OSGI_T +# @INTERNAL +# @DESCRIPTION: +# We define _OSGI_T so that it does not contain a slash at the end. +# According to Paludis guys, there is currently a proposal for EAPIs that +# would require all variables to end with a slash. +_OSGI_T="${T/%\//}" + +# must get Diego to commit something like this to portability.eclass +_canonicalise() { + if type -p realpath > /dev/null; then + realpath "${@}" + elif type -p readlink > /dev/null; then + readlink -f "${@}" + else + # can't die, subshell + eerror "No readlink nor realpath found, cannot canonicalise" + fi +} + +# @FUNCTION: _java-osgi_plugin +# @USAGE: <plugin name> +# @INTERNAL +# @DESCRIPTION: +# This is an internal function, not to be called directly. +# +# @CODE +# _java-osgi_plugin "JSch" +# @CODE +# +# @param $1 - bundle name +_java-osgi_plugin() { + # We hardcode Gentoo as the vendor name + + cat > "${_OSGI_T}/tmp_jar/plugin.properties" <<-EOF + bundleName="${1}" + vendorName="Gentoo" + EOF +} + +# @FUNCTION: _java-osgi_makejar +# @USAGE: <jar name> <symbolic name> <bundle name> <header name> +# @INTERNAL +# @DESCRIPTION: +# This is an internal function, not to be called directly. +# +# @CODE +# _java-osgi_makejar "dist/${PN}.jar" "com.jcraft.jsch" "JSch" "com.jcraft.jsch, com.jcraft.jsch.jce;x-internal:=true" +# @CODE +# +# @param $1 - name of jar to repackage with OSGi +# @param $2 - bundle symbolic name +# @param $3 - bundle name +# @param $4 - export-package header +_java-osgi_makejar() { + debug-print-function ${FUNCNAME} "$@" + + (( ${#} < 4 )) && die "Four arguments are needed for _java-osgi_makejar()" + + local absoluteJarPath="$(_canonicalise ${1})" + local jarName="$(basename ${1})" + + mkdir "${_OSGI_T}/tmp_jar" || die "Unable to create directory ${_OSGI_T}/tmp_jar" + [[ -d "${_OSGI_T}/osgi" ]] || mkdir "${_OSGI_T}/osgi" || die "Unable to create directory ${_OSGI_T}/osgi" + + cd "${_OSGI_T}/tmp_jar" && jar xf "${absoluteJarPath}" && cd - > /dev/null \ + || die "Unable to uncompress correctly the original jar" + + cat > "${_OSGI_T}/tmp_jar/META-INF/MANIFEST.MF" <<-EOF + Manifest-Version: 1.0 + Bundle-ManifestVersion: 2 + Bundle-Name: %bundleName + Bundle-Vendor: %vendorName + Bundle-Localization: plugin + Bundle-SymbolicName: ${2} + Bundle-Version: ${PV} + Export-Package: ${4} + EOF + + _java-osgi_plugin "${3}" + + jar cfm "${_OSGI_T}/osgi/${jarName}" "${_OSGI_T}/tmp_jar/META-INF/MANIFEST.MF" \ + -C "${_OSGI_T}/tmp_jar/" . > /dev/null || die "Unable to recreate the OSGi compliant jar" + rm -rf "${_OSGI_T}/tmp_jar" +} + +# @FUNCTION: @java-osgi_dojar +# @USAGE: <jar name> <symbolic name> <bundle name> <header name> +# @DESCRIPTION: +# Rewrites a jar, and produce an OSGi compliant jar from arguments given on the command line. +# The arguments given correspond to the minimal set of headers +# that must be present on a Manifest file of an OSGi package. +# If you need more headers, you should use the *-fromfile functions below, +# that create the Manifest from a file. +# It will call java-pkg_dojar at the end. +# +# @CODE +# java-osgi_dojar "dist/${PN}.jar" "com.jcraft.jsch" "JSch" "com.jcraft.jsch, com.jcraft.jsch.jce;x-internal:=true" +# @CODE +# +# @param $1 - name of jar to repackage with OSGi +# @param $2 - bundle symbolic name +# @param $3 - bundle name +# @param $4 - export-package-header +java-osgi_dojar() { + debug-print-function ${FUNCNAME} "$@" + local jarName="$(basename ${1})" + _java-osgi_makejar "$@" + java-pkg_dojar "${_OSGI_T}/osgi/${jarName}" +} + +# @FUNCTION: java-osgi_newjar +# @USAGE: <jar name> <symbolic name> <bundle name> <header name> +# @DESCRIPTION: +# Rewrites a jar, and produce an OSGi compliant jar. +# The arguments given correspond to the minimal set of headers +# that must be present on a Manifest file of an OSGi package. +# If you need more headers, you should use the *-fromfile functions below, +# that create the Manifest from a file. +# It will call java-pkg_newjar at the end. +# +# @CODE +# java-osgi_newjar "dist/${PN}.jar" "com.jcraft.jsch" "JSch" "com.jcraft.jsch, com.jcraft.jsch.jce;x-internal:=true" +# @CODE +# +# @param $1 - name of jar to repackage with OSGi +# @param $2 (optional) - name of the target jar. It will default to package name if not specified. +# @param $3 - bundle symbolic name +# @param $4 - bundle name +# @param $5 - export-package header +java-osgi_newjar() { + debug-print-function ${FUNCNAME} "$@" + local jarName="$(basename $1)" + + if (( ${#} > 4 )); then + _java-osgi_makejar "${1}" "${3}" "${4}" "${5}" + java-pkg_newjar "${_OSGI_T}/osgi/${jarName}" "${2}" + else + _java-osgi_makejar "$@" + java-pkg_newjar "${_OSGI_T}/osgi/${jarName}" + fi +} + +# @FUNCTION:_java-osgi_makejar-fromfile +# @USAGE: <jar to repackage with OSGi> <Manifest file> <bundle name> <version rewriting> +# @INTERNAL +# @DESCRIPTION: +# This is an internal function, not to be called directly. +# +# @CODE +# _java-osgi_makejar-fromfile "dist/${PN}.jar" "${FILESDIR}/MANIFEST.MF" "JSch" 1 +# @CODE +# +# @param $1 - name of jar to repackage with OSGi +# @param $2 - path to the Manifest file +# @param $3 - bundle name +# @param $4 - automatic version rewriting (0 or 1) +_java-osgi_makejar-fromfile() { + debug-print-function ${FUNCNAME} "$@" + + ((${#} < 4)) && die "Four arguments are needed for _java-osgi_makejar-fromfile()" + + local absoluteJarPath="$(_canonicalise ${1})" + local jarName="$(basename ${1})" + + mkdir "${_OSGI_T}/tmp_jar" || die "Unable to create directory ${_OSGI_T}/tmp_jar" + [[ -d "${_OSGI_T}/osgi" ]] || mkdir "${_OSGI_T}/osgi" || die "Unable to create directory ${_OSGI_T}/osgi" + + cd "${_OSGI_T}/tmp_jar" && jar xf "${absoluteJarPath}" && cd - > /dev/null \ + || die "Unable to uncompress correctly the original jar" + + [[ -e "${2}" ]] || die "Manifest file ${2} not found" + + # We automatically change the version if automatic version rewriting is on + + if (( ${4} )); then + cat "${2}" | sed "s/Bundle-Version:.*/Bundle-Version: ${PV}/" > \ + "${_OSGI_T}/tmp_jar/META-INF/MANIFEST.MF" + else + cat "${2}" > "${_OSGI_T}/tmp_jar/META-INF/MANIFEST.MF" + fi + + _java-osgi_plugin "${3}" + + jar cfm "${_OSGI_T}/osgi/${jarName}" "${_OSGI_T}/tmp_jar/META-INF/MANIFEST.MF" \ + -C "${_OSGI_T}/tmp_jar/" . > /dev/null || die "Unable to recreate the OSGi compliant jar" + rm -rf "${_OSGI_T}/tmp_jar" +} + +# @FUNCTION: java-osgi_newjar-fromfile +# @USAGE: <jar to repackage with OSGi> <Manifest file> <bundle name> <version rewriting> +# @DESCRIPTION: +# This function produces an OSGi compliant jar from a given manifest file. +# The Manifest Bundle-Version header will be replaced by the current version +# of the package, unless the --no-auto-version option is given. +# It will call java-pkg_newjar at the end. +# +# @CODE +# java-osgi_newjar-fromfile "dist/${PN}.jar" "${FILESDIR}/MANIFEST.MF" "Standard Widget Toolkit for GTK 2.0" +# @CODE +# +# @param $opt +# --no-auto-version - This option disables automatic rewriting of the +# version in the Manifest file +# +# @param $1 - name of jar to repackage with OSGi +# @param $2 (optional) - name of the target jar. It will default to package name if not specified. +# @param $3 - path to the Manifest file +# @param $4 - bundle name +java-osgi_newjar-fromfile() { + debug-print-function ${FUNCNAME} "$@" + local versionRewriting=1 + + if [[ "${1}" == "--no-auto-version" ]]; then + versionRewriting=0 + shift + fi + local jarName="$(basename ${1})" + + if (( ${#} > 3 )); then + _java-osgi_makejar-fromfile "${1}" "${3}" "${4}" "${versionRewriting}" + java-pkg_newjar "${_OSGI_T}/osgi/${jarName}" "${2}" + else + _java-osgi_makejar-fromfile "$@" "${versionRewriting}" + java-pkg_newjar "${_OSGI_T}/osgi/${jarName}" + fi +} + +# @FUNCTION: java-osgi_dojar-fromfile +# @USAGE: <jar to repackage with OSGi> <Manifest file> <bundle name> +# @DESCRIPTION: +# This function produces an OSGi compliant jar from a given manifestfile. +# The Manifest Bundle-Version header will be replaced by the current version +# of the package, unless the --no-auto-version option is given. +# It will call java-pkg_dojar at the end. +# +# @CODE +# java-osgi_dojar-fromfile "dist/${PN}.jar" "${FILESDIR}/MANIFEST.MF" "Standard Widget Toolkit for GTK 2.0" +# @CODE +# +# @param $opt +# --no-auto-version - This option disables automatic rewriting of the +# version in the Manifest file +# +# @param $1 - name of jar to repackage with OSGi +# @param $2 - path to the Manifest file +# @param $3 - bundle name +java-osgi_dojar-fromfile() { + debug-print-function ${FUNCNAME} "$@" + local versionRewriting=1 + + if [[ "${1}" == "--no-auto-version" ]]; then + versionRewriting=0 + shift + fi + local jarName="$(basename ${1})" + + _java-osgi_makejar-fromfile "$@" "${versionRewriting}" + java-pkg_dojar "${_OSGI_T}/osgi/${jarName}" +} diff --git a/eclass/java-pkg-2.eclass b/eclass/java-pkg-2.eclass new file mode 100644 index 0000000..bd5e92d --- /dev/null +++ b/eclass/java-pkg-2.eclass @@ -0,0 +1,155 @@ +# Copyright 2004-2015 Gentoo Foundation +# Distributed under the terms of the GNU General Public License v2 + +# @ECLASS: java-pkg-2.eclass +# @MAINTAINER: +# java@gentoo.org +# @AUTHOR: +# Thomas Matthijs <axxo@gentoo.org> +# @BLURB: Eclass for Java Packages +# @DESCRIPTION: +# This eclass should be inherited for pure Java packages, or by packages which +# need to use Java. + +inherit java-utils-2 + +# @ECLASS-VARIABLE: JAVA_PKG_IUSE +# @DEFAULT_UNSET +# @DESCRIPTION: +# Use JAVA_PKG_IUSE instead of IUSE for doc, source and examples so that +# the eclass can automatically add the needed dependencies for the java-pkg_do* +# functions. +IUSE="${JAVA_PKG_IUSE}" + +# Java packages need java-config, and a fairly new release of Portage. +# JAVA_PKG_E_DEPEND is defined in java-utils.eclass. +DEPEND="${JAVA_PKG_E_DEPEND}" + +# Nothing special for RDEPEND... just the same as DEPEND. +RDEPEND="${DEPEND}" + +# Commons packages follow the same rules so do it here +if [[ ${CATEGORY} = dev-java && ${PN} = commons-* ]]; then + HOMEPAGE="http://commons.apache.org/${PN#commons-}/" + SRC_URI="mirror://apache/${PN/-///}/source/${P}-src.tar.gz" +fi + +case "${EAPI:-0}" in + 0|1) EXPORT_FUNCTIONS pkg_setup src_compile pkg_preinst ;; + *) EXPORT_FUNCTIONS pkg_setup src_prepare src_compile pkg_preinst ;; +esac + +# @FUNCTION: java-pkg-2_pkg_setup +# @DESCRIPTION: +# pkg_setup initializes the Java environment + +java-pkg-2_pkg_setup() { + java-pkg_init +} + + +# @FUNCTION: java-pkg-2_src_prepare +# @DESCRIPTION: +# wrapper for java-utils-2_src_prepare + +java-pkg-2_src_prepare() { + java-utils-2_src_prepare +} + + +# @FUNCTION: java-pkg-2_src_compile +# @DESCRIPTION: +# Default src_compile for java packages +# +# @CODE +# Variables: +# EANT_BUILD_XML - controls the location of the build.xml (default: ./build.xml) +# EANT_FILTER_COMPILER - Calls java-pkg_filter-compiler with the value +# EANT_BUILD_TARGET - the ant target/targets to execute (default: jar) +# EANT_DOC_TARGET - the target to build extra docs under the doc use flag +# (default: javadoc; declare empty to disable completely) +# EANT_GENTOO_CLASSPATH - @see eant documention in java-utils-2.eclass +# EANT_EXTRA_ARGS - extra arguments to pass to eant +# EANT_ANT_TASKS - modifies the ANT_TASKS variable in the eant environment +# @CODE + +java-pkg-2_src_compile() { + if [[ -e "${EANT_BUILD_XML:=build.xml}" ]]; then + # auto generate classpath + java-pkg_gen-cp EANT_GENTOO_CLASSPATH + + [[ "${EANT_FILTER_COMPILER}" ]] && \ + java-pkg_filter-compiler ${EANT_FILTER_COMPILER} + local antflags="${EANT_BUILD_TARGET:=jar}" + if has doc ${IUSE} && [[ -n "${EANT_DOC_TARGET=javadoc}" ]]; then + antflags="${antflags} $(use_doc ${EANT_DOC_TARGET})" + fi + local tasks + [[ ${EANT_ANT_TASKS} ]] && tasks="${ANT_TASKS} ${EANT_ANT_TASKS}" + ANT_TASKS="${tasks:-${ANT_TASKS}}" \ + eant ${antflags} -f "${EANT_BUILD_XML}" ${EANT_EXTRA_ARGS} "${@}" + else + echo "${FUNCNAME}: ${EANT_BUILD_XML} not found so nothing to do." + fi +} + +# @FUNCTION: java-pkg-2_src_test +# @DESCRIPTION: +# src_test, not exported. + +java-pkg-2_src_test() { + [[ -e "${EANT_BUILD_XML:=build.xml}" ]] || return + + if [[ ${EANT_TEST_TARGET} ]] || < "${EANT_BUILD_XML}" tr -d "\n" | grep -Eq "<target\b[^>]*\bname=[\"']test[\"']"; then + local opts task_re junit_re pkg + + if [[ ${EANT_TEST_JUNIT_INTO} ]]; then + java-pkg_jar-from --into "${EANT_TEST_JUNIT_INTO}" junit + fi + + if [[ ${EANT_TEST_GENTOO_CLASSPATH} ]]; then + EANT_GENTOO_CLASSPATH="${EANT_TEST_GENTOO_CLASSPATH}" + fi + + ANT_TASKS=${EANT_TEST_ANT_TASKS:-${ANT_TASKS:-${EANT_ANT_TASKS}}} + + task_re="\bdev-java/ant-junit(4)?(-[^:]+)?(:\S+)\b" + junit_re="\bdev-java/junit(-[^:]+)?(:\S+)\b" + + if [[ ${DEPEND} =~ ${task_re} ]]; then + pkg="ant-junit${BASH_REMATCH[1]}${BASH_REMATCH[3]}" + pkg="${pkg%:0}" + + if [[ ${ANT_TASKS} && "${ANT_TASKS}" != none ]]; then + ANT_TASKS="${ANT_TASKS} ${pkg}" + else + ANT_TASKS="${pkg}" + fi + elif [[ ${DEPEND} =~ ${junit_re} ]]; then + pkg="junit${BASH_REMATCH[2]}" + pkg="${pkg%:0}" + + opts="-Djunit.jar=\"$(java-pkg_getjar ${pkg} junit.jar)\"" + + if [[ ${EANT_GENTOO_CLASSPATH} ]]; then + EANT_GENTOO_CLASSPATH+=",${pkg}" + else + EANT_GENTOO_CLASSPATH="${pkg}" + fi + fi + + eant ${opts} -f "${EANT_BUILD_XML}" \ + ${EANT_EXTRA_ARGS} ${EANT_TEST_EXTRA_ARGS} ${EANT_TEST_TARGET:-test} + + else + echo "${FUNCNAME}: No test target in ${EANT_BUILD_XML}" + fi +} + +# @FUNCTION: java-pkg-2_pkg_preinst +# @DESCRIPTION: +# wrapper for java-utils-2_pkg_preinst + +java-pkg-2_pkg_preinst() { + java-utils-2_pkg_preinst +} diff --git a/eclass/java-pkg-opt-2.eclass b/eclass/java-pkg-opt-2.eclass new file mode 100644 index 0000000..fa72421 --- /dev/null +++ b/eclass/java-pkg-opt-2.eclass @@ -0,0 +1,60 @@ +# Copyright 2004-2015 Gentoo Foundation +# Distributed under the terms of the GNU General Public License v2 + +# @ECLASS: java-pkg-opt-2.eclass +# @MAINTAINER: +# java@gentoo.org +# @AUTHOR: +# Thomas Matthijs <axxo@gentoo.org> +# @BLURB: Eclass for package with optional Java support +# @DESCRIPTION: +# Inherit this eclass instead of java-pkg-2 if you only need optional Java +# support. + +inherit java-utils-2 + +# @ECLASS-VARIABLE: JAVA_PKG_OPT_USE +# @DESCRIPTION: +# USE flag to control if optional Java stuff is build. Defaults to 'java'. +JAVA_PKG_OPT_USE=${JAVA_PKG_OPT_USE:-java} + +DEPEND="${JAVA_PKG_OPT_USE}? ( ${JAVA_PKG_E_DEPEND} )" +RDEPEND="${DEPEND}" + +# See java-pkg-2.eclass for JAVA_PKG_IUSE documentation +IUSE="${JAVA_PKG_IUSE} ${JAVA_PKG_OPT_USE}" + +case "${EAPI:-0}" in + 0|1) EXPORT_FUNCTIONS pkg_setup pkg_preinst ;; + *) EXPORT_FUNCTIONS pkg_setup src_prepare pkg_preinst ;; +esac + +# @FUNCTION: java-pkg-opt-2_pkg_setup +# @DESCRIPTION: +# default pkg_setup, wrapper for java-utils-2_pkg_init + +java-pkg-opt-2_pkg_setup() { + use ${JAVA_PKG_OPT_USE} && java-pkg_init +} + + +# @FUNCTION: java-pkg-opt-2_src_prepare +# @DESCRIPTION: +# default src_prepare, wrapper for java-utils-2_src_prepare + +java-pkg-opt-2_src_prepare() { + use ${JAVA_PKG_OPT_USE} && java-utils-2_src_prepare + case "${EAPI:-0}" in + [0-5]) ;; + *) use ${JAVA_PKG_OPT_USE} || eapply_user ;; + esac +} + + +# @FUNCTION: java-pkg-opt-2_pkg_preinst +# @DESCRIPTION: +# default pkg_preinst, wrapper for java-utils-2_pkg_preinst + +java-pkg-opt-2_pkg_preinst() { + use ${JAVA_PKG_OPT_USE} && java-utils-2_pkg_preinst +} diff --git a/eclass/java-pkg-simple.eclass b/eclass/java-pkg-simple.eclass new file mode 100644 index 0000000..a1ab0af --- /dev/null +++ b/eclass/java-pkg-simple.eclass @@ -0,0 +1,481 @@ +# Copyright 2004-2020 Gentoo Authors +# Distributed under the terms of the GNU General Public License v2 + +# @ECLASS: java-pkg-simple.eclass +# @MAINTAINER: +# java@gentoo.org +# @AUTHOR: +# Java maintainers (java@gentoo.org) +# @BLURB: Eclass for packaging Java software with ease. +# @DESCRIPTION: +# This class is intended to build pure Java packages from Java sources +# without the use of any build instructions shipped with the sources. +# There is no support for generating source files, or for controlling +# the META-INF of the resulting jar, although these issues may be +# addressed by an ebuild by putting corresponding files into the target +# directory before calling the src_compile function of this eclass. + +inherit java-utils-2 + +if ! has java-pkg-2 ${INHERITED}; then + eerror "java-pkg-simple eclass can only be inherited AFTER java-pkg-2" +fi + +EXPORT_FUNCTIONS src_compile src_install src_test + +# We are only interested in finding all java source files, wherever they may be. +S="${WORKDIR}" + +# handle dependencies for testing frameworks +if has test ${JAVA_PKG_IUSE}; then + local test_deps + for framework in ${JAVA_TESTING_FRAMEWORKS}; do + case ${framework} in + junit) + test_deps+=" dev-java/junit:0";; + junit-4) + test_deps+=" dev-java/junit:4";; + pkgdiff) + test_deps+=" amd64? ( dev-util/pkgdiff + dev-util/japi-compliance-checker )";; + testng) + test_deps+=" dev-java/testng:0";; + esac + done + [[ ${test_deps} ]] && DEPEND="test? ( ${test_deps} )" +fi + +# @ECLASS-VARIABLE: JAVA_GENTOO_CLASSPATH +# @DEFAULT_UNSET +# @DESCRIPTION: +# Comma or space separated list of java packages to include in the +# class path. The packages will also be registered as runtime +# dependencies of this new package. Dependencies will be calculated +# transitively. See "java-config -l" for appropriate package names. +# +# @CODE +# JAVA_GENTOO_CLASSPATH="foo,bar-2" +# @CODE + +# @ECLASS-VARIABLE: JAVA_GENTOO_CLASSPATH_EXTRA +# @DEFAULT_UNSET +# @DESCRIPTION: +# Extra list of colon separated path elements to be put on the +# classpath when compiling sources. + +# @ECLASS-VARIABLE: JAVA_CLASSPATH_EXTRA +# @DEFAULT_UNSET +# @DESCRIPTION: +# An extra comma or space separated list of java packages +# that are needed only during compiling sources. + +# @ECLASS-VARIABLE: JAVA_NEEDS_TOOLS +# @DEFAULT_UNSET +# @DESCRIPTION: +# Add tools.jar to the gentoo.classpath. Should only be used +# for build-time purposes, the dependency is not recorded to +# package.env. + +# @ECLASS-VARIABLE: JAVA_SRC_DIR +# @DEFAULT_UNSET +# @DESCRIPTION: +# An array of directories relative to ${S} which contain the sources +# of the application. If you set ${JAVA_SRC_DIR} to a string it works +# as well. The default value "" means it will get all source files +# inside ${S}. +# For the generated source package (if source is listed in +# ${JAVA_PKG_IUSE}), it is important that these directories are +# actually the roots of the corresponding source trees. +# +# @CODE +# JAVA_SRC_DIR=( "impl/src/main/java/" +# "arquillian/weld-ee-container/src/main/java/" +# ) +# @CODE + +# @DESCRIPTION: +# @ECLASS-VARIABLE: JAVA_RESOURCE_DIRS +# @DEFAULT_UNSET +# @DESCRIPTION: +# An array of directories relative to ${S} which contain the +# resources of the application. If you do not set the variable, +# there will be no resources added to the compiled jar file. +# +# @CODE +# JAVA_RESOURCE_DIRS=("src/java/resources/") +# @CODE + +# @ECLASS-VARIABLE: JAVA_ENCODING +# @DESCRIPTION: +# The character encoding used in the source files. +: ${JAVA_ENCODING:=UTF-8} + +# @ECLASS-VARIABLE: JAVAC_ARGS +# @DEFAULT_UNSET +# @DESCRIPTION: +# Additional arguments to be passed to javac. + +# @ECLASS-VARIABLE: JAVA_MAIN_CLASS +# @DEFAULT_UNSET +# @DESCRIPTION: +# If the java has a main class, you are going to set the +# variable so that we can generate a proper MANIFEST.MF +# and create a launcher. +# +# @CODE +# JAVA_MAIN_CLASS="org.gentoo.java.ebuilder.Main" +# @CODE + +# @ECLASS-VARIABLE: JAVADOC_ARGS +# @DEFAULT_UNSET +# @DESCRIPTION: +# Additional arguments to be passed to javadoc. + +# @ECLASS-VARIABLE: JAVA_JAR_FILENAME +# @DESCRIPTION: +# The name of the jar file to create and install. +: ${JAVA_JAR_FILENAME:=${PN}.jar} + +# @ECLASS-VARIABLE: JAVA_BINJAR_FILENAME +# @DEFAULT_UNSET +# @DESCRIPTION: +# The name of the binary jar file to be installed if +# USE FLAG 'binary' is set. + +# @ECLASS-VARIABLE: JAVA_LAUNCHER_FILENAME +# @DESCRIPTION: +# If ${JAVA_MAIN_CLASS} is set, we will create a launcher to +# execute the jar, and ${JAVA_LAUNCHER_FILENAME} will be the +# name of the script. +: ${JAVA_LAUNCHER_FILENAME:=${PN}-${SLOT}} + +# @ECLASS-VARIABLE: JAVA_TESTING_FRAMEWORKS +# @DEFAULT_UNSET +# @DESCRIPTION: +# A space separated list that defines which tests it should launch +# during src_test. +# +# @CODE +# JAVA_TESTING_FRAMEWORKS="junit pkgdiff" +# @CODE + +# @ECLASS-VARIABLE: JAVA_TEST_EXCLUDES +# @DEFAULT_UNSET +# @DESCRIPTION: +# A array of classes that should not be executed during src_test(). +# +# @CODE +# JAVA_TEST_EXCLUDES=( "net.sf.cglib.CodeGenTestCase" "net.sf.cglib.TestAll" ) +# @CODE + +# @ECLASS-VARIABLE: JAVA_TEST_GENTOO_CLASSPATH +# @DEFAULT_UNSET +# @DESCRIPTION: +# The extra classpath we need while compiling and running the +# source code for testing. + +# @ECLASS-VARIABLE: JAVA_TEST_SRC_DIR +# @DEFAULT_UNSET +# @DESCRIPTION: +# An array of directories relative to ${S} which contain the +# sources for testing. It is almost equivalent to +# ${JAVA_SRC_DIR} in src_test. + +# @ECLASS-VARIABLE: JAVA_TEST_RESOURCE_DIRS +# @DEFAULT_UNSET +# @DESCRIPTION: +# It is almost equivalent to ${JAVA_RESOURCE_DIRS} in src_test. + +# @FUNCTION: java-pkg-simple_getclasspath +# @USAGE: java-pkg-simple_getclasspath +# @INTERNAL +# @DESCRIPTION: +# Get proper ${classpath} from ${JAVA_GENTOO_CLASSPATH_EXTRA}, +# ${JAVA_NEEDS_TOOLS}, ${JAVA_CLASSPATH_EXTRA} and +# ${JAVA_GENTOO_CLASSPATH}. We use it inside +# java-pkg-simple_src_compile and java-pkg-simple_src_test. +# +# Note that the variable "classpath" needs to be defined before +# calling this function. +java-pkg-simple_getclasspath() { + debug-print-function ${FUNCNAME} $* + + local dependency + local deep_jars="--with-dependencies" + local buildonly_jars="--build-only" + + # the extra classes that are not installed by portage + classpath+=":${JAVA_GENTOO_CLASSPATH_EXTRA}" + + # whether we need tools.jar + [[ ${JAVA_NEEDS_TOOLS} ]] && classpath+=":$(java-config --tools)" + + # the extra classes that are installed by portage + for dependency in ${JAVA_CLASSPATH_EXTRA}; do + classpath="${classpath}:$(java-pkg_getjars ${buildonly_jars}\ + ${deep_jars} ${dependency})" + done + + # add test dependencies if USE FLAG 'test' is set + if has test ${JAVA_PKG_IUSE} && use test; then + for dependency in ${JAVA_TEST_GENTOO_CLASSPATH}; do + classpath="${classpath}:$(java-pkg_getjars ${buildonly_jars}\ + ${deep_jars} ${dependency})" + done + fi + + # add the RUNTIME dependencies + for dependency in ${JAVA_GENTOO_CLASSPATH}; do + classpath="${classpath}:$(java-pkg_getjars ${deep_jars} ${dependency})" + done + + # purify classpath + while [[ $classpath = *::* ]]; do classpath="${classpath//::/:}"; done + classpath=${classpath%:} + classpath=${classpath#:} + + debug-print "CLASSPATH=${classpath}" +} + +# @FUNCTION: java-pkg-simple_test_with_pkgdiff_ +# @INTERNAL +# @DESCRIPTION: +# use japi-compliance-checker the ensure the compabitily of \*.class files, +# Besides, use pkgdiff to ensure the compatibility of resources. +java-pkg-simple_test_with_pkgdiff_() { + debug-print-function ${FUNCNAME} $* + + if [[ ! ${ARCH} == "amd64" ]]; then + elog "For architectures other than amd64, "\ + "the pkgdiff test is currently unavailable "\ + "because 'dev-util/japi-compliance-checker "\ + "and 'dev-util/pkgdiff' do not support those architectures." + return + fi + + local report1=${PN}-japi-compliance-checker.html + local report2=${PN}-pkgdiff.html + + # pkgdiff test + if [[ -f "${DISTDIR}/${JAVA_BINJAR_FILENAME}" ]]; then + # pkgdiff cannot deal with symlinks, so this is a workaround + cp "${DISTDIR}/${JAVA_BINJAR_FILENAME}" ./ \ + || die "Cannot copy binjar file to ${S}." + + # japi-compliance-checker + japi-compliance-checker ${JAVA_BINJAR_FILENAME} ${JAVA_JAR_FILENAME}\ + --lib=${PN} -v1 ${PV}-bin -v2 ${PV} -report-path ${report1}\ + --binary\ + || die "japi-compliance-checker returns $?,"\ + "check the report in ${S}/${report1}" + + # ignore META-INF since it does not matter + # ignore classes because japi-compilance checker will take care of it + pkgdiff ${JAVA_BINJAR_FILENAME} ${JAVA_JAR_FILENAME}\ + -vnum1 ${PV}-bin -vnum2 ${PV}\ + -skip-pattern "META-INF|.class$"\ + -name ${PN} -report-path ${report2}\ + || die "pkgdiff returns $?, check the report in ${S}/${report2}" + fi +} + +# @FUNCTION: java-pkg-simple_prepend_resources +# @USAGE: java-pkg-simple_prepend-resources <${classes}> <"${RESOURCE_DIRS[@]}"> +# @INTERNAL +# @DESCRIPTION: +# Copy things under "${JAVA_RESOURCE_DIRS[@]}" or "${JAVA_TEST_RESOURCE_DIRS[@]}" +# to ${classes}, so that `jar` will package resources together with classes. +# +# Note that you need to define a "classes" variable before calling +# this function. +java-pkg-simple_prepend_resources() { + debug-print-function ${FUNCNAME} $* + + local destination="${1}" + shift 1 + + # return if there is no resource dirs defined + [[ "$@" ]] || return + local resources=("${@}") + + # add resources directory to classpath + for resource in "${resources[@]}"; do + cp -rT "${resource:-.}" "${destination}"\ + || die "Could not copy resources from ${resource:-.} to ${destination}" + done +} + +# @FUNCTION: java-pkg-simple_src_compile +# @DESCRIPTION: +# src_compile for simple bare source java packages. Finds all *.java +# sources in ${JAVA_SRC_DIR}, compiles them with the classpath +# calculated from ${JAVA_GENTOO_CLASSPATH}, and packages the resulting +# classes to a single ${JAVA_JAR_FILENAME}. If the file +# target/META-INF/MANIFEST.MF exists, it is used as the manifest of the +# created jar. +# +# If USE FLAG 'binary' exists and is set, it will just copy +# ${JAVA_BINJAR_FILENAME} to ${S} and skip the rest of src_compile. +java-pkg-simple_src_compile() { + local sources=sources.lst classes=target/classes apidoc=target/api + + # auto generate classpath + java-pkg_gen-cp JAVA_GENTOO_CLASSPATH + + # do not compile if we decide to install binary jar + if has binary ${JAVA_PKG_IUSE} && use binary; then + # register the runtime dependencies + for dependency in ${JAVA_GENTOO_CLASSPATH//,/ }; do + java-pkg_record-jar_ ${dependency} + done + + cp "${DISTDIR}"/${JAVA_BINJAR_FILENAME} ${JAVA_JAR_FILENAME}\ + || die "Could not copy the binary jar file to ${S}" + return 0 + fi + + # gather sources + find "${JAVA_SRC_DIR[@]}" -name \*.java > ${sources} + + # create the target directory + mkdir -p ${classes} || die "Could not create target directory" + + # compile + local classpath="" + java-pkg-simple_getclasspath + java-pkg-simple_prepend_resources ${classes} "${JAVA_RESOURCE_DIRS[@]}" + + ejavac -d ${classes} -encoding ${JAVA_ENCODING}\ + ${classpath:+-classpath ${classpath}} ${JAVAC_ARGS}\ + @${sources} + + # javadoc + if has doc ${JAVA_PKG_IUSE} && use doc; then + mkdir -p ${apidoc} + ejavadoc -d ${apidoc} \ + -encoding ${JAVA_ENCODING} -docencoding UTF-8 -charset UTF-8 \ + ${classpath:+-classpath ${classpath}} ${JAVADOC_ARGS:- -quiet} \ + @${sources} || die "javadoc failed" + fi + + # package + local jar_args + if [[ -e ${classes}/META-INF/MANIFEST.MF ]]; then + jar_args="cfm ${JAVA_JAR_FILENAME} ${classes}/META-INF/MANIFEST.MF" + elif [[ ${JAVA_MAIN_CLASS} ]]; then + jar_args="cfe ${JAVA_JAR_FILENAME} ${JAVA_MAIN_CLASS}" + else + jar_args="cf ${JAVA_JAR_FILENAME}" + fi + jar ${jar_args} -C ${classes} . || die "jar failed" +} + +# @FUNCTION: java-pkg-simple_src_install +# @DESCRIPTION: +# src_install for simple single jar java packages. Simply installs +# ${JAVA_JAR_FILENAME}. It will also install a launcher if +# ${JAVA_MAIN_CLASS} is set. +java-pkg-simple_src_install() { + local sources=sources.lst classes=target/classes apidoc=target/api + + # install the jar file that we need + java-pkg_dojar ${JAVA_JAR_FILENAME} + + # install a wrapper if ${JAVA_MAIN_CLASS} is defined + if [[ ${JAVA_MAIN_CLASS} ]]; then + java-pkg_dolauncher "${JAVA_LAUNCHER_FILENAME}" --main ${JAVA_MAIN_CLASS} + fi + + # javadoc + if has doc ${JAVA_PKG_IUSE} && use doc; then + java-pkg_dojavadoc ${apidoc} + fi + + # dosrc + if has source ${JAVA_PKG_IUSE} && use source; then + local srcdirs="" + if [[ "${JAVA_SRC_DIR[@]}" ]]; then + local parent child + for parent in "${JAVA_SRC_DIR[@]}"; do + srcdirs="${srcdirs} ${parent}" + done + else + # take all directories actually containing any sources + srcdirs="$(cut -d/ -f1 ${sources} | sort -u)" + fi + java-pkg_dosrc ${srcdirs} + fi +} + +# @FUNCTION: java-pkg-simple_src_test +# @DESCRIPTION: +# src_test for simple single java jar file. +# It will perform test with frameworks that are defined in +# ${JAVA_TESTING_FRAMEWORKS}. +java-pkg-simple_src_test() { + local test_sources=test_sources.lst classes=target/test-classes + local tests_to_run classpath + + # do not continue if the USE FLAG 'test' is explicitly unset + # or no ${JAVA_TESTING_FRAMEWORKS} is specified + if ! has test ${JAVA_PKG_IUSE}; then + return + elif ! use test; then + return + elif [[ ! "${JAVA_TESTING_FRAMEWORKS}" ]]; then + return + fi + + # create the target directory + mkdir -p ${classes} || die "Could not create target directory for testing" + + # get classpath + classpath="${classes}:${JAVA_JAR_FILENAME}" + java-pkg-simple_getclasspath + java-pkg-simple_prepend_resources ${classes} "${JAVA_TEST_RESOURCE_DIRS[@]}" + + # gathering sources for testing + find "${JAVA_TEST_SRC_DIR[@]}" -name \*.java > ${test_sources} + + # compile + [[ -s ${test_sources} ]] && ejavac -d ${classes} ${JAVAC_ARGS} \ + -encoding ${JAVA_ENCODING} ${classpath:+-classpath ${classpath}} \ + @${test_sources} + + # grab a set of tests that testing framework will run + tests_to_run=$(find "${classes}" -type f\ + \( -name "*Test.class"\ + -o -name "Test*.class"\ + -o -name "*Tests.class"\ + -o -name "*TestCase.class" \)\ + ! -name "*Abstract*"\ + ! -name "*BaseTest*"\ + ! -name "*TestTypes*"\ + ! -name "*TestUtils*"\ + ! -name "*\$*") + tests_to_run=${tests_to_run//"${classes}"\/} + tests_to_run=${tests_to_run//.class} + tests_to_run=${tests_to_run//\//.} + + # exclude extra test classes, usually corner cases + # that the code above cannot handle + for class in "${JAVA_TEST_EXCLUDES[@]}"; do + tests_to_run=${tests_to_run//${class}} + done + + # launch test + for framework in ${JAVA_TESTING_FRAMEWORKS}; do + case ${framework} in + junit) + ejunit -classpath "${classpath}" ${tests_to_run};; + junit-4) + ejunit4 -classpath "${classpath}" ${tests_to_run};; + pkgdiff) + java-pkg-simple_test_with_pkgdiff_;; + testng) + etestng -classpath "${classpath}" ${tests_to_run};; + *) + elog "No suitable function found for framework ${framework}" + esac + done +} diff --git a/eclass/java-utils-2.eclass b/eclass/java-utils-2.eclass new file mode 100644 index 0000000..b0d4d8a --- /dev/null +++ b/eclass/java-utils-2.eclass @@ -0,0 +1,2959 @@ +# Copyright 2004-2020 Gentoo Authors +# Distributed under the terms of the GNU General Public License v2 + +# @ECLASS: java-utils-2.eclass +# @MAINTAINER: +# java@gentoo.org +# @AUTHOR: +# Thomas Matthijs <axxo@gentoo.org>, Karl Trygve Kalleberg <karltk@gentoo.org> +# @BLURB: Base eclass for Java packages +# @DESCRIPTION: +# This eclass provides functionality which is used by java-pkg-2.eclass, +# java-pkg-opt-2.eclass and java-ant-2 eclass, as well as from ebuilds. +# +# This eclass should not be inherited this directly from an ebuild. Instead, +# you should inherit java-pkg-2 for Java packages or java-pkg-opt-2 for packages +# that have optional Java support. In addition you can inherit java-ant-2 for +# Ant-based packages. + +# EAPI 7 has version functions built-in. Use eapi7-ver for all earlier eclasses. +# Keep versionator inheritance in case consumers are using it implicitly. +[[ ${EAPI} == [0123456] ]] && inherit eapi7-ver eutils multilib versionator + +IUSE="elibc_FreeBSD" + +# Make sure we use java-config-2 +export WANT_JAVA_CONFIG="2" + +# Prefix variables are only available for EAPI>=3 +has "${EAPI:-0}" 0 1 2 && ED="${D}" EPREFIX= EROOT="${ROOT}" + +has test ${JAVA_PKG_IUSE} && RESTRICT+=" !test? ( test )" + +# @VARIABLE: JAVA_PKG_E_DEPEND +# @INTERNAL +# @DESCRIPTION: +# This is a convience variable to be used from the other java eclasses. This is +# the version of java-config we want to use. Usually the latest stable version +# so that ebuilds can use new features without depending on specific versions. +JAVA_PKG_E_DEPEND=">=dev-java/java-config-2.2.0-r3" +has source ${JAVA_PKG_IUSE} && JAVA_PKG_E_DEPEND="${JAVA_PKG_E_DEPEND} source? ( app-arch/zip )" + +# @ECLASS-VARIABLE: JAVA_PKG_WANT_BOOTCLASSPATH +# @DEFAULT_UNSET +# @DESCRIPTION: +# The version of bootclasspath the package needs to work. Translates to a proper +# dependency. The bootclasspath can then be obtained by java-ant_rewrite-bootclasspath +if [[ -n "${JAVA_PKG_WANT_BOOTCLASSPATH}" ]]; then + if [[ "${JAVA_PKG_WANT_BOOTCLASSPATH}" == "1.5" ]]; then + JAVA_PKG_E_DEPEND="${JAVA_PKG_E_DEPEND} >=dev-java/gnu-classpath-0.98-r1:0.98" + else + eerror "Unknown value of JAVA_PKG_WANT_BOOTCLASSPATH" + # since die in global scope doesn't work, this will make repoman fail + JAVA_PKG_E_DEPEND="${JAVA_PKG_E_DEPEND} BAD_JAVA_PKG_WANT_BOOTCLASSPATH" + fi +fi + +# @ECLASS-VARIABLE: JAVA_PKG_ALLOW_VM_CHANGE +# @DESCRIPTION: +# Allow this eclass to change the active VM? +# If your system VM isn't sufficient for the package, the build will fail +# instead of trying to switch to another VM. +# +# Overriding the default can be useful for testing specific VMs locally, but +# should not be used in the final ebuild. +JAVA_PKG_ALLOW_VM_CHANGE=${JAVA_PKG_ALLOW_VM_CHANGE:="yes"} + +# @ECLASS-VARIABLE: JAVA_PKG_FORCE_VM +# @DEFAULT_UNSET +# @DESCRIPTION: +# Explicitly set a particular VM to use. If its not valid, it'll fall back to +# whatever /etc/java-config-2/build/jdk.conf would elect to use. +# +# Should only be used for testing and debugging. +# +# Example: use sun-jdk-1.5 to emerge foo: +# @CODE +# JAVA_PKG_FORCE_VM=sun-jdk-1.5 emerge foo +# @CODE + +# @ECLASS-VARIABLE: JAVA_PKG_WANT_BUILD_VM +# @DEFAULT_UNSET +# @DESCRIPTION: +# A list of VM handles to choose a build VM from. If the list contains the +# currently active VM use that one, otherwise step through the list till a +# usable/installed VM is found. +# +# This allows to use an explicit list of JDKs in DEPEND instead of a virtual. +# Users of this variable must make sure at least one of the listed handles is +# covered by DEPEND. +# Requires JAVA_PKG_WANT_SOURCE and JAVA_PKG_WANT_TARGET to be set as well. + +# @ECLASS-VARIABLE: JAVA_PKG_WANT_SOURCE +# @DEFAULT_UNSET +# @DESCRIPTION: +# Specify a non-standard Java source version for compilation (via javac -source +# parameter or Ant equivalent via build.xml rewriting done by java-ant-2 eclass). +# Normally this is determined from the jdk version specified in DEPEND. +# See java-pkg_get-source function below. +# +# Should generally only be used for testing and debugging. +# +# Use 1.4 source to emerge baz +# @CODE +# JAVA_PKG_WANT_SOURCE=1.4 emerge baz +# @CODE + +# @ECLASS-VARIABLE: JAVA_PKG_WANT_TARGET +# @DEFAULT_UNSET +# @DESCRIPTION: +# Same as JAVA_PKG_WANT_SOURCE (see above) but for javac -target parameter, +# which affects the version of generated bytecode. +# Normally this is determined from the jre/jdk version specified in RDEPEND. +# See java-pkg_get-target function below. +# +# Should generallyonly be used for testing and debugging. +# +# emerge bar to be compatible with 1.3 +# @CODE +# JAVA_PKG_WANT_TARGET=1.3 emerge bar +# @CODE + +# @ECLASS-VARIABLE: JAVA_PKG_DEBUG +# @DEFAULT_UNSET +# @DESCRIPTION: +# A variable to be set with "yes" or "y", or ANY string of length non equal to +# zero. When set, verbosity across java eclasses is increased and extra +# logging is displayed. +# @CODE +# JAVA_PKG_DEBUG="yes" +# @CODE + +# @ECLASS-VARIABLE: JAVA_RM_FILES +# @DEFAULT_UNSET +# @DESCRIPTION: +# An array containing a list of files to remove. If defined, this array will be +# automatically handed over to java-pkg_rm_files for processing during the +# src_prepare phase. +# +# @CODE +# JAVA_RM_FILES=( +# path/to/File1.java +# DELETEME.txt +# ) +# @CODE + +# @VARIABLE: JAVA_PKG_COMPILER_DIR +# @INTERNAL +# @DESCRIPTION: +# Directory where compiler settings are saved, without trailing slash. +# You probably shouldn't touch this variable except local testing. +JAVA_PKG_COMPILER_DIR=${JAVA_PKG_COMPILER_DIR:="/usr/share/java-config-2/compiler"} + +# @VARIABLE: JAVA_PKG_COMPILERS_CONF +# @INTERNAL +# @DESCRIPTION: +# Path to file containing information about which compiler to use. +# Can be overloaded, but it should be overloaded only for local testing. +JAVA_PKG_COMPILERS_CONF=${JAVA_PKG_COMPILERS_CONF:="/etc/java-config-2/build/compilers.conf"} + +# @ECLASS-VARIABLE: JAVA_PKG_FORCE_COMPILER +# @INTERNAL +# @DEFAULT_UNSET +# @DESCRIPTION: +# Explicitly set a list of compilers to choose from. This is normally read from +# JAVA_PKG_COMPILERS_CONF. +# +# Useful for local testing. +# +# Use jikes and javac, in that order +# @CODE +# JAVA_PKG_FORCE_COMPILER="jikes javac" +# @CODE + +# @ECLASS-VARIABLE: JAVA_PKG_FORCE_ANT_TASKS +# @DEFAULT_UNSET +# @DESCRIPTION: +# An $IFS separated list of ant tasks. Can be set in environment before calling +# emerge/ebuild to override variables set in ebuild, mainly for testing before +# putting the resulting (WANT_)ANT_TASKS into ebuild. Affects only ANT_TASKS in +# eant() call, not the dependencies specified in WANT_ANT_TASKS. +# +# @CODE +# JAVA_PKG_FORCE_ANT_TASKS="ant-junit ant-trax" \ +# ebuild foo.ebuild compile +# @CODE + +# TODO document me +JAVA_PKG_QA_VIOLATIONS=0 + +# @FUNCTION: java-pkg_doexamples +# @USAGE: [--subdir <subdir>] <file1/dir1> [<file2> ...] +# @DESCRIPTION: +# Installs given arguments to /usr/share/doc/${PF}/examples +# If you give it only one parameter and it is a directory it will install +# everything in that directory to the examples directory. +# +# @CODE +# Parameters: +# --subdir - If the examples need a certain directory structure +# $* - list of files to install +# +# Examples: +# java-pkg_doexamples demo +# java-pkg_doexamples demo/* examples/* +# @CODE +java-pkg_doexamples() { + debug-print-function ${FUNCNAME} $* + + [[ ${#} -lt 1 ]] && die "At least one argument needed" + + java-pkg_check-phase install + java-pkg_init_paths_ + + local dest=/usr/share/doc/${PF}/examples + if [[ ${1} == --subdir ]]; then + local dest=${dest}/${2} + dodir ${dest} + shift 2 + fi + + if [[ ${#} = 1 && -d ${1} ]]; then + ( # dont want to pollute calling env + insinto "${dest}" + doins -r ${1}/* + ) || die "Installing examples failed" + else + ( # dont want to pollute calling env + insinto "${dest}" + doins -r "$@" + ) || die "Installing examples failed" + fi + + # Let's make a symlink to the directory we have everything else under + dosym "${dest}" "${JAVA_PKG_SHAREPATH}/examples" || die +} + +# @FUNCTION: java-pkg_addres +# @USAGE: <jar> <dir> [<find arguments> ...] +# @DESCRIPTION: +# Adds resource files to an existing jar. +# It is important that the directory given is actually the root of the +# corresponding resource tree. The target directory as well as +# sources.lst, MANIFEST.MF, *.class, *.jar, and *.java files are +# automatically excluded. Symlinks are always followed. Additional +# arguments are passed through to find. +# +# @CODE +# java-pkg_addres ${PN}.jar resources ! -name "*.html" +# @CODE +# +# @param $1 - jar file +# @param $2 - resource tree directory +# @param $* - arguments to pass to find +java-pkg_addres() { + debug-print-function ${FUNCNAME} $* + + [[ ${#} -lt 2 ]] && die "at least two arguments needed" + + local jar=$(realpath "$1" || die "realpath $1 failed") + local dir="$2" + shift 2 + + pushd "${dir}" > /dev/null || die "pushd ${dir} failed" + find -L -type f ! -path "./target/*" ! -path "./sources.lst" ! -name "MANIFEST.MF" ! -regex ".*\.\(class\|jar\|java\)" "${@}" -print0 | xargs -r0 jar uf "${jar}" || die "jar failed" + popd > /dev/null || die "popd failed" +} + +# @FUNCTION: java-pkg_rm_files +# @USAGE: <File1.java> [File2.java] ... +# @DESCRIPTION: +# Remove unneeded files in ${S}. +# +# Every now and then, you'll run into situations whereby a file needs removing, +# be it a unit test or a regular java class. +# +# You can use this function by either: +# - calling it yourself in src_prepare() and feeding java-pkg_rm_files with +# the list of files you wish to remove. +# - defining an array in the ebuild named JAVA_RM_FILES with the list of files +# you wish to remove. +# +# Both way work and it is left to the developer's preferences. If the +# JAVA_RM_FILES array is defined, it will be automatically handed over to +# java-pkg_rm_files during the src_prepare phase. +# +# See java-utils-2_src_prepare. +# +# @CODE +# java-pkg_rm_files File1.java File2.java +# @CODE +# +# @param $* - list of files to remove. +java-pkg_rm_files() { + debug-print-function ${FUNCNAME} $* + local IFS="\n" + for filename in "$@"; do + [[ ! -f "${filename}" ]] && die "${filename} is not a regular file. Aborting." + einfo "Removing unneeded file ${filename}" + rm -f "${S}/${filename}" || die "cannot remove ${filename}" + eend $? + done +} + +# @FUNCTION: java-pkg_dojar +# @USAGE: <jar1> [<jar2> ...] +# @DESCRIPTION: +# Installs any number of jars. +# Jar's will be installed into /usr/share/${PN}(-${SLOT})/lib/ by default. +# You can use java-pkg_jarinto to change this path. +# You should never install a jar with a package version in the filename. +# Instead, use java-pkg_newjar defined below. +# +# @CODE +# java-pkg_dojar dist/${PN}.jar dist/${PN}-core.jar +# @CODE +# +# @param $* - list of jars to install +java-pkg_dojar() { + debug-print-function ${FUNCNAME} $* + + [[ ${#} -lt 1 ]] && die "At least one argument needed" + + java-pkg_check-phase install + java-pkg_init_paths_ + + # Create JARDEST if it doesn't exist + dodir ${JAVA_PKG_JARDEST} + + local jar + # for each jar + for jar in "${@}"; do + local jar_basename=$(basename "${jar}") + + java-pkg_check-versioned-jar ${jar_basename} + + # check if it exists + if [[ -e "${jar}" ]] ; then + # Don't overwrite if jar has already been installed with the same + # name + local dest="${ED}${JAVA_PKG_JARDEST}/${jar_basename}" + if [[ -e "${dest}" ]]; then + ewarn "Overwriting ${dest}" + fi + + # install it into JARDEST if it's a non-symlink + if [[ ! -L "${jar}" ]] ; then + #but first check class version when in strict mode. + is-java-strict && java-pkg_verify-classes "${jar}" + + ( + insinto "${JAVA_PKG_JARDEST}" + doins "${jar}" + ) || die "failed to install ${jar}" + java-pkg_append_ JAVA_PKG_CLASSPATH "${EPREFIX}/${JAVA_PKG_JARDEST}/${jar_basename}" + debug-print "installed ${jar} to ${ED}${JAVA_PKG_JARDEST}" + # make a symlink to the original jar if it's symlink + else + # TODO use dosym, once we find something that could use it + # -nichoj + ln -s "$(readlink "${jar}")" "${ED}${JAVA_PKG_JARDEST}/${jar_basename}" + debug-print "${jar} is a symlink, linking accordingly" + fi + else + die "${jar} does not exist" + fi + done + + # Extra logging if enabled. + if [[ -n ${JAVA_PKG_DEBUG} ]]; then + einfo "Verbose logging for \"${FUNCNAME}\" function" + einfo "Jar file(s) destination: ${JAVA_PKG_JARDEST}" + einfo "Jar file(s) created: ${@}" + einfo "Complete command:" + einfo "${FUNCNAME} ${@}" + fi + + java-pkg_do_write_ +} + +# @FUNCTION: java-pkg_regjar +# @USAGE: </path/to/installed/jar> +# @DESCRIPTION: +# Records an already installed (in ${D}) jar in the package.env +# This would mostly be used if the package has make or a custom script to +# install things. +# +# WARNING: +# if you want to use shell expansion, you have to use ${D}/... as the for in +# this function will not be able to expand the path, here's an example: +# +# @CODE +# java-pkg_regjar ${D}/opt/my-java/lib/*.jar +# @CODE +# + +# TODO should we be making sure the jar is present on ${D} or wherever? +java-pkg_regjar() { + debug-print-function ${FUNCNAME} $* + + java-pkg_check-phase install + + [[ ${#} -lt 1 ]] && die "at least one argument needed" + + java-pkg_init_paths_ + + local jar jar_dir jar_file + for jar in "${@}"; do + # TODO use java-pkg_check-versioned-jar + if [[ -e "${jar}" || -e "${D}${jar}" ]]; then + [[ -d "${jar}" || -d "${D}${jar}" ]] \ + && die "Called ${FUNCNAME} on a directory $*" + + #check that class version correct when in strict mode + is-java-strict && java-pkg_verify-classes "${jar}" + + # nelchael: we should strip ${D} in this case too, here's why: + # imagine such call: + # java-pkg_regjar ${D}/opt/java/*.jar + # such call will fall into this case (-e ${jar}) and will + # record paths with ${D} in package.env + java-pkg_append_ JAVA_PKG_CLASSPATH "${jar#${D}}" + else + if [[ ${jar} = *\** ]]; then + eerror "The argument ${jar} to ${FUNCNAME}" + eerror "has * in it. If you want it to glob in" + eerror '${D} add ${D} to the argument.' + fi + debug-print "${jar} or ${D}${jar} not found" + die "${jar} does not exist" + fi + done + + java-pkg_do_write_ +} + +# @FUNCTION: java-pkg_newjar +# @USAGE: <path/to/oldname.jar> [<newname.jar>] +# @DESCRIPTION: +# Installs a jar with a new name (defaults to $PN.jar) +# +# For example, installs a versioned jar without the version +java-pkg_newjar() { + debug-print-function ${FUNCNAME} $* + + local original_jar="${1}" + local new_jar="${2:-${PN}.jar}" + local new_jar_dest="${T}/${new_jar}" + + [[ -z ${original_jar} ]] && die "Must specify a jar to install" + [[ ! -f ${original_jar} ]] \ + && die "${original_jar} does not exist or is not a file!" + + rm -f "${new_jar_dest}" || die "Failed to remove ${new_jar_dest}" + cp "${original_jar}" "${new_jar_dest}" \ + || die "Failed to copy ${original_jar} to ${new_jar_dest}" + java-pkg_dojar "${new_jar_dest}" +} + +# @FUNCTION: java-pkg_addcp +# @USAGE: <classpath> +# @DESCRIPTION: +# Add something to the package's classpath. For jars, you should use dojar, +# newjar, or regjar. This is typically used to add directories to the classpath. +# The parameters of this function are appended to JAVA_PKG_CLASSPATH +java-pkg_addcp() { + java-pkg_append_ JAVA_PKG_CLASSPATH "${@}" + java-pkg_do_write_ +} + +# @FUNCTION: java-pkg_doso +# @USAGE: <path/to/file1.so> [...] +# @DESCRIPTION: +# Installs any number of JNI libraries +# They will be installed into /usr/lib by default, but java-pkg_sointo +# can be used change this path +# +# @CODE +# Example: +# java-pkg_doso *.so +# @CODE +java-pkg_doso() { + debug-print-function ${FUNCNAME} $* + + java-pkg_check-phase install + + [[ ${#} -lt 1 ]] && die "${FUNCNAME} requires at least one argument" + + java-pkg_init_paths_ + + local lib + # for each lib + for lib in "$@" ; do + # if the lib exists... + if [[ -e "${lib}" ]] ; then + # install if it isn't a symlink + if [[ ! -L "${lib}" ]] ; then + ( + insinto "${JAVA_PKG_LIBDEST}" + insopts -m0755 + doins "${lib}" + ) || die "failed to install ${lib}" + java-pkg_append_ JAVA_PKG_LIBRARY "${JAVA_PKG_LIBDEST}" + debug-print "Installing ${lib} to ${JAVA_PKG_LIBDEST}" + # otherwise make a symlink to the symlink's origin + else + dosym "$(readlink "${lib}")" "${JAVA_PKG_LIBDEST}/${lib##*/}" + debug-print "${lib} is a symlink, linking accordantly" + fi + # otherwise die + else + die "${lib} does not exist" + fi + done + + java-pkg_do_write_ +} + +# @FUNCTION: java-pkg_regso +# @USAGE: <file1.so> [...] +# @DESCRIPTION: +# Registers an already installed JNI library in package.env. +# +# @CODE +# Parameters: +# $@ - JNI libraries to register +# +# Example: +# java-pkg_regso *.so /path/*.so +# @CODE +java-pkg_regso() { + debug-print-function ${FUNCNAME} $* + + java-pkg_check-phase install + + [[ ${#} -lt 1 ]] && die "${FUNCNAME} requires at least one argument" + + java-pkg_init_paths_ + + local lib target_dir + for lib in "$@" ; do + # Check the absolute path of the lib + if [[ -e "${lib}" ]] ; then + target_dir="$(java-pkg_expand_dir_ ${lib})" + java-pkg_append_ JAVA_PKG_LIBRARY "/${target_dir#${D}}" + # Check the path of the lib relative to ${D} + elif [[ -e "${D}${lib}" ]]; then + target_dir="$(java-pkg_expand_dir_ ${D}${lib})" + java-pkg_append_ JAVA_PKG_LIBRARY "${target_dir}" + else + die "${lib} does not exist" + fi + done + + java-pkg_do_write_ +} + +# @FUNCTION: java-pkg_jarinto +# @USAGE: </path/to/install/jars/into> +# @DESCRIPTION: +# Changes the path jars are installed into via subsequent java-pkg_dojar calls. +java-pkg_jarinto() { + debug-print-function ${FUNCNAME} $* + + JAVA_PKG_JARDEST="${1}" +} + +# @FUNCTION: java-pkg_sointo +# @USAGE: </path/to/install/sofiles/into> +# @DESCRIPTION: +# Changes the path that JNI libraries are installed into via subsequent +# java-pkg_doso calls. +java-pkg_sointo() { + debug-print-function ${FUNCNAME} $* + + JAVA_PKG_LIBDEST="${1}" +} + +# @FUNCTION: java-pkg_dohtml +# @USAGE: <path/to/javadoc/documentation> [...] +# @DESCRIPTION: +# Install Javadoc HTML documentation. Usage of java-pkg_dojavadoc is preferred. +# +# @CODE +# java-pkg_dohtml dist/docs/ +# @CODE +java-pkg_dohtml() { + debug-print-function ${FUNCNAME} $* + + [[ ${#} -lt 1 ]] && die "At least one argument required for ${FUNCNAME}" + + # Do away with dohtml and rely on dodoc instead to do the deed. + docinto html + dodoc "$@" + + # This probably shouldn't be here but it provides + # a reasonable way to catch # docs for all of the + # old ebuilds. + java-pkg_recordjavadoc +} + +# @FUNCTION: java-pkg_dojavadoc +# @USAGE: [--symlink destination] <path/to/javadocs/root> +# @DESCRIPTION: +# Installs javadoc documentation. This should be controlled by the doc use flag. +# +# @CODE +# Parameters: +# $1: optional --symlink creates to symlink like this for html +# documentation bundles. +# $2: - The javadoc root directory. +# +# Examples: +# java-pkg_dojavadoc docs/api +# java-pkg_dojavadoc --symlink apidocs docs/api +# @CODE +java-pkg_dojavadoc() { + debug-print-function ${FUNCNAME} $* + + # For html documentation bundles that link to Javadoc + local symlink + if [[ ${1} = --symlink ]]; then + symlink=${2} + shift 2 + fi + + local dir="$1" + local dest=/usr/share/doc/${PF}/html + + # QA checks + + java-pkg_check-phase install + java-pkg_init_paths_ + + [[ -z "${dir}" ]] && die "Must specify a directory!" + [[ ! -d "${dir}" ]] && die "${dir} does not exist, or isn't a directory!" + if [[ ! -e "${dir}/index.html" ]]; then + local msg="No index.html in javadoc directory" + ewarn "${msg}" + is-java-strict && die "${msg}" + fi + + if [[ -e ${D}/${dest}/api ]]; then + eerror "${dest} already exists. Will not overwrite." + die "${dest}" + fi + + # Renaming to match our directory layout + + local dir_to_install="${dir}" + if [[ "$(basename "${dir}")" != "api" ]]; then + dir_to_install="${T}/api" + # TODO use doins + cp -r "${dir}" "${dir_to_install}" || die "cp failed" + fi + + # Actual installation + java-pkg_dohtml -r "${dir_to_install}" + + # Let's make a symlink to the directory we have everything else under + dosym ${dest}/api "${JAVA_PKG_SHAREPATH}/api" || die + + if [[ ${symlink} ]]; then + debug-print "symlinking ${dest}/{api,${symlink}}" + dosym ${dest}/{api,${symlink}} || die + fi + + # Extra logging if enabled. + if [[ -n ${JAVA_PKG_DEBUG} ]]; then + einfo "Verbose logging for \"${FUNCNAME}\" function" + einfo "Documentation destination: ${dest}" + einfo "Directory to install: ${dir_to_install}" + einfo "Complete command:" + einfo "${FUNCNAME} ${@}" + fi +} + +# @FUNCTION: java-pkg_dosrc +# @USAGE: <path/to/sources> [...] +# @DESCRIPTION: +# Installs a zip containing the source for a package, so it can used in +# from IDEs like eclipse and netbeans. +# Ebuild needs to DEPEND on app-arch/zip to use this. It also should be controlled by USE=source. +# +# @CODE +# Example: +# java-pkg_dosrc src/* +# @CODE + +# TODO change so it the arguments it takes are the base directories containing +# source -nichoj +# +# TODO should we be able to handle multiple calls to dosrc? -nichoj +# +# TODO maybe we can take an existing zip/jar? -nichoj +# +# FIXME apparently this fails if you give it an empty directories +java-pkg_dosrc() { + debug-print-function ${FUNCNAME} $* + + [ ${#} -lt 1 ] && die "At least one argument needed" + + java-pkg_check-phase install + + [[ ${#} -lt 1 ]] && die "At least one argument needed" + + if ! [[ ${DEPEND} = *app-arch/zip* ]]; then + local msg="${FUNCNAME} called without app-arch/zip in DEPEND" + java-pkg_announce-qa-violation ${msg} + fi + + java-pkg_init_paths_ + + local zip_name="${PN}-src.zip" + local zip_path="${T}/${zip_name}" + local dir + for dir in "${@}"; do + local dir_parent=$(dirname "${dir}") + local dir_name=$(basename "${dir}") + pushd ${dir_parent} > /dev/null || die "problem entering ${dir_parent}" + zip -q -r ${zip_path} ${dir_name} -i '*.java' + local result=$? + # 12 means zip has nothing to do + if [[ ${result} != 12 && ${result} != 0 ]]; then + die "failed to zip ${dir_name}" + fi + popd >/dev/null || die + done + + # Install the zip + ( + insinto "${JAVA_PKG_SOURCESPATH}" + doins ${zip_path} + ) || die "Failed to install source" + + JAVA_SOURCES="${JAVA_PKG_SOURCESPATH}/${zip_name}" + + # Extra logging if enabled. + if [[ -n ${JAVA_PKG_DEBUG} ]]; then + einfo "Verbose logging for \"${FUNCNAME}\" function" + einfo "Zip filename created: ${zip_name}" + einfo "Zip file destination: ${JAVA_PKG_SOURCESPATH}" + einfo "Directories zipped: ${@}" + einfo "Complete command:" + einfo "${FUNCNAME} ${@}" + fi + + java-pkg_do_write_ +} + +# @FUNCTION: java-pkg_dolauncher +# @USAGE: <filename> [options] +# @DESCRIPTION: +# Make a wrapper script to lauch/start this package +# If necessary, the wrapper will switch to the appropriate VM. +# +# Can be called without parameters if the package installs only one jar +# that has the Main-class attribute set. The wrapper will be named ${PN}. +# +# @CODE +# Parameters: +# $1 - filename of launcher to create +# $2 - options, as follows: +# --main the.main.class.to.start +# --jar /the/jar/too/launch.jar or just <name>.jar +# --java_args 'Extra arguments to pass to java' +# --pkg_args 'Extra arguments to pass to the package' +# --pwd Directory the launcher changes to before executing java +# -into Directory to install the launcher to, instead of /usr/bin +# -pre Prepend contents of this file to the launcher +# @CODE +java-pkg_dolauncher() { + debug-print-function ${FUNCNAME} $* + + java-pkg_check-phase install + java-pkg_init_paths_ + + if [[ ${#} = 0 ]]; then + local name="${PN}" + else + local name="${1}" + shift + fi + + # TODO rename to launcher + local target="${T}/${name}" + local var_tmp="${T}/launcher_variables_tmp" + local target_dir pre + + # Process the other the rest of the arguments + while [[ -n "${1}" && -n "${2}" ]]; do + local var="${1}" value="${2}" + if [[ "${var:0:2}" == "--" ]]; then + local var=${var:2} + echo "gjl_${var}=\"${value}\"" >> "${var_tmp}" + local gjl_${var}="${value}" + elif [[ "${var}" == "-into" ]]; then + target_dir="${value}" + elif [[ "${var}" == "-pre" ]]; then + pre="${value}" + fi + shift 2 + done + + # Test if no --jar and --main arguments were given and + # in that case check if the package only installs one jar + # and use that jar. + if [[ -z "${gjl_jar}" && -z "${gjl_main}" ]]; then + local cp="${JAVA_PKG_CLASSPATH}" + if [[ "${cp/:}" = "${cp}" && "${cp%.jar}" != "${cp}" ]]; then + echo "gjl_jar=\"${JAVA_PKG_CLASSPATH}\"" >> "${var_tmp}" + else + local msg="Not enough information to create a launcher given." + msg="${msg} Please give --jar or --main argument to ${FUNCNAME}." + die "${msg}" + fi + fi + + # Write the actual script + echo "#!/bin/bash" > "${target}" + if [[ -n "${pre}" ]]; then + if [[ -f "${pre}" ]]; then + cat "${pre}" >> "${target}" + else + die "-pre specified file '${pre}' does not exist" + fi + fi + echo "gjl_package=${JAVA_PKG_NAME}" >> "${target}" + cat "${var_tmp}" >> "${target}" + rm -f "${var_tmp}" + echo "source ${EPREFIX}/usr/share/java-config-2/launcher/launcher.bash" >> "${target}" + + if [[ -n "${target_dir}" ]]; then + ( + into "${target_dir}" + dobin "${target}" + ) + local ret=$? + return ${ret} + else + dobin "${target}" + fi +} + +# @FUNCTION: java-pkg_dowar +# @DESCRIPTION: +# Install war files. +# TODO document +java-pkg_dowar() { + debug-print-function ${FUNCNAME} $* + + # Check for arguments + [[ ${#} -lt 1 ]] && die "At least one argument needed" + java-pkg_check-phase install + + java-pkg_init_paths_ + + local war + for war in $* ; do + local warpath + # TODO evaluate if we want to handle symlinks differently -nichoj + # Check for symlink + if [[ -L "${war}" ]] ; then + cp "${war}" "${T}" + warpath="${T}$(basename "${war}")" + # Check for directory + # TODO evaluate if we want to handle directories differently -nichoj + elif [[ -d "${war}" ]] ; then + echo "dowar: warning, skipping directory ${war}" + continue + else + warpath="${war}" + fi + + # Install those files like you mean it + ( + insopts -m0644 + insinto "${JAVA_PKG_WARDEST}" + doins ${warpath} + ) + done +} + +# @FUNCTION: java-pkg_recordjavadoc +# @INTERNAL +# @DESCRIPTION: +# Scan for JavaDocs, and record their existence in the package.env file + +# TODO make sure this in the proper section +java-pkg_recordjavadoc() +{ + debug-print-function ${FUNCNAME} $* + # the find statement is important + # as some packages include multiple trees of javadoc + JAVADOC_PATH="$(find ${D}/usr/share/doc/ -name allclasses-frame.html -printf '%h:')" + # remove $D - TODO: check this is ok with all cases of the above + JAVADOC_PATH="${JAVADOC_PATH//${D}}" + if [[ -n "${JAVADOC_PATH}" ]] ; then + debug-print "javadocs found in ${JAVADOC_PATH%:}" + java-pkg_do_write_ + else + debug-print "No javadocs found" + fi +} + + +# @FUNCTION: java-pkg_jar-from +# @USAGE: [--build-only] [--with-dependencies] [--virtual] [--into dir] <package> [<package.jar>] [<destination.jar>] +# @DESCRIPTION: +# Makes a symlink to a jar from a certain package +# A lot of java packages include dependencies in a lib/ directory +# You can use this function to replace these bundled dependencies. +# The dependency is recorded into package.env DEPEND line, unless "--build-only" +# is passed as the very first argument, for jars that have to be present only +# at build time and are not needed on runtime (junit testing etc). +# +# @CODE +# Example: get all jars from xerces slot 2 +# java-pkg_jar-from xerces-2 +# +# Example: get a specific jar from xerces slot 2 +# java-pkg_jar-from xerces-2 xml-apis.jar +# +# Example: get a specific jar from xerces slot 2, and name it diffrently +# java-pkg_jar-from xerces-2 xml-apis.jar xml.jar +# +# Example: get junit.jar which is needed only for building +# java-pkg_jar-from --build-only junit junit.jar +# @CODE +# +# @CODE +# Parameters +# --build-only - makes the jar(s) not added into package.env DEPEND line. +# (assumed automatically when called inside src_test) +# --with-dependencies - get jars also from requested package's dependencies +# transitively. +# --virtual - Packages passed to this function are to be handled as virtuals +# and will not have individual jar dependencies recorded. +# --into $dir - symlink jar(s) into $dir (must exist) instead of . +# $1 - Package to get jars from, or comma-separated list of packages in +# case other parameters are not used. +# $2 - jar from package. If not specified, all jars will be used. +# $3 - When a single jar is specified, destination filename of the +# symlink. Defaults to the name of the jar. +# @CODE + +# TODO could probably be cleaned up a little +java-pkg_jar-from() { + debug-print-function ${FUNCNAME} $* + + local build_only="" + local destdir="." + local deep="" + local virtual="" + local record_jar="" + + [[ "${EBUILD_PHASE}" == "test" ]] && build_only="build" + + while [[ "${1}" == --* ]]; do + if [[ "${1}" = "--build-only" ]]; then + build_only="build" + elif [[ "${1}" = "--with-dependencies" ]]; then + deep="--with-dependencies" + elif [[ "${1}" = "--virtual" ]]; then + virtual="true" + elif [[ "${1}" = "--into" ]]; then + destdir="${2}" + shift + else + die "java-pkg_jar-from called with unknown parameter: ${1}" + fi + shift + done + + local target_pkg="${1}" target_jar="${2}" destjar="${3}" + + [[ -z ${target_pkg} ]] && die "Must specify a package" + + if [[ "${EAPI}" == "1" ]]; then + target_pkg="${target_pkg//:/-}" + fi + + # default destjar to the target jar + [[ -z "${destjar}" ]] && destjar="${target_jar}" + + local error_msg="There was a problem getting the classpath for ${target_pkg}." + local classpath + classpath="$(java-config ${deep} --classpath=${target_pkg})" + [[ $? != 0 ]] && die ${error_msg} + + # When we have commas this functions is called to bring jars from multiple + # packages. This affects recording of dependencencies performed later + # which expects one package only, so we do it here. + if [[ ${target_pkg} = *,* ]]; then + for pkg in ${target_pkg//,/ }; do + java-pkg_ensure-dep "${build_only}" "${pkg}" + [[ -z "${build_only}" ]] && java-pkg_record-jar_ "${pkg}" + done + # setting this disables further record-jar_ calls later + record_jar="true" + else + java-pkg_ensure-dep "${build_only}" "${target_pkg}" + fi + + # Record the entire virtual as a dependency so that + # no jars are missed. + if [[ -z "${build_only}" && -n "${virtual}" ]]; then + java-pkg_record-jar_ "${target_pkg}" + # setting this disables further record-jars_ calls later + record_jar="true" + fi + + pushd ${destdir} > /dev/null \ + || die "failed to change directory to ${destdir}" + + local jar + for jar in ${classpath//:/ }; do + local jar_name=$(basename "${jar}") + if [[ ! -f "${jar}" ]] ; then + debug-print "${jar} from ${target_pkg} does not exist" + die "Installation problems with jars in ${target_pkg} - is it installed?" + fi + # If no specific target jar was indicated, link it + if [[ -z "${target_jar}" ]] ; then + [[ -f "${target_jar}" ]] && rm "${target_jar}" + ln -snf "${jar}" \ + || die "Failed to make symlink from ${jar} to ${jar_name}" + if [[ -z "${record_jar}" ]]; then + if [[ -z "${build_only}" ]]; then + java-pkg_record-jar_ "${target_pkg}" "${jar}" + else + java-pkg_record-jar_ --build-only "${target_pkg}" "${jar}" + fi + fi + # otherwise, if the current jar is the target jar, link it + elif [[ "${jar_name}" == "${target_jar}" ]] ; then + [[ -f "${destjar}" ]] && rm "${destjar}" + ln -snf "${jar}" "${destjar}" \ + || die "Failed to make symlink from ${jar} to ${destjar}" + if [[ -z "${record_jar}" ]]; then + if [[ -z "${build_only}" ]]; then + java-pkg_record-jar_ "${target_pkg}" "${jar}" + else + java-pkg_record-jar_ --build-only "${target_pkg}" "${jar}" + fi + fi + popd > /dev/null || die + return 0 + fi + done + popd > /dev/null || die + # if no target was specified, we're ok + if [[ -z "${target_jar}" ]] ; then + return 0 + # otherwise, die bitterly + else + die "Failed to find ${target_jar:-jar} in ${target_pkg}" + fi +} + +# @FUNCTION: java-pkg_jarfrom +# @DESCRIPTION: +# See java-pkg_jar-from +java-pkg_jarfrom() { + java-pkg_jar-from "$@" +} + +# @FUNCTION: java-pkg_getjars +# @USAGE: [--build-only] [--with-dependencies] <package1>[,<package2>...] +# @DESCRIPTION: +# Get the classpath provided by any number of packages +# Among other things, this can be passed to 'javac -classpath' or 'ant -lib'. +# The providing packages are recorded as dependencies into package.env DEPEND +# line, unless "--build-only" is passed as the very first argument, for jars +# that have to be present only at build time and are not needed on runtime +# (junit testing etc). +# +# @CODE +# Example: Get the classpath for xerces-2 and xalan, +# java-pkg_getjars xerces-2,xalan +# +# Example Return: +# /usr/share/xerces-2/lib/xml-apis.jar:/usr/share/xerces-2/lib/xmlParserAPIs.jar:/usr/share/xalan/lib/xalan.jar +# +# +# Parameters: +# --build-only - makes the jar(s) not added into package.env DEPEND line. +# (assumed automatically when called inside src_test) +# --with-dependencies - get jars also from requested package's dependencies +# transitively. +# $1 - list of packages to get jars from +# (passed to java-config --classpath) +# @CODE +java-pkg_getjars() { + debug-print-function ${FUNCNAME} $* + + local build_only="" + local deep="" + + [[ "${EBUILD_PHASE}" == "test" ]] && build_only="build" + + while [[ "${1}" == --* ]]; do + if [[ "${1}" = "--build-only" ]]; then + build_only="build" + elif [[ "${1}" = "--with-dependencies" ]]; then + deep="--with-dependencies" + else + die "java-pkg_jar-from called with unknown parameter: ${1}" + fi + shift + done + + [[ ${#} -ne 1 ]] && die "${FUNCNAME} takes only one argument besides --*" + + + local pkgs="${1}" + + if [[ "${EAPI}" == "1" ]]; then + pkgs="${pkgs//:/-}" + fi + + jars="$(java-config ${deep} --classpath=${pkgs})" + [[ $? != 0 ]] && die "java-config --classpath=${pkgs} failed" + debug-print "${pkgs}:${jars}" + + for pkg in ${pkgs//,/ }; do + java-pkg_ensure-dep "${build_only}" "${pkg}" + done + + for pkg in ${pkgs//,/ }; do + if [[ -z "${build_only}" ]]; then + java-pkg_record-jar_ "${pkg}" + else + java-pkg_record-jar_ --build-only "${pkg}" + fi + done + + echo "${jars}" +} + +# @FUNCTION: java-pkg_getjar +# @USAGE: [--build-only] [--virtual] <package> <jarfile> +# @DESCRIPTION: +# Get the complete path of a single jar from a package +# The providing package is recorded as runtime dependency into package.env +# DEPEND line, unless "--build-only" is passed as the very first argument, for +# jars that have to be present only at build time and are not needed on runtime +# (junit testing etc). +# +# @CODE +# Example: +# java-pkg_getjar xerces-2 xml-apis.jar +# returns +# /usr/share/xerces-2/lib/xml-apis.jar +# +# Parameters: +# --build-only - makes the jar not added into package.env DEPEND line. +# --virtual - Packages passed to this function are to be handled as virtuals +# and will not have individual jar dependencies recorded. +# $1 - package to use +# $2 - jar to get +# @CODE +java-pkg_getjar() { + debug-print-function ${FUNCNAME} $* + + local build_only="" + local virtual="" + local record_jar="" + + [[ "${EBUILD_PHASE}" == "test" ]] && build_only="build" + + while [[ "${1}" == --* ]]; do + if [[ "${1}" = "--build-only" ]]; then + build_only="build" + elif [[ "${1}" == "--virtual" ]]; then + virtual="true" + else + die "java-pkg_getjar called with unknown parameter: ${1}" + fi + shift + done + + [[ ${#} -ne 2 ]] && die "${FUNCNAME} takes only two arguments besides --*" + + local pkg="${1}" target_jar="${2}" jar + + if [[ "${EAPI}" == "1" ]]; then + pkg="${pkg//:/-}" + fi + + [[ -z ${pkg} ]] && die "Must specify package to get a jar from" + [[ -z ${target_jar} ]] && die "Must specify jar to get" + + local error_msg="Could not find classpath for ${pkg}. Are you sure its installed?" + local classpath + classpath=$(java-config --classpath=${pkg}) + [[ $? != 0 ]] && die ${error_msg} + + java-pkg_ensure-dep "${build_only}" "${pkg}" + + # Record the package(Virtual) as a dependency and then set build_only + # So that individual jars are not recorded. + if [[ -n "${virtual}" ]]; then + if [[ -z "${build_only}" ]]; then + java-pkg_record-jar_ "${pkg}" + else + java-pkg_record-jar_ --build-only "${pkg}" + fi + record_jar="true" + fi + + for jar in ${classpath//:/ }; do + if [[ ! -f "${jar}" ]] ; then + die "Installation problem with jar ${jar} in ${pkg} - is it installed?" + fi + + if [[ "$(basename ${jar})" == "${target_jar}" ]] ; then + # Only record jars that aren't build-only + if [[ -z "${record_jar}" ]]; then + if [[ -z "${build_only}" ]]; then + java-pkg_record-jar_ "${pkg}" "${jar}" + else + java-pkg_record-jar_ --build-only "${pkg}" "${jar}" + fi + fi + echo "${jar}" + return 0 + fi + done + + die "Could not find ${target_jar} in ${pkg}" + return 1 +} + +# @FUNCTION: java-pkg_register-dependency +# @USAGE: <package>[,<package2>...] [<jarfile>] +# @DESCRIPTION: +# Registers runtime dependency on a package, list of packages, or a single jar +# from a package, into package.env DEPEND line. Can only be called in +# src_install phase. +# Intended for binary packages where you don't need to symlink the jars or get +# their classpath during build. As such, the dependencies only need to be +# specified in ebuild's RDEPEND, and should be omitted in DEPEND. +# +# @CODE +# Parameters: +# $1 - comma-separated list of packages, or a single package +# $2 - if param $1 is a single package, optionally specify the jar +# to depend on +# +# Examples: +# Record the dependency on whole xerces-2 and xalan, +# java-pkg_register-dependency xerces-2,xalan +# +# Record the dependency on ant.jar from ant-core +# java-pkg_register-dependency ant-core ant.jar +# @CODE +# +# Note: Passing both list of packages as the first parameter AND specifying the +# jar as the second is not allowed and will cause the function to die. We assume +# that there's more chance one passes such combination as a mistake, than that +# there are more packages providing identically named jar without class +# collisions. +java-pkg_register-dependency() { + debug-print-function ${FUNCNAME} $* + + java-pkg_check-phase install + + [[ ${#} -gt 2 ]] && die "${FUNCNAME} takes at most two arguments" + + local pkgs="${1}" + local jar="${2}" + + [[ -z "${pkgs}" ]] && die "${FUNCNAME} called with no package(s) specified" + + if [[ "${EAPI}" == "1" ]]; then + pkgs="${pkgs//:/-}" + fi + + if [[ -z "${jar}" ]]; then + for pkg in ${pkgs//,/ }; do + java-pkg_ensure-dep runtime "${pkg}" + java-pkg_record-jar_ "${pkg}" + done + else + [[ ${pkgs} == *,* ]] && \ + die "${FUNCNAME} called with both package list and jar name" + java-pkg_ensure-dep runtime "${pkgs}" + java-pkg_record-jar_ "${pkgs}" "${jar}" + fi + + java-pkg_do_write_ +} + +# @FUNCTION: java-pkg_register-optional-dependency +# @USAGE: <package>[,<package2>...] [<jarfile>] +# @DESCRIPTION: +# Registers optional runtime dependency on a package, list of packages, or a +# single jar from a package, into package.env OPTIONAL_DEPEND line. Can only be +# called in src_install phase. +# Intended for packages that can use other packages when those are in classpath. +# Will be put on classpath by launcher if they are installed. Typical case is +# JDBC implementations for various databases. It's better than having USE flag +# for each implementation triggering hard dependency. +# +# @CODE +# Parameters: +# $1 - comma-separated list of packages, or a single package +# $2 - if param $1 is a single package, optionally specify the jar to depend on +# +# Example: +# Record the optional dependency on some jdbc providers +# java-pkg_register-optional-dependency jdbc-jaybird,jtds-1.2,jdbc-mysql +# @CODE +# +# Note: Passing both list of packages as the first parameter AND specifying the +# jar as the second is not allowed and will cause the function to die. We assume +# that there's more chance one passes such combination as a mistake, than that +# there are more packages providing identically named jar without class +# collisions. +java-pkg_register-optional-dependency() { + debug-print-function ${FUNCNAME} $* + + java-pkg_check-phase install + + [[ ${#} -gt 2 ]] && die "${FUNCNAME} takes at most two arguments" + + local pkgs="${1}" + local jar="${2}" + + [[ -z "${pkgs}" ]] && die "${FUNCNAME} called with no package(s) specified" + + if [[ "${EAPI}" == "1" ]]; then + pkgs="${pkgs//:/-}" + fi + + if [[ -z "${jar}" ]]; then + for pkg in ${pkgs//,/ }; do + java-pkg_record-jar_ --optional "${pkg}" + done + else + [[ ${pkgs} == *,* ]] && \ + die "${FUNCNAME} called with both package list and jar name" + java-pkg_record-jar_ --optional "${pkgs}" "${jar}" + fi + + java-pkg_do_write_ +} + +# @FUNCTION: java-pkg_register-environment-variable +# @USAGE: <name> <value> +# @DESCRIPTION: +# Register an arbitrary environment variable into package.env. The gjl launcher +# for this package or any package depending on this will export it into +# environement before executing java command. +# Must only be called in src_install phase. +JAVA_PKG_EXTRA_ENV="${T}/java-pkg-extra-env" +JAVA_PKG_EXTRA_ENV_VARS="" +java-pkg_register-environment-variable() { + debug-print-function ${FUNCNAME} $* + + java-pkg_check-phase install + + [[ ${#} != 2 ]] && die "${FUNCNAME} takes two arguments" + + echo "${1}=\"${2}\"" >> ${JAVA_PKG_EXTRA_ENV} + JAVA_PKG_EXTRA_ENV_VARS="${JAVA_PKG_EXTRA_ENV_VARS} ${1}" + + java-pkg_do_write_ +} + +# @FUNCTION: java-pkg_get-bootclasspath +# @USAGE: <version> +# @DESCRIPTION: +# Returns classpath of a given bootclasspath-providing package version. +# +# @param $1 - the version of bootclasspath (e.g. 1.5), 'auto' for bootclasspath +# of the current JDK +java-pkg_get-bootclasspath() { + local version="${1}" + + local bcp + case "${version}" in + auto) + bcp="$(java-config -g BOOTCLASSPATH)" + ;; + 1.5) + bcp="$(java-pkg_getjars --build-only gnu-classpath-0.98)" + ;; + *) + eerror "unknown parameter of java-pkg_get-bootclasspath" + die "unknown parameter of java-pkg_get-bootclasspath" + ;; + esac + + echo "${bcp}" +} + + +# This function reads stdin, and based on that input, figures out how to +# populate jars from the filesystem. +# Need to figure out a good way of making use of this, ie be able to use a +# string that was built instead of stdin +# NOTE: this isn't quite ready for primetime. +#java-pkg_populate-jars() { +# local line +# +# read line +# while [[ -n "${line}" ]]; do +# # Ignore comments +# [[ ${line%%#*} == "" ]] && continue +# +# # get rid of any spaces +# line="${line// /}" +# +# # format: path=jarinfo +# local path=${line%%=*} +# local jarinfo=${line##*=} +# +# # format: jar@package +# local jar=${jarinfo%%@*}.jar +# local package=${jarinfo##*@} +# if [[ -n ${replace_only} ]]; then +# [[ ! -f $path ]] && die "No jar exists at ${path}" +# fi +# if [[ -n ${create_parent} ]]; then +# local parent=$(dirname ${path}) +# mkdir -p "${parent}" +# fi +# java-pkg_jar-from "${package}" "${jar}" "${path}" +# +# read line +# done +#} + +# @FUNCTION: java-pkg_find-normal-jars +# @USAGE: [<path/to/directory>] +# @DESCRIPTION: +# Find the files with suffix .jar file in the given directory (default: $WORKDIR) +java-pkg_find-normal-jars() { + local dir=$1 + [[ "${dir}" ]] || dir="${WORKDIR}" + local found + for jar in $(find "${dir}" -name "*.jar" -type f); do + echo "${jar}" + found="true" + done + [[ "${found}" ]] + return $? +} + +# @FUNCTION: java-pkg_ensure-no-bundled-jars +# @DESCRIPTION: +# Try to locate bundled jar files in ${WORKDIR} and die if found. +# This function should be called after WORKDIR has been populated with symlink +# to system jar files or bundled jars removed. +java-pkg_ensure-no-bundled-jars() { + debug-print-function ${FUNCNAME} $* + + local bundled_jars=$(java-pkg_find-normal-jars) + if [[ -n ${bundled_jars} ]]; then + echo "Bundled jars found:" + local jar + for jar in ${bundled_jars}; do + echo $(pwd)${jar/./} + done + die "Bundled jars found!" + fi +} + +# @FUNCTION: java-pkg_ensure-vm-version-sufficient +# @INTERNAL +# @DESCRIPTION: +# Checks if we have a sufficient VM and dies if we don't. +java-pkg_ensure-vm-version-sufficient() { + debug-print-function ${FUNCNAME} $* + + if ! java-pkg_is-vm-version-sufficient; then + debug-print "VM is not suffient" + eerror "Current Java VM cannot build this package" + einfo "Please use \"eselect java-vm set system\" to set the correct one" + die "Active Java VM cannot build this package" + fi +} + +# @FUNCTION: java-pkg_is-vm-version-sufficient +# @INTERNAL +# @DESCRIPTION: +# @RETURN: zero - VM is sufficient; non-zero - VM is not sufficient +java-pkg_is-vm-version-sufficient() { + debug-print-function ${FUNCNAME} $* + + depend-java-query --is-sufficient "${DEPEND}" > /dev/null + return $? +} + +# @FUNCTION: java-pkg_ensure-vm-version-eq +# @INTERNAL +# @DESCRIPTION: +# Die if the current VM is not equal to the argument passed. +# +# @param $@ - Desired VM version to ensure +java-pkg_ensure-vm-version-eq() { + debug-print-function ${FUNCNAME} $* + + if ! java-pkg_is-vm-version-eq $@ ; then + debug-print "VM is not suffient" + eerror "This package requires a Java VM version = $@" + einfo "Please use \"eselect java-vm set system\" to set the correct one" + die "Active Java VM too old" + fi +} + +# @FUNCTION: java-pkg_is-vm-version-eq +# @USAGE: <version> +# @INTERNAL +# @RETURN: zero - VM versions are equal; non-zero - VM version are not equal +java-pkg_is-vm-version-eq() { + debug-print-function ${FUNCNAME} $* + + local needed_version="$@" + + [[ -z "${needed_version}" ]] && die "need an argument" + + local vm_version="$(java-pkg_get-vm-version)" + + vm_version="$(ver_cut 1-2 "${vm_version}")" + needed_version="$(ver_cut 1-2 "${needed_version}")" + + if [[ -z "${vm_version}" ]]; then + debug-print "Could not get JDK version from DEPEND" + return 1 + else + if [[ "${vm_version}" == "${needed_version}" ]]; then + debug-print "Detected a JDK(${vm_version}) = ${needed_version}" + return 0 + else + debug-print "Detected a JDK(${vm_version}) != ${needed_version}" + return 1 + fi + fi +} + +# @FUNCTION: java-pkg_ensure-vm-version-ge +# @INTERNAL +# @DESCRIPTION: +# Die if the current VM is not greater than the desired version +# +# @param $@ - VM version to compare current to +java-pkg_ensure-vm-version-ge() { + debug-print-function ${FUNCNAME} $* + + if ! java-pkg_is-vm-version-ge "$@" ; then + debug-print "vm is not suffient" + eerror "This package requires a Java VM version >= $@" + einfo "Please use \"eselect java-vm set system\" to set the correct one" + die "Active Java VM too old" + fi +} + +# @FUNCTION: java-pkg_is-vm-version-ge +# @INTERNAL +# @DESCRIPTION: +# @CODE +# Parameters: +# $@ - VM version to compare current VM to +# @CODE +# @RETURN: zero - current VM version is greater than checked version; +# non-zero - current VM version is not greater than checked version +java-pkg_is-vm-version-ge() { + debug-print-function ${FUNCNAME} $* + + local needed_version=$@ + local vm_version=$(java-pkg_get-vm-version) + if [[ -z "${vm_version}" ]]; then + debug-print "Could not get JDK version from DEPEND" + return 1 + else + if ver_test "${vm_version}" -ge "${needed_version}"; then + debug-print "Detected a JDK(${vm_version}) >= ${needed_version}" + return 0 + else + debug-print "Detected a JDK(${vm_version}) < ${needed_version}" + return 1 + fi + fi +} + +java-pkg_set-current-vm() { + export GENTOO_VM=${1} +} + +java-pkg_get-current-vm() { + echo ${GENTOO_VM} +} + +java-pkg_current-vm-matches() { + has $(java-pkg_get-current-vm) ${@} + return $? +} + +# @FUNCTION: java-pkg_get-source +# @DESCRIPTION: +# Determines what source version should be used, for passing to -source. +# Unless you want to break things you probably shouldn't set _WANT_SOURCE +# +# @RETURN: string - Either the lowest possible source, or JAVA_PKG_WANT_SOURCE +java-pkg_get-source() { + echo ${JAVA_PKG_WANT_SOURCE:-$(depend-java-query --get-lowest "${DEPEND} ${RDEPEND}")} +} + +# @FUNCTION: java-pkg_get-target +# @DESCRIPTION: +# Determines what target version should be used, for passing to -target. +# If you don't care about lower versions, you can set _WANT_TARGET to the +# version of your JDK. +# +# @RETURN: string - Either the lowest possible target, or JAVA_PKG_WANT_TARGET +java-pkg_get-target() { + echo ${JAVA_PKG_WANT_TARGET:-$(depend-java-query --get-lowest "${DEPEND} ${RDEPEND}")} +} + +# @FUNCTION: java-pkg_get-javac +# @DESCRIPTION: +# Returns the compiler executable +java-pkg_get-javac() { + debug-print-function ${FUNCNAME} $* + + java-pkg_init-compiler_ + local compiler="${GENTOO_COMPILER}" + + local compiler_executable + if [[ "${compiler}" = "javac" ]]; then + # nothing fancy needs to be done for javac + compiler_executable="javac" + else + # for everything else, try to determine from an env file + + local compiler_env="/usr/share/java-config-2/compiler/${compiler}" + if [[ -f ${compiler_env} ]]; then + local old_javac=${JAVAC} + unset JAVAC + # try to get value of JAVAC + compiler_executable="$(source ${compiler_env} 1>/dev/null 2>&1; echo ${JAVAC})" + export JAVAC=${old_javac} + + if [[ -z ${compiler_executable} ]]; then + die "JAVAC is empty or undefined in ${compiler_env}" + fi + + # check that it's executable + if [[ ! -x ${compiler_executable} ]]; then + die "${compiler_executable} doesn't exist, or isn't executable" + fi + else + die "Could not find environment file for ${compiler}" + fi + fi + echo ${compiler_executable} +} + +# @FUNCTION: java-pkg_javac-args +# @DESCRIPTION: +# If an ebuild uses javac directly, instead of using ejavac, it should call this +# to know what -source/-target to use. +# +# @RETURN: string - arguments to pass to javac, complete with -target and -source +java-pkg_javac-args() { + debug-print-function ${FUNCNAME} $* + + local want_source="$(java-pkg_get-source)" + local want_target="$(java-pkg_get-target)" + + local source_str="-source ${want_source}" + local target_str="-target ${want_target}" + + debug-print "want source: ${want_source}" + debug-print "want target: ${want_target}" + + if [[ -z "${want_source}" || -z "${want_target}" ]]; then + die "Could not find valid -source/-target values for javac" + else + echo "${source_str} ${target_str}" + fi +} + +# @FUNCTION: java-pkg_get-jni-cflags +# @DESCRIPTION: +# Echos the CFLAGS for JNI compilations +java-pkg_get-jni-cflags() { + local flags="-I${JAVA_HOME}/include" + + local platform="linux" + use elibc_FreeBSD && platform="freebsd" + + # TODO do a check that the directories are valid + flags="${flags} -I${JAVA_HOME}/include/${platform}" + + echo ${flags} +} + +java-pkg_ensure-gcj() { + # was enforcing sys-devel/gcc[gcj] + die "${FUNCNAME} was removed. Use use-deps available as of EAPI 2 instead. #261562" +} + +java-pkg_ensure-test() { + # was enforcing USE=test if FEATURES=test + die "${FUNCNAME} was removed. Package mangers handle this already. #278965" +} + +# @FUNCTION: java-pkg_register-ant-task +# @USAGE: [--version x.y] [<name>] +# @DESCRIPTION: +# Register this package as ant task, so that ant will load it when no specific +# ANT_TASKS are specified. Note that even without this registering, all packages +# specified in ANT_TASKS will be loaded. Mostly used by the actual ant tasks +# packages, but can be also used by other ebuilds that used to symlink their +# .jar into /usr/share/ant-core/lib to get autoloaded, for backwards +# compatibility. +# +# @CODE +# Parameters +# --version x.y Register only for ant version x.y (otherwise for any ant +# version). Used by the ant-* packages to prevent loading of mismatched +# ant-core ant tasks after core was updated, before the tasks are updated, +# without a need for blockers. +# $1 Name to register as. Defaults to JAVA_PKG_NAME ($PN[-$SLOT]) +# @CODE +java-pkg_register-ant-task() { + local TASKS_DIR="tasks" + + # check for --version x.y parameters + while [[ -n "${1}" && -n "${2}" ]]; do + local var="${1#--}" + local val="${2}" + if [[ "${var}" == "version" ]]; then + TASKS_DIR="tasks-${val}" + else + die "Unknown parameter passed to java-pkg_register-ant-tasks: ${1} ${2}" + fi + shift 2 + done + + local TASK_NAME="${1:-${JAVA_PKG_NAME}}" + + dodir /usr/share/ant/${TASKS_DIR} + touch "${ED}/usr/share/ant/${TASKS_DIR}/${TASK_NAME}" +} + +# @FUNCTION: java-pkg_ant-tasks-depend +# @INTERNAL +# @DESCRIPTION: +# Translates the WANT_ANT_TASKS variable into valid dependencies. +java-pkg_ant-tasks-depend() { + debug-print-function ${FUNCNAME} ${WANT_ANT_TASKS} + + if [[ -n "${WANT_ANT_TASKS}" ]]; then + local DEP="" + for i in ${WANT_ANT_TASKS} + do + if [[ ${i} = ant-* ]]; then + DEP="${DEP}dev-java/${i} " + elif [[ ${i} = */*:* ]]; then + DEP="${DEP}${i} " + else + echo "Invalid atom in WANT_ANT_TASKS: ${i}" + return 1 + fi + done + echo ${DEP} + return 0 + else + return 0 + fi +} + + +# @FUNCTION: ejunit_ +# @INTERNAL +# @DESCRIPTION: +# Internal Junit wrapper function. Makes it easier to run the tests and checks for +# dev-java/junit in DEPEND. Launches the tests using junit.textui.TestRunner. +# @CODE +# Parameters: +# $1 - junit package (junit or junit-4) +# $2 - -cp or -classpath +# $3 - classpath; junit and recorded dependencies get appended +# $@ - the rest of the parameters are passed to java +# @CODE +ejunit_() { + debug-print-function ${FUNCNAME} $* + + local pkgs + if [[ -f ${JAVA_PKG_DEPEND_FILE} ]]; then + for atom in $(cat ${JAVA_PKG_DEPEND_FILE} | tr : ' '); do + pkgs=${pkgs},$(echo ${atom} | sed -re "s/^.*@//") + done + fi + + local junit=${1} + shift 1 + + local cp=$(java-pkg_getjars --with-dependencies ${junit}${pkgs}) + if [[ ${1} = -cp || ${1} = -classpath ]]; then + cp="${2}:${cp}" + shift 2 + else + cp=".:${cp}" + fi + + local runner=junit.textui.TestRunner + if [[ "${junit}" == "junit-4" ]] ; then + runner=org.junit.runner.JUnitCore + fi + debug-print "Calling: java -cp \"${cp}\" -Djava.io.tmpdir=\"${T}\" -Djava.awt.headless=true ${runner} ${@}" + java -cp "${cp}" -Djava.io.tmpdir="${T}/" -Djava.awt.headless=true ${runner} "${@}" || die "Running junit failed" +} + +# @FUNCTION: ejunit +# @DESCRIPTION: +# Junit wrapper function. Makes it easier to run the tests and checks for +# dev-java/junit in DEPEND. Launches the tests using org.junit.runner.JUnitCore. +# +# @CODE +# Parameters: +# $1 - -cp or -classpath +# $2 - classpath; junit and recorded dependencies get appended +# $@ - the rest of the parameters are passed to java +# +# Examples: +# ejunit -cp build/classes org.blinkenlights.jid3.test.AllTests +# ejunit org.blinkenlights.jid3.test.AllTests +# ejunit org.blinkenlights.jid3.test.FirstTest org.blinkenlights.jid3.test.SecondTest +# @CODE +ejunit() { + debug-print-function ${FUNCNAME} $* + + ejunit_ "junit" "${@}" +} + +# @FUNCTION: ejunit4 +# @DESCRIPTION: +# Junit4 wrapper function. Makes it easier to run the tests and checks for +# dev-java/junit:4 in DEPEND. Launches the tests using junit.textui.TestRunner. +# +# @CODE +# Parameters: +# $1 - -cp or -classpath +# $2 - classpath; junit and recorded dependencies get appended +# $@ - the rest of the parameters are passed to java +# +# Examples: +# ejunit4 -cp build/classes org.blinkenlights.jid3.test.AllTests +# ejunit4 org.blinkenlights.jid3.test.AllTests +# ejunit4 org.blinkenlights.jid3.test.FirstTest \ +# org.blinkenlights.jid3.test.SecondTest +# @CODE +ejunit4() { + debug-print-function ${FUNCNAME} $* + + ejunit_ "junit-4" "${@}" +} + +# @FUNCTION: etestng +# @USAGE: etestng_ [-cp $classpath] <test classes> +# @INTERNAL +# @DESCRIPTION: +# Testng wrapper function. Makes it easier to run the tests. +# Launches the tests using org.testng.TestNG. +# +# @CODE +# $1 - -cp or -classpath +# $2 - the classpath passed to it +# $@ - test classes for testng to run. +# @CODE +etestng() { + debug-print-function ${FUNCNAME} $* + + local runner=org.testng.TestNG + local cp=$(java-pkg_getjars --with-dependencies testng) + local tests + + if [[ ${1} = -cp || ${1} = -classpath ]]; then + cp="${cp}:${2}" + shift 2 + else + cp="${cp}:." + fi + + for test in ${@}; do + tests+="${test}," + done + + debug-print "java -cp \"${cp}\" -Djava.io.tmpdir=\"${T}\""\ + "-Djava.awt.headless=true ${runner}"\ + "-usedefaultlisteners false -testclass ${tests}" + java -cp "${cp}" -Djava.io.tmpdir=\"${T}\" -Djava.awt.headless=true\ + ${runner} -usedefaultlisteners false -testclass ${tests}\ + || die "Running TestNG failed." +} + +# @FUNCTION: java-utils-2_src_prepare +# @DESCRIPTION: +# src_prepare Searches for bundled jars +# Don't call directly, but via java-pkg-2_src_prepare! +java-utils-2_src_prepare() { + case ${EAPI:-0} in + [0-5]) + java-pkg_func-exists java_prepare && java_prepare ;; + *) + java-pkg_func-exists java_prepare && + eqawarn "java_prepare is no longer called, define src_prepare instead." + eapply_user ;; + esac + + # Check for files in JAVA_RM_FILES array. + if [[ ${JAVA_RM_FILES[@]} ]]; then + debug-print "$FUNCNAME: removing unneeded files" + java-pkg_rm_files "${JAVA_RM_FILES[@]}" + fi + + if is-java-strict; then + echo "Searching for bundled jars:" + java-pkg_find-normal-jars || echo "None found." + echo "Searching for bundled classes (no output if none found):" + find "${WORKDIR}" -name "*.class" + echo "Search done." + fi +} + +# @FUNCTION: java-utils-2_pkg_preinst +# @DESCRIPTION: +# pkg_preinst Searches for missing and unneeded dependencies +# Don't call directly, but via java-pkg-2_pkg_preinst! +java-utils-2_pkg_preinst() { + if is-java-strict; then + if [[ ! -e "${JAVA_PKG_ENV}" ]] || has ant-tasks ${INHERITED}; then + return + fi + + if has_version dev-java/java-dep-check; then + local output=$(GENTOO_VM= java-dep-check --image "${D}" "${JAVA_PKG_ENV}") + [[ ${output} ]] && ewarn "${output}" + else + eerror "Install dev-java/java-dep-check for dependency checking" + fi + fi +} + +# @FUNCTION: eant +# @USAGE: <ant_build_target(s)> +# @DESCRIPTION: +# Ant wrapper function. Will use the appropriate compiler, based on user-defined +# compiler. Will also set proper ANT_TASKS from the variable ANT_TASKS, +# variables: +# +# @CODE +# Variables: +# EANT_GENTOO_CLASSPATH - calls java-pkg_getjars for the value and adds to the +# gentoo.classpath property. Be sure to call java-ant_rewrite-classpath in src_unpack. +# EANT_NEEDS_TOOLS - add tools.jar to the gentoo.classpath. Should only be used +# for build-time purposes, the dependency is not recorded to +# package.env! +# ANT_TASKS - used to determine ANT_TASKS before calling Ant. +# @CODE +eant() { + debug-print-function ${FUNCNAME} $* + + if [[ ${EBUILD_PHASE} = compile ]]; then + java-ant-2_src_configure + fi + + if ! has java-ant-2 ${INHERITED}; then + local msg="You should inherit java-ant-2 when using eant" + java-pkg_announce-qa-violation "${msg}" + fi + + local antflags="-Dnoget=true -Dmaven.mode.offline=true -Dbuild.sysclasspath=ignore" + + java-pkg_init-compiler_ + local compiler="${GENTOO_COMPILER}" + + local compiler_env="${JAVA_PKG_COMPILER_DIR}/${compiler}" + local build_compiler="$(source ${compiler_env} 1>/dev/null 2>&1; echo ${ANT_BUILD_COMPILER})" + if [[ "${compiler}" != "javac" && -z "${build_compiler}" ]]; then + die "ANT_BUILD_COMPILER undefined in ${compiler_env}" + fi + + if [[ ${compiler} != "javac" ]]; then + antflags="${antflags} -Dbuild.compiler=${build_compiler}" + # Figure out any extra stuff to put on the classpath for compilers aside + # from javac + # ANT_BUILD_COMPILER_DEPS should be something that could be passed to + # java-config -p + local build_compiler_deps="$(source ${JAVA_PKG_COMPILER_DIR}/${compiler} 1>/dev/null 2>&1; echo ${ANT_BUILD_COMPILER_DEPS})" + if [[ -n ${build_compiler_deps} ]]; then + antflags="${antflags} -lib $(java-config -p ${build_compiler_deps})" + fi + fi + + for arg in "${@}"; do + if [[ ${arg} = -lib ]]; then + if is-java-strict; then + eerror "You should not use the -lib argument to eant because it will fail" + eerror "with JAVA_PKG_STRICT. Please use for example java-pkg_jar-from" + eerror "or ant properties to make dependencies available." + eerror "For ant tasks use WANT_ANT_TASKS or ANT_TASKS from." + eerror "split ant (>=dev-java/ant-core-1.7)." + die "eant -lib is deprecated/forbidden" + else + echo "eant -lib is deprecated. Turn JAVA_PKG_STRICT on for" + echo "more info." + fi + fi + done + + # parse WANT_ANT_TASKS for atoms + local want_ant_tasks + for i in ${WANT_ANT_TASKS}; do + if [[ ${i} = */*:* ]]; then + i=${i#*/} + i=${i%:0} + want_ant_tasks+="${i/:/-} " + else + want_ant_tasks+="${i} " + fi + done + # default ANT_TASKS to WANT_ANT_TASKS, if ANT_TASKS is not set explicitly + ANT_TASKS="${ANT_TASKS:-${want_ant_tasks% }}" + + # override ANT_TASKS with JAVA_PKG_FORCE_ANT_TASKS if it's set + ANT_TASKS="${JAVA_PKG_FORCE_ANT_TASKS:-${ANT_TASKS}}" + + # if ant-tasks is not set by ebuild or forced, use none + ANT_TASKS="${ANT_TASKS:-none}" + + # at this point, ANT_TASKS should be "all", "none" or explicit list + if [[ "${ANT_TASKS}" == "all" ]]; then + einfo "Using all available ANT_TASKS" + elif [[ "${ANT_TASKS}" == "none" ]]; then + einfo "Disabling all optional ANT_TASKS" + else + einfo "Using following ANT_TASKS: ${ANT_TASKS}" + fi + + export ANT_TASKS + + [[ -n ${JAVA_PKG_DEBUG} ]] && antflags="${antflags} --execdebug -debug" + [[ -n ${PORTAGE_QUIET} ]] && antflags="${antflags} -q" + + local gcp="${EANT_GENTOO_CLASSPATH}" + local getjarsarg="" + + if [[ ${EBUILD_PHASE} = "test" ]]; then + antflags="${antflags} -DJunit.present=true" + getjarsarg="--with-dependencies" + + local re="\bant-junit4?([-:]\S+)?\b" + [[ ${ANT_TASKS} =~ ${re} ]] && gcp+=" ${BASH_REMATCH[0]}" + else + antflags="${antflags} -Dmaven.test.skip=true" + fi + + local cp + + for atom in ${gcp}; do + cp+=":$(java-pkg_getjars ${getjarsarg} ${atom})" + done + + [[ ${EANT_NEEDS_TOOLS} ]] && cp+=":$(java-config --tools)" + [[ ${EANT_GENTOO_CLASSPATH_EXTRA} ]] && cp+=":${EANT_GENTOO_CLASSPATH_EXTRA}" + + if [[ ${cp#:} ]]; then + # It seems ant does not like single quotes around ${cp} + # And ant 1.9.13+ also does not like double quotes around ${cp} + # https://bz.apache.org/bugzilla/show_bug.cgi?id=58898 + antflags="${antflags} -Dgentoo.classpath=${cp#:}" + fi + + [[ -n ${JAVA_PKG_DEBUG} ]] && echo ant ${antflags} "${@}" + debug-print "Calling ant (GENTOO_VM: ${GENTOO_VM}): ${antflags} ${@}" + ant ${antflags} "${@}" || die "eant failed" +} + +# @FUNCTION: ejavac +# @USAGE: <javac_arguments> +# @DESCRIPTION: +# Javac wrapper function. Will use the appropriate compiler, based on +# /etc/java-config/compilers.conf +ejavac() { + debug-print-function ${FUNCNAME} $* + + local compiler_executable + compiler_executable=$(java-pkg_get-javac) + + local javac_args + javac_args="$(java-pkg_javac-args)" + + if [[ -n ${JAVA_PKG_DEBUG} ]]; then + einfo "Verbose logging for \"${FUNCNAME}\" function" + einfo "Compiler executable: ${compiler_executable}" + einfo "Extra arguments: ${javac_args}" + einfo "Complete command:" + einfo "${compiler_executable} ${javac_args} ${@}" + fi + + ebegin "Compiling" + ${compiler_executable} ${javac_args} "${@}" || die "ejavac failed" +} + +# @FUNCTION: ejavadoc +# @USAGE: <javadoc_arguments> +# @DESCRIPTION: +# javadoc wrapper function. Will set some flags based on the VM version +# due to strict javadoc rules in 1.8. +ejavadoc() { + debug-print-function ${FUNCNAME} $* + + local javadoc_args="" + + if java-pkg_is-vm-version-ge "1.8" ; then + javadoc_args="-Xdoclint:none" + fi + + if [[ -n ${JAVA_PKG_DEBUG} ]]; then + einfo "Verbose logging for \"${FUNCNAME}\" function" + einfo "Javadoc executable: javadoc" + einfo "Extra arguments: ${javadoc_args}" + einfo "Complete command:" + einfo "javadoc ${javadoc_args} ${@}" + fi + + ebegin "Generating JavaDoc" + javadoc ${javadoc_args} "${@}" || die "ejavadoc failed" +} + +# @FUNCTION: java-pkg_filter-compiler +# @USAGE: <compiler(s)_to_filter> +# @DESCRIPTION: +# Used to prevent the use of some compilers. Should be used in src_compile. +# Basically, it just appends onto JAVA_PKG_FILTER_COMPILER +java-pkg_filter-compiler() { + JAVA_PKG_FILTER_COMPILER="${JAVA_PKG_FILTER_COMPILER} $@" +} + +# @FUNCTION: java-pkg_force-compiler +# @USAGE: <compiler(s)_to_force> +# @DESCRIPTION: +# Used to force the use of particular compilers. Should be used in src_compile. +# A common use of this would be to force ecj-3.1 to be used on amd64, to avoid +# OutOfMemoryErrors that may come up. +java-pkg_force-compiler() { + JAVA_PKG_FORCE_COMPILER="$@" +} + +# @FUNCTION: use_doc +# @DESCRIPTION: +# +# Helper function for getting ant to build javadocs. If the user has USE=doc, +# then 'javadoc' or the argument are returned. Otherwise, there is no return. +# +# The output of this should be passed to ant. +# @CODE +# Parameters: +# $@ - Option value to return. Defaults to 'javadoc' +# +# Examples: +# build javadocs by calling 'javadoc' target +# eant $(use_doc) +# +# build javadocs by calling 'apidoc' target +# eant $(use_doc apidoc) +# @CODE +# @RETURN string - Name of the target to create javadocs +use_doc() { + use doc && echo ${@:-javadoc} +} + + +# @FUNCTION: java-pkg_init +# @INTERNAL +# @DESCRIPTION: +# The purpose of this function, as the name might imply, is to initialize the +# Java environment. It ensures that that there aren't any environment variables +# that'll muss things up. It initializes some variables, which are used +# internally. And most importantly, it'll switch the VM if necessary. +# +# This shouldn't be used directly. Instead, java-pkg and java-pkg-opt will +# call it during each of the phases of the merge process. +java-pkg_init() { + debug-print-function ${FUNCNAME} $* + + # Don't set up build environment if installing from binary. #206024 #258423 + [[ "${MERGE_TYPE}" == "binary" ]] && return + # Also try Portage's nonstandard EMERGE_FROM for old EAPIs, if it doesn't + # work nothing is lost. + has ${EAPI:-0} 0 1 2 3 && [[ "${EMERGE_FROM}" == "binary" ]] && return + + unset JAVAC + unset JAVA_HOME + + java-config --help >/dev/null || { + eerror "" + eerror "Can't run java-config --help" + eerror "Have you upgraded python recently but haven't" + eerror "run python-updater yet?" + die "Can't run java-config --help" + } + + # People do all kinds of weird things. + # https://forums.gentoo.org/viewtopic-p-3943166.html + local silence="${SILENCE_JAVA_OPTIONS_WARNING}" + local accept="${I_WANT_GLOBAL_JAVA_OPTIONS}" + if [[ -n ${_JAVA_OPTIONS} && -z ${accept} && -z ${silence} ]]; then + ewarn "_JAVA_OPTIONS changes what java -version outputs at least for" + ewarn "sun-jdk vms and and as such break configure scripts that" + ewarn "use it (for example app-office/openoffice) so we filter it out." + ewarn "Use SILENCE_JAVA_OPTIONS_WARNING=true in the environment (use" + ewarn "make.conf for example) to silence this warning or" + ewarn "I_WANT_GLOBAL_JAVA_OPTIONS to not filter it." + fi + + if [[ -z ${accept} ]]; then + # export _JAVA_OPTIONS= doesn't work because it will show up in java + # -version output + unset _JAVA_OPTIONS + # phase hooks make this run many times without this + I_WANT_GLOBAL_JAVA_OPTIONS="true" + fi + + java-pkg_switch-vm + PATH=${JAVA_HOME}/bin:${PATH} + + # TODO we will probably want to set JAVAC and JAVACFLAGS + + # Do some QA checks + java-pkg_check-jikes + + # Can't use unset here because Portage does not save the unset + # see https://bugs.gentoo.org/show_bug.cgi?id=189417#c11 + + # When users have crazy classpaths some packages can fail to compile. + # and everything should work with empty CLASSPATH. + # This also helps prevent unexpected dependencies on random things + # from the CLASSPATH. + export CLASSPATH= + + # Unset external ANT_ stuff + export ANT_TASKS= + export ANT_OPTS= + export ANT_RESPECT_JAVA_HOME= +} + +# @FUNCTION: java-pkg-init-compiler_ +# @INTERNAL +# @DESCRIPTION: +# This function attempts to figure out what compiler should be used. It does +# this by reading the file at JAVA_PKG_COMPILERS_CONF, and checking the +# COMPILERS variable defined there. +# This can be overridden by a list in JAVA_PKG_FORCE_COMPILER +# +# It will go through the list of compilers, and verify that it supports the +# target and source that are needed. If it is not suitable, then the next +# compiler is checked. When JAVA_PKG_FORCE_COMPILER is defined, this checking +# isn't done. +# +# Once the which compiler to use has been figured out, it is set to +# GENTOO_COMPILER. +# +# If you hadn't guessed, JAVA_PKG_FORCE_COMPILER is for testing only. +# +# If the user doesn't defined anything in JAVA_PKG_COMPILERS_CONF, or no +# suitable compiler was found there, then the default is to use javac provided +# by the current VM. +# +# +# @RETURN name of the compiler to use +java-pkg_init-compiler_() { + debug-print-function ${FUNCNAME} $* + + if [[ -n ${GENTOO_COMPILER} ]]; then + debug-print "GENTOO_COMPILER already set" + return + fi + + local compilers; + if [[ -z ${JAVA_PKG_FORCE_COMPILER} ]]; then + compilers="$(source ${JAVA_PKG_COMPILERS_CONF} 1>/dev/null 2>&1; echo ${COMPILERS})" + else + compilers=${JAVA_PKG_FORCE_COMPILER} + fi + + debug-print "Read \"${compilers}\" from ${JAVA_PKG_COMPILERS_CONF}" + + # Figure out if we should announce what compiler we're using + local compiler + for compiler in ${compilers}; do + debug-print "Checking ${compiler}..." + # javac should always be alright + if [[ ${compiler} = "javac" ]]; then + debug-print "Found javac... breaking" + export GENTOO_COMPILER="javac" + break + fi + + if has ${compiler} ${JAVA_PKG_FILTER_COMPILER}; then + if [[ -z ${JAVA_PKG_FORCE_COMPILER} ]]; then + einfo "Filtering ${compiler}" >&2 + continue + fi + fi + + # for non-javac, we need to make sure it supports the right target and + # source + local compiler_env="${JAVA_PKG_COMPILER_DIR}/${compiler}" + if [[ -f ${compiler_env} ]]; then + local desired_target="$(java-pkg_get-target)" + local desired_source="$(java-pkg_get-source)" + + + # Verify that the compiler supports target + local supported_target=$(source ${compiler_env} 1>/dev/null 2>&1; echo ${SUPPORTED_TARGET}) + if ! has ${desired_target} ${supported_target}; then + ewarn "${compiler} does not support -target ${desired_target}, skipping" + continue + fi + + # Verify that the compiler supports source + local supported_source=$(source ${compiler_env} 1>/dev/null 2>&1; echo ${SUPPORTED_SOURCE}) + if ! has ${desired_source} ${supported_source}; then + ewarn "${compiler} does not support -source ${desired_source}, skipping" + continue + fi + + # if you get here, then the compiler should be good to go + export GENTOO_COMPILER="${compiler}" + break + else + ewarn "Could not find configuration for ${compiler}, skipping" + ewarn "Perhaps it is not installed?" + continue + fi + done + + # If it hasn't been defined already, default to javac + if [[ -z ${GENTOO_COMPILER} ]]; then + if [[ -n ${compilers} ]]; then + einfo "No suitable compiler found: defaulting to JDK default for compilation" >&2 + else + # probably don't need to notify users about the default. + :;#einfo "Defaulting to javac for compilation" >&2 + fi + if java-config -g GENTOO_COMPILER 2> /dev/null; then + export GENTOO_COMPILER=$(java-config -g GENTOO_COMPILER) + else + export GENTOO_COMPILER=javac + fi + else + einfo "Using ${GENTOO_COMPILER} for compilation" >&2 + fi + +} + +# @FUNCTION: init_paths_ +# @INTERNAL +# @DESCRIPTION: +# Initializes some variables that will be used. These variables are mostly used +# to determine where things will eventually get installed. +java-pkg_init_paths_() { + debug-print-function ${FUNCNAME} $* + + local pkg_name + if [[ "${SLOT%/*}" == "0" ]] ; then + JAVA_PKG_NAME="${PN}" + else + JAVA_PKG_NAME="${PN}-${SLOT%/*}" + fi + + JAVA_PKG_SHAREPATH="/usr/share/${JAVA_PKG_NAME}" + JAVA_PKG_SOURCESPATH="${JAVA_PKG_SHAREPATH}/sources/" + JAVA_PKG_ENV="${ED}${JAVA_PKG_SHAREPATH}/package.env" + JAVA_PKG_VIRTUALS_PATH="/usr/share/java-config-2/virtuals" + JAVA_PKG_VIRTUAL_PROVIDER="${ED}${JAVA_PKG_VIRTUALS_PATH}/${JAVA_PKG_NAME}" + + [[ -z "${JAVA_PKG_JARDEST}" ]] && JAVA_PKG_JARDEST="${JAVA_PKG_SHAREPATH}/lib" + [[ -z "${JAVA_PKG_LIBDEST}" ]] && JAVA_PKG_LIBDEST="/usr/$(get_libdir)/${JAVA_PKG_NAME}" + [[ -z "${JAVA_PKG_WARDEST}" ]] && JAVA_PKG_WARDEST="${JAVA_PKG_SHAREPATH}/webapps" + + # TODO maybe only print once? + debug-print "JAVA_PKG_SHAREPATH: ${JAVA_PKG_SHAREPATH}" + debug-print "JAVA_PKG_ENV: ${JAVA_PKG_ENV}" + debug-print "JAVA_PKG_JARDEST: ${JAVA_PKG_JARDEST}" + debug-print "JAVA_PKG_LIBDEST: ${JAVA_PKG_LIBDEST}" + debug-print "JAVA_PKG_WARDEST: ${JAVA_PKG_WARDEST}" +} + +# @FUNCTION: java-pkg_do_write_ +# @INTERNAL +# @DESCRIPTION: +# Writes the package.env out to disk. +# +# TODO change to do-write, to match everything else +java-pkg_do_write_() { + debug-print-function ${FUNCNAME} $* + java-pkg_init_paths_ + # Create directory for package.env + dodir "${JAVA_PKG_SHAREPATH}" + + # Create package.env + ( + echo "DESCRIPTION=\"${DESCRIPTION}\"" + echo "GENERATION=\"2\"" + echo "SLOT=\"${SLOT}\"" + echo "CATEGORY=\"${CATEGORY}\"" + echo "PVR=\"${PVR}\"" + + [[ -n "${JAVA_PKG_CLASSPATH}" ]] && echo "CLASSPATH=\"${JAVA_PKG_CLASSPATH}\"" + [[ -n "${JAVA_PKG_LIBRARY}" ]] && echo "LIBRARY_PATH=\"${JAVA_PKG_LIBRARY}\"" + [[ -n "${JAVA_PROVIDE}" ]] && echo "PROVIDES=\"${JAVA_PROVIDE}\"" + [[ -f "${JAVA_PKG_DEPEND_FILE}" ]] \ + && echo "DEPEND=\"$(sort -u "${JAVA_PKG_DEPEND_FILE}" | tr '\n' ':')\"" + [[ -f "${JAVA_PKG_OPTIONAL_DEPEND_FILE}" ]] \ + && echo "OPTIONAL_DEPEND=\"$(sort -u "${JAVA_PKG_OPTIONAL_DEPEND_FILE}" | tr '\n' ':')\"" + echo "VM=\"$(echo ${RDEPEND} ${DEPEND} | sed -e 's/ /\n/g' | sed -n -e '/virtual\/\(jre\|jdk\)/ { p;q }')\"" # TODO cleanup ! + [[ -f "${JAVA_PKG_BUILD_DEPEND_FILE}" ]] \ + && echo "BUILD_DEPEND=\"$(sort -u "${JAVA_PKG_BUILD_DEPEND_FILE}" | tr '\n' ':')\"" + ) > "${JAVA_PKG_ENV}" + + # register target/source + local target="$(java-pkg_get-target)" + local source="$(java-pkg_get-source)" + [[ -n ${target} ]] && echo "TARGET=\"${target}\"" >> "${JAVA_PKG_ENV}" + [[ -n ${source} ]] && echo "SOURCE=\"${source}\"" >> "${JAVA_PKG_ENV}" + + # register javadoc info + [[ -n ${JAVADOC_PATH} ]] && echo "JAVADOC_PATH=\"${JAVADOC_PATH}\"" \ + >> ${JAVA_PKG_ENV} + # register source archives + [[ -n ${JAVA_SOURCES} ]] && echo "JAVA_SOURCES=\"${JAVA_SOURCES}\"" \ + >> ${JAVA_PKG_ENV} + + echo "MERGE_VM=\"${GENTOO_VM}\"" >> "${JAVA_PKG_ENV}" + [[ -n ${GENTOO_COMPILER} ]] && echo "MERGE_COMPILER=\"${GENTOO_COMPILER}\"" >> "${JAVA_PKG_ENV}" + + # extra env variables + if [[ -n "${JAVA_PKG_EXTRA_ENV_VARS}" ]]; then + cat "${JAVA_PKG_EXTRA_ENV}" >> "${JAVA_PKG_ENV}" || die + # nested echo to remove leading/trailing spaces + echo "ENV_VARS=\"$(echo ${JAVA_PKG_EXTRA_ENV_VARS})\"" \ + >> "${JAVA_PKG_ENV}" || die + fi + + # Strip unnecessary leading and trailing colons + # TODO try to cleanup if possible + sed -e "s/=\":/=\"/" -e "s/:\"$/\"/" -i "${JAVA_PKG_ENV}" || die "Did you forget to call java_init ?" +} + +# @FUNCTION: java-pkg_record-jar_ +# @INTERNAL +# @DESCRIPTION: +# Record an (optional) dependency to the package.env +# @CODE +# Parameters: +# --optional - record dependency as optional +# --build - record dependency as build_only +# $1 - package to record +# $2 - (optional) jar of package to record +# @CODE +JAVA_PKG_DEPEND_FILE="${T}/java-pkg-depend" +JAVA_PKG_OPTIONAL_DEPEND_FILE="${T}/java-pkg-optional-depend" +JAVA_PKG_BUILD_DEPEND_FILE="${T}/java-pkg-build-depend" + +java-pkg_record-jar_() { + debug-print-function ${FUNCNAME} $* + + local depend_file="${JAVA_PKG_DEPEND_FILE}" + case "${1}" in + "--optional") depend_file="${JAVA_PKG_OPTIONAL_DEPEND_FILE}"; shift;; + "--build-only") depend_file="${JAVA_PKG_BUILD_DEPEND_FILE}"; shift;; + esac + + local pkg=${1} jar=${2} append + if [[ -z "${jar}" ]]; then + append="${pkg}" + else + append="$(basename ${jar})@${pkg}" + fi + + echo "${append}" >> "${depend_file}" +} + +# @FUNCTION: java-pkg_append_ +# @INTERNAL +# @DESCRIPTION: +# Appends a value to a variable +# +# @CODE +# Parameters: +# $1 variable name to modify +# $2 value to append +# +# Examples: +# java-pkg_append_ CLASSPATH foo.jar +# @CODE +java-pkg_append_() { + debug-print-function ${FUNCNAME} $* + + local var="${1}" value="${2}" + if [[ -z "${!var}" ]] ; then + export ${var}="${value}" + else + local oldIFS=${IFS} cur haveit + IFS=':' + for cur in ${!var}; do + if [[ ${cur} == ${value} ]]; then + haveit="yes" + break + fi + done + [[ -z ${haveit} ]] && export ${var}="${!var}:${value}" + IFS=${oldIFS} + fi +} + +# @FUNCTION: java-pkg_expand_dir_ +# @INTERNAL +# @DESCRIPTION: +# Gets the full path of the file/directory's parent. +# @CODE +# Parameters: +# $1 - file/directory to find parent directory for +# @CODE +# @RETURN: path to $1's parent directory +java-pkg_expand_dir_() { + pushd "$(dirname "${1}")" >/dev/null 2>&1 || die + pwd + popd >/dev/null 2>&1 || die +} + +# @FUNCTION: java-pkg_func-exists +# @INTERNAL +# @DESCRIPTION: +# Does the indicated function exist? +# @RETURN: 0 - function is declared, 1 - function is undeclared +java-pkg_func-exists() { + declare -F ${1} > /dev/null +} + +# @FUNCTION: java-pkg_setup-vm +# @INTERNAL +# @DESCRIPTION: +# Sets up the environment for a specific VM +java-pkg_setup-vm() { + debug-print-function ${FUNCNAME} $* + + local vendor="$(java-pkg_get-vm-vendor)" + if [[ "${vendor}" == "sun" ]] && java-pkg_is-vm-version-ge "1.5" ; then + addpredict "/dev/random" + elif [[ "${vendor}" == "ibm" ]]; then + addpredict "/proc/self/maps" + addpredict "/proc/cpuinfo" + addpredict "/proc/self/coredump_filter" + elif [[ "${vendor}" == "oracle" ]]; then + addpredict "/dev/random" + addpredict "/proc/self/coredump_filter" + elif [[ "${vendor}" == icedtea* ]] && java-pkg_is-vm-version-ge "1.7" ; then + addpredict "/dev/random" + addpredict "/proc/self/coredump_filter" + elif [[ "${vendor}" == "jrockit" ]]; then + addpredict "/proc/cpuinfo" + fi +} + +# @FUNCTION: java-pkg_needs-vm +# @INTERNAL +# @DESCRIPTION: +# Does the current package depend on virtual/jdk or does it set +# JAVA_PKG_WANT_BUILD_VM? +# +# @RETURN: 0 - Package depends on virtual/jdk; 1 - Package does not depend on virtual/jdk +java-pkg_needs-vm() { + debug-print-function ${FUNCNAME} $* + + if [[ -n "$(echo ${JAVA_PKG_NV_DEPEND:-${DEPEND}} | sed -e '\:virtual/jdk:!d')" ]]; then + return 0 + fi + + [[ -n "${JAVA_PKG_WANT_BUILD_VM}" ]] && return 0 + + return 1 +} + +# @FUNCTION: java-pkg_get-current-vm +# @INTERNAL +# @RETURN - The current VM being used +java-pkg_get-current-vm() { + java-config -f +} + +# @FUNCTION: java-pkg_get-vm-vendor +# @INTERNAL +# @RETURN - The vendor of the current VM +java-pkg_get-vm-vendor() { + debug-print-function ${FUNCNAME} $* + + local vm="$(java-pkg_get-current-vm)" + vm="${vm/-*/}" + echo "${vm}" +} + +# @FUNCTION: java-pkg_get-vm-version +# @INTERNAL +# @RETURN - The version of the current VM +java-pkg_get-vm-version() { + debug-print-function ${FUNCNAME} $* + + java-config -g PROVIDES_VERSION +} + +# @FUNCTION: java-pkg_build-vm-from-handle +# @INTERNAL +# @DESCRIPTION: +# Selects a build vm from a list of vm handles. First checks for the system-vm +# beeing usable, then steps through the listed handles till a suitable vm is +# found. +# +# @RETURN - VM handle of an available JDK +java-pkg_build-vm-from-handle() { + debug-print-function ${FUNCNAME} "$*" + + local vm + vm=$(java-pkg_get-current-vm 2>/dev/null) + if [[ $? -eq 0 ]]; then + if has ${vm} ${JAVA_PKG_WANT_BUILD_VM}; then + echo ${vm} + return 0 + fi + fi + + for vm in ${JAVA_PKG_WANT_BUILD_VM}; do + if java-config-2 --select-vm=${vm} 2>/dev/null; then + echo ${vm} + return 0 + fi + done + + eerror "${FUNCNAME}: No vm found for handles: ${JAVA_PKG_WANT_BUILD_VM}" + return 1 +} + +# @FUNCTION: java-pkg_switch-vm +# @INTERNAL +# @DESCRIPTION: +# Switch VM if we're allowed to (controlled by JAVA_PKG_ALLOW_VM_CHANGE), and +# verify that the current VM is sufficient. +# Setup the environment for the VM being used. +java-pkg_switch-vm() { + debug-print-function ${FUNCNAME} $* + + if java-pkg_needs-vm; then + # Use the VM specified by JAVA_PKG_FORCE_VM + if [[ -n "${JAVA_PKG_FORCE_VM}" ]]; then + # If you're forcing the VM, I hope you know what your doing... + debug-print "JAVA_PKG_FORCE_VM used: ${JAVA_PKG_FORCE_VM}" + export GENTOO_VM="${JAVA_PKG_FORCE_VM}" + # if we're allowed to switch the vm... + elif [[ "${JAVA_PKG_ALLOW_VM_CHANGE}" == "yes" ]]; then + # if there is an explicit list of handles to choose from + if [[ -n "${JAVA_PKG_WANT_BUILD_VM}" ]]; then + debug-print "JAVA_PKG_WANT_BUILD_VM used: ${JAVA_PKG_WANT_BUILD_VM}" + GENTOO_VM=$(java-pkg_build-vm-from-handle) + if [[ $? != 0 ]]; then + eerror "${FUNCNAME}: No VM found for handles: ${JAVA_PKG_WANT_BUILD_VM}" + die "${FUNCNAME}: Failed to determine VM for building" + fi + # JAVA_PKG_WANT_SOURCE and JAVA_PKG_WANT_TARGET are required as + # they can't be deduced from handles. + if [[ -z "${JAVA_PKG_WANT_SOURCE}" ]]; then + eerror "JAVA_PKG_WANT_BUILD_VM specified but not JAVA_PKG_WANT_SOURCE" + die "Specify JAVA_PKG_WANT_SOURCE" + fi + if [[ -z "${JAVA_PKG_WANT_TARGET}" ]]; then + eerror "JAVA_PKG_WANT_BUILD_VM specified but not JAVA_PKG_WANT_TARGET" + die "Specify JAVA_PKG_WANT_TARGET" + fi + # otherwise determine a vm from dep string + else + debug-print "depend-java-query: NV_DEPEND: ${JAVA_PKG_NV_DEPEND:-${DEPEND}}" + GENTOO_VM="$(depend-java-query --get-vm "${JAVA_PKG_NV_DEPEND:-${DEPEND}}")" + if [[ -z "${GENTOO_VM}" || "${GENTOO_VM}" == "None" ]]; then + eerror "Unable to determine VM for building from dependencies:" + echo "NV_DEPEND: ${JAVA_PKG_NV_DEPEND:-${DEPEND}}" + die "Failed to determine VM for building." + fi + fi + export GENTOO_VM + # otherwise just make sure the current VM is sufficient + else + java-pkg_ensure-vm-version-sufficient + fi + debug-print "Using: $(java-config -f)" + + java-pkg_setup-vm + + export JAVA=$(java-config --java) + export JAVAC=$(java-config --javac) + JAVACFLAGS="$(java-pkg_javac-args)" + [[ -n ${JAVACFLAGS_EXTRA} ]] && JAVACFLAGS="${JAVACFLAGS_EXTRA} ${JAVACFLAGS}" + export JAVACFLAGS + + export JAVA_HOME="$(java-config -g JAVA_HOME)" + export JDK_HOME=${JAVA_HOME} + + #TODO If you know a better solution let us know. + java-pkg_append_ LD_LIBRARY_PATH "$(java-config -g LDPATH)" + + local tann="${T}/announced-vm" + # With the hooks we should only get here once from pkg_setup but better safe than sorry + # if people have for example modified eclasses some where + if [[ -n "${JAVA_PKG_DEBUG}" ]] || [[ ! -f "${tann}" ]] ; then + einfo "Using: $(java-config -f)" + [[ ! -f "${tann}" ]] && touch "${tann}" + fi + + else + [[ -n "${JAVA_PKG_DEBUG}" ]] && ewarn "!!! This package inherits java-pkg but doesn't depend on a JDK. -bin or broken dependency!!!" + fi +} + +# @FUNCTION: java-pkg_die +# @INTERNAL +# @DESCRIPTION: +# Enhanced die for Java packages, which displays some information that may be +# useful for debugging bugs on bugzilla. +#register_die_hook java-pkg_die +if ! has java-pkg_die ${EBUILD_DEATH_HOOKS}; then + EBUILD_DEATH_HOOKS="${EBUILD_DEATH_HOOKS} java-pkg_die" +fi + +java-pkg_die() { + echo "!!! When you file a bug report, please include the following information:" >&2 + echo "GENTOO_VM=${GENTOO_VM} CLASSPATH=\"${CLASSPATH}\" JAVA_HOME=\"${JAVA_HOME}\"" >&2 + echo "JAVACFLAGS=\"${JAVACFLAGS}\" COMPILER=\"${GENTOO_COMPILER}\"" >&2 + echo "and of course, the output of emerge --info =${P}" >&2 +} + + +# TODO document +# List jars in the source directory, ${S} +java-pkg_jar-list() { + if [[ -n "${JAVA_PKG_DEBUG}" ]]; then + einfo "Linked Jars" + find "${S}" -type l -name '*.jar' -print0 | xargs -0 -r -n 500 ls -ald | sed -e "s,${WORKDIR},\${WORKDIR}," + einfo "Jars" + find "${S}" -type f -name '*.jar' -print0 | xargs -0 -r -n 500 ls -ald | sed -e "s,${WORKDIR},\${WORKDIR}," + einfo "Classes" + find "${S}" -type f -name '*.class' -print0 | xargs -0 -r -n 500 ls -ald | sed -e "s,${WORKDIR},\${WORKDIR}," + fi +} + +# @FUNCTION: java-pkg_verify-classes +# @INTERNAL +# @DESCRIPTION: +# Verify that the classes were compiled for the right source / target. Dies if +# not. +# @CODE +# $1 (optional) - the file to check, otherwise checks whole ${D} +# @CODE +java-pkg_verify-classes() { + #$(find ${D} -type f -name '*.jar' -o -name '*.class') + + local version_verify_1="${EPREFIX}/usr/$(get_libdir)/javatoolkit/bin/class-version-verify.py" + local version_verify_2="${EPREFIX}/usr/libexec/javatoolkit/class-version-verify.py" + + if [[ -x "${version_verify_1}" ]]; then + local version_verify=${version_verify_1} + else + local version_verify=${version_verify_2} + fi + + if [[ ! -x "${version_verify}" ]]; then + ewarn "Unable to perform class version checks as" + ewarn "class-version-verify.py is unavailable" + ewarn "Please install dev-java/javatoolkit." + return + fi + + local target=$(java-pkg_get-target) + local result + local log="${T}/class-version-verify.log" + if [[ -n "${1}" ]]; then + ${version_verify} -v -t ${target} "${1}" > "${log}" + result=$? + else + ebegin "Verifying java class versions (target: ${target})" + ${version_verify} -v -t ${target} -r "${D}" > "${log}" + result=$? + eend ${result} + fi + [[ -n ${JAVA_PKG_DEBUG} ]] && cat "${log}" + if [[ ${result} != 0 ]]; then + eerror "Incorrect bytecode version found" + [[ -n "${1}" ]] && eerror "in file: ${1}" + eerror "See ${log} for more details." + die "Incorrect bytecode found" + fi +} + +# @FUNCTION: java-pkg_ensure-dep +# @INTERNAL +# @DESCRIPTION: +# Check that a package being used in jarfrom, getjars and getjar is contained +# within DEPEND or RDEPEND with the correct SLOT. See this mail for details: +# https://archives.gentoo.org/gentoo-dev/message/dcb644f89520f4bbb61cc7bbe45fdf6e +# @CODE +# Parameters: +# $1 - empty - check both vars; "runtime" or "build" - check only +# RDEPEND, resp. DEPEND +# $2 - Package name and slot. +# @CODE +java-pkg_ensure-dep() { + debug-print-function ${FUNCNAME} $* + + local limit_to="${1}" + local target_pkg="${2}" + local dev_error="" + + # Transform into a regular expression to look for a matching package + # and SLOT. SLOTs don't have to be numeric so foo-bar could either + # mean foo-bar:0 or foo:bar. So you want to get your head around the + # line below? + # + # * The target package first has any dots escaped, e.g. foo-1.2 + # becomes foo-1\.2. + # + # * sed then looks at the component following the last - or : + # character, or the whole string if there is no - or : + # character. It uses this to build a new regexp with two + # significant branches. + # + # * The first checks for the whole target package string, optionally + # followed by a version number, and then :0. + # + # * The second checks for the first part of the target package + # string, optionally followed by a version number, followed by the + # aforementioned component, treating that as a SLOT. + # + local stripped_pkg=/$(sed -r 's/[-:]?([^-:]+)$/(\0(-[^:]+)?:0|(-[^:]+)?:\1)/' <<< "${target_pkg//./\\.}")\\b + + debug-print "Matching against: ${stripped_pkg}" + + # Uncomment the lines below once we've dealt with more of these + # otherwise we'll be tempted to turn JAVA_PKG_STRICT off while + # getting hit with a wave of bug reports. :( + + if [[ ${limit_to} != runtime && ! ( "${DEPEND}" =~ $stripped_pkg ) ]]; then + dev_error="The ebuild is attempting to use ${target_pkg}, which is not " + dev_error+="declared with a SLOT in DEPEND." +# if is-java-strict; then +# die "${dev_error}" +# else + eqawarn "java-pkg_ensure-dep: ${dev_error}" +# eerror "Because you have ${target_pkg} installed," +# eerror "the package will build without problems, but please" +# eerror "report this to https://bugs.gentoo.org." +# fi + elif [[ ${limit_to} != build && ! ( "${RDEPEND}${PDEPEND}" =~ ${stripped_pkg} ) ]]; then + dev_error="The ebuild is attempting to use ${target_pkg}, which is not " + dev_error+="declared with a SLOT in [RP]DEPEND and --build-only wasn't given." +# if is-java-strict; then +# die "${dev_error}" +# else + eqawarn "java-pkg_ensure-dep: ${dev_error}" +# eerror "The package will build without problems, but may fail to run" +# eerror "if you don't have ${target_pkg} installed," +# eerror "so please report this to https://bugs.gentoo.org." +# fi + fi +} + +java-pkg_check-phase() { + local phase=${1} + local funcname=${FUNCNAME[1]} + if [[ ${EBUILD_PHASE} != ${phase} ]]; then + local msg="${funcname} used outside of src_${phase}" + java-pkg_announce-qa-violation "${msg}" + fi +} + +java-pkg_check-versioned-jar() { + local jar=${1} + + if [[ ${jar} =~ ${PV} ]]; then + java-pkg_announce-qa-violation "installing versioned jar '${jar}'" + fi +} + +java-pkg_check-jikes() { + if has jikes ${IUSE}; then + java-pkg_announce-qa-violation "deprecated USE flag 'jikes' in IUSE" + fi +} + +java-pkg_announce-qa-violation() { + local nodie + if [[ ${1} == "--nodie" ]]; then + nodie="true" + shift + fi + echo "Java QA Notice: $@" >&2 + increment-qa-violations + [[ -z "${nodie}" ]] && is-java-strict && die "${@}" +} + +increment-qa-violations() { + let "JAVA_PKG_QA_VIOLATIONS+=1" + export JAVA_PKG_QA_VIOLATIONS +} + +is-java-strict() { + [[ -n ${JAVA_PKG_STRICT} ]] + return $? +} + +# @FUNCTION: java-pkg_clean +# @DESCRIPTION: +# Java package cleaner function. This will remove all *.class and *.jar +# files, removing any bundled dependencies. +java-pkg_clean() { + if [[ -z "${JAVA_PKG_NO_CLEAN}" ]]; then + find "${@}" '(' -name '*.class' -o -name '*.jar' ')' -type f -delete -print || die + fi +} + +# @FUNCTION: java-pkg_gen-cp +# @INTERNAL +# @DESCRIPTION: +# Java package generate classpath will create a classpath based on +# special variable CP_DEPEND in the ebuild. +# +# @CODE +# Parameters: +# $1 - classpath variable either EANT_GENTOO_CLASSPATH or JAVA_GENTOO_CLASSPATH +# @CODE +java-pkg_gen-cp() { + debug-print-function ${FUNCNAME} "${@}" + + local atom + for atom in ${CP_DEPEND}; do + if [[ ${atom} =~ /(([[:alnum:]+_-]+)-[0-9]+(\.[0-9]+)*[a-z]?(_[[:alnum:]]+)*(-r[0-9]*)?|[[:alnum:]+_-]+):([[:alnum:]+_.-]+) ]]; then + atom=${BASH_REMATCH[2]:-${BASH_REMATCH[1]}} + [[ ${BASH_REMATCH[6]} != 0 ]] && atom+=-${BASH_REMATCH[6]} + local regex="(^|\s|,)${atom}($|\s|,)" + [[ ${!1} =~ ${regex} ]] || declare -g ${1}+=${!1:+,}${atom} + else + die "Invalid CP_DEPEND atom ${atom}, ensure a SLOT is included" + fi + done +} diff --git a/eclass/java-virtuals-2.eclass b/eclass/java-virtuals-2.eclass new file mode 100644 index 0000000..987ff44 --- /dev/null +++ b/eclass/java-virtuals-2.eclass @@ -0,0 +1,54 @@ +# Copyright 1999-2015 Gentoo Foundation +# Distributed under the terms of the GNU General Public License v2 + +# @ECLASS: java-virtuals-2.eclass +# @MAINTAINER: +# java@gentoo.org +# @AUTHOR: +# Original Author: Alistair John Bush <ali_bush@gentoo.org> +# @BLURB: Java virtuals eclass +# @DESCRIPTION: +# To provide a default (and only) src_install function for ebuilds in the +# java-virtuals category. + +inherit java-utils-2 + +DEPEND=">=dev-java/java-config-2.2.0-r3" +RDEPEND="${DEPEND}" + +S="${WORKDIR}" + +EXPORT_FUNCTIONS src_install + +# @FUNCTION: java-virtuals-2_src_install +# @DESCRIPTION: +# default src_install + +java-virtuals-2_src_install() { + java-virtuals-2_do_write +} + +# @FUNCTION: java-pkg_do_virtuals_write +# @INTERNAL +# @DESCRIPTION: +# Writes the virtual env file out to disk. + +java-virtuals-2_do_write() { + java-pkg_init_paths_ + + dodir "${JAVA_PKG_VIRTUALS_PATH}" + { + if [[ -n "${JAVA_VIRTUAL_PROVIDES}" ]]; then + echo "PROVIDERS=\"${JAVA_VIRTUAL_PROVIDES}\"" + fi + + if [[ -n "${JAVA_VIRTUAL_VM}" ]]; then + echo "VM=\"${JAVA_VIRTUAL_VM}\"" + fi + + if [[ -n "${JAVA_VIRTUAL_VM_CLASSPATH}" ]]; then + echo "VM_CLASSPATH=\"${JAVA_VIRTUAL_VM_CLASSPATH}\"" + fi + echo "MULTI_PROVIDER=\"${JAVA_VIRTUAL_MULTI=FALSE}\"" + } > "${JAVA_PKG_VIRTUAL_PROVIDER}" +} diff --git a/eclass/java-vm-2.eclass b/eclass/java-vm-2.eclass new file mode 100644 index 0000000..6c6d14c --- /dev/null +++ b/eclass/java-vm-2.eclass @@ -0,0 +1,320 @@ +# Copyright 1999-2019 Gentoo Authors +# Distributed under the terms of the GNU General Public License v2 + +# @ECLASS: java-vm-2.eclass +# @MAINTAINER: +# java@gentoo.org +# @SUPPORTED_EAPIS: 5 6 +# @BLURB: Java Virtual Machine eclass +# @DESCRIPTION: +# This eclass provides functionality which assists with installing +# virtual machines, and ensures that they are recognized by java-config. + +case ${EAPI:-0} in + 5|6) ;; + *) die "EAPI=${EAPI} is not supported" ;; +esac + +inherit multilib pax-utils prefix xdg-utils + +EXPORT_FUNCTIONS pkg_setup pkg_postinst pkg_prerm pkg_postrm + +RDEPEND=" + >=dev-java/java-config-2.2.0-r3 + >=app-eselect/eselect-java-0.4.0" +DEPEND="${RDEPEND}" + +export WANT_JAVA_CONFIG=2 + + +# @ECLASS-VARIABLE: JAVA_VM_CONFIG_DIR +# @INTERNAL +# @DESCRIPTION: +# Where to place the vm env file. +JAVA_VM_CONFIG_DIR="/usr/share/java-config-2/vm" + +# @ECLASS-VARIABLE: JAVA_VM_DIR +# @INTERNAL +# @DESCRIPTION: +# Base directory for vm links. +JAVA_VM_DIR="/usr/lib/jvm" + +# @ECLASS-VARIABLE: JAVA_VM_SYSTEM +# @INTERNAL +# @DESCRIPTION: +# Link for system-vm +JAVA_VM_SYSTEM="/etc/java-config-2/current-system-vm" + +# @ECLASS-VARIABLE: JAVA_VM_BUILD_ONLY +# @DESCRIPTION: +# Set to YES to mark a vm as build-only. +JAVA_VM_BUILD_ONLY="${JAVA_VM_BUILD_ONLY:-FALSE}" + + +# @FUNCTION: java-vm-2_pkg_setup +# @DESCRIPTION: +# default pkg_setup +# +# Initialize vm handle. + +java-vm-2_pkg_setup() { + if [[ "${SLOT}" != "0" ]]; then + VMHANDLE=${PN}-${SLOT} + else + VMHANDLE=${PN} + fi +} + + +# @FUNCTION: java-vm-2_pkg_postinst +# @DESCRIPTION: +# default pkg_postinst +# +# Set the generation-2 system VM, if it isn't set or the setting is +# invalid. Also update mime database. + +java-vm-2_pkg_postinst() { + if [[ ! -d ${EROOT}${JAVA_VM_SYSTEM} ]]; then + eselect java-vm set system "${VMHANDLE}" + einfo "${P} set as the default system-vm." + fi + + xdg_desktop_database_update +} + + +# @FUNCTION: java-vm-2_pkg_prerm +# @DESCRIPTION: +# default pkg_prerm +# +# Warn user if removing system-vm. + +java-vm-2_pkg_prerm() { + if [[ $(GENTOO_VM= java-config -f 2>/dev/null) == ${VMHANDLE} && -z ${REPLACED_BY_VERSION} ]]; then + ewarn "It appears you are removing your system-vm! Please run" + ewarn "\"eselect java-vm list\" to list available VMs, then use" + ewarn "\"eselect java-vm set system\" to set a new system-vm!" + fi +} + + +# @FUNCTION: java-vm-2_pkg_postrm +# @DESCRIPTION: +# default pkg_postrm +# +# Update mime database. + +java-vm-2_pkg_postrm() { + xdg_desktop_database_update +} + + +# @FUNCTION: get_system_arch +# @DESCRIPTION: +# Get Java specific arch name. +# +# NOTE the mips and sparc values are best guesses. Oracle uses sparcv9 +# but does OpenJDK use sparc64? We don't support OpenJDK on sparc or any +# JVM on mips though so it doesn't matter much. + +get_system_arch() { + local abi=${1-${ABI}} + + case $(get_abi_CHOST ${abi}) in + mips*l*) echo mipsel ;; + mips*) echo mips ;; + powerpc64le*) echo ppc64le ;; + *) + case ${abi} in + *_fbsd) get_system_arch ${abi%_fbsd} ;; + arm64) echo aarch64 ;; + hppa) echo parisc ;; + sparc32) echo sparc ;; + sparc64) echo sparcv9 ;; + x86*) echo i386 ;; + *) echo ${abi} ;; + esac ;; + esac +} + + +# @FUNCTION: set_java_env +# @DESCRIPTION: +# Installs a vm env file. +# DEPRECATED, use java-vm_install-env instead. + +set_java_env() { + debug-print-function ${FUNCNAME} $* + + local platform="$(get_system_arch)" + local env_file="${ED}${JAVA_VM_CONFIG_DIR}/${VMHANDLE}" + + if [[ ${1} ]]; then + local source_env_file="${1}" + else + local source_env_file="${FILESDIR}/${VMHANDLE}.env" + fi + + if [[ ! -f ${source_env_file} ]]; then + die "Unable to find the env file: ${source_env_file}" + fi + + dodir ${JAVA_VM_CONFIG_DIR} + sed \ + -e "s/@P@/${P}/g" \ + -e "s/@PN@/${PN}/g" \ + -e "s/@PV@/${PV}/g" \ + -e "s/@PF@/${PF}/g" \ + -e "s/@SLOT@/${SLOT}/g" \ + -e "s/@PLATFORM@/${platform}/g" \ + -e "s/@LIBDIR@/$(get_libdir)/g" \ + -e "/^LDPATH=.*lib\\/\\\"/s|\"\\(.*\\)\"|\"\\1${platform}/:\\1${platform}/server/\"|" \ + < "${source_env_file}" \ + > "${env_file}" || die "sed failed" + + ( + echo "VMHANDLE=\"${VMHANDLE}\"" + echo "BUILD_ONLY=\"${JAVA_VM_BUILD_ONLY}\"" + ) >> "${env_file}" + + eprefixify ${env_file} + + [[ -n ${JAVA_PROVIDE} ]] && echo "PROVIDES=\"${JAVA_PROVIDE}\"" >> ${env_file} + + local java_home=$(source "${env_file}"; echo ${JAVA_HOME}) + [[ -z ${java_home} ]] && die "No JAVA_HOME defined in ${env_file}" + + # Make the symlink + dodir "${JAVA_VM_DIR}" + dosym ${java_home#${EPREFIX}} ${JAVA_VM_DIR}/${VMHANDLE} +} + + +# @FUNCTION: java-vm_install-env +# @DESCRIPTION: +# +# Installs a Java VM environment file. The source can be specified but +# defaults to ${FILESDIR}/${VMHANDLE}.env.sh. +# +# Environment variables within this file will be resolved. You should +# escape the $ when referring to variables that should be resolved later +# such as ${JAVA_HOME}. Subshells may be used but avoid using double +# quotes. See icedtea-bin.env.sh for a good example. + +java-vm_install-env() { + debug-print-function ${FUNCNAME} "$*" + + local env_file="${ED}${JAVA_VM_CONFIG_DIR}/${VMHANDLE}" + local source_env_file="${1-${FILESDIR}/${VMHANDLE}.env.sh}" + + if [[ ! -f "${source_env_file}" ]]; then + die "Unable to find the env file: ${source_env_file}" + fi + + dodir "${JAVA_VM_CONFIG_DIR}" + + # Here be dragons! ;) -- Chewi + eval echo "\"$(cat <<< "$(sed 's:":\\":g' "${source_env_file}")")\"" > "${env_file}" || + die "failed to create Java env file" + + ( + echo "VMHANDLE=\"${VMHANDLE}\"" + echo "BUILD_ONLY=\"${JAVA_VM_BUILD_ONLY}\"" + [[ ${JAVA_PROVIDE} ]] && echo "PROVIDES=\"${JAVA_PROVIDE}\"" || true + ) >> "${env_file}" || die "failed to append to Java env file" + + local java_home=$(unset JAVA_HOME; source "${env_file}"; echo ${JAVA_HOME}) + [[ -z ${java_home} ]] && die "No JAVA_HOME defined in ${env_file}" + + # Make the symlink + dodir "${JAVA_VM_DIR}" + dosym "${java_home#${EPREFIX}}" "${JAVA_VM_DIR}/${VMHANDLE}" +} + + +# @FUNCTION: java-vm_set-pax-markings +# @DESCRIPTION: +# Set PaX markings on all JDK/JRE executables to allow code-generation on +# the heap by the JIT compiler. +# +# The markings need to be set prior to the first invocation of the the freshly +# built / installed VM. Be it before creating the Class Data Sharing archive or +# generating cacerts. Otherwise a PaX enabled kernel will kill the VM. +# Bug #215225 #389751 +# +# @CODE +# Parameters: +# $1 - JDK/JRE base directory. +# +# Examples: +# java-vm_set-pax-markings "${S}" +# java-vm_set-pax-markings "${ED}"/opt/${P} +# @CODE + +java-vm_set-pax-markings() { + debug-print-function ${FUNCNAME} "$*" + [[ $# -ne 1 ]] && die "${FUNCNAME}: takes exactly one argument" + [[ ! -f "${1}"/bin/java ]] \ + && die "${FUNCNAME}: argument needs to be JDK/JRE base directory" + + local executables=( "${1}"/bin/* ) + [[ -d "${1}"/jre ]] && executables+=( "${1}"/jre/bin/* ) + + # Usually disabling MPROTECT is sufficient. + local pax_markings="m" + # On x86 for heap sizes over 700MB disable SEGMEXEC and PAGEEXEC as well. + use x86 && pax_markings+="sp" + + pax-mark ${pax_markings} $(list-paxables "${executables[@]}") +} + + +# @FUNCTION: java-vm_revdep-mask +# @DESCRIPTION: +# Installs a revdep-rebuild control file which SEARCH_DIR_MASK set to the path +# where the VM is installed. Prevents pointless rebuilds - see bug #177925. +# Also gives a notice to the user. +# +# @CODE +# Parameters: +# $1 - Path of the VM (defaults to /opt/${P} if not set) +# +# Examples: +# java-vm_revdep-mask +# java-vm_revdep-mask /path/to/jdk/ +# +# @CODE + +java-vm_revdep-mask() { + debug-print-function ${FUNCNAME} "$*" + + local VMROOT="${1-"${EPREFIX}"/opt/${P}}" + + dodir /etc/revdep-rebuild + echo "SEARCH_DIRS_MASK=\"${VMROOT}\"" >> "${ED}/etc/revdep-rebuild/61-${VMHANDLE}" \ + || die "Failed to write revdep-rebuild mask file" +} + + +# @FUNCTION: java-vm_sandbox-predict +# @DESCRIPTION: +# Install a sandbox control file. Specified paths won't cause a sandbox +# violation if opened read write but no write takes place. See bug 388937#c1 +# +# @CODE +# Examples: +# java-vm_sandbox-predict /dev/random /proc/self/coredump_filter +# @CODE + +java-vm_sandbox-predict() { + debug-print-function ${FUNCNAME} "$*" + [[ -z "${1}" ]] && die "${FUNCNAME} takes at least one argument" + + local path path_arr=("$@") + # subshell this to prevent IFS bleeding out dependant on bash version. + # could use local, which *should* work, but that requires a lot of testing. + path=$(IFS=":"; echo "${path_arr[*]}") + dodir /etc/sandbox.d + echo "SANDBOX_PREDICT=\"${path}\"" > "${ED}/etc/sandbox.d/20${VMHANDLE}" \ + || die "Failed to write sandbox control file" +} diff --git a/eclass/kde.org.eclass b/eclass/kde.org.eclass new file mode 100644 index 0000000..819b73d --- /dev/null +++ b/eclass/kde.org.eclass @@ -0,0 +1,263 @@ +# Copyright 1999-2020 Gentoo Authors +# Distributed under the terms of the GNU General Public License v2 + +# @ECLASS: kde.org.eclass +# @MAINTAINER: +# kde@gentoo.org +# @SUPPORTED_EAPIS: 7 +# @BLURB: Support eclass for packages that are hosted on kde.org infrastructure. +# @DESCRIPTION: +# This eclass is mainly providing facilities for the upstream release groups +# Frameworks, Plasma, Release Service to assemble default SRC_URI for tarballs, +# set up git-r3.eclass for stable/master branch versions or restrict access to +# unreleased (packager access only) tarballs in Gentoo KDE overlay, but it may +# be also used by any other package hosted on kde.org. +# It also contains default meta variables for settings not specific to any +# particular build system. + +if [[ -z ${_KDE_ORG_ECLASS} ]]; then +_KDE_ORG_ECLASS=1 + +# @ECLASS-VARIABLE: KDE_BUILD_TYPE +# @DESCRIPTION: +# If PV matches "*9999*", this is automatically set to "live". +# Otherwise, this is automatically set to "release". +KDE_BUILD_TYPE="release" +if [[ ${PV} = *9999* ]]; then + KDE_BUILD_TYPE="live" +fi +export KDE_BUILD_TYPE + +if [[ ${KDE_BUILD_TYPE} = live ]]; then + inherit git-r3 +fi + +EXPORT_FUNCTIONS pkg_nofetch src_unpack + +# @ECLASS-VARIABLE: KDE_ORG_NAME +# @DESCRIPTION: +# If unset, default value is set to ${PN}. +# Name of the package as hosted on kde.org mirrors. +: ${KDE_ORG_NAME:=$PN} + +# @ECLASS-VARIABLE: KDE_RELEASE_SERVICE +# @DESCRIPTION: +# If set to "false", do nothing. +# If set to "true", set SRC_URI accordingly and apply KDE_UNRELEASED. +: ${KDE_RELEASE_SERVICE:=false} + +# @ECLASS-VARIABLE: KDE_SELINUX_MODULE +# @DESCRIPTION: +# If set to "none", do nothing. +# For any other value, add selinux to IUSE, and depending on that useflag +# add a dependency on sec-policy/selinux-${KDE_SELINUX_MODULE} to (R)DEPEND. +: ${KDE_SELINUX_MODULE:=none} + +case ${KDE_SELINUX_MODULE} in + none) ;; + *) + IUSE+=" selinux" + RDEPEND+=" selinux? ( sec-policy/selinux-${KDE_SELINUX_MODULE} )" + ;; +esac + +# @ECLASS-VARIABLE: KDE_UNRELEASED +# @INTERNAL +# @DESCRIPTION: +# An array of $CATEGORY-$PV pairs of packages that are unreleased upstream. +# Any package matching this will have fetch restriction enabled, and receive +# a proper error message via pkg_nofetch. +KDE_UNRELEASED=( ) + +HOMEPAGE="https://kde.org/" + +case ${CATEGORY} in + kde-apps) + KDE_RELEASE_SERVICE=true + ;; + kde-plasma) + HOMEPAGE="https://kde.org/plasma-desktop" + ;; + kde-frameworks) + HOMEPAGE="https://kde.org/products/frameworks/" + SLOT=5/${PV} + [[ ${KDE_BUILD_TYPE} = release ]] && SLOT=$(ver_cut 1)/$(ver_cut 1-2) + ;; + *) ;; +esac + +_kde.org_is_unreleased() { + local pair + for pair in "${KDE_UNRELEASED[@]}" ; do + if [[ "${pair}" = "${CATEGORY}-${PV}" ]]; then + return 0 + elif [[ ${KDE_RELEASE_SERVICE} = true ]]; then + if [[ "${pair/kde-apps/${CATEGORY}}" = "${CATEGORY}-${PV}" ]]; then + return 0 + fi + fi + done + + return 1 +} + +# Determine fetch location for released tarballs +_kde.org_calculate_src_uri() { + debug-print-function ${FUNCNAME} "$@" + + local _src_uri="mirror://kde/" + + if [[ ${KDE_RELEASE_SERVICE} = true ]]; then + case ${PV} in + ??.??.[6-9]? ) + _src_uri+="unstable/release-service/${PV}/src/" + RESTRICT+=" mirror" + ;; + *) _src_uri+="stable/release-service/${PV}/src/" ;; + esac + fi + + case ${CATEGORY} in + kde-frameworks) + _src_uri+="stable/frameworks/$(ver_cut 1-2)/" + case ${PN} in + kdelibs4support | \ + kdesignerplugin | \ + kdewebkit | \ + khtml | \ + kjs | \ + kjsembed | \ + kmediaplayer | \ + kross | \ + kxmlrpcclient) + _src_uri+="portingAids/" + ;; + esac + ;; + kde-plasma) + case ${PV} in + 5.??.[6-9]?* ) + _src_uri+="unstable/plasma/$(ver_cut 1-3)/" + RESTRICT+=" mirror" + ;; + *) _src_uri+="stable/plasma/$(ver_cut 1-3)/" ;; + esac + ;; + esac + + if [[ ${PN} = kdevelop* ]]; then + case ${PV} in + *.*.[6-9]? ) + _src_uri+="unstable/kdevelop/${PV}/src/" + RESTRICT+=" mirror" + ;; + *) _src_uri+="stable/kdevelop/${PV}/src/" ;; + esac + fi + + SRC_URI="${_src_uri}${KDE_ORG_NAME}-${PV}.tar.xz" + + if _kde.org_is_unreleased ; then + RESTRICT+=" fetch" + fi +} + +# Determine fetch location for live sources +_kde.org_calculate_live_repo() { + debug-print-function ${FUNCNAME} "$@" + + SRC_URI="" + + # @ECLASS-VARIABLE: EGIT_MIRROR + # @DESCRIPTION: + # This variable allows easy overriding of default kde mirror service + # (anongit) with anything else you might want to use. + EGIT_MIRROR=${EGIT_MIRROR:=https://invent.kde.org/kde} + + if [[ ${PV} == ??.??.49.9999 && ${KDE_RELEASE_SERVICE} = true ]]; then + EGIT_BRANCH="release/$(ver_cut 1-2)" + fi + + if [[ ${PV} != 9999 && ${CATEGORY} = kde-plasma ]]; then + EGIT_BRANCH="Plasma/$(ver_cut 1-2)" + fi + + if [[ ${PV} != 9999 && ${PN} = kdevelop* ]]; then + EGIT_BRANCH="$(ver_cut 1-2)" + fi + + # @ECLASS-VARIABLE: EGIT_REPONAME + # @DESCRIPTION: + # This variable allows overriding of default repository + # name. Specify only if this differs from PN and KDE_ORG_NAME. + EGIT_REPO_URI="${EGIT_MIRROR}/${EGIT_REPONAME:=$KDE_ORG_NAME}.git" +} + +case ${KDE_BUILD_TYPE} in + live) _kde.org_calculate_live_repo ;; + *) + _kde.org_calculate_src_uri + debug-print "${LINENO} ${ECLASS} ${FUNCNAME}: SRC_URI is ${SRC_URI}" + ;; +esac + + +if [[ ${KDE_BUILD_TYPE} = release ]]; then + S=${WORKDIR}/${KDE_ORG_NAME}-${PV} +fi + +# @FUNCTION: kde.org_pkg_nofetch +# @DESCRIPTION: +# Intended for use in the KDE overlay. If this package matches something in +# KDE_UNRELEASED, display a giant warning that the package has not yet been +# released upstream and should not be used. +kde.org_pkg_nofetch() { + if ! _kde.org_is_unreleased ; then + return + fi + + local sched_uri="https://community.kde.org/Schedules" + case ${CATEGORY} in + kde-frameworks) sched_uri+="/Frameworks" ;; + kde-plasma) sched_uri+="/Plasma_5" ;; + *) + [[ ${KDE_RELEASE_SERVICE} = true ]] && + sched_uri+="/release_service/$(ver_cut 1-2)_Release_Schedule" + ;; + esac + + eerror " _ _ _ _ ____ _____ _ _____ _ ____ _____ ____ " + eerror "| | | | \ | | _ \| ____| | | ____| / \ / ___|| ____| _ \ " + eerror "| | | | \| | |_) | _| | | | _| / _ \ \___ \| _| | | | |" + eerror "| |_| | |\ | _ <| |___| |___| |___ / ___ \ ___) | |___| |_| |" + eerror " \___/|_| \_|_| \_\_____|_____|_____/_/ \_\____/|_____|____/ " + eerror " " + eerror " ____ _ ____ _ __ _ ____ _____ " + eerror "| _ \ / \ / ___| |/ / / \ / ___| ____|" + eerror "| |_) / _ \| | | ' / / _ \| | _| _| " + eerror "| __/ ___ \ |___| . \ / ___ \ |_| | |___ " + eerror "|_| /_/ \_\____|_|\_\/_/ \_\____|_____|" + eerror + eerror "${CATEGORY}/${P} has not been released to the public yet" + eerror "and is only available to packagers right now." + eerror "" + eerror "This is not a bug. Please do not file bugs or contact upstream about this." + eerror "" + eerror "Please consult the upstream release schedule to see when this " + eerror "package is scheduled to be released:" + eerror "${sched_uri}" +} + +# @FUNCTION: kde.org_src_unpack +# @DESCRIPTION: +# Unpack the sources, automatically handling both release and live ebuilds. +kde.org_src_unpack() { + debug-print-function ${FUNCNAME} "$@" + + case ${KDE_BUILD_TYPE} in + live) git-r3_src_unpack ;& + *) default ;; + esac +} + +fi diff --git a/eclass/kernel-2.eclass b/eclass/kernel-2.eclass new file mode 100644 index 0000000..dccd39e --- /dev/null +++ b/eclass/kernel-2.eclass @@ -0,0 +1,1674 @@ +# Copyright 1999-2020 Gentoo Authors +# Distributed under the terms of the GNU General Public License v2 + +# @ECLASS: kernel-2.eclass +# @MAINTAINER: +# Gentoo Kernel project <kernel@gentoo.org> +# @AUTHOR: +# John Mylchreest <johnm@gentoo.org> +# Mike Pagano <mpagano@gentoo.org> +# <so many, many others, please add yourself> +# @SUPPORTED_EAPIS: 2 3 4 5 6 +# @BLURB: Eclass for kernel packages +# @DESCRIPTION: +# This is the kernel.eclass rewrite for a clean base regarding the 2.6 +# series of kernel with back-compatibility for 2.4 +# Please direct your bugs to the current eclass maintainer :) +# added functionality: +# unipatch - a flexible, singular method to extract, add and remove patches. + +# @ECLASS-VARIABLE: K_USEPV +# @DEFAULT_UNSET +# @DESCRIPTION: +# When setting the EXTRAVERSION variable, it should +# add PV to the end. +# this is useful for things like wolk. IE: +# EXTRAVERSION would be something like : -wolk-4.19-r1 + +# @ECLASS-VARIABLE: K_NODRYRUN +# @DEFAULT_UNSET +# @DESCRIPTION: +# if this is set then patch --dry-run will not +# be run. Certain patches will fail with this parameter +# See bug #507656 + +# @ECLASS-VARIABLE: K_NOSETEXTRAVERSION +# @DEFAULT_UNSET +# @DESCRIPTION: +# if this is set then EXTRAVERSION will not be +# automatically set within the kernel Makefile + +# @ECLASS-VARIABLE: K_NOUSENAME +# @DEFAULT_UNSET +# @DESCRIPTION: +# if this is set then EXTRAVERSION will not include the +# first part of ${PN} in EXTRAVERSION + +# @ECLASS-VARIABLE: K_NOUSEPR +# @DEFAULT_UNSET +# @DESCRIPTION: +# if this is set then EXTRAVERSION will not include the +# anything based on ${PR}. + +# @ECLASS-VARIABLE: K_PREPATCHED +# @DEFAULT_UNSET +# @DESCRIPTION: +# if the patchset is prepatched (ie: pf-sources, +# zen-sources etc) it will use PR (ie: -r5) as the +# patchset version for and not use it as a true package +# revision + +# @ECLASS-VARIABLE: K_EXTRAEINFO +# @DEFAULT_UNSET +# @DESCRIPTION: +# this is a new-line seperated list of einfo displays in +# postinst and can be used to carry additional postinst +# messages + +# @ECLASS-VARIABLE: K_EXTRAELOG +# @DEFAULT_UNSET +# @DESCRIPTION: +# same as K_EXTRAEINFO except using elog instead of einfo + +# @ECLASS-VARIABLE: K_EXTRAEWARN +# @DEFAULT_UNSET +# @DESCRIPTION: +# same as K_EXTRAEINFO except using ewarn instead of einfo + +# @ECLASS-VARIABLE: K_SYMLINK +# @DEFAULT_UNSET +# @DESCRIPTION: +# if this is set, then forcably create symlink anyway + +# @ECLASS-VARIABLE: K_BASE_VER +# @DEFAULT_UNSET +# @DESCRIPTION: +# for git-sources, declare the base version this patch is +# based off of. + +# @ECLASS-VARIABLE: K_DEFCONFIG +# @DEFAULT_UNSET +# @DESCRIPTION: +# Allow specifying a different defconfig target. +# If length zero, defaults to "defconfig". + +# @ECLASS-VARIABLE: K_WANT_GENPATCHES +# @DEFAULT_UNSET +# @DESCRIPTION: +# Apply genpatches to kernel source. Provide any +# combination of "base", "extras" or "experimental". + +# @ECLASS-VARIABLE: K_EXP_GENPATCHES_PULL +# @DEFAULT_UNSET +# @DESCRIPTION: +# If set, we pull "experimental" regardless of the USE FLAG +# but expect the ebuild maintainer to use K_EXP_GENPATCHES_LIST. + +# @ECLASS-VARIABLE: K_EXP_GENPATCHES_NOUSE +# @DEFAULT_UNSET +# @DESCRIPTION: +# If set, no USE flag will be provided for "experimental"; +# as a result the user cannot choose to apply those patches. + +# @ECLASS-VARIABLE: K_EXP_GENPATCHES_LIST +# @DEFAULT_UNSET +# @DESCRIPTION: +# A list of patches to pick from "experimental" to apply when +# the USE flag is unset and K_EXP_GENPATCHES_PULL is set. + +# @ECLASS-VARIABLE: K_FROM_GIT +# @DEFAULT_UNSET +# @DESCRIPTION: +# If set, this variable signals that the kernel sources derives +# from a git tree and special handling will be applied so that +# any patches that are applied will actually apply. + +# @ECLASS-VARIABLE: K_GENPATCHES_VER +# @DEFAULT_UNSET +# @DESCRIPTION: +# The version of the genpatches tarball(s) to apply. +# A value of "5" would apply genpatches-2.6.12-5 to +# my-sources-2.6.12.ebuild + +# @ECLASS-VARIABLE: K_SECURITY_UNSUPPORTED +# @DEFAULT_UNSET +# @DESCRIPTION: +# If set, this kernel is unsupported by Gentoo Security +# to the current eclass maintainer :) + +# @ECLASS-VARIABLE: K_DEBLOB_AVAILABLE +# @DEFAULT_UNSET +# @DESCRIPTION: +# A value of "0" will disable all of the optional deblob +# code. If empty, will be set to "1" if deblobbing is +# possible. Test ONLY for "1". + +# @ECLASS-VARIABLE: K_DEBLOB_TAG +# @DEFAULT_UNSET +# @DESCRIPTION: +# This will be the version of deblob script. It's a upstream SVN tag +# such asw -gnu or -gnu1. + +# @ECLASS-VARIABLE: K_PREDEBLOBBED +# @DEFAULT_UNSET +# @DESCRIPTION: +# This kernel was already deblobbed elsewhere. +# If false, either optional deblobbing will be available +# or the license will note the inclusion of linux-firmware code. + +# @ECLASS-VARIABLE: K_LONGTERM +# @DEFAULT_UNSET +# @DESCRIPTION: +# If set, the eclass will search for the kernel source +# in the long term directories on the upstream servers +# as the location has been changed by upstream + +# @ECLASS-VARIABLE: H_SUPPORTEDARCH +# @DEFAULT_UNSET +# @DESCRIPTION: +# this should be a space separated list of ARCH's which +# can be supported by the headers ebuild + +# @ECLASS-VARIABLE: UNIPATCH_LIST +# @DEFAULT_UNSET +# @DESCRIPTION: +# space delimetered list of patches to be applied to the kernel + +# @ECLASS-VARIABLE: UNIPATCH_EXCLUDE +# @DEFAULT_UNSET +# @DESCRIPTION: +# An addition var to support exlusion based completely +# on "<passedstring>*" and not "<passedno#>_*" +# this should _NOT_ be used from the ebuild as this is +# reserved for end users passing excludes from the cli + +# @ECLASS-VARIABLE: UNIPATCH_DOCS +# @DEFAULT_UNSET +# @DESCRIPTION: +# space delimemeted list of docs to be installed to +# the doc dir + +# @ECLASS-VARIABLE: UNIPATCH_STRICTORDER +# @DEFAULT_UNSET +# @DESCRIPTION: +# if this is set places patches into directories of +# order, so they are applied in the order passed +# Changing any other variable in this eclass is not supported; you can request +# for additional variables to be added by contacting the current maintainer. +# If you do change them, there is a chance that we will not fix resulting bugs; +# that of course does not mean we're not willing to help. + +inherit toolchain-funcs +[[ ${EAPI:-0} == [012345] ]] && inherit epatch +[[ ${EAPI:-0} == [0123456] ]] && inherit estack eapi7-ver +case ${EAPI:-0} in + 2|3|4|5|6) + EXPORT_FUNCTIONS src_{unpack,prepare,compile,install,test} \ + pkg_{setup,preinst,postinst,postrm} ;; + *) die "${ECLASS}: EAPI ${EAPI} not supported" ;; +esac + +# Added by Daniel Ostrow <dostrow@gentoo.org> +# This is an ugly hack to get around an issue with a 32-bit userland on ppc64. +# I will remove it when I come up with something more reasonable. +[[ ${PROFILE_ARCH} == "ppc64" ]] && CHOST="powerpc64-${CHOST#*-}" + +export CTARGET=${CTARGET:-${CHOST}} +if [[ ${CTARGET} == ${CHOST} && ${CATEGORY/cross-} != ${CATEGORY} ]]; then + export CTARGET=${CATEGORY/cross-} +fi + +HOMEPAGE="https://www.kernel.org/ https://wiki.gentoo.org/wiki/Kernel ${HOMEPAGE}" +: ${LICENSE:="GPL-2"} + +# This is the latest KV_PATCH of the deblob tool available from the +# libre-sources upstream. If you bump this, you MUST regenerate the Manifests +# for ALL kernel-2 consumer packages where deblob is available. +: ${DEBLOB_MAX_VERSION:=38} + +# No need to run scanelf/strip on kernel sources/headers (bug #134453). +RESTRICT="binchecks strip" + +# set LINUX_HOSTCFLAGS if not already set +: ${LINUX_HOSTCFLAGS:="-Wall -Wstrict-prototypes -Os -fomit-frame-pointer -I${S}/include"} + + +# @FUNCTION: debug-print-kernel2-variables +# @USAGE: +# @DESCRIPTION: +# this function exists only to help debug kernel-2.eclass +# if you are adding new functionality in, put a call to it +# at the start of src_unpack, or during SRC_URI/dep generation. + +debug-print-kernel2-variables() { + for v in PVR CKV OKV KV KV_FULL KV_MAJOR KV_MINOR KV_PATCH RELEASETYPE \ + RELEASE UNIPATCH_LIST_DEFAULT UNIPATCH_LIST_GENPATCHES \ + UNIPATCH_LIST S KERNEL_URI K_WANT_GENPATCHES ; do + debug-print "${v}: ${!v}" + done +} + +# @FUNCTION: handle_genpatches +# @USAGE: [--set-unipatch-list] +# @DESCRIPTION: +# add genpatches to list of patches to apply if wanted + +handle_genpatches() { + local tarball want_unipatch_list + [[ -z ${K_WANT_GENPATCHES} || -z ${K_GENPATCHES_VER} ]] && return 1 + + if [[ -n ${1} ]]; then + # set UNIPATCH_LIST_GENPATCHES only on explicit request + # since that requires 'use' call which can be used only in phase + # functions, while the function is also called in global scope + if [[ ${1} == --set-unipatch-list ]]; then + want_unipatch_list=1 + else + die "Usage: ${FUNCNAME} [--set-unipatch-list]" + fi + fi + + debug-print "Inside handle_genpatches" + local OKV_ARRAY + IFS="." read -r -a OKV_ARRAY <<<"${OKV}" + + # for > 3.0 kernels, handle genpatches tarball name + # genpatches for 3.0 and 3.0.1 might be named + # genpatches-3.0-1.base.tar.xz and genpatches-3.0-2.base.tar.xz + # respectively. Handle this. + + for i in ${K_WANT_GENPATCHES} ; do + if [[ ${KV_MAJOR} -ge 3 ]]; then + if [[ ${#OKV_ARRAY[@]} -ge 3 ]]; then + tarball="genpatches-${KV_MAJOR}.${KV_MINOR}-${K_GENPATCHES_VER}.${i}.tar.xz" + else + tarball="genpatches-${KV_MAJOR}.${KV_PATCH}-${K_GENPATCHES_VER}.${i}.tar.xz" + fi + else + tarball="genpatches-${OKV}-${K_GENPATCHES_VER}.${i}.tar.xz" + fi + + local use_cond_start="" use_cond_end="" + + if [[ "${i}" == "experimental" && -z ${K_EXP_GENPATCHES_PULL} && -z ${K_EXP_GENPATCHES_NOUSE} ]] ; then + use_cond_start="experimental? ( " + use_cond_end=" )" + + if [[ -n ${want_unipatch_list} ]] && use experimental ; then + UNIPATCH_LIST_GENPATCHES+=" ${DISTDIR}/${tarball}" + debug-print "genpatches tarball: $tarball" + fi + elif [[ -n ${want_unipatch_list} ]]; then + UNIPATCH_LIST_GENPATCHES+=" ${DISTDIR}/${tarball}" + debug-print "genpatches tarball: $tarball" + fi + GENPATCHES_URI+=" ${use_cond_start}$(echo https://dev.gentoo.org/~{alicef,mpagano,whissi}/dist/genpatches/${tarball})${use_cond_end}" + done +} + +# @FUNCTION: detect_version +# @USAGE: +# @DESCRIPTION: +# this function will detect and set +# - OKV: Original Kernel Version (2.6.0/2.6.0-test11) +# - KV: Kernel Version (2.6.0-gentoo/2.6.0-test11-gentoo-r1) +# - EXTRAVERSION: The additional version appended to OKV (-gentoo/-gentoo-r1) +detect_version() { + + # We've already run, so nothing to do here. + [[ -n ${KV_FULL} ]] && return 0 + + # CKV is used as a comparison kernel version, which is used when + # PV doesnt reflect the genuine kernel version. + # this gets set to the portage style versioning. ie: + # CKV=2.6.11_rc4 + CKV=${CKV:-${PV}} + OKV=${OKV:-${CKV}} + OKV=${OKV/_beta/-test} + OKV=${OKV/_rc/-rc} + OKV=${OKV/-r*} + OKV=${OKV/_p*} + + KV_MAJOR=$(ver_cut 1 ${OKV}) + # handle if OKV is X.Y or X.Y.Z (e.g. 3.0 or 3.0.1) + local OKV_ARRAY + IFS="." read -r -a OKV_ARRAY <<<"${OKV}" + + # if KV_MAJOR >= 3, then we have no more KV_MINOR + #if [[ ${KV_MAJOR} -lt 3 ]]; then + if [[ ${#OKV_ARRAY[@]} -ge 3 ]]; then + KV_MINOR=$(ver_cut 2 ${OKV}) + KV_PATCH=$(ver_cut 3 ${OKV}) + if [[ ${KV_MAJOR}${KV_MINOR}${KV_PATCH} -ge 269 ]]; then + KV_EXTRA=$(ver_cut 4- ${OKV}) + KV_EXTRA=${KV_EXTRA/[-_]*} + else + KV_PATCH=$(ver_cut 3- ${OKV}) + fi + else + KV_PATCH=$(ver_cut 2 ${OKV}) + KV_EXTRA=$(ver_cut 3- ${OKV}) + KV_EXTRA=${KV_EXTRA/[-_]*} + fi + + debug-print "KV_EXTRA is ${KV_EXTRA}" + + KV_PATCH=${KV_PATCH/[-_]*} + + local v n=0 missing + #if [[ ${KV_MAJOR} -lt 3 ]]; then + if [[ ${#OKV_ARRAY[@]} -ge 3 ]]; then + for v in CKV OKV KV_{MAJOR,MINOR,PATCH} ; do + [[ -z ${!v} ]] && n=1 && missing="${missing}${v} "; + done + else + for v in CKV OKV KV_{MAJOR,PATCH} ; do + [[ -z ${!v} ]] && n=1 && missing="${missing}${v} "; + done + fi + + [[ $n -eq 1 ]] && \ + eerror "Missing variables: ${missing}" && \ + die "Failed to extract kernel version (try explicit CKV in ebuild)!" + unset v n missing + +# if [[ ${KV_MAJOR} -ge 3 ]]; then + if [[ ${#OKV_ARRAY[@]} -lt 3 ]]; then + KV_PATCH_ARR=(${KV_PATCH//\./ }) + + # at this point 031412, Linus is putting all 3.x kernels in a + # 3.x directory, may need to revisit when 4.x is released + KERNEL_BASE_URI="https://www.kernel.org/pub/linux/kernel/v${KV_MAJOR}.x" + + [[ -n "${K_LONGTERM}" ]] && + KERNEL_BASE_URI="${KERNEL_BASE_URI}/longterm/v${KV_MAJOR}.${KV_PATCH_ARR}" + else + #KERNEL_BASE_URI="https://www.kernel.org/pub/linux/kernel/v${KV_MAJOR}.0" + #KERNEL_BASE_URI="https://www.kernel.org/pub/linux/kernel/v${KV_MAJOR}.${KV_MINOR}" + if [[ ${KV_MAJOR} -ge 3 ]]; then + KERNEL_BASE_URI="https://www.kernel.org/pub/linux/kernel/v${KV_MAJOR}.x" + else + KERNEL_BASE_URI="https://www.kernel.org/pub/linux/kernel/v${KV_MAJOR}.${KV_MINOR}" + fi + + [[ -n "${K_LONGTERM}" ]] && + #KERNEL_BASE_URI="${KERNEL_BASE_URI}/longterm" + KERNEL_BASE_URI="${KERNEL_BASE_URI}/longterm/v${KV_MAJOR}.${KV_MINOR}.${KV_PATCH}" + fi + + debug-print "KERNEL_BASE_URI is ${KERNEL_BASE_URI}" + + if [[ ${#OKV_ARRAY[@]} -ge 3 ]] && [[ ${KV_MAJOR} -ge 3 ]]; then + # handle non genpatch using sources correctly + if [[ -z ${K_WANT_GENPATCHES} && -z ${K_GENPATCHES_VER} && ${KV_PATCH} -gt 0 ]]; then + KERNEL_URI="${KERNEL_BASE_URI}/patch-${OKV}.xz" + UNIPATCH_LIST_DEFAULT="${DISTDIR}/patch-${CKV}.xz" + fi + KERNEL_URI="${KERNEL_URI} ${KERNEL_BASE_URI}/linux-${KV_MAJOR}.${KV_MINOR}.tar.xz" + else + KERNEL_URI="${KERNEL_BASE_URI}/linux-${OKV}.tar.xz" + fi + + RELEASE=${CKV/${OKV}} + RELEASE=${RELEASE/_beta} + RELEASE=${RELEASE/_rc/-rc} + RELEASE=${RELEASE/_pre/-pre} + # We cannot trivally call kernel_is here, because it calls us to detect the + # version + #kernel_is ge 2 6 && RELEASE=${RELEASE/-pre/-git} + [ $(($KV_MAJOR * 1000 + ${KV_MINOR:-0})) -ge 2006 ] && RELEASE=${RELEASE/-pre/-git} + RELEASETYPE=${RELEASE//[0-9]} + + # Now we know that RELEASE is the -rc/-git + # and RELEASETYPE is the same but with its numerics stripped + # we can work on better sorting EXTRAVERSION. + # first of all, we add the release + EXTRAVERSION="${RELEASE}" + debug-print "0 EXTRAVERSION:${EXTRAVERSION}" + [[ -n ${KV_EXTRA} ]] && [[ ${KV_MAJOR} -lt 3 ]] && EXTRAVERSION=".${KV_EXTRA}${EXTRAVERSION}" + + debug-print "1 EXTRAVERSION:${EXTRAVERSION}" + if [[ -n "${K_NOUSEPR}" ]]; then + # Don't add anything based on PR to EXTRAVERSION + debug-print "1.0 EXTRAVERSION:${EXTRAVERSION}" + elif [[ -n ${K_PREPATCHED} ]]; then + debug-print "1.1 EXTRAVERSION:${EXTRAVERSION}" + EXTRAVERSION="${EXTRAVERSION}-${PN/-*}${PR/r}" + elif [[ "${ETYPE}" = "sources" ]]; then + debug-print "1.2 EXTRAVERSION:${EXTRAVERSION}" + # For some sources we want to use the PV in the extra version + # This is because upstream releases with a completely different + # versioning scheme. + case ${PN/-*} in + wolk) K_USEPV=1;; + vserver) K_USEPV=1;; + esac + + [[ -z "${K_NOUSENAME}" ]] && EXTRAVERSION="${EXTRAVERSION}-${PN/-*}" + [[ -n "${K_USEPV}" ]] && EXTRAVERSION="${EXTRAVERSION}-${PV//_/-}" + [[ -n "${PR//r0}" ]] && EXTRAVERSION="${EXTRAVERSION}-${PR}" + fi + debug-print "2 EXTRAVERSION:${EXTRAVERSION}" + + # The only messing around which should actually effect this is for KV_EXTRA + # since this has to limit OKV to MAJ.MIN.PAT and strip EXTRA off else + # KV_FULL evaluates to MAJ.MIN.PAT.EXT.EXT after EXTRAVERSION + + if [[ -n ${KV_EXTRA} ]]; then + if [[ -n ${KV_MINOR} ]]; then + OKV="${KV_MAJOR}.${KV_MINOR}.${KV_PATCH}" + else + OKV="${KV_MAJOR}.${KV_PATCH}" + fi + KERNEL_URI="${KERNEL_BASE_URI}/patch-${CKV}.xz + ${KERNEL_BASE_URI}/linux-${OKV}.tar.xz" + UNIPATCH_LIST_DEFAULT="${DISTDIR}/patch-${CKV}.xz" + fi + + # We need to set this using OKV, but we need to set it before we do any + # messing around with OKV based on RELEASETYPE + KV_FULL=${OKV}${EXTRAVERSION} + + # we will set this for backwards compatibility. + S="${WORKDIR}"/linux-${KV_FULL} + KV=${KV_FULL} + + # -rc-git pulls can be achieved by specifying CKV + # for example: + # CKV="2.6.11_rc3_pre2" + # will pull: + # linux-2.6.10.tar.xz & patch-2.6.11-rc3.xz & patch-2.6.11-rc3-git2.xz + + if [[ ${KV_MAJOR}${KV_MINOR} -eq 26 ]]; then + + if [[ ${RELEASETYPE} == -rc ]] || [[ ${RELEASETYPE} == -pre ]]; then + OKV="${KV_MAJOR}.${KV_MINOR}.$((${KV_PATCH} - 1))" + KERNEL_URI="${KERNEL_BASE_URI}/testing/patch-${CKV//_/-}.xz + ${KERNEL_BASE_URI}/linux-${OKV}.tar.xz" + UNIPATCH_LIST_DEFAULT="${DISTDIR}/patch-${CKV//_/-}.xz" + fi + + if [[ ${RELEASETYPE} == -git ]]; then + KERNEL_URI="${KERNEL_BASE_URI}/snapshots/patch-${OKV}${RELEASE}.xz + ${KERNEL_BASE_URI}/linux-${OKV}.tar.xz" + UNIPATCH_LIST_DEFAULT="${DISTDIR}/patch-${OKV}${RELEASE}.xz" + fi + + if [[ ${RELEASETYPE} == -rc-git ]]; then + OKV="${KV_MAJOR}.${KV_MINOR}.$((${KV_PATCH} - 1))" + KERNEL_URI="${KERNEL_BASE_URI}/snapshots/patch-${KV_MAJOR}.${KV_MINOR}.${KV_PATCH}${RELEASE}.xz + ${KERNEL_BASE_URI}/testing/patch-${KV_MAJOR}.${KV_MINOR}.${KV_PATCH}${RELEASE/-git*}.xz + ${KERNEL_BASE_URI}/linux-${OKV}.tar.xz" + + UNIPATCH_LIST_DEFAULT="${DISTDIR}/patch-${KV_MAJOR}.${KV_MINOR}.${KV_PATCH}${RELEASE/-git*}.xz ${DISTDIR}/patch-${KV_MAJOR}.${KV_MINOR}.${KV_PATCH}${RELEASE}.xz" + fi + else + KV_PATCH_ARR=(${KV_PATCH//\./ }) + + # the different majorminor versions have different patch start versions + OKV_DICT=(["2"]="${KV_MAJOR}.$((${KV_PATCH_ARR} - 1))" ["3"]="2.6.39" ["4"]="3.19") + + if [[ ${RELEASETYPE} == -rc ]] || [[ ${RELEASETYPE} == -pre ]]; then + + OKV=${K_BASE_VER:-$OKV_DICT["${KV_MAJOR}"]} + + # as of 12/5/2017, the rc patch is no longer offered as a compressed + # file, and no longer is it mirrored on kernel.org + if ver_test "${KV_MAJOR}.${KV_PATCH}" -ge "4.12"; then + KERNEL_URI="https://git.kernel.org/torvalds/p/v${KV_FULL}/v${OKV} -> patch-${KV_FULL}.patch + ${KERNEL_BASE_URI}/linux-${OKV}.tar.xz" + UNIPATCH_LIST_DEFAULT="${DISTDIR}/patch-${CKV//_/-}.patch" + else + KERNEL_URI="${KERNEL_BASE_URI}/testing/patch-${CKV//_/-}.xz + ${KERNEL_BASE_URI}/linux-${OKV}.tar.xz" + UNIPATCH_LIST_DEFAULT="${DISTDIR}/patch-${CKV//_/-}.xz" + fi + fi + + if [[ ${RELEASETYPE} == -git ]]; then + KERNEL_URI="${KERNEL_BASE_URI}/snapshots/patch-${OKV}${RELEASE}.xz + ${KERNEL_BASE_URI}/linux-${OKV}.tar.xz" + UNIPATCH_LIST_DEFAULT="${DISTDIR}/patch-${OKV}${RELEASE}.xz" + fi + + if [[ ${RELEASETYPE} == -rc-git ]]; then + OKV=${K_BASE_VER:-$OKV_DICT["${KV_MAJOR}"]} + KERNEL_URI="${KERNEL_BASE_URI}/snapshots/patch-${KV_MAJOR}.${KV_PATCH}${RELEASE}.xz + ${KERNEL_BASE_URI}/testing/patch-${KV_MAJOR}.${KV_PATCH}${RELEASE/-git*}.xz + ${KERNEL_BASE_URI}/linux-${OKV}.tar.xz" + + UNIPATCH_LIST_DEFAULT="${DISTDIR}/patch-${KV_MAJOR}.${KV_PATCH}${RELEASE/-git*}.xz ${DISTDIR}/patch-${KV_MAJOR}.${KV_PATCH}${RELEASE}.xz" + fi + + + fi + + debug-print-kernel2-variables + + handle_genpatches +} + +# @FUNCTION: kernel_is +# @USAGE: <conditional version | version> +# @DESCRIPTION: +# user for comparing kernel versions +# or just identifying a version +# e.g kernel_is 2 4 +# e.g kernel_is ge 4.8.11 +# Note: duplicated in linux-info.eclass +kernel_is() { + # ALL of these should be set before we can safely continue this function. + # some of the sources have in the past had only one set. + local v n=0 + for v in OKV KV_{MAJOR,MINOR,PATCH} ; do [[ -z ${!v} ]] && n=1 ; done + [[ $n -eq 1 ]] && detect_version + unset v n + + # Now we can continue + local operator test value + + case ${1#-} in + lt) operator="-lt"; shift;; + gt) operator="-gt"; shift;; + le) operator="-le"; shift;; + ge) operator="-ge"; shift;; + eq) operator="-eq"; shift;; + *) operator="-eq";; + esac + [[ $# -gt 3 ]] && die "Error in kernel-2_kernel_is(): too many parameters" + + : $(( test = (KV_MAJOR << 16) + (KV_MINOR << 8) + KV_PATCH )) + : $(( value = (${1:-${KV_MAJOR}} << 16) + (${2:-${KV_MINOR}} << 8) + ${3:-${KV_PATCH}} )) + [ ${test} ${operator} ${value} ] +} + +# @FUNCTION: kernel_is_2_4 +# @USAGE: +# @DESCRIPTION: +# return true if kernel is version 2.4 +kernel_is_2_4() { + kernel_is 2 4 +} + +# @FUNCTION: kernel_is_2_6 +# @USAGE: +# @DESCRIPTION: +# return true if kernel is version 2.6 +kernel_is_2_6() { + kernel_is 2 6 || kernel_is 2 5 +} + +# Capture the sources type and set DEPENDs +if [[ ${ETYPE} == sources ]]; then + DEPEND="!build? ( + sys-apps/sed + >=sys-devel/binutils-2.11.90.0.31 + )" + RDEPEND="!build? ( + dev-lang/perl + sys-devel/bc + sys-devel/bison + sys-devel/flex + sys-devel/make + >=sys-libs/ncurses-5.2 + virtual/libelf + virtual/pkgconfig + )" + + SLOT="${PVR}" + DESCRIPTION="Sources based on the Linux Kernel." + IUSE="symlink build" + + # Bug #266157, deblob for libre support + if [[ -z ${K_PREDEBLOBBED} ]] ; then + # Bug #359865, force a call to detect_version if needed + kernel_is ge 2 6 27 && \ + [[ -z "${K_DEBLOB_AVAILABLE}" ]] && \ + kernel_is le 2 6 ${DEBLOB_MAX_VERSION} && \ + K_DEBLOB_AVAILABLE=1 + if [[ ${K_DEBLOB_AVAILABLE} == "1" ]] ; then + PYTHON_COMPAT=( python2_7 ) + + inherit python-any-r1 + + IUSE="${IUSE} deblob" + + # Reflect that kernels contain firmware blobs unless otherwise + # stripped. Starting with version 4.14, the whole firmware + # tree has been dropped from the kernel. + kernel_is lt 4 14 && LICENSE+=" !deblob? ( linux-firmware )" + + DEPEND+=" deblob? ( ${PYTHON_DEPS} )" + + if [[ -n KV_MINOR ]]; then + DEBLOB_PV="${KV_MAJOR}.${KV_MINOR}.${KV_PATCH}" + else + DEBLOB_PV="${KV_MAJOR}.${KV_PATCH}" + fi + + if [[ ${KV_MAJOR} -ge 3 ]]; then + DEBLOB_PV="${KV_MAJOR}.${KV_MINOR}" + fi + + # deblob svn tag, default is -gnu, to change, use K_DEBLOB_TAG in ebuild + K_DEBLOB_TAG=${K_DEBLOB_TAG:--gnu} + DEBLOB_A="deblob-${DEBLOB_PV}" + DEBLOB_CHECK_A="deblob-check-${DEBLOB_PV}" + DEBLOB_HOMEPAGE="https://www.fsfla.org/svn/fsfla/software/linux-libre/releases/tags/" + DEBLOB_URI_PATH="${DEBLOB_PV}${K_DEBLOB_TAG}" + DEBLOB_CHECK_URI="${DEBLOB_HOMEPAGE}/${DEBLOB_URI_PATH}/deblob-check -> ${DEBLOB_CHECK_A}" + DEBLOB_URI="${DEBLOB_HOMEPAGE}/${DEBLOB_URI_PATH}/${DEBLOB_A}" + HOMEPAGE="${HOMEPAGE} ${DEBLOB_HOMEPAGE}" + + KERNEL_URI="${KERNEL_URI} + deblob? ( + ${DEBLOB_URI} + ${DEBLOB_CHECK_URI} + )" + elif kernel_is lt 4 14; then + # Deblobbing is not available, so just mark kernels older + # than 4.14 as tainted with non-libre materials. + LICENSE+=" linux-firmware" + fi + fi + +elif [[ ${ETYPE} == headers ]]; then + DESCRIPTION="Linux system headers" + IUSE="headers-only" + + # Since we should NOT honour KBUILD_OUTPUT in headers + # lets unset it here. + unset KBUILD_OUTPUT + + SLOT="0" +fi + +# Cross-compile support functions + +# @FUNCTION: kernel_header_destdir +# @USAGE: +# @DESCRIPTION: +# return header destination directory +kernel_header_destdir() { + [[ ${CTARGET} == ${CHOST} ]] \ + && echo /usr/include \ + || echo /usr/${CTARGET}/usr/include +} + +# @FUNCTION: cross_pre_c_headers +# @USAGE: +# @DESCRIPTION: +# set use if necessary for cross compile support +cross_pre_c_headers() { + use headers-only && [[ ${CHOST} != ${CTARGET} ]] +} + +# @FUNCTION: env_setup_xmakeopts +# @USAGE: +# @DESCRIPTION: +# set the ARCH/CROSS_COMPILE when cross compiling + +env_setup_xmakeopts() { + # Kernel ARCH != portage ARCH + export KARCH=$(tc-arch-kernel) + + # When cross-compiling, we need to set the ARCH/CROSS_COMPILE + # variables properly or bad things happen ! + xmakeopts="ARCH=${KARCH}" + if [[ ${CTARGET} != ${CHOST} ]] && ! cross_pre_c_headers ; then + xmakeopts="${xmakeopts} CROSS_COMPILE=${CTARGET}-" + elif type -p ${CHOST}-ar > /dev/null ; then + xmakeopts="${xmakeopts} CROSS_COMPILE=${CHOST}-" + fi + xmakeopts="${xmakeopts} HOSTCC=$(tc-getBUILD_CC)" + export xmakeopts +} + +# @FUNCTION: unpack_2_4 +# @USAGE: +# @DESCRIPTION: +# unpack and generate .config for 2.4 kernels + +unpack_2_4() { + # this file is required for other things to build properly, + # so we autogenerate it + make -s mrproper ${xmakeopts} || die "make mrproper failed" + make -s symlinks ${xmakeopts} || die "make symlinks failed" + make -s include/linux/version.h ${xmakeopts} || die "make include/linux/version.h failed" + echo ">>> version.h compiled successfully." +} + +# @FUNCTION: unpack_2_6 +# @USAGE: +# @DESCRIPTION: +# unpack and generate .config for 2.6 kernels + +unpack_2_6() { + # this file is required for other things to build properly, so we + # autogenerate it ... generate a .config to keep version.h build from + # spitting out an annoying warning + make -s mrproper ${xmakeopts} 2>/dev/null \ + || die "make mrproper failed" + + # quick fix for bug #132152 which triggers when it cannot include linux + # headers (ie, we have not installed it yet) + if ! make -s defconfig ${xmakeopts} &>/dev/null 2>&1 ; then + touch .config + eerror "make defconfig failed." + eerror "assuming you dont have any headers installed yet and continuing" + fi + + make -s include/linux/version.h ${xmakeopts} 2>/dev/null \ + || die "make include/linux/version.h failed" + rm -f .config >/dev/null +} + +# @FUNCTION: universal_unpack +# @USAGE: +# @DESCRIPTION: +# unpack kernel sources + +universal_unpack() { + debug-print "Inside universal_unpack" + + local OKV_ARRAY + IFS="." read -r -a OKV_ARRAY <<<"${OKV}" + + cd "${WORKDIR}" + if [[ ${#OKV_ARRAY[@]} -ge 3 ]] && [[ ${KV_MAJOR} -ge 3 ]]; then + unpack linux-${KV_MAJOR}.${KV_MINOR}.tar.xz + else + unpack linux-${OKV}.tar.xz + fi + + if [[ -d "linux" ]]; then + debug-print "Moving linux to linux-${KV_FULL}" + mv linux linux-${KV_FULL} \ + || die "Unable to move source tree to ${KV_FULL}." + elif [[ "${OKV}" != "${KV_FULL}" ]]; then + if [[ ${#OKV_ARRAY[@]} -ge 3 ]] && [[ ${KV_MAJOR} -ge 3 ]] && + [[ "${ETYPE}" = "sources" ]]; then + debug-print "moving linux-${KV_MAJOR}.${KV_MINOR} to linux-${KV_FULL} " + mv linux-${KV_MAJOR}.${KV_MINOR} linux-${KV_FULL} \ + || die "Unable to move source tree to ${KV_FULL}." + else + debug-print "moving linux-${OKV} to linux-${KV_FULL} " + mv linux-${OKV} linux-${KV_FULL} \ + || die "Unable to move source tree to ${KV_FULL}." + fi + elif [[ ${#OKV_ARRAY[@]} -ge 3 ]] && [[ ${KV_MAJOR} -ge 3 ]]; then + mv linux-${KV_MAJOR}.${KV_MINOR} linux-${KV_FULL} \ + || die "Unable to move source tree to ${KV_FULL}." + fi + cd "${S}" + + # remove all backup files + find . -iname "*~" -exec rm {} \; 2> /dev/null + +} + +# @FUNCTION: unpack_set_extraversion +# @USAGE: +# @DESCRIPTION: +# handle EXTRAVERSION + +unpack_set_extraversion() { + cd "${S}" + sed -i -e "s:^\(EXTRAVERSION =\).*:\1 ${EXTRAVERSION}:" Makefile + cd "${OLDPWD}" +} + +# @FUNCTION: unpack_fix_install_path +# @USAGE: +# @DESCRIPTION: +# Should be done after patches have been applied +# Otherwise patches that modify the same area of Makefile will fail + +unpack_fix_install_path() { + cd "${S}" + sed -i -e 's:#export\tINSTALL_PATH:export\tINSTALL_PATH:' Makefile +} + +# Compile Functions + +# @FUNCTION: compile_headers +# @USAGE: +# @DESCRIPTION: +# header compilation + +compile_headers() { + env_setup_xmakeopts + + # if we couldnt obtain HOSTCFLAGS from the Makefile, + # then set it to something sane + local HOSTCFLAGS=$(getfilevar HOSTCFLAGS "${S}"/Makefile) + HOSTCFLAGS=${HOSTCFLAGS:--Wall -Wstrict-prototypes -O2 -fomit-frame-pointer} + + if kernel_is 2 4; then + yes "" | make oldconfig ${xmakeopts} + echo ">>> make oldconfig complete" + make dep ${xmakeopts} + elif kernel_is 2 6; then + # 2.6.18 introduces headers_install which means we dont need any + # of this crap anymore :D + kernel_is ge 2 6 18 && return 0 + + # autoconf.h isnt generated unless it already exists. plus, we have + # no guarantee that any headers are installed on the system... + [[ -f ${EROOT}usr/include/linux/autoconf.h ]] \ + || touch include/linux/autoconf.h + + # if K_DEFCONFIG isn't set, force to "defconfig" + # needed by mips + if [[ -z ${K_DEFCONFIG} ]]; then + if kernel_is ge 2 6 16 ; then + case ${CTARGET} in + powerpc64*) K_DEFCONFIG="ppc64_defconfig";; + powerpc*) K_DEFCONFIG="pmac32_defconfig";; + *) K_DEFCONFIG="defconfig";; + esac + else + K_DEFCONFIG="defconfig" + fi + fi + + # if there arent any installed headers, then there also isnt an asm + # symlink in /usr/include/, and make defconfig will fail, so we have + # to force an include path with $S. + HOSTCFLAGS="${HOSTCFLAGS} -I${S}/include/" + ln -sf asm-${KARCH} "${S}"/include/asm || die + cross_pre_c_headers && return 0 + + make ${K_DEFCONFIG} HOSTCFLAGS="${HOSTCFLAGS}" ${xmakeopts} || die "defconfig failed (${K_DEFCONFIG})" + if compile_headers_tweak_config ; then + yes "" | make oldconfig HOSTCFLAGS="${HOSTCFLAGS}" ${xmakeopts} || die "2nd oldconfig failed" + fi + make prepare HOSTCFLAGS="${HOSTCFLAGS}" ${xmakeopts} || die "prepare failed" + make prepare-all HOSTCFLAGS="${HOSTCFLAGS}" ${xmakeopts} || die "prepare failed" + fi +} + +# @FUNCTION: compile_headers_tweak_config +# @USAGE: +# @DESCRIPTION: +# some targets can be very very picky, so let's finesse the +# .config based upon any info we may have + +compile_headers_tweak_config() { + case ${CTARGET} in + sh*) + sed -i '/CONFIG_CPU_SH/d' .config || die + echo "CONFIG_CPU_SH${CTARGET:2:1}=y" >> .config + return 0;; + esac + + # no changes, so lets do nothing + return 1 +} + +# install functions + +# @FUNCTION: install_universal +# @USAGE: +# @DESCRIPTION: +# Fix permissions in tarball + +install_universal() { + cd "${WORKDIR}" + chown -R 0:0 * >& /dev/null + chmod -R a+r-w+X,u+w * + cd ${OLDPWD} +} + +# @FUNCTION: install_headers +# @USAGE: +# @DESCRIPTION: +# Install headers + +install_headers() { + local ddir=$(kernel_header_destdir) + + # 2.6.18 introduces headers_install which means we dont need any + # of this crap anymore :D + if kernel_is ge 2 6 18 ; then + env_setup_xmakeopts + emake headers_install INSTALL_HDR_PATH="${ED}"${ddir}/.. ${xmakeopts} || die + + # let other packages install some of these headers + rm -rf "${ED}"${ddir}/scsi || die #glibc/uclibc/etc... + return 0 + fi + + # Do not use "linux/*" as that can cause problems with very long + # $S values where the cmdline to cp is too long + pushd "${S}" >/dev/null + dodir ${ddir}/linux + cp -pPR "${S}"/include/linux "${ED}"${ddir}/ || die + rm -rf "${ED}"${ddir}/linux/modules || die + + dodir ${ddir}/asm + cp -pPR "${S}"/include/asm/* "${ED}"${ddir}/asm || die + + if kernel_is 2 6 ; then + dodir ${ddir}/asm-generic + cp -pPR "${S}"/include/asm-generic/* "${ED}"${ddir}/asm-generic || die + fi + + # clean up + find "${D}" -name '*.orig' -exec rm -f {} \; + + popd >/dev/null +} + +# @FUNCTION: install_sources +# @USAGE: +# @DESCRIPTION: +# Install sources + +install_sources() { + local file + + cd "${S}" + dodir /usr/src + echo ">>> Copying sources ..." + + file="$(find ${WORKDIR} -iname "docs" -type d)" + if [[ -n ${file} ]]; then + for file in $(find ${file} -type f); do + echo "${file//*docs\/}" >> "${S}"/patches.txt + echo "===================================================" >> "${S}"/patches.txt + cat ${file} >> "${S}"/patches.txt + echo "===================================================" >> "${S}"/patches.txt + echo "" >> "${S}"/patches.txt + done + fi + + mv "${WORKDIR}"/linux* "${ED}"usr/src || die + + if [[ -n "${UNIPATCH_DOCS}" ]] ; then + for i in ${UNIPATCH_DOCS}; do + dodoc "${T}"/${i} + done + fi +} + +# @FUNCTION: preinst_headers +# @USAGE: +# @DESCRIPTION: +# Headers preinst steps + +preinst_headers() { + local ddir=$(kernel_header_destdir) + [[ -L ${EPREFIX}${ddir}/linux ]] && { rm "${EPREFIX}"${ddir}/linux || die; } + [[ -L ${EPREFIX}${ddir}/asm ]] && { rm "${EPREFIX}"${ddir}/asm || die; } +} + +# @FUNCTION: postinst_sources +# @USAGE: +# @DESCRIPTION: +# Sources post installation function. +# see inline comments + +postinst_sources() { + local MAKELINK=0 + + # if we have USE=symlink, then force K_SYMLINK=1 + use symlink && K_SYMLINK=1 + + # We do support security on a deblobbed kernel, bug #555878. + # If some particular kernel version doesn't have security + # supported because of USE=deblob or otherwise, one can still + # set K_SECURITY_UNSUPPORTED on a per ebuild basis. + #[[ $K_DEBLOB_AVAILABLE == 1 ]] && \ + # use deblob && \ + # K_SECURITY_UNSUPPORTED=deblob + + # if we are to forcably symlink, delete it if it already exists first. + if [[ ${K_SYMLINK} -gt 0 ]]; then + [[ -h ${EROOT}usr/src/linux ]] && { rm "${EROOT}"usr/src/linux || die; } + MAKELINK=1 + fi + + # if the link doesnt exist, lets create it + [[ ! -h ${EROOT}usr/src/linux ]] && MAKELINK=1 + + if [[ ${MAKELINK} == 1 ]]; then + ln -sf linux-${KV_FULL} "${EROOT}"usr/src/linux || die + fi + + # Don't forget to make directory for sysfs + [[ ! -d ${EROOT}sys ]] && kernel_is 2 6 && { mkdir "${EROOT}"sys || die ; } + + echo + elog "If you are upgrading from a previous kernel, you may be interested" + elog "in the following document:" + elog " - General upgrade guide: https://wiki.gentoo.org/wiki/Kernel/Upgrade" + echo + + # if K_EXTRAEINFO is set then lets display it now + if [[ -n ${K_EXTRAEINFO} ]]; then + echo ${K_EXTRAEINFO} | fmt | + while read -s ELINE; do einfo "${ELINE}"; done + fi + + # if K_EXTRAELOG is set then lets display it now + if [[ -n ${K_EXTRAELOG} ]]; then + echo ${K_EXTRAELOG} | fmt | + while read -s ELINE; do elog "${ELINE}"; done + fi + + # if K_EXTRAEWARN is set then lets display it now + if [[ -n ${K_EXTRAEWARN} ]]; then + echo ${K_EXTRAEWARN} | fmt | + while read -s ELINE; do ewarn "${ELINE}"; done + fi + + # optionally display security unsupported message + # Start with why + if [[ -n ${K_SECURITY_UNSUPPORTED} ]]; then + ewarn "${PN} is UNSUPPORTED by Gentoo Security." + fi + # And now the general message. + if [[ -n ${K_SECURITY_UNSUPPORTED} ]]; then + ewarn "This means that it is likely to be vulnerable to recent security issues." + echo + ewarn "Upstream kernel developers recommend always running the latest " + ewarn "release of any current long term supported Linux kernel version." + ewarn "To see a list of these versions, their most current release and " + ewarn "long term support status, please go to https://www.kernel.org ." + echo + ewarn "For specific information on why this kernel is unsupported, please read:" + ewarn "https://wiki.gentoo.org/wiki/Project:Kernel_Security" + fi + + # warn sparc users that they need to do cross-compiling with >= 2.6.25(bug #214765) + KV_MAJOR=$(ver_cut 1 ${OKV}) + KV_MINOR=$(ver_cut 2 ${OKV}) + KV_PATCH=$(ver_cut 3 ${OKV}) + if [[ "$(tc-arch)" = "sparc" ]]; then + if [[ $(gcc-major-version) -lt 4 && $(gcc-minor-version) -lt 4 ]]; then + if [[ ${KV_MAJOR} -ge 3 ]] || ver_test ${KV_MAJOR}.${KV_MINOR}.${KV_PATCH} -gt 2.6.24 ; then + echo + elog "NOTE: Since 2.6.25 the kernel Makefile has changed in a way that" + elog "you now need to do" + elog " make CROSS_COMPILE=sparc64-unknown-linux-gnu-" + elog "instead of just" + elog " make" + elog "to compile the kernel. For more information please browse to" + elog "https://bugs.gentoo.org/show_bug.cgi?id=214765" + echo + fi + fi + fi +} + +# pkg_setup functions + +# @FUNCTION: setup_headers +# @USAGE: +# @DESCRIPTION: +# Determine if ${PN} supports arch + +setup_headers() { + [[ -z ${H_SUPPORTEDARCH} ]] && H_SUPPORTEDARCH=${PN/-*/} + for i in ${H_SUPPORTEDARCH}; do + [[ $(tc-arch) == "${i}" ]] && H_ACCEPT_ARCH="yes" + done + + if [[ ${H_ACCEPT_ARCH} != "yes" ]]; then + echo + eerror "This version of ${PN} does not support $(tc-arch)." + eerror "Please merge the appropriate sources, in most cases" + eerror "(but not all) this will be called $(tc-arch)-headers." + die "Package unsupported for $(tc-arch)" + fi +} + +# @FUNCTION: unipatch +# @USAGE: <list of patches to apply> +# @DESCRIPTION: +# Universal function that will apply patches to source + +unipatch() { + local i x y z extention PIPE_CMD UNIPATCH_DROP KPATCH_DIR PATCH_DEPTH ELINE + local STRICT_COUNT PATCH_LEVEL myLC_ALL myLANG + + # set to a standard locale to ensure sorts are ordered properly. + myLC_ALL="${LC_ALL}" + myLANG="${LANG}" + LC_ALL="C" + LANG="" + + [ -z "${KPATCH_DIR}" ] && KPATCH_DIR="${WORKDIR}/patches/" + [ ! -d ${KPATCH_DIR} ] && mkdir -p ${KPATCH_DIR} + + # We're gonna need it when doing patches with a predefined patchlevel + eshopts_push -s extglob + + # This function will unpack all passed tarballs, add any passed patches, + # and remove any passed patchnumbers + # usage can be either via an env var or by params + # although due to the nature we pass this within this eclass + # it shall be by param only. + # -z "${UNIPATCH_LIST}" ] && UNIPATCH_LIST="${@}" + UNIPATCH_LIST="${@}" + + #unpack any passed tarballs + for i in ${UNIPATCH_LIST}; do + if echo ${i} | grep -qs -e "\.tar" -e "\.tbz" -e "\.tgz" ; then + if [ -n "${UNIPATCH_STRICTORDER}" ]; then + unset z + STRICT_COUNT=$((10#${STRICT_COUNT:=0} + 1)) + for((y=0; y<$((6 - ${#STRICT_COUNT})); y++)); + do z="${z}0"; + done + PATCH_ORDER="${z}${STRICT_COUNT}" + + mkdir -p "${KPATCH_DIR}/${PATCH_ORDER}" + pushd "${KPATCH_DIR}/${PATCH_ORDER}" >/dev/null + unpack ${i##*/} + popd >/dev/null + else + pushd "${KPATCH_DIR}" >/dev/null + unpack ${i##*/} + popd >/dev/null + fi + + [[ ${i} == *:* ]] && echo ">>> Strict patch levels not currently supported for tarballed patchsets" + else + extention=${i/*./} + extention=${extention/:*/} + PIPE_CMD="" + case ${extention} in + xz) PIPE_CMD="xz -dc";; + lzma) PIPE_CMD="lzma -dc";; + bz2) PIPE_CMD="bzip2 -dc";; + patch*) PIPE_CMD="cat";; + diff) PIPE_CMD="cat";; + gz|Z|z) PIPE_CMD="gzip -dc";; + ZIP|zip) PIPE_CMD="unzip -p";; + *) UNIPATCH_DROP="${UNIPATCH_DROP} ${i/:*/}";; + esac + + PATCH_LEVEL=${i/*([^:])?(:)} + i=${i/:*/} + x=${i/*\//} + x=${x/\.${extention}/} + + if [ -n "${PIPE_CMD}" ]; then + if [ ! -r "${i}" ]; then + echo + eerror "FATAL: unable to locate:" + eerror "${i}" + eerror "for read-only. The file either has incorrect permissions" + eerror "or does not exist." + die Unable to locate ${i} + fi + + if [ -n "${UNIPATCH_STRICTORDER}" ]; then + unset z + STRICT_COUNT=$((10#${STRICT_COUNT:=0} + 1)) + for((y=0; y<$((6 - ${#STRICT_COUNT})); y++)); + do z="${z}0"; + done + PATCH_ORDER="${z}${STRICT_COUNT}" + + mkdir -p ${KPATCH_DIR}/${PATCH_ORDER}/ + $(${PIPE_CMD} ${i} > ${KPATCH_DIR}/${PATCH_ORDER}/${x}.patch${PATCH_LEVEL}) || die "uncompressing patch failed" + else + $(${PIPE_CMD} ${i} > ${KPATCH_DIR}/${x}.patch${PATCH_LEVEL}) || die "uncompressing patch failed" + fi + fi + fi + + # If experimental was not chosen by the user, drop experimental patches not in K_EXP_GENPATCHES_LIST. + if [[ "${i}" == *"genpatches-"*".experimental."* && -n ${K_EXP_GENPATCHES_PULL} ]] ; then + if [[ -z ${K_EXP_GENPATCHES_NOUSE} ]] && use experimental; then + continue + fi + + local j + for j in ${KPATCH_DIR}/*/50*_*.patch*; do + for k in ${K_EXP_GENPATCHES_LIST} ; do + [[ "$(basename ${j})" == ${k}* ]] && continue 2 + done + UNIPATCH_DROP+=" $(basename ${j})" + done + else + UNIPATCH_LIST_GENPATCHES+=" ${DISTDIR}/${tarball}" + debug-print "genpatches tarball: $tarball" + + local GCC_MAJOR_VER=$(gcc-major-version) + local GCC_MINOR_VER=$(gcc-minor-version) + + # optimization patch for gcc < 8.X and kernel > 4.13 + if kernel_is ge 4 13 ; then + if [[ ${GCC_MAJOR_VER} -lt 8 ]] && [[ ${GCC_MAJOR_VER} -gt 4 ]]; then + UNIPATCH_DROP+=" 5011_enable-cpu-optimizations-for-gcc8.patch" + UNIPATCH_DROP+=" 5012_enable-cpu-optimizations-for-gcc91.patch" + UNIPATCH_DROP+=" 5013_enable-cpu-optimizations-for-gcc10.patch" + # optimization patch for gcc >= 8 and kernel ge 4.13 + elif [[ "${GCC_MAJOR_VER}" -eq 8 ]]; then + # support old kernels for a period. For now, remove as all gcc versions required are masked + UNIPATCH_DROP+=" 5010_enable-additional-cpu-optimizations-for-gcc.patch" + UNIPATCH_DROP+=" 5010_enable-additional-cpu-optimizations-for-gcc-4.9.patch" + UNIPATCH_DROP+=" 5012_enable-cpu-optimizations-for-gcc91.patch" + UNIPATCH_DROP+=" 5013_enable-cpu-optimizations-for-gcc10.patch" + elif [[ "${GCC_MAJOR_VER}" -eq 9 ]] && [[ ${GCC_MINOR_VER} -ge 1 ]]; then + UNIPATCH_DROP+=" 5010_enable-additional-cpu-optimizations-for-gcc.patch" + UNIPATCH_DROP+=" 5010_enable-additional-cpu-optimizations-for-gcc-4.9.patch" + UNIPATCH_DROP+=" 5011_enable-cpu-optimizations-for-gcc8.patch" + UNIPATCH_DROP+=" 5013_enable-cpu-optimizations-for-gcc10.patch" + elif [[ "${GCC_MAJOR_VER}" -eq 10 ]] && [[ ${GCC_MINOR_VER} -ge 1 ]]; then + UNIPATCH_DROP+=" 5010_enable-additional-cpu-optimizations-for-gcc.patch" + UNIPATCH_DROP+=" 5010_enable-additional-cpu-optimizations-for-gcc-4.9.patch" + UNIPATCH_DROP+=" 5011_enable-cpu-optimizations-for-gcc8.patch" + UNIPATCH_DROP+=" 5012_enable-cpu-optimizations-for-gcc91.patch" + else + UNIPATCH_DROP+=" 5010_enable-additional-cpu-optimizations-for-gcc.patch" + UNIPATCH_DROP+=" 5010_enable-additional-cpu-optimizations-for-gcc-4.9.patch" + UNIPATCH_DROP+=" 5011_enable-cpu-optimizations-for-gcc8.patch" + UNIPATCH_DROP+=" 5012_enable-cpu-optimizations-for-gcc91.patch" + UNIPATCH_DROP+=" 5013_enable-cpu-optimizations-for-gcc10.patch" + fi + else + UNIPATCH_DROP+=" 5010_enable-additional-cpu-optimizations-for-gcc.patch" + UNIPATCH_DROP+=" 5010_enable-additional-cpu-optimizations-for-gcc-4.9.patch" + UNIPATCH_DROP+=" 5011_enable-cpu-optimizations-for-gcc8.patch" + UNIPATCH_DROP+=" 5012_enable-cpu-optimizations-for-gcc91.patch" + UNIPATCH_DROP+=" 5013_enable-cpu-optimizations-for-gcc10.patch" + fi + fi + done + + #populate KPATCH_DIRS so we know where to look to remove the excludes + x=${KPATCH_DIR} + KPATCH_DIR="" + for i in $(find ${x} -type d | sort -n); do + KPATCH_DIR="${KPATCH_DIR} ${i}" + done + + # do not apply fbcondecor patch to sparc/sparc64 as it breaks boot + # bug #272676 + if [[ "$(tc-arch)" = "sparc" || "$(tc-arch)" = "sparc64" ]]; then + if [[ ${KV_MAJOR} -ge 3 ]] || ver_test ${KV_MAJOR}.${KV_MINOR}.${KV_PATCH} -gt 2.6.28 ; then + if [[ ! -z ${K_WANT_GENPATCHES} ]] ; then + UNIPATCH_DROP="${UNIPATCH_DROP} *_fbcondecor*.patch" + echo + ewarn "fbcondecor currently prevents sparc/sparc64 from booting" + ewarn "for kernel versions >= 2.6.29. Removing fbcondecor patch." + ewarn "See https://bugs.gentoo.org/show_bug.cgi?id=272676 for details" + echo + fi + fi + fi + + #so now lets get rid of the patchno's we want to exclude + UNIPATCH_DROP="${UNIPATCH_EXCLUDE} ${UNIPATCH_DROP}" + for i in ${UNIPATCH_DROP}; do + ebegin "Excluding Patch #${i}" + for x in ${KPATCH_DIR}; do rm -f ${x}/${i}* 2>/dev/null; done + eend $? + done + + # and now, finally, we patch it :) + for x in ${KPATCH_DIR}; do + for i in $(find ${x} -maxdepth 1 -iname "*.patch*" -or -iname "*.diff*" | sort -n); do + STDERR_T="${T}/${i/*\//}" + STDERR_T="${STDERR_T/.patch*/.err}" + + [ -z ${i/*.patch*/} ] && PATCH_DEPTH=${i/*.patch/} + #[ -z ${i/*.diff*/} ] && PATCH_DEPTH=${i/*.diff/} + + if [ -z "${PATCH_DEPTH}" ]; then PATCH_DEPTH=0; fi + + #################################################################### + # IMPORTANT: This code is to support kernels which cannot be # + # tested with the --dry-run parameter # + # # + # These patches contain a removal of a symlink, followed by # + # addition of a file with the same name as the symlink in the # + # same location; this causes the dry-run to fail, see bug #507656. # + # # + # https://bugs.gentoo.org/show_bug.cgi?id=507656 # + #################################################################### + if [[ -n ${K_NODRYRUN} ]] ; then + ebegin "Applying ${i/*\//} (-p1)" + if [ $(patch -p1 --no-backup-if-mismatch -f < ${i} >> ${STDERR_T}) "$?" -le 2 ]; then + eend 0 + rm ${STDERR_T} || die + else + eend 1 + eerror "Failed to apply patch ${i/*\//}" + eerror "Please attach ${STDERR_T} to any bug you may post." + eshopts_pop + die "Failed to apply ${i/*\//} on patch depth 1." + fi + fi + #################################################################### + + while [ ${PATCH_DEPTH} -lt 5 ] && [ -z ${K_NODRYRUN} ]; do + echo "Attempting Dry-run:" >> ${STDERR_T} + echo "cmd: patch -p${PATCH_DEPTH} --no-backup-if-mismatch --dry-run -f < ${i}" >> ${STDERR_T} + echo "=======================================================" >> ${STDERR_T} + if [ $(patch -p${PATCH_DEPTH} --no-backup-if-mismatch --dry-run -f < ${i} >> ${STDERR_T}) $? -eq 0 ]; then + ebegin "Applying ${i/*\//} (-p${PATCH_DEPTH})" + echo "Attempting patch:" > ${STDERR_T} + echo "cmd: patch -p${PATCH_DEPTH} --no-backup-if-mismatch -f < ${i}" >> ${STDERR_T} + echo "=======================================================" >> ${STDERR_T} + if [ $(patch -p${PATCH_DEPTH} --no-backup-if-mismatch -f < ${i} >> ${STDERR_T}) "$?" -eq 0 ]; then + eend 0 + rm ${STDERR_T} || die + break + else + eend 1 + eerror "Failed to apply patch ${i/*\//}" + eerror "Please attach ${STDERR_T} to any bug you may post." + eshopts_pop + die "Failed to apply ${i/*\//} on patch depth ${PATCH_DEPTH}." + fi + else + PATCH_DEPTH=$((${PATCH_DEPTH} + 1)) + fi + done + if [ ${PATCH_DEPTH} -eq 5 ]; then + eerror "Failed to dry-run patch ${i/*\//}" + eerror "Please attach ${STDERR_T} to any bug you may post." + eshopts_pop + die "Unable to dry-run patch on any patch depth lower than 5." + fi + done + done + + # When genpatches is used, we want to install 0000_README which documents + # the patches that were used; such that the user can see them, bug #301478. + if [[ ! -z ${K_WANT_GENPATCHES} ]] ; then + UNIPATCH_DOCS="${UNIPATCH_DOCS} 0000_README" + fi + + # When files listed in UNIPATCH_DOCS are found in KPATCH_DIR's, we copy it + # to the temporary directory and remember them in UNIPATCH_DOCS to install + # them during the install phase. + local tmp + for x in ${KPATCH_DIR}; do + for i in ${UNIPATCH_DOCS}; do + if [[ -f ${x}/${i} ]] ; then + tmp="${tmp} ${i}" + cp -f "${x}/${i}" "${T}"/ || die + fi + done + done + UNIPATCH_DOCS="${tmp}" + + # clean up KPATCH_DIR's - fixes bug #53610 + for x in ${KPATCH_DIR}; do rm -Rf ${x}; done + + LC_ALL="${myLC_ALL}" + LANG="${myLANG}" + eshopts_pop +} + +# @FUNCTION: getfilevar +# @USAGE: <variable> <configfile> +# @DESCRIPTION: +# pulled from linux-info + +getfilevar() { + local workingdir basefname basedname xarch=$(tc-arch-kernel) + + if [[ -z ${1} ]] && [[ ! -f ${2} ]]; then + echo -e "\n" + eerror "getfilevar requires 2 variables, with the second a valid file." + eerror " getfilevar <VARIABLE> <CONFIGFILE>" + else + workingdir=${PWD} + basefname=$(basename ${2}) + basedname=$(dirname ${2}) + unset ARCH + + cd ${basedname} + echo -e "include ${basefname}\ne:\n\t@echo \$(${1})" | \ + make ${BUILD_FIXES} -s -f - e 2>/dev/null + cd ${workingdir} + + ARCH=${xarch} + fi +} + +# @FUNCTION: detect_arch +# @USAGE: +# @DESCRIPTION: +# This function sets ARCH_URI and ARCH_PATCH +# with the neccessary info for the arch sepecific compatibility +# patchsets. + +detect_arch() { + + local ALL_ARCH LOOP_ARCH LOOP_ARCH_L COMPAT_URI i TC_ARCH_KERNEL + + # COMPAT_URI is the contents of ${ARCH}_URI + # ARCH_URI is the URI for all the ${ARCH}_URI patches + # ARCH_PATCH is ARCH_URI broken into files for UNIPATCH + + ARCH_URI="" + ARCH_PATCH="" + TC_ARCH_KERNEL="" + ALL_ARCH="ALPHA AMD64 ARM HPPA IA64 M68K MIPS PPC PPC64 S390 SH SPARC X86" + + for LOOP_ARCH in ${ALL_ARCH}; do + COMPAT_URI="${LOOP_ARCH}_URI" + COMPAT_URI="${!COMPAT_URI}" + + declare -l LOOP_ARCH_L=${LOOP_ARCH} + + [[ -n ${COMPAT_URI} ]] && \ + ARCH_URI="${ARCH_URI} ${LOOP_ARCH_L}? ( ${COMPAT_URI} )" + + declare -u TC_ARCH_KERNEL=$(tc-arch-kernel) + if [[ ${LOOP_ARCH} == ${TC_ARCH_KERNEL} ]]; then + for i in ${COMPAT_URI}; do + ARCH_PATCH="${ARCH_PATCH} ${DISTDIR}/${i/*\//}" + done + fi + + done +} + +# @FUNCTION: headers___fix +# @USAGE: +# @DESCRIPTION: +# Voodoo to partially fix broken upstream headers. +# note: do not put inline/asm/volatile together (breaks "inline asm volatile") + +headers___fix() { + sed -i \ + -e '/^\#define.*_TYPES_H/{:loop n; bloop}' \ + -e 's:\<\([us]\(8\|16\|32\|64\)\)\>:__\1:g' \ + -e "s/\([[:space:]]\)inline\([[:space:](]\)/\1__inline__\2/g" \ + -e "s/\([[:space:]]\)asm\([[:space:](]\)/\1__asm__\2/g" \ + -e "s/\([[:space:]]\)volatile\([[:space:](]\)/\1__volatile__\2/g" \ + "$@" +} + +# @FUNCTION: kernel-2_src_unpack +# @USAGE: +# @DESCRIPTION: +# unpack sources, handle genpatches, deblob + +kernel-2_src_unpack() { + universal_unpack + debug-print "Doing unipatch" + + # request UNIPATCH_LIST_GENPATCHES in phase since it calls 'use' + handle_genpatches --set-unipatch-list + [[ -n ${UNIPATCH_LIST} || -n ${UNIPATCH_LIST_DEFAULT} || -n ${UNIPATCH_LIST_GENPATCHES} ]] && \ + unipatch "${UNIPATCH_LIST_DEFAULT} ${UNIPATCH_LIST_GENPATCHES} ${UNIPATCH_LIST}" + + debug-print "Doing premake" + + # allow ebuilds to massage the source tree after patching but before + # we run misc `make` functions below + [[ $(type -t kernel-2_hook_premake) == "function" ]] && kernel-2_hook_premake + + debug-print "Doing unpack_set_extraversion" + + [[ -z ${K_NOSETEXTRAVERSION} ]] && unpack_set_extraversion + unpack_fix_install_path + + # Setup xmakeopts and cd into sourcetree. + env_setup_xmakeopts + cd "${S}" + + # We dont need a version.h for anything other than headers + # at least, I should hope we dont. If this causes problems + # take out the if/fi block and inform me please. + # unpack_2_6 should now be 2.6.17 safe anyways + if [[ ${ETYPE} == headers ]]; then + kernel_is 2 4 && unpack_2_4 + kernel_is 2 6 && unpack_2_6 + fi + + if [[ $K_DEBLOB_AVAILABLE == 1 ]] && use deblob ; then + cp "${DISTDIR}/${DEBLOB_A}" "${T}" || die "cp ${DEBLOB_A} failed" + cp "${DISTDIR}/${DEBLOB_CHECK_A}" "${T}/deblob-check" || die "cp ${DEBLOB_CHECK_A} failed" + chmod +x "${T}/${DEBLOB_A}" "${T}/deblob-check" || die "chmod deblob scripts failed" + fi + + # fix a problem on ppc where TOUT writes to /usr/src/linux breaking sandbox + # only do this for kernel < 2.6.27 since this file does not exist in later + # kernels + if [[ -n ${KV_MINOR} ]] && ver_test ${KV_MAJOR}.${KV_MINOR}.${KV_PATCH} -lt 2.6.27 ; then + sed -i \ + -e 's|TOUT := .tmp_gas_check|TOUT := $(T).tmp_gas_check|' \ + "${S}"/arch/ppc/Makefile + else + sed -i \ + -e 's|TOUT := .tmp_gas_check|TOUT := $(T).tmp_gas_check|' \ + "${S}"/arch/powerpc/Makefile + fi +} + +# @FUNCTION: kernel-2_src_prepare +# @USAGE: +# @DESCRIPTION: +# Apply any user patches + +kernel-2_src_prepare() { + + debug-print "Applying any user patches" + + # apply any user patches + case ${EAPI:-0} in + 0|1|2|3|4|5) epatch_user ;; + 6) eapply_user ;; + esac +} + +# @FUNCTION: kernel-2_src_compile +# @USAGE: +# @DESCRIPTION: +# conpile headers or run deblob script + +kernel-2_src_compile() { + cd "${S}" + [[ ${ETYPE} == headers ]] && compile_headers + + if [[ $K_DEBLOB_AVAILABLE == 1 ]] && use deblob ; then + echo ">>> Running deblob script ..." + python_setup + sh "${T}/${DEBLOB_A}" --force || die "Deblob script failed to run!!!" + fi +} + +# @FUNCTION: kernel-2_src_test +# @USAGE: +# @DESCRIPTION: +# if you leave it to the default src_test, it will run make to +# find whether test/check targets are present; since "make test" +# actually produces a few support files, they are installed even +# though the package is binchecks-restricted. +# +# Avoid this altogether by making the function moot. +kernel-2_src_test() { :; } + +# @FUNCTION: kernel-2_pkg_preinst +# @DESCRIPTION: +# if ETYPE = headers, call preinst_headers + +kernel-2_pkg_preinst() { + [[ ${ETYPE} == headers ]] && preinst_headers +} + +# @FUNCTION: kernel-2_src_install +# @USAGE: +# @DESCRIPTION: +# Install headers or sources dependant on ETYPE + +kernel-2_src_install() { + install_universal + [[ ${ETYPE} == headers ]] && install_headers + [[ ${ETYPE} == sources ]] && install_sources +} + +# @FUNCTION: kernel-2_pkg_postinst +# @USAGE: +# @DESCRIPTION: +# call postinst_sources for ETYPE = sources + +kernel-2_pkg_postinst() { + [[ ${ETYPE} == sources ]] && postinst_sources +} + +# @FUNCTION: kernel-2_pkg_setup +# @USAGE: +# @DESCRIPTION: +# check for supported kernel version, die if ETYPE is unknown, call setup_headers +# if necessary + +kernel-2_pkg_setup() { + if kernel_is 2 4; then + if [[ $(gcc-major-version) -ge 4 ]] ; then + echo + ewarn "Be warned !! >=sys-devel/gcc-4.0.0 isn't supported with linux-2.4!" + ewarn "Either switch to another gcc-version (via gcc-config) or use a" + ewarn "newer kernel that supports gcc-4." + echo + ewarn "Also be aware that bugreports about gcc-4 not working" + ewarn "with linux-2.4 based ebuilds will be closed as INVALID!" + echo + fi + fi + + ABI="${KERNEL_ABI}" + if [[ ${ETYPE} != sources ]] && [[ ${ETYPE} != headers ]]; then + eerror "Unknown ETYPE=\"${ETYPE}\", must be \"sources\" or \"headers\"" + die "Unknown ETYPE=\"${ETYPE}\", must be \"sources\" or \"headers\"" + fi + + [[ ${ETYPE} == headers ]] && setup_headers + [[ ${ETYPE} == sources ]] && echo ">>> Preparing to unpack ..." +} + +# @FUNCTION: kernel-2_pkg_postrm +# @USAGE: +# @DESCRIPTION: +# Notify the user that after a depclean, there may be sources +# left behind that need to be manually cleaned + +kernel-2_pkg_postrm() { + # This warning only makes sense for kernel sources. + [[ ${ETYPE} == headers ]] && return 0 + + # If there isn't anything left behind, then don't complain. + [[ -e ${EROOT}usr/src/linux-${KV_FULL} ]] || return 0 + echo + ewarn "Note: Even though you have successfully unmerged " + ewarn "your kernel package, directories in kernel source location: " + ewarn "${EROOT}usr/src/linux-${KV_FULL}" + ewarn "with modified files will remain behind. By design, package managers" + ewarn "will not remove these modified files and the directories they reside in." + echo + ewarn "For more detailed kernel removal instructions, please see: " + ewarn "https://wiki.gentoo.org/wiki/Kernel/Removal" + echo +} diff --git a/eclass/kernel-build.eclass b/eclass/kernel-build.eclass new file mode 100644 index 0000000..249f038 --- /dev/null +++ b/eclass/kernel-build.eclass @@ -0,0 +1,235 @@ +# Copyright 2020-2021 Gentoo Authors +# Distributed under the terms of the GNU General Public License v2 + +# @ECLASS: kernel-build.eclass +# @MAINTAINER: +# Distribution Kernel Project <dist-kernel@gentoo.org> +# @AUTHOR: +# Michał Górny <mgorny@gentoo.org> +# @SUPPORTED_EAPIS: 7 +# @BLURB: Build mechanics for Distribution Kernels +# @DESCRIPTION: +# This eclass provides the logic to build a Distribution Kernel from +# source and install it. Post-install and test logic is inherited +# from kernel-install.eclass. +# +# The ebuild must take care of unpacking the kernel sources, copying +# an appropriate .config into them (e.g. in src_prepare()) and setting +# correct S. The eclass takes care of respecting savedconfig, building +# the kernel and installing it along with its modules and subset +# of sources needed to build external modules. + +if [[ ! ${_KERNEL_BUILD_ECLASS} ]]; then + +case "${EAPI:-0}" in + 0|1|2|3|4|5|6) + die "Unsupported EAPI=${EAPI:-0} (too old) for ${ECLASS}" + ;; + 7) + ;; + *) + die "Unsupported EAPI=${EAPI} (unknown) for ${ECLASS}" + ;; +esac + +inherit savedconfig toolchain-funcs kernel-install + +BDEPEND=" + sys-devel/bc + sys-devel/flex + virtual/libelf + virtual/yacc" + +# @FUNCTION: kernel-build_src_configure +# @DESCRIPTION: +# Prepare the toolchain for building the kernel, get the default .config +# or restore savedconfig, and get build tree configured for modprep. +kernel-build_src_configure() { + debug-print-function ${FUNCNAME} "${@}" + + # force ld.bfd if we can find it easily + local LD="$(tc-getLD)" + if type -P "${LD}.bfd" &>/dev/null; then + LD+=.bfd + fi + + tc-export_build_env + MAKEARGS=( + V=1 + + HOSTCC="$(tc-getBUILD_CC)" + HOSTCXX="$(tc-getBUILD_CXX)" + HOSTCFLAGS="${BUILD_CFLAGS}" + HOSTLDFLAGS="${BUILD_LDFLAGS}" + + CROSS_COMPILE=${CHOST}- + AS="$(tc-getAS)" + CC="$(tc-getCC)" + LD="${LD}" + AR="$(tc-getAR)" + NM="$(tc-getNM)" + STRIP=":" + OBJCOPY="$(tc-getOBJCOPY)" + OBJDUMP="$(tc-getOBJDUMP)" + + # we need to pass it to override colliding Gentoo envvar + ARCH=$(tc-arch-kernel) + ) + + restore_config .config + [[ -f .config ]] || die "Ebuild error: please copy default config into .config" + + if [[ -z "${KV_LOCALVERSION}" ]]; then + KV_LOCALVERSION=$(sed -n -e 's#^CONFIG_LOCALVERSION="\(.*\)"$#\1#p' \ + .config) + fi + + mkdir -p "${WORKDIR}"/modprep || die + mv .config "${WORKDIR}"/modprep/ || die + emake O="${WORKDIR}"/modprep "${MAKEARGS[@]}" olddefconfig + emake O="${WORKDIR}"/modprep "${MAKEARGS[@]}" modules_prepare + cp -pR "${WORKDIR}"/modprep "${WORKDIR}"/build || die +} + +# @FUNCTION: kernel-build_src_compile +# @DESCRIPTION: +# Compile the kernel sources. +kernel-build_src_compile() { + debug-print-function ${FUNCNAME} "${@}" + + emake O="${WORKDIR}"/build "${MAKEARGS[@]}" all +} + +# @FUNCTION: kernel-build_src_test +# @DESCRIPTION: +# Test the built kernel via qemu. This just wraps the logic +# from kernel-install.eclass with the correct paths. +kernel-build_src_test() { + debug-print-function ${FUNCNAME} "${@}" + local targets=( modules_install ) + # on arm or arm64 you also need dtb + if use arm || use arm64; then + targets+=( dtbs_install ) + fi + + emake O="${WORKDIR}"/build "${MAKEARGS[@]}" \ + INSTALL_MOD_PATH="${T}" INSTALL_PATH="${ED}/boot" "${targets[@]}" + + local ver="${PV}${KV_LOCALVERSION}" + kernel-install_test "${ver}" \ + "${WORKDIR}/build/$(dist-kernel_get_image_path)" \ + "${T}/lib/modules/${ver}" +} + +# @FUNCTION: kernel-build_src_install +# @DESCRIPTION: +# Install the built kernel along with subset of sources +# into /usr/src/linux-${PV}. Install the modules. Save the config. +kernel-build_src_install() { + debug-print-function ${FUNCNAME} "${@}" + + # do not use 'make install' as it behaves differently based + # on what kind of installkernel is installed + local targets=( modules_install ) + # on arm or arm64 you also need dtb + if use arm || use arm64; then + targets+=( dtbs_install ) + fi + + emake O="${WORKDIR}"/build "${MAKEARGS[@]}" \ + INSTALL_MOD_PATH="${ED}" INSTALL_PATH="${ED}/boot" "${targets[@]}" + + # note: we're using mv rather than doins to save space and time + # install main and arch-specific headers first, and scripts + local kern_arch=$(tc-arch-kernel) + local ver="${PV}${KV_LOCALVERSION}" + dodir "/usr/src/linux-${ver}/arch/${kern_arch}" + mv include scripts "${ED}/usr/src/linux-${ver}/" || die + mv "arch/${kern_arch}/include" \ + "${ED}/usr/src/linux-${ver}/arch/${kern_arch}/" || die + # some arches need module.lds linker script to build external modules + if [[ -f arch/${kern_arch}/kernel/module.lds ]]; then + insinto "/usr/src/linux-${ver}/arch/${kern_arch}/kernel" + doins "arch/${kern_arch}/kernel/module.lds" + fi + + # remove everything but Makefile* and Kconfig* + find -type f '!' '(' -name 'Makefile*' -o -name 'Kconfig*' ')' \ + -delete || die + find -type l -delete || die + cp -p -R * "${ED}/usr/src/linux-${ver}/" || die + + cd "${WORKDIR}" || die + # strip out-of-source build stuffs from modprep + # and then copy built files as well + find modprep -type f '(' \ + -name Makefile -o \ + -name '*.[ao]' -o \ + '(' -name '.*' -a -not -name '.config' ')' \ + ')' -delete || die + rm modprep/source || die + cp -p -R modprep/. "${ED}/usr/src/linux-${ver}"/ || die + + # install the kernel and files needed for module builds + insinto "/usr/src/linux-${ver}" + doins build/{System.map,Module.symvers} + local image_path=$(dist-kernel_get_image_path) + cp -p "build/${image_path}" "${ED}/usr/src/linux-${ver}/${image_path}" || die + + # building modules fails with 'vmlinux has no symtab?' if stripped + use ppc64 && dostrip -x "/usr/src/linux-${ver}/${image_path}" + + # strip empty directories + find "${D}" -type d -empty -exec rmdir {} + || die + + # fix source tree and build dir symlinks + dosym ../../../usr/src/linux-${ver} /lib/modules/${ver}/build + dosym ../../../usr/src/linux-${ver} /lib/modules/${ver}/source + + save_config build/.config +} + +# @FUNCTION: kernel-build_pkg_postinst +# @DESCRIPTION: +# Combine postinst from kernel-install and savedconfig eclasses. +kernel-build_pkg_postinst() { + kernel-install_pkg_postinst + savedconfig_pkg_postinst +} + +# @FUNCTION: kernel-build_merge_configs +# @USAGE: [distro.config...] +# @DESCRIPTION: +# Merge the config files specified as arguments (if any) into +# the '.config' file in the current directory, then merge +# any user-supplied configs from ${BROOT}/etc/kernel/config.d/*.config. +# The '.config' file must exist already and contain the base +# configuration. +kernel-build_merge_configs() { + debug-print-function ${FUNCNAME} "${@}" + + [[ -f .config ]] || die "${FUNCNAME}: .config does not exist" + has .config "${@}" && + die "${FUNCNAME}: do not specify .config as parameter" + + local shopt_save=$(shopt -p nullglob) + shopt -s nullglob + local user_configs=( "${BROOT}"/etc/kernel/config.d/*.config ) + shopt -u nullglob + + if [[ ${#user_configs[@]} -gt 0 ]]; then + elog "User config files are being applied:" + local x + for x in "${user_configs[@]}"; do + elog "- ${x}" + done + fi + + ./scripts/kconfig/merge_config.sh -m -r \ + .config "${@}" "${user_configs[@]}" || die +} + +_KERNEL_BUILD_ECLASS=1 +fi + +EXPORT_FUNCTIONS src_configure src_compile src_test src_install pkg_postinst diff --git a/eclass/kernel-install.eclass b/eclass/kernel-install.eclass new file mode 100644 index 0000000..b8109f4 --- /dev/null +++ b/eclass/kernel-install.eclass @@ -0,0 +1,433 @@ +# Copyright 2020-2021 Gentoo Authors +# Distributed under the terms of the GNU General Public License v2 + +# @ECLASS: kernel-install.eclass +# @MAINTAINER: +# Distribution Kernel Project <dist-kernel@gentoo.org> +# @AUTHOR: +# Michał Górny <mgorny@gentoo.org> +# @SUPPORTED_EAPIS: 7 +# @BLURB: Installation mechanics for Distribution Kernels +# @DESCRIPTION: +# This eclass provides the logic needed to test and install different +# kinds of Distribution Kernel packages, including both kernels built +# from source and distributed as binaries. The eclass relies on the +# ebuild installing a subset of built kernel tree into +# /usr/src/linux-${PV} containing the kernel image in its standard +# location and System.map. +# +# The eclass exports src_test, pkg_postinst and pkg_postrm. +# Additionally, the inherited mount-boot eclass exports pkg_pretend. +# It also stubs out pkg_preinst and pkg_prerm defined by mount-boot. + +# @ECLASS-VARIABLE: KV_LOCALVERSION +# @DEFAULT_UNSET +# @DESCRIPTION: +# A string containing the kernel LOCALVERSION, e.g. '-gentoo'. +# Needs to be set only when installing binary kernels, +# kernel-build.eclass obtains it from kernel config. + +if [[ ! ${_KERNEL_INSTALL_ECLASS} ]]; then + +case "${EAPI:-0}" in + 0|1|2|3|4|5|6) + die "Unsupported EAPI=${EAPI:-0} (too old) for ${ECLASS}" + ;; + 7) + ;; + *) + die "Unsupported EAPI=${EAPI} (unknown) for ${ECLASS}" + ;; +esac + +inherit dist-kernel-utils mount-boot toolchain-funcs + +SLOT="${PV}" +IUSE="+initramfs test" +RESTRICT+=" + !test? ( test ) + test? ( userpriv ) + arm? ( test ) +" + +# install-DEPEND actually +# note: we need installkernel with initramfs support! +RDEPEND=" + || ( + sys-kernel/installkernel-gentoo + sys-kernel/installkernel-systemd-boot + ) + initramfs? ( >=sys-kernel/dracut-049-r3 )" +BDEPEND=" + test? ( + dev-tcltk/expect + sys-apps/coreutils + sys-kernel/dracut + sys-fs/e2fsprogs + amd64? ( app-emulation/qemu[qemu_softmmu_targets_x86_64] ) + arm64? ( app-emulation/qemu[qemu_softmmu_targets_aarch64] ) + ppc64? ( app-emulation/qemu[qemu_softmmu_targets_ppc64] ) + x86? ( app-emulation/qemu[qemu_softmmu_targets_i386] ) + )" + +# @FUNCTION: kernel-install_update_symlink +# @USAGE: <target> <version> +# @DESCRIPTION: +# Update the kernel source symlink at <target> (full path) with a link +# to <target>-<version> if it's either missing or pointing out to +# an older version of this package. +kernel-install_update_symlink() { + debug-print-function ${FUNCNAME} "${@}" + + [[ ${#} -eq 2 ]] || die "${FUNCNAME}: invalid arguments" + local target=${1} + local version=${2} + + if [[ ! -e ${target} ]]; then + ebegin "Creating ${target} symlink" + ln -f -n -s "${target##*/}-${version}" "${target}" + eend ${?} + else + local symlink_target=$(readlink "${target}") + local symlink_ver=${symlink_target#${target##*/}-} + local updated= + if [[ ${symlink_target} == ${target##*/}-* && \ + -z ${symlink_ver//[0-9.]/} ]] + then + local symlink_pkg=${CATEGORY}/${PN}-${symlink_ver} + # if the current target is either being replaced, or still + # installed (probably depclean candidate), update the symlink + if has "${symlink_ver}" ${REPLACING_VERSIONS} || + has_version -r "~${symlink_pkg}" + then + ebegin "Updating ${target} symlink" + ln -f -n -s "${target##*/}-${version}" "${target}" + eend ${?} + updated=1 + fi + fi + + if [[ ! ${updated} ]]; then + elog "${target} points at another kernel, leaving it as-is." + elog "Please use 'eselect kernel' to update it when desired." + fi + fi +} + +# @FUNCTION: kernel-install_get_qemu_arch +# @DESCRIPTION: +# Get appropriate qemu suffix for the current ${ARCH}. +kernel-install_get_qemu_arch() { + debug-print-function ${FUNCNAME} "${@}" + + case ${ARCH} in + amd64) + echo x86_64 + ;; + x86) + echo i386 + ;; + arm) + echo arm + ;; + arm64) + echo aarch64 + ;; + ppc64) + echo ppc64 + ;; + *) + die "${FUNCNAME}: unsupported ARCH=${ARCH}" + ;; + esac +} + +# @FUNCTION: kernel-install_create_init +# @USAGE: <filename> +# @DESCRIPTION: +# Create minimal /sbin/init +kernel-install_create_init() { + debug-print-function ${FUNCNAME} "${@}" + + [[ ${#} -eq 1 ]] || die "${FUNCNAME}: invalid arguments" + [[ -z ${1} ]] && die "${FUNCNAME}: empty argument specified" + + local output="${1}" + [[ -f ${output} ]] && die "${FUNCNAME}: ${output} already exists" + + cat <<-_EOF_ >"${T}/init.c" || die + #include <stdio.h> + int main() { + printf("Hello, World!\n"); + return 0; + } + _EOF_ + + $(tc-getBUILD_CC) -Os -static "${T}/init.c" -o "${output}" || die + $(tc-getBUILD_STRIP) "${output}" || die +} + +# @FUNCTION: kernel-install_create_qemu_image +# @USAGE: <filename> +# @DESCRIPTION: +# Create minimal qemu raw image +kernel-install_create_qemu_image() { + debug-print-function ${FUNCNAME} "${@}" + + [[ ${#} -eq 1 ]] || die "${FUNCNAME}: invalid arguments" + [[ -z ${1} ]] && die "${FUNCNAME}: empty argument specified" + + local image="${1}" + [[ -f ${image} ]] && die "${FUNCNAME}: ${image} already exists" + + local imageroot="${T}/imageroot" + [[ -d ${imageroot} ]] && die "${FUNCNAME}: ${imageroot} already exists" + mkdir "${imageroot}" || die + + # some layout needed to pass dracut's usable_root() validation + mkdir -p "${imageroot}"/{bin,dev,etc,lib,proc,root,sbin,sys} || die + touch "${imageroot}/lib/ld-fake.so" || die + + kernel-install_create_init "${imageroot}/sbin/init" + + # image may be smaller if needed + truncate -s 4M "${image}" || die + mkfs.ext4 -v -d "${imageroot}" -L groot "${image}" || die +} + +# @FUNCTION: kernel-install_test +# @USAGE: <version> <image> <modules> +# @DESCRIPTION: +# Test that the kernel can successfully boot a minimal system image +# in qemu. <version> is the kernel version, <image> path to the image, +# <modules> path to module tree. +kernel-install_test() { + debug-print-function ${FUNCNAME} "${@}" + + [[ ${#} -eq 3 ]] || die "${FUNCNAME}: invalid arguments" + local version=${1} + local image=${2} + local modules=${3} + + local qemu_arch=$(kernel-install_get_qemu_arch) + + dracut \ + --conf /dev/null \ + --confdir /dev/null \ + --no-hostonly \ + --kmoddir "${modules}" \ + "${T}/initrd" "${version}" || die + + kernel-install_create_qemu_image "${T}/fs.img" + + cd "${T}" || die + + local qemu_extra_args= + local qemu_extra_append= + + case ${qemu_arch} in + aarch64) + qemu_extra_args="-M virt -cpu cortex-a57 -smp 1" + qemu_extra_append="console=ttyAMA0" + ;; + i386|x86_64) + qemu_extra_args="-cpu max" + qemu_extra_append="console=ttyS0,115200n8" + ;; + ppc64) + qemu_extra_args="-nodefaults" + ;; + *) + : + ;; + esac + + cat > run.sh <<-EOF || die + #!/bin/sh + exec qemu-system-${qemu_arch} \ + ${qemu_extra_args} \ + -m 512M \ + -nographic \ + -no-reboot \ + -kernel '${image}' \ + -initrd '${T}/initrd' \ + -serial mon:stdio \ + -drive file=fs.img,format=raw,index=0,media=disk \ + -append 'root=LABEL=groot ${qemu_extra_append}' + EOF + chmod +x run.sh || die + # TODO: initramfs does not let core finish starting on some systems, + # figure out how to make it better at that + expect - <<-EOF || die "Booting kernel failed" + set timeout 900 + spawn ./run.sh + expect { + "terminating on signal" { + send_error "\n* Qemu killed" + exit 1 + } + "OS terminated" { + send_error "\n* Qemu terminated OS" + exit 1 + } + "Kernel panic" { + send_error "\n* Kernel panic" + exit 1 + } + "Entering emergency mode" { + send_error "\n* Initramfs failed to start the system" + exit 1 + } + "Hello, World!" { + send_error "\n* Booted successfully" + exit 0 + } + timeout { + send_error "\n* Kernel boot timed out" + exit 2 + } + } + EOF +} + +# @FUNCTION: kernel-install_pkg_pretend +# @DESCRIPTION: +# Check for missing optional dependencies and output warnings. +kernel-install_pkg_pretend() { + debug-print-function ${FUNCNAME} "${@}" + + if ! has_version -d sys-kernel/linux-firmware; then + ewarn "sys-kernel/linux-firmware not found installed on your system." + ewarn "This package provides various firmware files that may be needed" + ewarn "for your hardware to work. If in doubt, it is recommended" + ewarn "to pause or abort the build process and install it before" + ewarn "resuming." + + if use initramfs; then + elog + elog "If you decide to install linux-firmware later, you can rebuild" + elog "the initramfs via issuing a command equivalent to:" + elog + elog " emerge --config ${CATEGORY}/${PN}:${SLOT}" + fi + fi +} + +# @FUNCTION: kernel-install_src_test +# @DESCRIPTION: +# Boilerplate function to remind people to call the tests. +kernel-install_src_test() { + debug-print-function ${FUNCNAME} "${@}" + + die "Please redefine src_test() and call kernel-install_test()." +} + +# @FUNCTION: kernel-install_pkg_preinst +# @DESCRIPTION: +# Stub out mount-boot.eclass. +kernel-install_pkg_preinst() { + debug-print-function ${FUNCNAME} "${@}" + + # (no-op) +} + +# @FUNCTION: kernel-install_install_all +# @USAGE: <ver> +# @DESCRIPTION: +# Build an initramfs for the kernel and install the kernel. This is +# called from pkg_postinst() and pkg_config(). <ver> is the full +# kernel version. +kernel-install_install_all() { + debug-print-function ${FUNCNAME} "${@}" + + [[ ${#} -eq 1 ]] || die "${FUNCNAME}: invalid arguments" + local ver=${1} + + local success= + # not an actual loop but allows error handling with 'break' + while :; do + nonfatal mount-boot_check_status || break + + local image_path=$(dist-kernel_get_image_path) + if use initramfs; then + # putting it alongside kernel image as 'initrd' makes + # kernel-install happier + nonfatal dist-kernel_build_initramfs \ + "${EROOT}/usr/src/linux-${ver}/${image_path%/*}/initrd" \ + "${ver}" || break + fi + + nonfatal dist-kernel_install_kernel "${ver}" \ + "${EROOT}/usr/src/linux-${ver}/${image_path}" \ + "${EROOT}/usr/src/linux-${ver}/System.map" || break + + success=1 + break + done + + if [[ ! ${success} ]]; then + eerror + eerror "The kernel files were copied to disk successfully but the kernel" + eerror "was not deployed successfully. Once you resolve the problems," + eerror "please run the equivalent of the following command to try again:" + eerror + eerror " emerge --config ${CATEGORY}/${PN}:${SLOT}" + die "Kernel install failed, please fix the problems and run emerge --config ${CATEGORY}/${PN}:${SLOT}" + fi +} + +# @FUNCTION: kernel-install_pkg_postinst +# @DESCRIPTION: +# Build an initramfs for the kernel, install it and update +# the /usr/src/linux symlink. +kernel-install_pkg_postinst() { + debug-print-function ${FUNCNAME} "${@}" + + local ver="${PV}${KV_LOCALVERSION}" + kernel-install_update_symlink "${EROOT}/usr/src/linux" "${ver}" + + if [[ -z ${ROOT} ]]; then + kernel-install_install_all "${ver}" + fi +} + +# @FUNCTION: kernel-install_pkg_prerm +# @DESCRIPTION: +# Stub out mount-boot.eclass. +kernel-install_pkg_prerm() { + debug-print-function ${FUNCNAME} "${@}" + + # (no-op) +} + +# @FUNCTION: kernel-install_pkg_postrm +# @DESCRIPTION: +# No-op at the moment. Will be used to remove obsolete kernels +# in the future. +kernel-install_pkg_postrm() { + debug-print-function ${FUNCNAME} "${@}" + + if [[ -z ${ROOT} ]] && use initramfs; then + local ver="${PV}${KV_LOCALVERSION}" + local image_path=$(dist-kernel_get_image_path) + ebegin "Removing initramfs" + rm -f "${EROOT}/usr/src/linux-${ver}/${image_path%/*}/initrd" && + find "${EROOT}/usr/src/linux-${ver}" -depth -type d -empty -delete + eend ${?} + fi +} + +# @FUNCTION: kernel-install_pkg_config +# @DESCRIPTION: +# Rebuild the initramfs and reinstall the kernel. +kernel-install_pkg_config() { + [[ -z ${ROOT} ]] || die "ROOT!=/ not supported currently" + + kernel-install_install_all "${PV}${KV_LOCALVERSION}" +} + +_KERNEL_INSTALL_ECLASS=1 +fi + +EXPORT_FUNCTIONS src_test pkg_preinst pkg_postinst pkg_prerm pkg_postrm +EXPORT_FUNCTIONS pkg_config pkg_pretend diff --git a/eclass/kodi-addon.eclass b/eclass/kodi-addon.eclass new file mode 100644 index 0000000..fc2a7a8 --- /dev/null +++ b/eclass/kodi-addon.eclass @@ -0,0 +1,37 @@ +# Copyright 1999-2020 Gentoo Authors +# Distributed under the terms of the GNU General Public License v2 + +# @ECLASS: kodi-addon.eclass +# @MAINTAINER: +# candrews@gentoo.org +# @SUPPORTED_EAPIS: 4 5 6 7 +# @BLURB: Helper for correct building and (importantly) installing Kodi addon packages. +# @DESCRIPTION: +# Provides a src_configure function for correct CMake configuration + +case "${EAPI:-0}" in + 4|5|6) + inherit cmake-utils multilib + ;; + 7) + inherit cmake + ;; + *) die "EAPI=${EAPI} is not supported" ;; +esac + +EXPORT_FUNCTIONS src_configure + +# @FUNCTION: kodi-addon_src_configure +# @DESCRIPTION: +# Configure handling for Kodi addons +kodi-addon_src_configure() { + + mycmakeargs+=( + -DCMAKE_INSTALL_LIBDIR=${EPREFIX%/}/usr/$(get_libdir)/kodi + ) + + case ${EAPI} in + 4|5|6) cmake-utils_src_configure ;; + 7) cmake_src_configure ;; + esac +} diff --git a/eclass/l10n.eclass b/eclass/l10n.eclass new file mode 100644 index 0000000..7bd8f38 --- /dev/null +++ b/eclass/l10n.eclass @@ -0,0 +1,174 @@ +# Copyright 1999-2020 Gentoo Authors +# Distributed under the terms of the GNU General Public License v2 + +# @ECLASS: l10n.eclass +# @MAINTAINER: +# Ulrich Müller <ulm@gentoo.org> +# @AUTHOR: +# Ben de Groot <yngwin@gentoo.org> +# @BLURB: convenience functions to handle localizations +# @DESCRIPTION: +# The l10n (localization) eclass offers a number of functions to more +# conveniently handle localizations (translations) offered by packages. +# These are meant to prevent code duplication for such boring tasks as +# determining the cross-section between the user's set LINGUAS and what +# is offered by the package. + +if [[ -z ${_L10N_ECLASS} ]]; then +_L10N_ECLASS=1 + +# @ECLASS-VARIABLE: PLOCALES +# @DEFAULT_UNSET +# @DESCRIPTION: +# Variable listing the locales for which localizations are offered by +# the package. +# +# Example: PLOCALES="cy de el_GR en_US pt_BR vi zh_CN" + +# @ECLASS-VARIABLE: PLOCALE_BACKUP +# @DEFAULT_UNSET +# @DESCRIPTION: +# In some cases the package fails when none of the offered PLOCALES are +# selected by the user. In that case this variable should be set to a +# default locale (usually 'en' or 'en_US') as backup. +# +# Example: PLOCALE_BACKUP="en_US" + +# @FUNCTION: l10n_for_each_locale_do +# @USAGE: <function> +# @DESCRIPTION: +# Convenience function for processing localizations. The parameter should +# be a function (defined in the consuming eclass or ebuild) which takes +# an individual localization as (last) parameter. +# +# Example: l10n_for_each_locale_do install_locale +l10n_for_each_locale_do() { + local locs x + locs=$(l10n_get_locales) + for x in ${locs}; do + "${@}" ${x} || die "failed to process enabled ${x} locale" + done +} + +# @FUNCTION: l10n_for_each_disabled_locale_do +# @USAGE: <function> +# @DESCRIPTION: +# Complementary to l10n_for_each_locale_do, this function will process +# locales that are disabled. This could be used for example to remove +# locales from a Makefile, to prevent them from being built needlessly. +l10n_for_each_disabled_locale_do() { + local locs x + locs=$(l10n_get_locales disabled) + for x in ${locs}; do + "${@}" ${x} || die "failed to process disabled ${x} locale" + done +} + +# @FUNCTION: l10n_find_plocales_changes +# @USAGE: <translations dir> <filename pre pattern> <filename post pattern> +# @DESCRIPTION: +# Ebuild maintenance helper function to find changes in package offered +# locales when doing a version bump. This could be added for example to +# src_prepare +# +# Example: l10n_find_plocales_changes "${S}/src/translations" "${PN}_" '.ts' +l10n_find_plocales_changes() { + [[ $# -ne 3 ]] && die "Exactly 3 arguments are needed!" + ebegin "Looking in ${1} for new locales" + pushd "${1}" >/dev/null || die "Cannot access ${1}" + local current= x= + for x in ${2}*${3} ; do + x=${x#"${2}"} + x=${x%"${3}"} + current+="${x} " + done + popd >/dev/null + # RHS will be sorted with single spaces so ensure the LHS is too + # before attempting to compare them for equality. See bug #513242. + # Run them both through the same sorting algorithm so we don't have + # to worry about them being the same. + if [[ "$(printf '%s\n' ${PLOCALES} | LC_ALL=C sort)" != "$(printf '%s\n' ${current} | LC_ALL=C sort)" ]] ; then + eend 1 "There are changes in locales! This ebuild should be updated to:" + eerror "PLOCALES=\"${current%[[:space:]]}\"" + return 1 + else + eend 0 + fi +} + +# @FUNCTION: l10n_get_locales +# @USAGE: [disabled] +# @DESCRIPTION: +# Determine which LINGUAS the user has enabled that are offered by the +# package, as listed in PLOCALES, and return them. In case no locales +# are selected, fall back on PLOCALE_BACKUP. When the disabled argument +# is given, return the disabled locales instead of the enabled ones. +l10n_get_locales() { + local loc locs + if [[ -z ${LINGUAS+set} ]]; then + # enable all if unset + locs=${PLOCALES} + else + for loc in ${LINGUAS}; do + has ${loc} ${PLOCALES} && locs+="${loc} " + done + fi + [[ -z ${locs} ]] && locs=${PLOCALE_BACKUP} + if [[ ${1} == disabled ]]; then + local disabled_locs + for loc in ${PLOCALES}; do + has ${loc} ${locs} || disabled_locs+="${loc} " + done + locs=${disabled_locs} + fi + printf "%s" "${locs}" +} + +# @FUNCTION: strip-linguas +# @USAGE: [<allow LINGUAS>|<-i|-u> <directories of .po files>] +# @DESCRIPTION: +# Make sure that LINGUAS only contains languages that a package can +# support. The first form allows you to specify a list of LINGUAS. +# The -i builds a list of po files found in all the directories and uses +# the intersection of the lists. The -u builds a list of po files found +# in all the directories and uses the union of the lists. +strip-linguas() { + local ls newls nols + if [[ $1 == "-i" ]] || [[ $1 == "-u" ]] ; then + local op=$1; shift + ls=$(find "$1" -name '*.po' -exec basename {} .po ';'); shift + local d f + for d in "$@" ; do + if [[ ${op} == "-u" ]] ; then + newls=${ls} + else + newls="" + fi + for f in $(find "$d" -name '*.po' -exec basename {} .po ';') ; do + if [[ ${op} == "-i" ]] ; then + has ${f} ${ls} && newls="${newls} ${f}" + else + has ${f} ${ls} || newls="${newls} ${f}" + fi + done + ls=${newls} + done + else + ls="$@" + fi + + nols="" + newls="" + for f in ${LINGUAS} ; do + if has ${f} ${ls} ; then + newls="${newls} ${f}" + else + nols="${nols} ${f}" + fi + done + [[ -n ${nols} ]] \ + && einfo "Sorry, but ${PN} does not support the LINGUAS:" ${nols} + export LINGUAS=${newls:1} +} + +fi diff --git a/eclass/latex-package.eclass b/eclass/latex-package.eclass new file mode 100644 index 0000000..3d2c097 --- /dev/null +++ b/eclass/latex-package.eclass @@ -0,0 +1,245 @@ +# Copyright 1999-2020 Gentoo Authors +# Distributed under the terms of the GNU General Public License v2 + +# @ECLASS: latex-package.eclass +# @MAINTAINER: +# TeX team <tex@gentoo.org> +# @AUTHOR: +# Matthew Turk <satai@gentoo.org> +# Martin Ehmsen <ehmsen@gentoo.org> +# @SUPPORTED_EAPIS: 7 +# @BLURB: An eclass for easy installation of LaTeX packages +# @DESCRIPTION: +# This eClass is designed to be easy to use and implement. The vast majority of +# LaTeX packages will only need to define SRC_URI (and sometimes S) for a +# successful installation. If fonts need to be installed, then the variable +# SUPPLIER must also be defined. +# +# However, those packages that contain subdirectories must process each +# subdirectory individually. For example, a package that contains directories +# DIR1 and DIR2 must call latex-package_src_compile() and +# latex-package_src_install() in each directory, as shown here: +# +# src_compile() { +# cd ${S} +# cd DIR1 +# latex-package_src_compile +# cd .. +# cd DIR2 +# latex-package_src_compile +# } +# +# src_install() { +# cd ${S} +# cd DIR1 +# latex-package_src_install +# cd .. +# cd DIR2 +# latex-package_src_install +# } +# +# The eClass automatically takes care of rehashing TeX's cache (ls-lR) after +# installation and after removal, as well as creating final documentation from +# TeX files that come with the source. Note that we break TeX layout standards +# by placing documentation in /usr/share/doc/${PN} +# +# For examples of basic installations, check out dev-tex/aastex and +# dev-tex/leaflet . +# +# NOTE: The CTAN "directory grab" function creates files with different MD5 +# signatures EVERY TIME. For this reason, if you are grabbing from the CTAN, +# you must either grab each file individually, or find a place to mirror an +# archive of them. (iBiblio) + +if [[ -z ${_LATEX_PACKAGE_ECLASS} ]]; then +_LATEX_PACKAGE_ECLASS=1 + +RDEPEND="virtual/latex-base" +DEPEND="${RDEPEND} + >=sys-apps/texinfo-4.2-r5" + +case ${EAPI:-0} in + [0-6]) + die "Unsupported EAPI=${EAPI:-0} (too old) for ${ECLASS}" ;; + 7) ;; + *) die "Unsupported EAPI=${EAPI} (unknown) for ${ECLASS}" ;; +esac + +HOMEPAGE="http://www.tug.org/" +TEXMF="/usr/share/texmf-site" + +# @ECLASS-VARIABLE: SUPPLIER +# @DESCRIPTION: +# This refers to the font supplier; it should be overridden (see eclass +# DESCRIPTION above) +SUPPLIER="misc" + +# @ECLASS-VARIABLE: LATEX_DOC_ARGUMENTS +# @DESCRIPTION: +# When compiling documentation (.tex/.dtx), this variable will be passed +# to pdflatex as additional argument (e.g. -shell-escape). This variable +# must be set after inherit, as it gets automatically cleared otherwise. +LATEX_DOC_ARGUMENTS="" + +# @FUNCTION: latex-package_src_doinstall +# @USAGE: [ module ] +# @DESCRIPTION: +# [module] can be one or more of: sh, sty, cls, fd, clo, def, cfg, dvi, ps, pdf, +# tex, dtx, tfm, vf, afm, pfb, ttf, bst, styles, doc, fonts, bin, or all. +# If [module] is not given, all is assumed. +# It installs the files found in the current directory to the standard locations +# for a TeX installation +latex-package_src_doinstall() { + debug-print function $FUNCNAME $* + + # Avoid generating font cache outside of the sandbox + export VARTEXFONTS="${T}/fonts" + + # This actually follows the directions for a "single-user" system + # at http://www.ctan.org/installationadvice/ modified for gentoo. + [[ -z ${1} ]] && latex-package_src_install all + + while [[ ${1} ]]; do + case ${1} in + "sh") + while IFS= read -r -d '' i; do + dobin ${i} + done < <(find -maxdepth 1 -type f -name "*.${1}" -print0) + ;; + + "sty" | "cls" | "fd" | "clo" | "def" | "cfg") + while IFS= read -r -d '' i; do + insinto ${TEXMF}/tex/latex/${PN} + doins ${i} + done < <(find -maxdepth 1 -type f -name "*.${1}" -print0) + ;; + + "dvi" | "ps" | "pdf") + while IFS= read -r -d '' i; do + insinto /usr/share/doc/${PF} + doins ${i} + dosym /usr/share/doc/${PF}/$(basename ${i}) ${TEXMF}/doc/latex/${PN}/${i} + docompress -x /usr/share/doc/${PF}/$(basename ${i}) + done < <(find -maxdepth 1 -type f -name "*.${1}" -print0) + ;; + + "tex" | "dtx") + if ! in_iuse doc || use doc ; then + while IFS= read -r -d '' i; do + [[ -n ${LATEX_PACKAGE_SKIP} ]] && + has ${i##*/} ${LATEX_PACKAGE_SKIP} && + continue + + einfo "Making documentation: ${i}" + # some macros need compiler called twice, do it here. + set -- pdflatex ${LATEX_DOC_ARGUMENTS} --halt-on-error --interaction=nonstopmode ${i} + if "${@}"; then + "${@}" + else + einfo "pdflatex failed, trying texi2dvi" + texi2dvi -q -c --language=latex ${i} || die + fi + done < <(find -maxdepth 1 -type f -name "*.${1}" -print0) + fi + ;; + + "tfm" | "vf" | "afm") + while IFS= read -r -d '' i; do + insinto ${TEXMF}/fonts/${1}/${SUPPLIER}/${PN} + doins ${i} + done < <(find -maxdepth 1 -type f -name "*.${1}" -print0) + ;; + + "pfb") + while IFS= read -r -d '' i; do + insinto ${TEXMF}/fonts/type1/${SUPPLIER}/${PN} + doins ${i} + done < <(find -maxdepth 1 -type f -name "*.pfb" -print0) + ;; + "ttf") + while IFS= read -r -d '' i; do + insinto ${TEXMF}/fonts/truetype/${SUPPLIER}/${PN} + doins ${i} + done < <(find -maxdepth 1 -type f -name "*.ttf" -print0) + ;; + "bst") + while IFS= read -r -d '' i; do + insinto ${TEXMF}/bibtex/bst/${PN} + doins ${i} + done < <(find -maxdepth 1 -type f -name "*.bst" -print0) + ;; + + "styles") + latex-package_src_doinstall sty cls fd clo def cfg bst + ;; + + "doc") + latex-package_src_doinstall tex dtx dvi ps pdf + ;; + + "fonts") + latex-package_src_doinstall tfm vf afm pfb ttf + ;; + + "bin") + latex-package_src_doinstall sh + ;; + + "all") + latex-package_src_doinstall styles fonts bin doc + ;; + esac + shift + done +} + +# @FUNCTION: latex-package_src_compile +# @DESCRIPTION: +# Calls latex for each *.ins in the current directory in order to generate the +# relevant files that will be installed +latex-package_src_compile() { + debug-print function $FUNCNAME $* + while IFS= read -r -d '' i; do + einfo "Extracting from ${i}" + latex --halt-on-error --interaction=nonstopmode ${i} || die + done < <(find -maxdepth 1 -type f -name "*.ins" -print0) +} + +# @FUNCTION: latex-package_src_install +# @DESCRIPTION: +# Installs the package +latex-package_src_install() { + debug-print function $FUNCNAME $* + latex-package_src_doinstall all + einstalldocs +} + +# @FUNCTION: latex-package_pkg_postinst +# @DESCRIPTION: +# Calls latex-package_rehash to ensure the TeX installation is consistent with +# the kpathsea database +latex-package_pkg_postinst() { + debug-print function $FUNCNAME $* + latex-package_rehash +} + +# @FUNCTION: latex-package_pkg_postrm +# @DESCRIPTION: +# Calls latex-package_rehash to ensure the TeX installation is consistent with +# the kpathsea database +latex-package_pkg_postrm() { + debug-print function $FUNCNAME $* + latex-package_rehash +} + +# @FUNCTION: latex-package_rehash +# @DESCRIPTION: +# Rehashes the kpathsea database, according to the current TeX installation +latex-package_rehash() { + debug-print function $FUNCNAME $* + texmf-update +} + +EXPORT_FUNCTIONS src_compile src_install pkg_postinst pkg_postrm + +fi diff --git a/eclass/libretro-core.eclass b/eclass/libretro-core.eclass new file mode 100644 index 0000000..f5f6306 --- /dev/null +++ b/eclass/libretro-core.eclass @@ -0,0 +1,210 @@ +# Copyright 2018-2020 Gentoo Authors +# Distributed under the terms of the GNU General Public License v2 + +# @ECLASS: libretro-core.eclass +# @MAINTAINER: +# candrews@gentoo.org +# @AUTHOR: +# Cecil Curry <leycec@gmail.com> +# Craig Andrews <candrews@gentoo.org> +# @SUPPORTED_EAPIS: 6 7 +# @BLURB: Simplify libretro core ebuilds +# @DESCRIPTION: +# The libretro eclass is designed to streamline the construction of +# ebuilds for Libretro core ebuilds. +# +# Libretro cores can be found under https://github.com/libretro/ +# +# They all use the same basic make based build system, are located +# in the same github account, and do not release named or numbered +# versions (so ebuild versions for git commits are keys). +# This eclass covers those commonalities reducing much duplication +# between the ebuilds. +# @EXAMPLE: +# @CODE +# EAPI=7 +# +# LIBRETRO_CORE_NAME="2048" +# LIBRETRO_COMMIT_SHA="45655d3662e4cbcd8afb28e2ee3f5494a75888de" +# KEYWORDS="~amd64 ~x86" +# inherit libretro-core +# +# DESCRIPTION="Port of 2048 puzzle game to the libretro API" +# LICENSE="Unlicense" +# SLOT="0" +# @CODE + +if [[ -z ${_LIBRETRO_CORE_ECLASS} ]]; then +_LIBRETRO_CORE_ECLASS=1 + +IUSE="debug" + +# @ECLASS-VARIABLE: LIBRETRO_CORE_NAME +# @REQUIRED +# @DESCRIPTION: +# Name of this Libretro core. The libretro-core_src_install() phase function +# will install the shared library "${S}/${LIBRETRO_CORE_NAME}_libretro.so" as a +# Libretro core. Defaults to the name of the current package with the +# "libretro-" prefix excluded and hyphens replaced with underscores +# (e.g. genesis_plus_gx for libretro-genesis-plus-gx) +if [[ -z "${LIBRETRO_CORE_NAME}" ]]; then + LIBRETRO_CORE_NAME=${PN#libretro-} + LIBRETRO_CORE_NAME=${LIBRETRO_CORE_NAME//-/_} +fi + +# @ECLASS-VARIABLE: LIBRETRO_COMMIT_SHA +# @DESCRIPTION: +# Commit SHA used for SRC_URI will die if not set in <9999 ebuilds. +# Needs to be set before inherit. + +# @ECLASS-VARIABLE: LIBRETRO_REPO_NAME +# @REQUIRED +# @DESCRIPTION: +# Contains the real repo name of the core formatted as "repouser/reponame". +# Needs to be set before inherit. Otherwise defaults to "libretro/${PN}" +: ${LIBRETRO_REPO_NAME:="libretro/libretro-${LIBRETRO_CORE_NAME}"} + +: ${HOMEPAGE:="https://github.com/${LIBRETRO_REPO_NAME}"} + +if [[ ${PV} == *9999 ]]; then + : ${EGIT_REPO_URI:="https://github.com/${LIBRETRO_REPO_NAME}.git"} + inherit git-r3 +else + [[ -z "${LIBRETRO_COMMIT_SHA}" ]] && die "LIBRETRO_COMMIT_SHA must be set before inherit." + S="${WORKDIR}/${LIBRETRO_REPO_NAME##*/}-${LIBRETRO_COMMIT_SHA}" + : ${SRC_URI:="https://github.com/${LIBRETRO_REPO_NAME}/archive/${LIBRETRO_COMMIT_SHA}.tar.gz -> ${P}.tar.gz"} +fi +inherit flag-o-matic toolchain-funcs + +case "${EAPI:-0}" in + 6|7) + EXPORT_FUNCTIONS src_unpack src_prepare src_compile src_install + ;; + *) + die "EAPI=${EAPI} is not supported" ;; +esac + +# @FUNCTION: libretro-core_src_unpack +# @DESCRIPTION: +# The libretro-core src_unpack function which is exported. +# +# This function retrieves the remote Libretro core info files. +libretro-core_src_unpack() { + # If this is a live ebuild, retrieve this core's remote repository. + if [[ ${PV} == *9999 ]]; then + git-r3_src_unpack + # Add used commit SHA for version information, the above could also work. + LIBRETRO_COMMIT_SHA=$(git -C "${WORKDIR}/${P}" rev-parse HEAD) + # Else, unpack this core's local tarball. + else + default_src_unpack + fi +} + +# @FUNCTION: libretro-core_src_prepare +# @DESCRIPTION: +# The libretro-core src_prepare function which is exported. +# +# This function prepares the source by making custom modifications. +libretro-core_src_prepare() { + default_src_prepare + # Populate COMMIT for GIT_VERSION + local custom_libretro_commit_sha="\" ${LIBRETRO_COMMIT_SHA:0:7}\"" + local makefile + local flags_modified=0 + local shopt_saved=$(shopt -p nullglob) + shopt -s nullglob + for makefile in "${S}"/[Mm]akefile* "${S}"/target-libretro/[Mm]akefile*; do + # * Convert CRLF to LF + # * Expand *FLAGS to prevent potential self-references + # * Where LDFLAGS directly define the link version + # script append LDFLAGS and LIBS + # * Where SHARED is used to provide shared linking + # flags ensure final link command includes LDFLAGS + # and LIBS + # * Always use $(CFLAGS) when calling $(CC) + # * Add short-rev to Makefile + sed \ + -e 's/\r$//g' \ + -e "/flags.*=/s|-O[[:digit:]]|${CFLAGS}|g" \ + -e "/CFLAGS.*=/s|-O[[:digit:]]|${CFLAGS}|g" \ + -e "/CXXFLAGS.*=/s|-O[[:digit:]]|${CXXFLAGS}|g" \ + -e "/.*,--version-script=.*/s|$| ${LDFLAGS} ${LIBS}|g" \ + -e "/\$(CC)/s|\(\$(SHARED)\)|\1 ${LDFLAGS} ${LIBS}|" \ + -e 's|\(\$(CC)\)|\1 \$(CFLAGS)|g' \ + -e "s/GIT_VERSION\s.=.*$/GIT_VERSION=${custom_libretro_commit_sha}/g" \ + -i "${makefile}" || die "Failed to use custom cflags in ${makefile}" + done + ${shopt_saved} + export OPTFLAGS="${CFLAGS}" +} + +# @VARIABLE: myemakeargs +# @DEFAULT_UNSET +# @DESCRIPTION: +# Optional emake arguments as a bash array. Should be defined before calling +# src_compile. +# @CODE +# src_compile() { +# local myemakeargs=( +# $(usex neon "HAVE_NEON=1" "") +# ) +# libretro-core_src_compile +# } +# @CODE + +# @FUNCTION: libretro-core_src_compile +# @DESCRIPTION: +# The libretro-core src_compile function which is exported. +# +# This function compiles the shared library for this Libretro core. +libretro-core_src_compile() { + # most (if not all) libretro makefiles use DEBUG=1 + # to enable additional debug features. + emake CC=$(tc-getCC) CXX=$(tc-getCXX) \ + $(usex debug "DEBUG=1" "") "${myemakeargs[@]}" \ + $([[ -f makefile.libretro ]] && echo '-f makefile.libretro') \ + $([[ -f Makefile.libretro ]] && echo '-f Makefile.libretro') +} + +# @VARIABLE: LIBRETRO_CORE_LIB_FILE +# @DEFAULT_UNSET +# @DESCRIPTION: +# Absolute path of this Libretro core's shared library. +# src_install. +# @CODE +# src_install() { +# local LIBRETRO_CORE_LIB_FILE="${S}/somecore_libretro.so" +# +# libretro-core_src_install +# } +# @CODE + +# @FUNCTION: libretro-core_src_install +# @DESCRIPTION: +# The libretro-core src_install function which is exported. +# +# This function installs the shared library for this Libretro core. +libretro-core_src_install() { + local LIBRETRO_CORE_LIB_FILE=${LIBRETRO_CORE_LIB_FILE:-"${S}/${LIBRETRO_CORE_NAME}_libretro.so"} + + # Absolute path of the directory containing Libretro shared libraries. + local libretro_lib_dir="/usr/$(get_libdir)/libretro" + # If this core's shared library exists, install that. + if [[ -f "${LIBRETRO_CORE_LIB_FILE}" ]]; then + exeinto "${libretro_lib_dir}" + doexe "${LIBRETRO_CORE_LIB_FILE}" + else + # Basename of this library. + local lib_basename="${LIBRETRO_CORE_LIB_FILE##*/}" + + # Absolute path to which this library was installed. + local lib_file_target="${ED}${libretro_lib_dir}/${lib_basename}" + + # If this library was *NOT* installed, fail. + [[ -f "${lib_file_target}" ]] || + die "Libretro core shared library \"${lib_file_target}\" not installed." + fi +} + +fi # end _LIBRETRO_CORE_ECLASS guard diff --git a/eclass/libtool.eclass b/eclass/libtool.eclass new file mode 100644 index 0000000..4565c8a --- /dev/null +++ b/eclass/libtool.eclass @@ -0,0 +1,49 @@ +# Copyright 1999-2018 Gentoo Foundation +# Distributed under the terms of the GNU General Public License v2 + +# @ECLASS: libtool.eclass +# @MAINTAINER: +# base-system@gentoo.org +# @SUPPORTED_EAPIS: 0 1 2 3 4 5 6 7 +# @BLURB: quickly update bundled libtool code +# @DESCRIPTION: +# This eclass patches ltmain.sh distributed with libtoolized packages with the +# relink and portage patch among others +# +# Note, this eclass does not require libtool as it only applies patches to +# generated libtool files. We do not run the libtoolize program because that +# requires a regeneration of the main autotool files in order to work properly. + +if [[ -z ${_LIBTOOL_ECLASS} ]]; then +_LIBTOOL_ECLASS=1 + +case ${EAPI:-0} in + 0|1|2|3|4|5|6) DEPEND=">=app-portage/elt-patches-20170815" ;; + 7) BDEPEND=">=app-portage/elt-patches-20170815" ;; + *) die "${ECLASS}: EAPI ${EAPI} not supported" ;; +esac + +inherit toolchain-funcs + +# @FUNCTION: elibtoolize +# @USAGE: [dirs] [--portage] [--reverse-deps] [--patch-only] [--remove-internal-dep=xxx] [--shallow] [--no-uclibc] +# @DESCRIPTION: +# Apply a smorgasbord of patches to bundled libtool files. This function +# should always be safe to run. If no directories are specified, then +# ${S} will be searched for appropriate files. +# +# If the --shallow option is used, then only ${S}/ltmain.sh will be patched. +# +# The other options should be avoided in general unless you know what's going on. +elibtoolize() { + type -P eltpatch &>/dev/null || die "eltpatch not found; is app-portage/elt-patches installed?" + + ELT_LOGDIR=${T} \ + LD=$(tc-getLD) \ + eltpatch "${@}" || die "eltpatch failed" +} + +uclibctoolize() { die "Use elibtoolize"; } +darwintoolize() { die "Use elibtoolize"; } + +fi diff --git a/eclass/linux-info.eclass b/eclass/linux-info.eclass new file mode 100644 index 0000000..11a8908 --- /dev/null +++ b/eclass/linux-info.eclass @@ -0,0 +1,963 @@ +# Copyright 1999-2020 Gentoo Authors +# Distributed under the terms of the GNU General Public License v2 + +# @ECLASS: linux-info.eclass +# @MAINTAINER: +# kernel@gentoo.org +# @AUTHOR: +# Original author: John Mylchreest <johnm@gentoo.org> +# @BLURB: eclass used for accessing kernel related information +# @DESCRIPTION: +# This eclass is used as a central eclass for accessing kernel +# related information for source or binary already installed. +# It is vital for linux-mod.eclass to function correctly, and is split +# out so that any ebuild behaviour "templates" are abstracted out +# using additional eclasses. +# +# "kernel config" in this file means: +# The .config of the currently installed sources is used as the first +# preference, with a fall-back to bundled config (/proc/config.gz) if available. +# +# Before using any of the config-handling functions in this eclass, you must +# ensure that one of the following functions has been called (in order of +# preference), otherwise you will get bugs like #364041): +# linux-info_pkg_setup +# linux-info_get_any_version +# get_version +# get_running_version + +# A Couple of env vars are available to effect usage of this eclass +# These are as follows: + +# @ECLASS-VARIABLE: KERNEL_DIR +# @DESCRIPTION: +# A string containing the directory of the target kernel sources. The default value is +# "/usr/src/linux" + +# @ECLASS-VARIABLE: CONFIG_CHECK +# @DESCRIPTION: +# A string containing a list of .config options to check for before +# proceeding with the install. +# +# e.g.: CONFIG_CHECK="MTRR" +# +# You can also check that an option doesn't exist by +# prepending it with an exclamation mark (!). +# +# e.g.: CONFIG_CHECK="!MTRR" +# +# To simply warn about a missing option, prepend a '~'. +# It may be combined with '!'. +# +# In general, most checks should be non-fatal. The only time fatal checks should +# be used is for building kernel modules or cases that a compile will fail +# without the option. +# +# This is to allow usage of binary kernels, and minimal systems without kernel +# sources. + +# @ECLASS-VARIABLE: ERROR_<CFG> +# @DESCRIPTION: +# A string containing the error message to display when the check against CONFIG_CHECK +# fails. <CFG> should reference the appropriate option used in CONFIG_CHECK. +# +# e.g.: ERROR_MTRR="MTRR exists in the .config but shouldn't!!" + +# @ECLASS-VARIABLE: KBUILD_OUTPUT +# @DESCRIPTION: +# A string passed on commandline, or set from the kernel makefile. It contains the directory +# which is to be used as the kernel object directory. + +# There are also a couple of variables which are set by this, and shouldn't be +# set by hand. These are as follows: + +# @ECLASS-VARIABLE: KV_FULL +# @DESCRIPTION: +# A read-only variable. It's a string containing the full kernel version. ie: 2.6.9-gentoo-johnm-r1 + +# @ECLASS-VARIABLE: KV_MAJOR +# @DESCRIPTION: +# A read-only variable. It's an integer containing the kernel major version. ie: 2 + +# @ECLASS-VARIABLE: KV_MINOR +# @DESCRIPTION: +# A read-only variable. It's an integer containing the kernel minor version. ie: 6 + +# @ECLASS-VARIABLE: KV_PATCH +# @DESCRIPTION: +# A read-only variable. It's an integer containing the kernel patch version. ie: 9 + +# @ECLASS-VARIABLE: KV_EXTRA +# @DESCRIPTION: +# A read-only variable. It's a string containing the kernel EXTRAVERSION. ie: -gentoo + +# @ECLASS-VARIABLE: KV_LOCAL +# @DESCRIPTION: +# A read-only variable. It's a string containing the kernel LOCALVERSION concatenation. ie: -johnm + +# @ECLASS-VARIABLE: KV_DIR +# @DESCRIPTION: +# A read-only variable. It's a string containing the kernel source directory, will be null if +# KERNEL_DIR is invalid. + +# @ECLASS-VARIABLE: KV_OUT_DIR +# @DESCRIPTION: +# A read-only variable. It's a string containing the kernel object directory, will be KV_DIR unless +# KBUILD_OUTPUT is used. This should be used for referencing .config. + +# And to ensure all the weirdness with crosscompile +inherit toolchain-funcs +[[ ${EAPI:-0} == [0123456] ]] && inherit eapi7-ver + +EXPORT_FUNCTIONS pkg_setup + +IUSE="kernel_linux" + +# Overwritable environment Var's +# --------------------------------------- +KERNEL_DIR="${KERNEL_DIR:-${ROOT%/}/usr/src/linux}" + + +# Bug fixes +# fix to bug #75034 +case ${ARCH} in + ppc) BUILD_FIXES="${BUILD_FIXES} TOUT=${T}/.tmp_gas_check";; + ppc64) BUILD_FIXES="${BUILD_FIXES} TOUT=${T}/.tmp_gas_check";; +esac + +# @FUNCTION: set_arch_to_kernel +# @DESCRIPTION: +# Set the env ARCH to match what the kernel expects. +set_arch_to_kernel() { export ARCH=$(tc-arch-kernel); } +# @FUNCTION: set_arch_to_portage +# @DESCRIPTION: +# Set the env ARCH to match what portage expects. +set_arch_to_portage() { export ARCH=$(tc-arch); } + +# qeinfo "Message" +# ------------------- +# qeinfo is a quiet einfo call when EBUILD_PHASE +# should not have visible output. +qout() { + local outputmsg type + type=${1} + shift + outputmsg="${@}" + case "${EBUILD_PHASE}" in + depend) unset outputmsg;; + clean) unset outputmsg;; + preinst) unset outputmsg;; + esac + [ -n "${outputmsg}" ] && ${type} "${outputmsg}" +} + +qeinfo() { qout einfo "${@}" ; } +qewarn() { qout ewarn "${@}" ; } +qeerror() { qout eerror "${@}" ; } + +# File Functions +# --------------------------------------- + +# @FUNCTION: getfilevar +# @USAGE: <variable> <configfile> +# @RETURN: the value of the variable +# @DESCRIPTION: +# It detects the value of the variable defined in the file configfile. This is +# done by including the configfile, and printing the variable with Make. +# It WILL break if your makefile has missing dependencies! +getfilevar() { + local ERROR basefname basedname myARCH="${ARCH}" + ERROR=0 + + [ -z "${1}" ] && ERROR=1 + [ ! -f "${2}" ] && ERROR=1 + + if [ "${ERROR}" = 1 ] + then + echo -e "\n" + eerror "getfilevar requires 2 variables, with the second a valid file." + eerror " getfilevar <VARIABLE> <CONFIGFILE>" + else + basefname="$(basename ${2})" + basedname="$(dirname ${2})" + unset ARCH + + # We use nonfatal because we want the caller to take care of things #373151 + [[ ${EAPI:-0} == [0123] ]] && nonfatal() { "$@"; } + echo -e "e:\\n\\t@echo \$(${1})\\ninclude ${basefname}" | \ + nonfatal emake -C "${basedname}" M="${T}" ${BUILD_FIXES} -s -f - 2>/dev/null + + ARCH=${myARCH} + fi +} + +# @FUNCTION: getfilevar_noexec +# @USAGE: <variable> <configfile> +# @RETURN: the value of the variable +# @DESCRIPTION: +# It detects the value of the variable defined in the file configfile. +# This is done with sed matching an expression only. If the variable is defined, +# you will run into problems. See getfilevar for those cases. +getfilevar_noexec() { + local ERROR basefname basedname mycat myARCH="${ARCH}" + ERROR=0 + mycat='cat' + + [ -z "${1}" ] && ERROR=1 + [ ! -f "${2}" ] && ERROR=1 + [ "${2%.gz}" != "${2}" ] && mycat='zcat' + + if [ "${ERROR}" = 1 ] + then + echo -e "\n" + eerror "getfilevar_noexec requires 2 variables, with the second a valid file." + eerror " getfilevar_noexec <VARIABLE> <CONFIGFILE>" + else + ${mycat} "${2}" | \ + sed -n \ + -e "/^[[:space:]]*${1}[[:space:]]*:\\?=[[:space:]]*\(.*\)\$/{ + s,^[^=]*[[:space:]]*=[[:space:]]*,,g ; + s,[[:space:]]*\$,,g ; + p + }" + fi +} + +# @ECLASS-VARIABLE: _LINUX_CONFIG_EXISTS_DONE +# @INTERNAL +# @DESCRIPTION: +# This is only set if one of the linux_config_*exists functions has been called. +# We use it for a QA warning that the check for a config has not been performed, +# as linux_chkconfig* in non-legacy mode WILL return an undefined value if no +# config is available at all. +_LINUX_CONFIG_EXISTS_DONE= + +linux_config_qa_check() { + local f="$1" + if [ -z "${_LINUX_CONFIG_EXISTS_DONE}" ]; then + ewarn "QA: You called $f before any linux_config_exists!" + ewarn "QA: The return value of $f will NOT guaranteed later!" + fi + + if ! use kernel_linux; then + die "$f called on non-Linux system, please fix the ebuild" + fi +} + +# @FUNCTION: linux_config_src_exists +# @RETURN: true or false +# @DESCRIPTION: +# It returns true if .config exists in a build directory otherwise false +linux_config_src_exists() { + export _LINUX_CONFIG_EXISTS_DONE=1 + use kernel_linux && [[ -n ${KV_OUT_DIR} && -s ${KV_OUT_DIR}/.config ]] +} + +# @FUNCTION: linux_config_bin_exists +# @RETURN: true or false +# @DESCRIPTION: +# It returns true if .config exists in /proc, otherwise false +linux_config_bin_exists() { + export _LINUX_CONFIG_EXISTS_DONE=1 + use kernel_linux && [[ -s /proc/config.gz ]] +} + +# @FUNCTION: linux_config_exists +# @RETURN: true or false +# @DESCRIPTION: +# It returns true if .config exists otherwise false +# +# This function MUST be checked before using any of the linux_chkconfig_* +# functions. +linux_config_exists() { + linux_config_src_exists || linux_config_bin_exists +} + +# @FUNCTION: linux_config_path +# @DESCRIPTION: +# Echo the name of the config file to use. If none are found, +# then return false. +linux_config_path() { + if linux_config_src_exists; then + echo "${KV_OUT_DIR}/.config" + elif linux_config_bin_exists; then + echo "/proc/config.gz" + else + return 1 + fi +} + +# @FUNCTION: require_configured_kernel +# @DESCRIPTION: +# This function verifies that the current kernel is configured (it checks against the existence of .config) +# otherwise it dies. +require_configured_kernel() { + if ! use kernel_linux; then + die "${FUNCNAME}() called on non-Linux system, please fix the ebuild" + fi + + if ! linux_config_src_exists; then + qeerror "Could not find a usable .config in the kernel source directory." + qeerror "Please ensure that ${KERNEL_DIR} points to a configured set of Linux sources." + qeerror "If you are using KBUILD_OUTPUT, please set the environment var so that" + qeerror "it points to the necessary object directory so that it might find .config." + die "Kernel not configured; no .config found in ${KV_OUT_DIR}" + fi + get_version || die "Unable to determine configured kernel version" +} + +# @FUNCTION: linux_chkconfig_present +# @USAGE: <option> +# @RETURN: true or false +# @DESCRIPTION: +# It checks that CONFIG_<option>=y or CONFIG_<option>=m is present in the current kernel .config +# If linux_config_exists returns false, the results of this are UNDEFINED. You +# MUST call linux_config_exists first. +linux_chkconfig_present() { + linux_config_qa_check linux_chkconfig_present + [[ $(getfilevar_noexec "CONFIG_$1" "$(linux_config_path)") == [my] ]] +} + +# @FUNCTION: linux_chkconfig_module +# @USAGE: <option> +# @RETURN: true or false +# @DESCRIPTION: +# It checks that CONFIG_<option>=m is present in the current kernel .config +# If linux_config_exists returns false, the results of this are UNDEFINED. You +# MUST call linux_config_exists first. +linux_chkconfig_module() { + linux_config_qa_check linux_chkconfig_module + [[ $(getfilevar_noexec "CONFIG_$1" "$(linux_config_path)") == m ]] +} + +# @FUNCTION: linux_chkconfig_builtin +# @USAGE: <option> +# @RETURN: true or false +# @DESCRIPTION: +# It checks that CONFIG_<option>=y is present in the current kernel .config +# If linux_config_exists returns false, the results of this are UNDEFINED. You +# MUST call linux_config_exists first. +linux_chkconfig_builtin() { + linux_config_qa_check linux_chkconfig_builtin + [[ $(getfilevar_noexec "CONFIG_$1" "$(linux_config_path)") == y ]] +} + +# @FUNCTION: linux_chkconfig_string +# @USAGE: <option> +# @RETURN: CONFIG_<option> +# @DESCRIPTION: +# It prints the CONFIG_<option> value of the current kernel .config (it requires a configured kernel). +# If linux_config_exists returns false, the results of this are UNDEFINED. You +# MUST call linux_config_exists first. +linux_chkconfig_string() { + linux_config_qa_check linux_chkconfig_string + getfilevar_noexec "CONFIG_$1" "$(linux_config_path)" +} + +# Versioning Functions +# --------------------------------------- + +# @FUNCTION: kernel_is +# @USAGE: [-lt -gt -le -ge -eq] <major_number> [minor_number patch_number] +# @RETURN: true or false +# @DESCRIPTION: +# It returns true when the current kernel version satisfies the comparison against the passed version. +# -eq is the default comparison. +# +# @CODE +# For Example where KV = 2.6.9 +# kernel_is 2 4 returns false +# kernel_is 2 returns true +# kernel_is 2 6 returns true +# kernel_is 2 6 8 returns false +# kernel_is 2 6 9 returns true +# @CODE + +# Note: duplicated in kernel-2.eclass +kernel_is() { + if ! use kernel_linux; then + die "${FUNCNAME}() called on non-Linux system, please fix the ebuild" + fi + + # if we haven't determined the version yet, we need to. + linux-info_get_any_version + + # Now we can continue + local operator test value + + case ${1#-} in + lt) operator="-lt"; shift;; + gt) operator="-gt"; shift;; + le) operator="-le"; shift;; + ge) operator="-ge"; shift;; + eq) operator="-eq"; shift;; + *) operator="-eq";; + esac + [[ $# -gt 3 ]] && die "Error in kernel-2_kernel_is(): too many parameters" + + : $(( test = (KV_MAJOR << 16) + (KV_MINOR << 8) + KV_PATCH )) + : $(( value = (${1:-${KV_MAJOR}} << 16) + (${2:-${KV_MINOR}} << 8) + ${3:-${KV_PATCH}} )) + [ ${test} ${operator} ${value} ] +} + +get_localversion() { + local lv_list i x + + local shopt_save=$(shopt -p nullglob) + shopt -s nullglob + local files=( ${1}/localversion* ) + ${shopt_save} + + # ignore files with ~ in it. + for i in "${files[@]}"; do + [[ -n ${i//*~*} ]] && lv_list="${lv_list} ${i}" + done + + for i in ${lv_list}; do + x="${x}$(<${i})" + done + x=${x/ /} + echo ${x} +} + +# Check if the Makefile is valid for direct parsing. +# Check status results: +# - PASS, use 'getfilevar' to extract values +# - FAIL, use 'getfilevar_noexec' to extract values +# The check may fail if: +# - make is not present +# - corruption exists in the kernel makefile +get_makefile_extract_function() { + local a='' b='' mkfunc='getfilevar' + a="$(getfilevar VERSION ${KERNEL_MAKEFILE})" + b="$(getfilevar_noexec VERSION ${KERNEL_MAKEFILE})" + [[ "${a}" != "${b}" ]] && mkfunc='getfilevar_noexec' + echo "${mkfunc}" +} + +# internal variable, so we know to only print the warning once +get_version_warning_done= + +# @FUNCTION: get_version +# @DESCRIPTION: +# It gets the version of the kernel inside KERNEL_DIR and populates the KV_FULL variable +# (if KV_FULL is already set it does nothing). +# +# The kernel version variables (KV_MAJOR, KV_MINOR, KV_PATCH, KV_EXTRA and KV_LOCAL) are also set. +# +# The KV_DIR is set using the KERNEL_DIR env var, the KV_DIR_OUT is set using a valid +# KBUILD_OUTPUT (in a decreasing priority list, we look for the env var, makefile var or the +# symlink /lib/modules/${KV_MAJOR}.${KV_MINOR}.${KV_PATCH}${KV_EXTRA}/build). +get_version() { + if ! use kernel_linux; then + die "${FUNCNAME}() called on non-Linux system, please fix the ebuild" + fi + + local tmplocal + + # no need to execute this twice assuming KV_FULL is populated. + # we can force by unsetting KV_FULL + [ -n "${KV_FULL}" ] && return 0 + + # if we dont know KV_FULL, then we need too. + # make sure KV_DIR isnt set since we need to work it out via KERNEL_DIR + unset KV_DIR + + # KV_DIR will contain the full path to the sources directory we should use + [ -z "${get_version_warning_done}" ] && \ + qeinfo "Determining the location of the kernel source code" + [ -d "${KERNEL_DIR}" ] && KV_DIR="${KERNEL_DIR}" + + if [ -z "${KV_DIR}" ] + then + if [ -z "${get_version_warning_done}" ]; then + get_version_warning_done=1 + qewarn "Unable to find kernel sources at ${KERNEL_DIR}" + #qeinfo "This package requires Linux sources." + if [ "${KERNEL_DIR}" == "/usr/src/linux" ] ; then + qeinfo "Please make sure that ${KERNEL_DIR} points at your running kernel, " + qeinfo "(or the kernel you wish to build against)." + qeinfo "Alternatively, set the KERNEL_DIR environment variable to the kernel sources location" + else + qeinfo "Please ensure that the KERNEL_DIR environment variable points at full Linux sources of the kernel you wish to compile against." + fi + fi + return 1 + fi + + # See if the kernel dir is actually an output dir. #454294 + if [ -z "${KBUILD_OUTPUT}" -a -L "${KERNEL_DIR}/source" ]; then + KBUILD_OUTPUT=${KERNEL_DIR} + KERNEL_DIR=$(readlink -f "${KERNEL_DIR}/source") + KV_DIR=${KERNEL_DIR} + fi + + if [ -z "${get_version_warning_done}" ]; then + qeinfo "Found kernel source directory:" + qeinfo " ${KV_DIR}" + fi + + if [ ! -s "${KV_DIR}/Makefile" ] + then + if [ -z "${get_version_warning_done}" ]; then + get_version_warning_done=1 + qeerror "Could not find a Makefile in the kernel source directory." + qeerror "Please ensure that ${KERNEL_DIR} points to a complete set of Linux sources" + fi + return 1 + fi + + # OK so now we know our sources directory, but they might be using + # KBUILD_OUTPUT, and we need this for .config and localversions-* + # so we better find it eh? + # do we pass KBUILD_OUTPUT on the CLI? + local OUTPUT_DIR=${KBUILD_OUTPUT} + + # keep track of it + KERNEL_MAKEFILE="${KV_DIR}/Makefile" + + if [[ -z ${OUTPUT_DIR} ]]; then + # Decide the function used to extract makefile variables. + local mkfunc=$(get_makefile_extract_function "${KERNEL_MAKEFILE}") + + # And if we didn't pass it, we can take a nosey in the Makefile. + OUTPUT_DIR=$(${mkfunc} KBUILD_OUTPUT "${KERNEL_MAKEFILE}") + fi + + # And contrary to existing functions I feel we shouldn't trust the + # directory name to find version information as this seems insane. + # So we parse ${KERNEL_MAKEFILE}. We should be able to trust that + # the Makefile is simple enough to use the noexec extract function. + # This has been true for every release thus far, and it's faster + # than using make to evaluate the Makefile every time. + KV_MAJOR=$(getfilevar_noexec VERSION "${KERNEL_MAKEFILE}") + KV_MINOR=$(getfilevar_noexec PATCHLEVEL "${KERNEL_MAKEFILE}") + KV_PATCH=$(getfilevar_noexec SUBLEVEL "${KERNEL_MAKEFILE}") + KV_EXTRA=$(getfilevar_noexec EXTRAVERSION "${KERNEL_MAKEFILE}") + + if [ -z "${KV_MAJOR}" -o -z "${KV_MINOR}" -o -z "${KV_PATCH}" ] + then + if [ -z "${get_version_warning_done}" ]; then + get_version_warning_done=1 + qeerror "Could not detect kernel version." + qeerror "Please ensure that ${KERNEL_DIR} points to a complete set of Linux sources." + fi + return 1 + fi + + [ -d "${OUTPUT_DIR}" ] && KV_OUT_DIR="${OUTPUT_DIR}" + if [ -n "${KV_OUT_DIR}" ]; + then + qeinfo "Found kernel object directory:" + qeinfo " ${KV_OUT_DIR}" + fi + # and if we STILL have not got it, then we better just set it to KV_DIR + KV_OUT_DIR="${KV_OUT_DIR:-${KV_DIR}}" + + # Grab the kernel release from the output directory. + # TODO: we MUST detect kernel.release being out of date, and 'return 1' from + # this function. + if [ -s "${KV_OUT_DIR}"/include/config/kernel.release ]; then + KV_LOCAL=$(<"${KV_OUT_DIR}"/include/config/kernel.release) + elif [ -s "${KV_OUT_DIR}"/.kernelrelease ]; then + KV_LOCAL=$(<"${KV_OUT_DIR}"/.kernelrelease) + else + KV_LOCAL= + fi + + # KV_LOCAL currently contains the full release; discard the first bits. + tmplocal=${KV_LOCAL#${KV_MAJOR}.${KV_MINOR}.${KV_PATCH}${KV_EXTRA}} + + # If the updated local version was not changed, the tree is not prepared. + # Clear out KV_LOCAL in that case. + # TODO: this does not detect a change in the localversion part between + # kernel.release and the value that would be generated. + if [ "$KV_LOCAL" = "$tmplocal" ]; then + KV_LOCAL= + else + KV_LOCAL=$tmplocal + fi + + # and in newer versions we can also pull LOCALVERSION if it is set. + # but before we do this, we need to find if we use a different object directory. + # This *WILL* break if the user is using localversions, but we assume it was + # caught before this if they are. + if [[ -z ${OUTPUT_DIR} ]] ; then + # Try to locate a kernel that is most relevant for us. + for OUTPUT_DIR in "${SYSROOT}" "${ROOT%/}" "" ; do + OUTPUT_DIR+="/lib/modules/${KV_MAJOR}.${KV_MINOR}.${KV_PATCH}${KV_EXTRA}${KV_LOCAL}/build" + if [[ -e ${OUTPUT_DIR} ]] ; then + break + fi + done + fi + + # And we should set KV_FULL to the full expanded version + KV_FULL="${KV_MAJOR}.${KV_MINOR}.${KV_PATCH}${KV_EXTRA}${KV_LOCAL}" + + qeinfo "Found sources for kernel version:" + qeinfo " ${KV_FULL}" + + return 0 +} + +# @FUNCTION: get_running_version +# @DESCRIPTION: +# It gets the version of the current running kernel and the result is the same as get_version() if the +# function can find the sources. +get_running_version() { + if ! use kernel_linux; then + die "${FUNCNAME}() called on non-Linux system, please fix the ebuild" + fi + + KV_FULL=$(uname -r) + + if [[ -f ${ROOT%/}/lib/modules/${KV_FULL}/source/Makefile && -f ${ROOT%/}/lib/modules/${KV_FULL}/build/Makefile ]]; then + KERNEL_DIR=$(readlink -f ${ROOT%/}/lib/modules/${KV_FULL}/source) + KBUILD_OUTPUT=$(readlink -f ${ROOT%/}/lib/modules/${KV_FULL}/build) + unset KV_FULL + get_version + return $? + elif [[ -f ${ROOT%/}/lib/modules/${KV_FULL}/source/Makefile ]]; then + KERNEL_DIR=$(readlink -f ${ROOT%/}/lib/modules/${KV_FULL}/source) + unset KV_FULL + get_version + return $? + elif [[ -f ${ROOT%/}/lib/modules/${KV_FULL}/build/Makefile ]]; then + KERNEL_DIR=$(readlink -f ${ROOT%/}/lib/modules/${KV_FULL}/build) + unset KV_FULL + get_version + return $? + else + # This handles a variety of weird kernel versions. Make sure to update + # tests/linux-info_get_running_version.sh if you want to change this. + local kv_full=${KV_FULL//[-+_]*} + KV_MAJOR=$(ver_cut 1 ${kv_full}) + KV_MINOR=$(ver_cut 2 ${kv_full}) + KV_PATCH=$(ver_cut 3 ${kv_full}) + KV_EXTRA="${KV_FULL#${KV_MAJOR}.${KV_MINOR}${KV_PATCH:+.${KV_PATCH}}}" + : ${KV_PATCH:=0} + fi + return 0 +} + +# This next function is named with the eclass prefix to avoid conflicts with +# some old versionator-like eclass functions. + +# @FUNCTION: linux-info_get_any_version +# @DESCRIPTION: +# This attempts to find the version of the sources, and otherwise falls back to +# the version of the running kernel. +linux-info_get_any_version() { + if ! use kernel_linux; then + die "${FUNCNAME}() called on non-Linux system, please fix the ebuild" + fi + + if ! get_version; then + ewarn "Unable to calculate Linux Kernel version for build, attempting to use running version" + if ! get_running_version; then + die "Unable to determine any Linux Kernel version, please report a bug" + fi + fi +} + + +# ebuild check functions +# --------------------------------------- + +# @FUNCTION: check_kernel_built +# @DESCRIPTION: +# This function verifies that the current kernel sources have been already prepared otherwise it dies. +check_kernel_built() { + if ! use kernel_linux; then + die "${FUNCNAME}() called on non-Linux system, please fix the ebuild" + fi + + # if we haven't determined the version yet, we need to + require_configured_kernel + + local versionh_path + if kernel_is -ge 3 7; then + versionh_path="include/generated/uapi/linux/version.h" + else + versionh_path="include/linux/version.h" + fi + + if [ ! -f "${KV_OUT_DIR}/${versionh_path}" ] + then + eerror "These sources have not yet been prepared." + eerror "We cannot build against an unprepared tree." + eerror "To resolve this, please type the following:" + eerror + eerror "# cd ${KV_DIR}" + eerror "# make oldconfig" + eerror "# make modules_prepare" + eerror + eerror "Then please try merging this module again." + die "Kernel sources need compiling first" + fi +} + +# @FUNCTION: check_modules_supported +# @DESCRIPTION: +# This function verifies that the current kernel support modules (it checks CONFIG_MODULES=y) otherwise it dies. +check_modules_supported() { + if ! use kernel_linux; then + die "${FUNCNAME}() called on non-Linux system, please fix the ebuild" + fi + + # if we haven't determined the version yet, we need too. + require_configured_kernel + + if ! linux_chkconfig_builtin "MODULES"; then + eerror "These sources do not support loading external modules." + eerror "to be able to use this module please enable \"Loadable modules support\"" + eerror "in your kernel, recompile and then try merging this module again." + die "No support for external modules in ${KV_FULL} config" + fi +} + +# @FUNCTION: check_extra_config +# @DESCRIPTION: +# It checks the kernel config options specified by CONFIG_CHECK. It dies only when a required config option (i.e. +# the prefix ~ is not used) doesn't satisfy the directive. Ignored on non-Linux systems. +check_extra_config() { + use kernel_linux || return + + local config negate die error reworkmodulenames + local soft_errors_count=0 hard_errors_count=0 config_required=0 + # store the value of the QA check, because otherwise we won't catch usages + # after if check_extra_config is called AND other direct calls are done + # later. + local old_LINUX_CONFIG_EXISTS_DONE="${_LINUX_CONFIG_EXISTS_DONE}" + + # if we haven't determined the version yet, we need to + linux-info_get_any_version + + # Determine if we really need a .config. The only time when we don't need + # one is when all of the CONFIG_CHECK options are prefixed with "~". + for config in ${CONFIG_CHECK}; do + if [[ "${config:0:1}" != "~" ]]; then + config_required=1 + break + fi + done + + if [[ ${config_required} == 0 ]]; then + # In the case where we don't require a .config, we can now bail out + # if the user has no .config as there is nothing to do. Otherwise + # code later will cause a failure due to missing .config. + if ! linux_config_exists; then + ewarn "Unable to check for the following kernel config options due" + ewarn "to absence of any configured kernel sources or compiled" + ewarn "config:" + for config in ${CONFIG_CHECK}; do + config=${config#\~} + config=${config#\!} + local_error="ERROR_${config}" + msg="${!local_error}" + if [[ -z ${msg} ]]; then + local_error="WARNING_${config}" + msg="${!local_error}" + fi + ewarn " - ${config}${msg:+ - }${msg}" + done + ewarn "You're on your own to make sure they are set if needed." + export LINUX_CONFIG_EXISTS_DONE="${old_LINUX_CONFIG_EXISTS_DONE}" + return 0 + fi + else + require_configured_kernel + fi + + einfo "Checking for suitable kernel configuration options..." + + for config in ${CONFIG_CHECK} + do + # if we specify any fatal, ensure we honor them + die=1 + error=0 + negate=0 + reworkmodulenames=0 + + if [[ ${config:0:1} == "~" ]]; then + die=0 + config=${config:1} + elif [[ ${config:0:1} == "@" ]]; then + die=0 + reworkmodulenames=1 + config=${config:1} + fi + if [[ ${config:0:1} == "!" ]]; then + negate=1 + config=${config:1} + fi + + if [[ ${negate} == 1 ]]; then + linux_chkconfig_present ${config} && error=2 + elif [[ ${reworkmodulenames} == 1 ]]; then + local temp_config="${config//*:}" i n + config="${config//:*}" + if linux_chkconfig_present ${config}; then + for i in ${MODULE_NAMES}; do + n="${i//${temp_config}}" + [[ -z ${n//\(*} ]] && \ + MODULE_IGNORE="${MODULE_IGNORE} ${temp_config}" + done + error=2 + fi + else + linux_chkconfig_present ${config} || error=1 + fi + + if [[ ${error} -gt 0 ]]; then + local report_func="eerror" local_error + local_error="ERROR_${config}" + local_error="${!local_error}" + + if [[ -z "${local_error}" ]]; then + # using old, deprecated format. + local_error="${config}_ERROR" + local_error="${!local_error}" + fi + if [[ ${die} == 0 && -z "${local_error}" ]]; then + #soft errors can be warnings + local_error="WARNING_${config}" + local_error="${!local_error}" + if [[ -n "${local_error}" ]] ; then + report_func="ewarn" + fi + fi + + if [[ -z "${local_error}" ]]; then + [[ ${error} == 1 ]] \ + && local_error="is not set when it should be." \ + || local_error="should not be set. But it is." + local_error="CONFIG_${config}:\t ${local_error}" + fi + if [[ ${die} == 0 ]]; then + ${report_func} " ${local_error}" + soft_errors_count=$[soft_errors_count + 1] + else + ${report_func} " ${local_error}" + hard_errors_count=$[hard_errors_count + 1] + fi + fi + done + + if [[ ${hard_errors_count} -gt 0 ]]; then + eerror "Please check to make sure these options are set correctly." + eerror "Failure to do so may cause unexpected problems." + eerror "Once you have satisfied these options, please try merging" + eerror "this package again." + export LINUX_CONFIG_EXISTS_DONE="${old_LINUX_CONFIG_EXISTS_DONE}" + die "Incorrect kernel configuration options" + elif [[ ${soft_errors_count} -gt 0 ]]; then + ewarn "Please check to make sure these options are set correctly." + ewarn "Failure to do so may cause unexpected problems." + else + eend 0 + fi + export LINUX_CONFIG_EXISTS_DONE="${old_LINUX_CONFIG_EXISTS_DONE}" +} + +check_zlibinflate() { + if ! use kernel_linux; then + die "${FUNCNAME}() called on non-Linux system, please fix the ebuild" + fi + + # if we haven't determined the version yet, we need to + require_configured_kernel + + # although I restructured this code - I really really really dont support it! + + # bug #27882 - zlib routines are only linked into the kernel + # if something compiled into the kernel calls them + # + # plus, for the cloop module, it appears that there's no way + # to get cloop.o to include a static zlib if CONFIG_MODVERSIONS + # is on + + local INFLATE + local DEFLATE + + einfo "Determining the usability of ZLIB_INFLATE support in your kernel" + + ebegin "checking ZLIB_INFLATE" + linux_chkconfig_builtin CONFIG_ZLIB_INFLATE + eend $? || die + + ebegin "checking ZLIB_DEFLATE" + linux_chkconfig_builtin CONFIG_ZLIB_DEFLATE + eend $? || die + + local LINENO_START + local LINENO_END + local SYMBOLS + local x + + LINENO_END="$(grep -n 'CONFIG_ZLIB_INFLATE y' ${KV_DIR}/lib/Config.in | cut -d : -f 1)" + LINENO_START="$(head -n $LINENO_END ${KV_DIR}/lib/Config.in | grep -n 'if \[' | tail -n 1 | cut -d : -f 1)" + (( LINENO_AMOUNT = $LINENO_END - $LINENO_START )) + (( LINENO_END = $LINENO_END - 1 )) + SYMBOLS="$(head -n $LINENO_END ${KV_DIR}/lib/Config.in | tail -n $LINENO_AMOUNT | sed -e 's/^.*\(CONFIG_[^\" ]*\).*/\1/g;')" + + # okay, now we have a list of symbols + # we need to check each one in turn, to see whether it is set or not + for x in $SYMBOLS ; do + if [ "${!x}" = "y" ]; then + # we have a winner! + einfo "${x} ensures zlib is linked into your kernel - excellent" + return 0 + fi + done + + eerror + eerror "This kernel module requires ZLIB library support." + eerror "You have enabled zlib support in your kernel, but haven't enabled" + eerror "enabled any option that will ensure that zlib is linked into your" + eerror "kernel." + eerror + eerror "Please ensure that you enable at least one of these options:" + eerror + + for x in $SYMBOLS ; do + eerror " * $x" + done + + eerror + eerror "Please remember to recompile and install your kernel, and reboot" + eerror "into your new kernel before attempting to load this kernel module." + + die "Kernel doesn't include zlib support" +} + +################################ +# Default pkg_setup +# Also used when inheriting linux-mod to force a get_version call +# @FUNCTION: linux-info_pkg_setup +# @DESCRIPTION: +# Force a get_version() call when inherited from linux-mod.eclass and then check if the kernel is configured +# to support the options specified in CONFIG_CHECK (if not null) +linux-info_pkg_setup() { + use kernel_linux || return + + linux-info_get_any_version + + if kernel_is 2 4; then + if [ "$( gcc-major-version )" -eq "4" ] ; then + echo + ewarn "Be warned !! >=sys-devel/gcc-4.0.0 isn't supported with" + ewarn "linux-2.4 (or modules building against a linux-2.4 kernel)!" + echo + ewarn "Either switch to another gcc-version (via gcc-config) or use a" + ewarn "newer kernel that supports gcc-4." + echo + ewarn "Also be aware that bugreports about gcc-4 not working" + ewarn "with linux-2.4 based ebuilds will be closed as INVALID!" + echo + fi + fi + + [ -n "${CONFIG_CHECK}" ] && check_extra_config; +} diff --git a/eclass/linux-mod.eclass b/eclass/linux-mod.eclass new file mode 100644 index 0000000..e0444ea --- /dev/null +++ b/eclass/linux-mod.eclass @@ -0,0 +1,769 @@ +# Copyright 1999-2021 Gentoo Authors +# Distributed under the terms of the GNU General Public License v2 + +# @ECLASS: linux-mod.eclass +# @MAINTAINER: +# kernel@gentoo.org +# @AUTHOR: +# John Mylchreest <johnm@gentoo.org>, +# Stefan Schweizer <genstef@gentoo.org> +# @BLURB: It provides the functionality required to install external modules against a kernel source tree. +# @DESCRIPTION: +# This eclass is used to interface with linux-info.eclass in such a way +# to provide the functionality and initial functions +# required to install external modules against a kernel source +# tree. + +# A Couple of env vars are available to effect usage of this eclass +# These are as follows: + +# @ECLASS-VARIABLE: MODULES_OPTIONAL_USE +# @DESCRIPTION: +# A string containing the USE flag to use for making this eclass optional +# The recommended non-empty value is 'modules' + +# @ECLASS-VARIABLE: MODULES_OPTIONAL_USE_IUSE_DEFAULT +# @DESCRIPTION: +# A boolean to control the IUSE default state for the MODULES_OPTIONAL_USE USE +# flag. Default value is unset (false). True represented by 1 or 'on', other +# values including unset treated as false. + +# @ECLASS-VARIABLE: KERNEL_DIR +# @DESCRIPTION: +# A string containing the directory of the target kernel sources. The default value is +# "/usr/src/linux" + +# @ECLASS-VARIABLE: ECONF_PARAMS +# @DESCRIPTION: +# It's a string containing the parameters to pass to econf. +# If this is not set, then econf isn't run. + +# @ECLASS-VARIABLE: BUILD_PARAMS +# @DESCRIPTION: +# It's a string with the parameters to pass to emake. + +# @ECLASS-VARIABLE: BUILD_TARGETS +# @DESCRIPTION: +# It's a string with the build targets to pass to make. The default value is "clean module" + +# @ECLASS-VARIABLE: MODULE_NAMES +# @DESCRIPTION: +# It's a string containing the modules to be built automatically using the default +# src_compile/src_install. It will only make ${BUILD_TARGETS} once in any directory. +# +# The structure of each MODULE_NAMES entry is as follows: +# +# modulename(libdir:srcdir:objdir) +# +# where: +# +# modulename = name of the module file excluding the .ko +# libdir = place in system modules directory where module is installed (by default it's misc) +# srcdir = place for ebuild to cd to before running make (by default it's ${S}) +# objdir = place the .ko and objects are located after make runs (by default it's set to srcdir) +# +# To get an idea of how these variables are used, here's a few lines +# of code from around line 540 in this eclass: +# +# einfo "Installing ${modulename} module" +# cd ${objdir} || die "${objdir} does not exist" +# insinto /lib/modules/${KV_FULL}/${libdir} +# doins ${modulename}.${KV_OBJ} || die "doins ${modulename}.${KV_OBJ} failed" +# +# For example: +# MODULE_NAMES="module_pci(pci:${S}/pci:${S}) module_usb(usb:${S}/usb:${S})" +# +# what this would do is +# +# cd "${S}"/pci +# make ${BUILD_PARAMS} ${BUILD_TARGETS} +# cd "${S}" +# insinto /lib/modules/${KV_FULL}/pci +# doins module_pci.${KV_OBJ} +# +# cd "${S}"/usb +# make ${BUILD_PARAMS} ${BUILD_TARGETS} +# cd "${S}" +# insinto /lib/modules/${KV_FULL}/usb +# doins module_usb.${KV_OBJ} + +# There is also support for automated modprobe.d file generation. +# This can be explicitly enabled by setting any of the following variables. + +# @ECLASS-VARIABLE: MODULESD_<modulename>_ENABLED +# @DESCRIPTION: +# This is used to disable the modprobe.d file generation otherwise the file will be +# always generated (unless no MODULESD_<modulename>_* variable is provided). Set to "no" to disable +# the generation of the file and the installation of the documentation. + +# @ECLASS-VARIABLE: MODULESD_<modulename>_EXAMPLES +# @DESCRIPTION: +# This is a bash array containing a list of examples which should +# be used. If you want us to try and take a guess set this to "guess". +# +# For each array_component it's added an options line in the modprobe.d file +# +# options array_component +# +# where array_component is "<modulename> options" (see modprobe.conf(5)) + +# @ECLASS-VARIABLE: MODULESD_<modulename>_ALIASES +# @DESCRIPTION: +# This is a bash array containing a list of associated aliases. +# +# For each array_component it's added an alias line in the modprobe.d file +# +# alias array_component +# +# where array_component is "wildcard <modulename>" (see modprobe.conf(5)) + +# @ECLASS-VARIABLE: MODULESD_<modulename>_ADDITIONS +# @DESCRIPTION: +# This is a bash array containing a list of additional things to +# add to the bottom of the file. This can be absolutely anything. +# Each entry is a new line. + +# @ECLASS-VARIABLE: MODULESD_<modulename>_DOCS +# @DESCRIPTION: +# This is a string list which contains the full path to any associated +# documents for <modulename>. These files are installed in the live tree. + +# @ECLASS-VARIABLE: KV_OBJ +# @DESCRIPTION: +# It's a read-only variable. It contains the extension of the kernel modules. + +inherit eutils linux-info multilib toolchain-funcs +EXPORT_FUNCTIONS pkg_setup pkg_preinst pkg_postinst src_install src_compile pkg_postrm + +case ${MODULES_OPTIONAL_USE_IUSE_DEFAULT:-n} in + [nNfF]*|[oO][fF]*|0|-) _modules_optional_use_iuse_default='' ;; + *) _modules_optional_use_iuse_default='+' ;; +esac + +[[ -n "${_modules_optional_use_iuse_default}" ]] && case ${EAPI:-0} in + 0) die "EAPI=${EAPI} is not supported with MODULES_OPTIONAL_USE_IUSE_DEFAULT due to lack of IUSE defaults" ;; +esac + +IUSE="kernel_linux dist-kernel + ${MODULES_OPTIONAL_USE:+${_modules_optional_use_iuse_default}}${MODULES_OPTIONAL_USE}" +SLOT="0" +RDEPEND=" + ${MODULES_OPTIONAL_USE}${MODULES_OPTIONAL_USE:+? (} + kernel_linux? ( + sys-apps/kmod[tools] + dist-kernel? ( virtual/dist-kernel:= ) + ) + ${MODULES_OPTIONAL_USE:+)}" +DEPEND="${RDEPEND} + ${MODULES_OPTIONAL_USE}${MODULES_OPTIONAL_USE:+? (} + sys-apps/sed + kernel_linux? ( virtual/linux-sources virtual/libelf ) + ${MODULES_OPTIONAL_USE:+)}" + +# eclass utilities +# ---------------------------------- + +check_vermagic() { + debug-print-function ${FUNCNAME} $* + + local curr_gcc_ver=$(gcc -dumpversion) + local tmpfile old_chost old_gcc_ver result=0 + [ -n "${MODULES_OPTIONAL_USE}" ] && use !${MODULES_OPTIONAL_USE} && return + + tmpfile=`find "${KV_DIR}/" -iname "*.o.cmd" -exec grep usr/lib/gcc {} \; -quit` + tmpfile=${tmpfile//*usr/lib} + tmpfile=${tmpfile//\/include*} + old_chost=${tmpfile//*gcc\/} + old_chost=${old_chost//\/*} + old_gcc_ver=${tmpfile//*\/} + + if [[ -z ${old_gcc_ver} || -z ${old_chost} ]]; then + ewarn "" + ewarn "Unable to detect what version of GCC was used to compile" + ewarn "the kernel. Build will continue, but you may experience problems." + elif [[ ${curr_gcc_ver} != ${old_gcc_ver} ]]; then + ewarn "" + ewarn "The version of GCC you are using (${curr_gcc_ver}) does" + ewarn "not match the version of GCC used to compile the" + ewarn "kernel (${old_gcc_ver})." + result=1 + elif [[ ${CHOST} != ${old_chost} ]]; then + ewarn "" + ewarn "The current CHOST (${CHOST}) does not match the chost" + ewarn "used when compiling the kernel (${old_chost})." + result=1 + fi + + if [[ ${result} -gt 0 ]]; then + ewarn "" + ewarn "Build will not continue, because you will experience problems." + ewarn "To fix this either change the version of GCC you wish to use" + ewarn "to match the kernel, or recompile the kernel first." + die "GCC Version Mismatch." + fi +} + +# @FUNCTION: use_m +# @RETURN: true or false +# @DESCRIPTION: +# It checks if the kernel version is greater than 2.6.5. +use_m() { + debug-print-function ${FUNCNAME} $* + + # if we haven't determined the version yet, we need too. + get_version; + + # if the kernel version is greater than 2.6.6 then we should use + # M= instead of SUBDIRS= + [ ${KV_MAJOR} -ge 3 ] && return 0 + [ ${KV_MAJOR} -eq 2 -a ${KV_MINOR} -gt 5 -a ${KV_PATCH} -gt 5 ] && \ + return 0 || return 1 +} + +# @FUNCTION: convert_to_m +# @USAGE: </path/to/the/file> +# @DESCRIPTION: +# It converts a file (e.g. a makefile) to use M= instead of SUBDIRS= +convert_to_m() { + debug-print-function ${FUNCNAME} $* + + if use_m + then + [ ! -f "${1}" ] && \ + die "convert_to_m() requires a filename as an argument" + ebegin "Converting ${1/${WORKDIR}\//} to use M= instead of SUBDIRS=" + sed -i 's:SUBDIRS=:M=:g' "${1}" + eend $? + fi +} + +# internal function +# +# FUNCTION: update_depmod +# DESCRIPTION: +# It updates the modules.dep file for the current kernel. +update_depmod() { + debug-print-function ${FUNCNAME} $* + + # if we haven't determined the version yet, we need too. + get_version; + + ebegin "Updating module dependencies for ${KV_FULL}" + if [ -r "${KV_OUT_DIR}"/System.map ] + then + depmod -ae -F "${KV_OUT_DIR}"/System.map -b "${ROOT:-/}" ${KV_FULL} + eend $? + else + ewarn + ewarn "${KV_OUT_DIR}/System.map not found." + ewarn "You must manually update the kernel module dependencies using depmod." + eend 1 + ewarn + fi +} + +# internal function +# +# FUNCTION: move_old_moduledb +# DESCRIPTION: +# It updates the location of the database used by the module-rebuild utility. +move_old_moduledb() { + debug-print-function ${FUNCNAME} $* + + local OLDDIR="${ROOT%/}"/usr/share/module-rebuild + local NEWDIR="${ROOT%/}"/var/lib/module-rebuild + + if [[ -f "${OLDDIR}"/moduledb ]]; then + [[ ! -d "${NEWDIR}" ]] && mkdir -p "${NEWDIR}" + [[ ! -f "${NEWDIR}"/moduledb ]] && \ + mv "${OLDDIR}"/moduledb "${NEWDIR}"/moduledb + rm -f "${OLDDIR}"/* + rmdir "${OLDDIR}" + fi +} + +# internal function +# +# FUNCTION: update_moduledb +# DESCRIPTION: +# It adds the package to the /var/lib/module-rebuild/moduledb database used by the module-rebuild utility. +update_moduledb() { + debug-print-function ${FUNCNAME} $* + + local MODULEDB_DIR="${ROOT%/}"/var/lib/module-rebuild + move_old_moduledb + + if [[ ! -f "${MODULEDB_DIR}"/moduledb ]]; then + [[ ! -d "${MODULEDB_DIR}" ]] && mkdir -p "${MODULEDB_DIR}" + touch "${MODULEDB_DIR}"/moduledb + fi + + if ! grep -qs ${CATEGORY}/${PN}-${PVR} "${MODULEDB_DIR}"/moduledb ; then + einfo "Adding module to moduledb." + echo "a:1:${CATEGORY}/${PN}-${PVR}" >> "${MODULEDB_DIR}"/moduledb + fi +} + +# internal function +# +# FUNCTION: remove_moduledb +# DESCRIPTION: +# It removes the package from the /var/lib/module-rebuild/moduledb database used by +# the module-rebuild utility. +remove_moduledb() { + debug-print-function ${FUNCNAME} $* + + local MODULEDB_DIR="${ROOT%/}"/var/lib/module-rebuild + move_old_moduledb + + if grep -qs ${CATEGORY}/${PN}-${PVR} "${MODULEDB_DIR}"/moduledb ; then + einfo "Removing ${CATEGORY}/${PN}-${PVR} from moduledb." + sed -i -e "/.*${CATEGORY}\/${PN}-${PVR}.*/d" "${MODULEDB_DIR}"/moduledb + fi +} + +# @FUNCTION: set_kvobj +# @DESCRIPTION: +# It sets the KV_OBJ variable. +set_kvobj() { + debug-print-function ${FUNCNAME} $* + + if kernel_is ge 2 6 + then + KV_OBJ="ko" + else + KV_OBJ="o" + fi + # Do we really need to know this? + # Lets silence it. + # einfo "Using KV_OBJ=${KV_OBJ}" +} + +get-KERNEL_CC() { + debug-print-function ${FUNCNAME} $* + + if [[ -n ${KERNEL_CC} ]] ; then + echo "${KERNEL_CC}" + return + fi + + local kernel_cc + if [ -n "${KERNEL_ABI}" ]; then + # In future, an arch might want to define CC_$ABI + #kernel_cc="$(get_abi_CC)" + #[ -z "${kernel_cc}" ] && + kernel_cc="$(tc-getCC $(ABI=${KERNEL_ABI} get_abi_CHOST))" + else + kernel_cc=$(tc-getCC) + fi + echo "${kernel_cc}" +} + +# internal function +# +# FUNCTION: +# USAGE: /path/to/the/modulename_without_extension +# RETURN: A file in /etc/modprobe.d +# DESCRIPTION: +# This function will generate and install the neccessary modprobe.d file from the +# information contained in the modules exported parms. +# (see the variables MODULESD_<modulename>_ENABLED, MODULESD_<modulename>_EXAMPLES, +# MODULESD_<modulename>_ALIASES, MODULESD_<modulename>_ADDITION and MODULESD_<modulename>_DOCS). +# +# At the end the documentation specified with MODULESD_<modulename>_DOCS is installed. +generate_modulesd() { + debug-print-function ${FUNCNAME} $* + [ -n "${MODULES_OPTIONAL_USE}" ] && use !${MODULES_OPTIONAL_USE} && return + + local currm_path currm currm_t t myIFS myVAR + local module_docs module_enabled module_aliases \ + module_additions module_examples module_modinfo module_opts + + for currm_path in ${@} + do + currm=${currm_path//*\/} + currm=$(echo ${currm} | tr '[:lower:]' '[:upper:]') + currm_t=${currm} + while [[ -z ${currm_t//*-*} ]]; do + currm_t=${currm_t/-/_} + done + + module_docs="$(eval echo \${MODULESD_${currm_t}_DOCS})" + module_enabled="$(eval echo \${MODULESD_${currm_t}_ENABLED})" + module_aliases="$(eval echo \${#MODULESD_${currm_t}_ALIASES[*]})" + module_additions="$(eval echo \${#MODULESD_${currm_t}_ADDITIONS[*]})" + module_examples="$(eval echo \${#MODULESD_${currm_t}_EXAMPLES[*]})" + + [[ ${module_aliases} -eq 0 ]] && unset module_aliases + [[ ${module_additions} -eq 0 ]] && unset module_additions + [[ ${module_examples} -eq 0 ]] && unset module_examples + + # If we specify we dont want it, then lets exit, otherwise we assume + # that if its set, we do want it. + [[ ${module_enabled} == no ]] && return 0 + + # unset any unwanted variables. + for t in ${!module_*} + do + [[ -z ${!t} ]] && unset ${t} + done + + [[ -z ${!module_*} ]] && return 0 + + # OK so now if we have got this far, then we know we want to continue + # and generate the modprobe.d file. + module_modinfo="$(modinfo -p ${currm_path}.${KV_OBJ})" + module_config="${T}/modulesd-${currm}" + + ebegin "Preparing file for modprobe.d" + #----------------------------------------------------------------------- + echo "# modprobe.d configuration file for ${currm}" >> "${module_config}" + #----------------------------------------------------------------------- + [[ -n ${module_docs} ]] && \ + echo "# For more information please read:" >> "${module_config}" + for t in ${module_docs} + do + echo "# ${t//*\/}" >> "${module_config}" + done + echo >> "${module_config}" + + #----------------------------------------------------------------------- + if [[ ${module_aliases} -gt 0 ]] + then + echo "# Internal Aliases - Do not edit" >> "${module_config}" + echo "# ------------------------------" >> "${module_config}" + + for((t=0; t<${module_aliases}; t++)) + do + echo "alias $(eval echo \${MODULESD_${currm}_ALIASES[$t]})" \ + >> "${module_config}" + done + echo '' >> "${module_config}" + fi + + #----------------------------------------------------------------------- + if [[ -n ${module_modinfo} ]] + then + echo >> "${module_config}" + echo "# Configurable module parameters" >> "${module_config}" + echo "# ------------------------------" >> "${module_config}" + myIFS="${IFS}" + IFS="$(echo -en "\n\b")" + + for t in ${module_modinfo} + do + myVAR="$(echo ${t#*:} | grep -o "[^ ]*[0-9][ =][^ ]*" | tail -1 | grep -o "[0-9]")" + if [[ -n ${myVAR} ]] + then + module_opts="${module_opts} ${t%%:*}:${myVAR}" + fi + echo -e "# ${t%%:*}:\t${t#*:}" >> "${module_config}" + done + IFS="${myIFS}" + echo '' >> "${module_config}" + fi + + #----------------------------------------------------------------------- + if [[ $(eval echo \${MODULESD_${currm}_ALIASES[0]}) == guess ]] + then + # So lets do some guesswork eh? + if [[ -n ${module_opts} ]] + then + echo "# For Example..." >> "${module_config}" + echo "# --------------" >> "${module_config}" + for t in ${module_opts} + do + echo "# options ${currm} ${t//:*}=${t//*:}" >> "${module_config}" + done + echo '' >> "${module_config}" + fi + elif [[ ${module_examples} -gt 0 ]] + then + echo "# For Example..." >> "${module_config}" + echo "# --------------" >> "${module_config}" + for((t=0; t<${module_examples}; t++)) + do + echo "options $(eval echo \${MODULESD_${currm}_EXAMPLES[$t]})" \ + >> "${module_config}" + done + echo '' >> "${module_config}" + fi + + #----------------------------------------------------------------------- + if [[ ${module_additions} -gt 0 ]] + then + for((t=0; t<${module_additions}; t++)) + do + echo "$(eval echo \${MODULESD_${currm}_ADDITIONS[$t]})" \ + >> "${module_config}" + done + echo '' >> "${module_config}" + fi + + #----------------------------------------------------------------------- + + # then we install it + insinto /etc/modprobe.d + newins "${module_config}" "${currm_path//*\/}.conf" + + # and install any documentation we might have. + [[ -n ${module_docs} ]] && dodoc ${module_docs} + done + eend 0 + return 0 +} + +# internal function +# +# FUNCTION: find_module_params +# USAGE: A string "NAME(LIBDIR:SRCDIR:OBJDIR)" +# RETURN: The string "modulename:NAME libdir:LIBDIR srcdir:SRCDIR objdir:OBJDIR" +# DESCRIPTION: +# Analyze the specification NAME(LIBDIR:SRCDIR:OBJDIR) of one module as described in MODULE_NAMES. +find_module_params() { + debug-print-function ${FUNCNAME} $* + + local matched_offset=0 matched_opts=0 test="${@}" temp_var result + local i=0 y=0 z=0 + + for((i=0; i<=${#test}; i++)) + do + case ${test:${i}:1} in + \() matched_offset[0]=${i};; + \:) matched_opts=$((${matched_opts} + 1)); + matched_offset[${matched_opts}]="${i}";; + \)) matched_opts=$((${matched_opts} + 1)); + matched_offset[${matched_opts}]="${i}";; + esac + done + + for((i=0; i<=${matched_opts}; i++)) + do + # i = offset were working on + # y = last offset + # z = current offset - last offset + # temp_var = temporary name + case ${i} in + 0) tempvar=${test:0:${matched_offset[0]}};; + *) y=$((${matched_offset[$((${i} - 1))]} + 1)) + z=$((${matched_offset[${i}]} - ${matched_offset[$((${i} - 1))]})); + z=$((${z} - 1)) + tempvar=${test:${y}:${z}};; + esac + + case ${i} in + 0) result="${result} modulename:${tempvar}";; + 1) result="${result} libdir:${tempvar}";; + 2) result="${result} srcdir:${tempvar}";; + 3) result="${result} objdir:${tempvar}";; + esac + done + + echo ${result} +} + +# default ebuild functions +# -------------------------------- + +# @FUNCTION: linux-mod_pkg_setup +# @DESCRIPTION: +# It checks the CONFIG_CHECK options (see linux-info.eclass(5)), verifies that the kernel is +# configured, verifies that the sources are prepared, verifies that the modules support is builtin +# in the kernel and sets the object extension KV_OBJ. +linux-mod_pkg_setup() { + debug-print-function ${FUNCNAME} $* + [ -n "${MODULES_OPTIONAL_USE}" ] && use !${MODULES_OPTIONAL_USE} && return + + local is_bin="${MERGE_TYPE}" + + # If we are installing a binpkg, take a different path. + # use MERGE_TYPE if available (eapi>=4); else use non-PMS EMERGE_FROM (eapi<4) + if has ${EAPI} 0 1 2 3; then + is_bin=${EMERGE_FROM} + fi + + if [[ ${is_bin} == binary ]]; then + linux-mod_pkg_setup_binary + return + fi + + # External modules use kernel symbols (bug #591832) + CONFIG_CHECK+=" !TRIM_UNUSED_KSYMS" + + linux-info_pkg_setup; + require_configured_kernel + check_kernel_built; + strip_modulenames; + [[ -n ${MODULE_NAMES} ]] && check_modules_supported + set_kvobj; + # Commented out with permission from johnm until a fixed version for arches + # who intentionally use different kernel and userland compilers can be + # introduced - Jason Wever <weeve@gentoo.org>, 23 Oct 2005 + #check_vermagic; +} + +# @FUNCTION: linux-mod_pkg_setup_binary +# @DESCRIPTION: +# Perform all kernel option checks non-fatally, as the .config and +# /proc/config.gz might not be present. Do not do anything that requires kernel +# sources. +linux-mod_pkg_setup_binary() { + debug-print-function ${FUNCNAME} $* + local new_CONFIG_CHECK + # ~ needs always to be quoted, else bash expands it. + for config in $CONFIG_CHECK ; do + optional='~' + [[ ${config:0:1} == "~" ]] && optional='' + new_CONFIG_CHECK="${new_CONFIG_CHECK} ${optional}${config}" + done + CONFIG_CHECK="${new_CONFIG_CHECK}" + linux-info_pkg_setup; +} + +strip_modulenames() { + debug-print-function ${FUNCNAME} $* + + local i + for i in ${MODULE_IGNORE}; do + MODULE_NAMES=${MODULE_NAMES//${i}(*} + done +} + +# @FUNCTION: linux-mod_src_compile +# @DESCRIPTION: +# It compiles all the modules specified in MODULE_NAMES. For each module the econf command is +# executed only if ECONF_PARAMS is defined, the name of the target is specified by BUILD_TARGETS +# while the options are in BUILD_PARAMS (all the modules share these variables). The compilation +# happens inside ${srcdir}. +# +# Look at the description of these variables for more details. +linux-mod_src_compile() { + debug-print-function ${FUNCNAME} $* + [ -n "${MODULES_OPTIONAL_USE}" ] && use !${MODULES_OPTIONAL_USE} && return + + local modulename libdir srcdir objdir i n myABI="${ABI}" + set_arch_to_kernel + ABI="${KERNEL_ABI}" + + [[ -n ${KERNEL_DIR} ]] && addpredict "${KERNEL_DIR}/null.dwo" + + BUILD_TARGETS=${BUILD_TARGETS:-clean module} + strip_modulenames; + cd "${S}" + touch Module.symvers + for i in ${MODULE_NAMES} + do + unset libdir srcdir objdir + for n in $(find_module_params ${i}) + do + eval ${n/:*}=${n/*:/} + done + libdir=${libdir:-misc} + srcdir=${srcdir:-${S}} + objdir=${objdir:-${srcdir}} + + if [ ! -f "${srcdir}/.built" ]; + then + cd "${srcdir}" + ln -s "${S}"/Module.symvers Module.symvers + einfo "Preparing ${modulename} module" + if [[ -n ${ECONF_PARAMS} ]] + then + econf ${ECONF_PARAMS} || \ + die "Unable to run econf ${ECONF_PARAMS}" + fi + + # This looks messy, but it is needed to handle multiple variables + # being passed in the BUILD_* stuff where the variables also have + # spaces that must be preserved. If don't do this, then the stuff + # inside the variables gets used as targets for Make, which then + # fails. + eval "emake HOSTCC=\"$(tc-getBUILD_CC)\" \ + CROSS_COMPILE=${CHOST}- \ + LDFLAGS=\"$(get_abi_LDFLAGS)\" \ + ${BUILD_FIXES} \ + ${BUILD_PARAMS} \ + ${BUILD_TARGETS} " \ + || die "Unable to emake HOSTCC="$(tc-getBUILD_CC)" CROSS_COMPILE=${CHOST}- LDFLAGS="$(get_abi_LDFLAGS)" ${BUILD_FIXES} ${BUILD_PARAMS} ${BUILD_TARGETS}" + cd "${OLDPWD}" + touch "${srcdir}"/.built + fi + done + + set_arch_to_portage + ABI="${myABI}" +} + +# @FUNCTION: linux-mod_src_install +# @DESCRIPTION: +# It install the modules specified in MODULES_NAME. The modules should be inside the ${objdir} +# directory and they are installed inside /lib/modules/${KV_FULL}/${libdir}. +# +# The modprobe.d configuration file is automatically generated if the +# MODULESD_<modulename>_* variables are defined. The only way to stop this process is by +# setting MODULESD_<modulename>_ENABLED=no. At the end the documentation specified via +# MODULESD_<modulename>_DOCS is also installed. +# +# Look at the description of these variables for more details. +linux-mod_src_install() { + debug-print-function ${FUNCNAME} $* + [ -n "${MODULES_OPTIONAL_USE}" ] && use !${MODULES_OPTIONAL_USE} && return + + local modulename libdir srcdir objdir i n + + [[ -n ${KERNEL_DIR} ]] && addpredict "${KERNEL_DIR}/null.dwo" + + strip_modulenames; + for i in ${MODULE_NAMES} + do + unset libdir srcdir objdir + for n in $(find_module_params ${i}) + do + eval ${n/:*}=${n/*:/} + done + libdir=${libdir:-misc} + srcdir=${srcdir:-${S}} + objdir=${objdir:-${srcdir}} + + einfo "Installing ${modulename} module" + cd "${objdir}" || die "${objdir} does not exist" + insinto /lib/modules/${KV_FULL}/${libdir} + doins ${modulename}.${KV_OBJ} || die "doins ${modulename}.${KV_OBJ} failed" + cd "${OLDPWD}" + + generate_modulesd "${objdir}/${modulename}" + done +} + +# @FUNCTION: linux-mod_pkg_preinst +# @DESCRIPTION: +# It checks what to do after having merged the package. +linux-mod_pkg_preinst() { + debug-print-function ${FUNCNAME} $* + [ -n "${MODULES_OPTIONAL_USE}" ] && use !${MODULES_OPTIONAL_USE} && return + + [ -d "${D%/}/lib/modules" ] && UPDATE_DEPMOD=true || UPDATE_DEPMOD=false + [ -d "${D%/}/lib/modules" ] && UPDATE_MODULEDB=true || UPDATE_MODULEDB=false +} + +# @FUNCTION: linux-mod_pkg_postinst +# @DESCRIPTION: +# It executes /sbin/depmod and adds the package to the /var/lib/module-rebuild/moduledb +# database (if ${D}/lib/modules is created)" +linux-mod_pkg_postinst() { + debug-print-function ${FUNCNAME} $* + [ -n "${MODULES_OPTIONAL_USE}" ] && use !${MODULES_OPTIONAL_USE} && return + + ${UPDATE_DEPMOD} && update_depmod; + ${UPDATE_MODULEDB} && update_moduledb; +} + +# @FUNCTION: linux-mod_pkg_postrm +# @DESCRIPTION: +# It removes the package from the /var/lib/module-rebuild/moduledb database but it doens't +# call /sbin/depmod because the modules are still installed. +linux-mod_pkg_postrm() { + debug-print-function ${FUNCNAME} $* + [ -n "${MODULES_OPTIONAL_USE}" ] && use !${MODULES_OPTIONAL_USE} && return + remove_moduledb; +} diff --git a/eclass/llvm.eclass b/eclass/llvm.eclass new file mode 100644 index 0000000..761ffdb --- /dev/null +++ b/eclass/llvm.eclass @@ -0,0 +1,228 @@ +# Copyright 1999-2020 Gentoo Authors +# Distributed under the terms of the GNU General Public License v2 + +# @ECLASS: llvm.eclass +# @MAINTAINER: +# Michał Górny <mgorny@gentoo.org> +# @AUTHOR: +# Michał Górny <mgorny@gentoo.org> +# @SUPPORTED_EAPIS: 6 7 +# @BLURB: Utility functions to build against slotted LLVM +# @DESCRIPTION: +# The llvm.eclass provides utility functions that can be used to build +# against specific version of slotted LLVM (with fallback to :0 for old +# versions). +# +# This eclass does not generate dependency strings. You need to write +# a proper dependency string yourself to guarantee that appropriate +# version of LLVM is installed. +# +# Example use for a package supporting LLVM 5 to 7: +# @CODE +# inherit cmake-utils llvm +# +# RDEPEND=" +# <sys-devel/llvm-8:= +# || ( +# sys-devel/llvm:7 +# sys-devel/llvm:6 +# sys-devel/llvm:5 +# ) +# " +# DEPEND=${RDEPEND} +# +# LLVM_MAX_SLOT=7 +# +# # only if you need to define one explicitly +# pkg_setup() { +# llvm_pkg_setup +# do-something-else +# } +# @CODE +# +# Example for a package needing LLVM+clang w/ a specific target: +# @CODE +# inherit cmake-utils llvm +# +# # note: do not use := on both clang and llvm, it can match different +# # slots then. clang pulls llvm in, so we can skip the latter. +# RDEPEND=" +# >=sys-devel/clang-6:=[llvm_targets_AMDGPU(+)] +# " +# DEPEND=${RDEPEND} +# +# llvm_check_deps() { +# has_version -d "sys-devel/clang:${LLVM_SLOT}[llvm_targets_AMDGPU(+)]" +# } +# @CODE + +case "${EAPI:-0}" in + 0|1|2|3|4|5) + die "Unsupported EAPI=${EAPI:-0} (too old) for ${ECLASS}" + ;; + 6|7) + ;; + *) + die "Unsupported EAPI=${EAPI} (unknown) for ${ECLASS}" + ;; +esac + +EXPORT_FUNCTIONS pkg_setup + +if [[ ! ${_LLVM_ECLASS} ]]; then + +# make sure that the versions installing straight into /usr/bin +# are uninstalled +DEPEND="!!sys-devel/llvm:0" + +# @ECLASS-VARIABLE: LLVM_MAX_SLOT +# @DEFAULT_UNSET +# @DESCRIPTION: +# Highest LLVM slot supported by the package. Needs to be set before +# llvm_pkg_setup is called. If unset, no upper bound is assumed. + +# @ECLASS-VARIABLE: _LLVM_KNOWN_SLOTS +# @INTERNAL +# @DESCRIPTION: +# Correct values of LLVM slots, newest first. +declare -g -r _LLVM_KNOWN_SLOTS=( {12..8} ) + +# @FUNCTION: get_llvm_prefix +# @USAGE: [-b|-d] [<max_slot>] +# @DESCRIPTION: +# Find the newest LLVM install that is acceptable for the package, +# and print an absolute path to it. +# +# If -b is specified, the checks are performed relative to BROOT, +# and BROOT-path is returned. This is appropriate when your package +# calls llvm-config executable. -b is supported since EAPI 7. +# +# If -d is specified, the checks are performed relative to ESYSROOT, +# and ESYSROOT-path is returned. This is appropriate when your package +# uses CMake find_package(LLVM). -d is the default. +# +# If <max_slot> is specified, then only LLVM versions that are not newer +# than <max_slot> will be considered. Otherwise, all LLVM versions would +# be considered acceptable. The function does not support specifying +# minimal supported version -- the developer must ensure that a version +# new enough is installed via providing appropriate dependencies. +# +# If llvm_check_deps() function is defined within the ebuild, it will +# be called to verify whether a particular slot is accepable. Within +# the function scope, LLVM_SLOT will be defined to the SLOT value +# (0, 4, 5...). The function should return a true status if the slot +# is acceptable, false otherwise. If llvm_check_deps() is not defined, +# the function defaults to checking whether sys-devel/llvm:${LLVM_SLOT} +# is installed. +get_llvm_prefix() { + debug-print-function ${FUNCNAME} "${@}" + + local hv_switch=-d + while [[ ${1} == -* ]]; do + case ${1} in + -b|-d) hv_switch=${1};; + *) break;; + esac + shift + done + + local prefix= + if [[ ${EAPI} != 6 ]]; then + case ${hv_switch} in + -b) + prefix=${BROOT} + ;; + -d) + prefix=${ESYSROOT} + ;; + esac + else + case ${hv_switch} in + -b) + die "${FUNCNAME} -b is not supported in EAPI ${EAPI}" + ;; + -d) + prefix=${EPREFIX} + hv_switch= + ;; + esac + fi + + local max_slot=${1} + local slot + for slot in "${_LLVM_KNOWN_SLOTS[@]}"; do + # skip higher slots + if [[ -n ${max_slot} ]]; then + if [[ ${max_slot} == ${slot} ]]; then + max_slot= + else + continue + fi + fi + + if declare -f llvm_check_deps >/dev/null; then + local LLVM_SLOT=${slot} + llvm_check_deps || continue + else + # check if LLVM package is installed + has_version ${hv_switch} "sys-devel/llvm:${slot}" || continue + fi + + echo "${prefix}/usr/lib/llvm/${slot}" + return + done + + # max_slot should have been unset in the iteration + if [[ -n ${max_slot} ]]; then + die "${FUNCNAME}: invalid max_slot=${max_slot}" + fi + + die "No LLVM slot${1:+ <= ${1}} found installed!" +} + +# @FUNCTION: llvm_pkg_setup +# @DESCRIPTION: +# Prepend the appropriate executable directory for the newest +# acceptable LLVM slot to the PATH. For path determination logic, +# please see the get_llvm_prefix documentation. +# +# The highest acceptable LLVM slot can be set in LLVM_MAX_SLOT variable. +# If it is unset or empty, any slot is acceptable. +# +# The PATH manipulation is only done for source builds. The function +# is a no-op when installing a binary package. +# +# If any other behavior is desired, the contents of the function +# should be inlined into the ebuild and modified as necessary. +llvm_pkg_setup() { + debug-print-function ${FUNCNAME} "${@}" + + if [[ ${MERGE_TYPE} != binary ]]; then + local llvm_path=$(get_llvm_prefix "${LLVM_MAX_SLOT}")/bin + local IFS=: + local split_path=( ${PATH} ) + local new_path=() + local x added= + + # prepend new path before first LLVM version found + for x in "${split_path[@]}"; do + if [[ ${x} == */usr/lib/llvm/*/bin ]]; then + if [[ ${x} != ${llvm_path} ]]; then + new_path+=( "${llvm_path}" ) + elif [[ ${added} && ${x} == ${llvm_path} ]]; then + # deduplicate + continue + fi + added=1 + fi + new_path+=( "${x}" ) + done + # ...or to the end of PATH + [[ ${added} ]] || new_path+=( "${llvm_path}" ) + + export PATH=${new_path[*]} + fi +} + +_LLVM_ECLASS=1 +fi diff --git a/eclass/llvm.org.eclass b/eclass/llvm.org.eclass new file mode 100644 index 0000000..e532c95 --- /dev/null +++ b/eclass/llvm.org.eclass @@ -0,0 +1,253 @@ +# Copyright 2019-2021 Gentoo Authors +# Distributed under the terms of the GNU General Public License v2 + +# @ECLASS: llvm.org.eclass +# @MAINTAINER: +# Michał Górny <mgorny@gentoo.org> +# @AUTHOR: +# Michał Górny <mgorny@gentoo.org> +# @BLURB: Common bits for fetching & unpacking llvm.org projects +# @DESCRIPTION: +# The llvm.org eclass provides common code to fetch and unpack parts +# of the llvm.org project tree. It takes care of handling both git +# checkouts and source tarballs, making it possible to unify the code +# of live and release ebuilds and effectively reduce the work needed +# to package new releases/RCs/branches. +# +# In order to use this eclass, the ebuild needs to declare +# LLVM_COMPONENTS and then call llvm.org_set_globals. If tests require +# additional components, they need to be listed in LLVM_TEST_COMPONENTS. +# The eclass exports an implementation of src_unpack() phase. +# +# Example: +# @CODE +# inherit llvm.org +# +# LLVM_COMPONENTS=( lld ) +# LLVM_TEST_COMPONENTS=( llvm/utils/lit ) +# llvm.org_set_globals +# @CODE + +case "${EAPI:-0}" in + 7) + ;; + *) + die "Unsupported EAPI=${EAPI} for ${ECLASS}" + ;; +esac + + +# == internal control bits == + +# @ECLASS-VARIABLE: _LLVM_MASTER_MAJOR +# @INTERNAL +# @DESCRIPTION: +# The major version of current LLVM trunk. Used to determine +# the correct branch to use. +_LLVM_MASTER_MAJOR=13 + +# @ECLASS-VARIABLE: _LLVM_SOURCE_TYPE +# @INTERNAL +# @DESCRIPTION: +# Source type to use: 'git' or 'tar'. +if [[ -z ${_LLVM_SOURCE_TYPE+1} ]]; then + if [[ ${PV} == *.9999 ]]; then + _LLVM_SOURCE_TYPE=git + else + _LLVM_SOURCE_TYPE=tar + fi +fi + +[[ ${_LLVM_SOURCE_TYPE} == git ]] && inherit git-r3 + +[[ ${PV} == ${_LLVM_MASTER_MAJOR}.* && ${_LLVM_SOURCE_TYPE} == tar ]] && + die "${ECLASS}: Release ebuild for master branch?!" + +inherit multiprocessing + + +# == control variables == + +# @ECLASS-VARIABLE: LLVM_COMPONENTS +# @REQUIRED +# @DESCRIPTION: +# List of components needed unconditionally. Specified as bash array +# with paths relative to llvm-project git. Automatically translated +# for tarball releases. +# +# The first path specified is used to construct default S. + +# @ECLASS-VARIABLE: LLVM_TEST_COMPONENTS +# @DEFAULT_UNSET +# @DESCRIPTION: +# List of additional components needed for tests. + +# @ECLASS-VARIABLE: LLVM_MANPAGES +# @DEFAULT_UNSET +# @DESCRIPTION: +# Set to 'build', include the dependency on dev-python/sphinx to build +# the manpages. If set to 'pregenerated', fetch and install +# pregenerated manpages from the archive. + + +# == global scope logic == + +# @FUNCTION: llvm.org_set_globals +# @DESCRIPTION: +# Set global variables. This must be called after setting LLVM_* +# variables used by the eclass. +llvm.org_set_globals() { + if [[ $(declare -p LLVM_COMPONENTS) != "declare -a"* ]]; then + die 'LLVM_COMPONENTS must be an array.' + fi + if declare -p LLVM_TEST_COMPONENTS &>/dev/null; then + if [[ $(declare -p LLVM_TEST_COMPONENTS) != "declare -a"* ]]; then + die 'LLVM_TEST_COMPONENTS must be an array.' + fi + fi + + if [[ ${_LLVM_SOURCE_TYPE} == git ]]; then + EGIT_REPO_URI="https://github.com/llvm/llvm-project.git" + + [[ ${PV} != ${_LLVM_MASTER_MAJOR}.* ]] && + EGIT_BRANCH="release/${PV%%.*}.x" + elif [[ ${_LLVM_SOURCE_TYPE} == tar ]]; then + SRC_URI+=" + https://github.com/llvm/llvm-project/archive/llvmorg-${PV/_/-}.tar.gz" + else + die "Invalid _LLVM_SOURCE_TYPE: ${LLVM_SOURCE_TYPE}" + fi + + S=${WORKDIR}/${LLVM_COMPONENTS[0]} + + if [[ -n ${LLVM_TEST_COMPONENTS+1} ]]; then + IUSE+=" test" + RESTRICT+=" !test? ( test )" + fi + + case ${LLVM_MANPAGES:-__unset__} in + __unset__) + # no manpage support + ;; + build) + IUSE+=" doc" + # NB: this is not always the correct dep but it does no harm + BDEPEND+=" dev-python/sphinx" + ;; + pregenerated) + IUSE+=" doc" + SRC_URI+=" + !doc? ( + https://dev.gentoo.org/~mgorny/dist/llvm/llvm-${PV}-manpages.tar.bz2 + )" + ;; + *) + die "Invalid LLVM_MANPAGES=${LLVM_MANPAGES}" + esac + + # === useful defaults for cmake-based packages === + + # least intrusive of all + CMAKE_BUILD_TYPE=RelWithDebInfo + + _LLVM_ORG_SET_GLOBALS_CALLED=1 +} + + +# == phase functions == + +EXPORT_FUNCTIONS src_unpack +if ver_test -ge 10.0.1_rc; then + EXPORT_FUNCTIONS src_prepare +fi + +# @FUNCTION: llvm.org_src_unpack +# @DESCRIPTION: +# Unpack or checkout requested LLVM components. +llvm.org_src_unpack() { + if [[ ! ${_LLVM_ORG_SET_GLOBALS_CALLED} ]]; then + die "llvm.org_set_globals must be called in global scope" + fi + + local components=( "${LLVM_COMPONENTS[@]}" ) + if [[ ${LLVM_TEST_COMPONENTS+1} ]] && use test; then + components+=( "${LLVM_TEST_COMPONENTS[@]}" ) + fi + + if [[ ${_LLVM_SOURCE_TYPE} == git ]]; then + git-r3_fetch + git-r3_checkout '' . '' "${components[@]}" + default_src_unpack + else + local archive=llvmorg-${PV/_/-}.tar.gz + ebegin "Unpacking from ${archive}" + tar -x -z -o --strip-components 1 \ + -f "${DISTDIR}/${archive}" \ + "${components[@]/#/llvm-project-${archive%.tar*}/}" || die + eend ${?} + + # unpack all remaining distfiles + local x + for x in ${A}; do + [[ ${x} != ${archive} ]] && unpack "${x}" + done + fi +} + +# @FUNCTION: llvm.org_src_prepare +# @DESCRIPTION: +# Call appropriate src_prepare (cmake or default) depending on inherited +# eclasses. Make sure that PATCHES and user patches are applied in top +# ${WORKDIR}, so that patches straight from llvm-project repository +# work correctly with -p1. +llvm.org_src_prepare() { + if declare -f cmake_src_prepare >/dev/null; then + # cmake eclasses force ${S} for default_src_prepare + # but use ${CMAKE_USE_DIR} for everything else + CMAKE_USE_DIR=${S} \ + S=${WORKDIR} \ + cmake_src_prepare + else + pushd "${WORKDIR}" >/dev/null || die + default_src_prepare + popd >/dev/null || die + fi +} + + +# == helper functions == + +# @ECLASS-VARIABLE: LIT_JOBS +# @USER_VARIABLE +# @DEFAULT_UNSET +# @DESCRIPTION: +# Number of test jobs to run simultaneously. If unset, defaults +# to '-j' in MAKEOPTS. If that is not found, default to nproc. + +# @FUNCTION: get_lit_flags +# @DESCRIPTION: +# Get the standard recommended lit flags for running tests, in CMake +# list form (;-separated). +get_lit_flags() { + echo "-vv;-j;${LIT_JOBS:-$(makeopts_jobs "${MAKEOPTS}" "$(get_nproc)")}" +} + +# @FUNCTION: llvm_are_manpages_built +# @DESCRIPTION: +# Return true (0) if manpages are going to be built from source, +# false (1) if preinstalled manpages will be used. +llvm_are_manpages_built() { + use doc || [[ ${LLVM_MANPAGES} == build ]] +} + +# @FUNCTION: llvm_install_manpages +# @DESCRIPTION: +# Install pregenerated manpages if available. No-op otherwise. +llvm_install_manpages() { + # install pre-generated manpages + if ! llvm_are_manpages_built; then + # (doman does not support custom paths) + insinto "/usr/lib/llvm/${SLOT}/share/man/man1" + doins "${WORKDIR}/llvm-${PV}-manpages/${LLVM_COMPONENTS[0]}"/*.1 + fi +} diff --git a/eclass/ltprune.eclass b/eclass/ltprune.eclass new file mode 100644 index 0000000..e7d8cd2 --- /dev/null +++ b/eclass/ltprune.eclass @@ -0,0 +1,176 @@ +# Copyright 1999-2020 Gentoo Authors +# Distributed under the terms of the GNU General Public License v2 + +# @ECLASS: ltprune.eclass +# @MAINTAINER: +# Michał Górny <mgorny@gentoo.org> +# @SUPPORTED_EAPIS: 0 1 2 3 4 5 6 +# @BLURB: Smart .la file pruning +# @DEPRECATED: none +# @DESCRIPTION: +# A function to locate and remove unnecessary .la files. +# +# Discouraged. Whenever possible, please use much simpler: +# @CODE +# find "${ED}" -name '*.la' -delete || die +# @CODE + +if [[ -z ${_LTPRUNE_ECLASS} ]]; then + +case ${EAPI:-0} in + 0|1|2|3|4|5|6) + ;; + *) + die "${ECLASS}: banned in EAPI=${EAPI}; use 'find' instead";; +esac + +inherit toolchain-funcs + +# @FUNCTION: prune_libtool_files +# @USAGE: [--all|--modules] +# @DESCRIPTION: +# Locate unnecessary libtool files (.la) and libtool static archives +# (.a) and remove them from installation image. +# +# By default, .la files are removed whenever the static linkage can +# either be performed using pkg-config or doesn't introduce additional +# flags. +# +# If '--modules' argument is passed, .la files for modules (plugins) are +# removed as well. This is usually useful when the package installs +# plugins and the plugin loader does not use .la files. +# +# If '--all' argument is passed, all .la files are removed without +# performing any heuristic on them. You shouldn't ever use that, +# and instead report a bug in the algorithm instead. +# +# The .a files are only removed whenever corresponding .la files state +# that they should not be linked to, i.e. whenever these files +# correspond to plugins. +# +# Note: if your package installs both static libraries and .pc files +# which use variable substitution for -l flags, you need to add +# pkg-config to your DEPEND. +prune_libtool_files() { + debug-print-function ${FUNCNAME} "$@" + + local removing_all removing_modules opt + for opt; do + case "${opt}" in + --all) + removing_all=1 + removing_modules=1 + ;; + --modules) + removing_modules=1 + ;; + *) + die "Invalid argument to ${FUNCNAME}(): ${opt}" + esac + done + + local f + local queue=() + while IFS= read -r -d '' f; do # for all .la files + local archivefile=${f/%.la/.a} + + # The following check is done by libtool itself. + # It helps us avoid removing random files which match '*.la', + # see bug #468380. + if ! sed -n -e '/^# Generated by .*libtool/q0;4q1' "${f}"; then + continue + fi + + [[ ${f} != ${archivefile} ]] || die 'regex sanity check failed' + local reason= pkgconfig_scanned= + local snotlink=$(sed -n -e 's:^shouldnotlink=::p' "${f}") + + if [[ ${snotlink} == yes ]]; then + + # Remove static libs we're not supposed to link against. + if [[ -f ${archivefile} ]]; then + einfo "Removing unnecessary ${archivefile#${D%/}} (static plugin)" + queue+=( "${archivefile}" ) + fi + + # The .la file may be used by a module loader, so avoid removing it + # unless explicitly requested. + if [[ ${removing_modules} ]]; then + reason='module' + fi + + else + + # Remove .la files when: + # - user explicitly wants us to remove all .la files, + # - respective static archive doesn't exist, + # - they are covered by a .pc file already, + # - they don't provide any new information (no libs & no flags). + + if [[ ${removing_all} ]]; then + reason='requested' + elif [[ ! -f ${archivefile} ]]; then + reason='no static archive' + elif [[ ! $(sed -nre \ + "s/^(dependency_libs|inherited_linker_flags)='(.*)'$/\2/p" \ + "${f}") ]]; then + reason='no libs & flags' + else + if [[ ! ${pkgconfig_scanned} ]]; then + # Create a list of all .pc-covered libs. + local pc_libs=() + if [[ ! ${removing_all} ]]; then + local pc + local tf=${T}/prune-lt-files.pc + local pkgconf=$(tc-getPKG_CONFIG) + + while IFS= read -r -d '' pc; do # for all .pc files + local arg libs + + # Use pkg-config if available (and works), + # fallback to sed. + if ${pkgconf} --exists "${pc}" &>/dev/null; then + sed -e '/^Requires:/d' "${pc}" > "${tf}" + libs=$(${pkgconf} --libs "${tf}") + else + libs=$(sed -ne 's/^Libs://p' "${pc}") + fi + + for arg in ${libs}; do + if [[ ${arg} == -l* ]]; then + if [[ ${arg} == '*$*' ]]; then + eerror "${FUNCNAME}: variable substitution likely failed in ${pc}" + eerror "(arg: ${arg})" + eerror "Most likely, you need to add virtual/pkgconfig to DEPEND." + die "${FUNCNAME}: unsubstituted variable found in .pc" + fi + + pc_libs+=( lib${arg#-l}.la ) + fi + done + done < <(find "${D}" -type f -name '*.pc' -print0) + + rm -f "${tf}" + fi + + pkgconfig_scanned=1 + fi # pkgconfig_scanned + + has "${f##*/}" "${pc_libs[@]}" && reason='covered by .pc' + fi # removal due to .pc + + fi # shouldnotlink==no + + if [[ ${reason} ]]; then + einfo "Removing unnecessary ${f#${D%/}} (${reason})" + queue+=( "${f}" ) + fi + done < <(find "${D}" -xtype f -name '*.la' -print0) + + if [[ ${queue[@]} ]]; then + rm -f "${queue[@]}" + fi +} + +_LTPRUNE_ECLASS=1 +fi #_LTPRUNE_ECLASS diff --git a/eclass/lua-single.eclass b/eclass/lua-single.eclass new file mode 100644 index 0000000..11c2790 --- /dev/null +++ b/eclass/lua-single.eclass @@ -0,0 +1,540 @@ +# Copyright 1999-2020 Gentoo Authors +# Distributed under the terms of the GNU General Public License v2 + +# @ECLASS: lua-single.eclass +# @MAINTAINER: +# William Hubbs <williamh@gentoo.org> +# Marek Szuba <marecki@gentoo.org> +# @AUTHOR: +# Marek Szuba <marecki@gentoo.org> +# Based on python-single-r1.eclass by Michał Górny <mgorny@gentoo.org> et al. +# @SUPPORTED_EAPIS: 7 +# @BLURB: An eclass for Lua packages not installed for multiple implementations. +# @DESCRIPTION: +# An extension of lua.eclass suite for packages which don't support being +# installed for multiple Lua implementations. This mostly includes software +# embedding Lua. +# +# This eclass sets correct IUSE. It also provides LUA_DEPS +# and LUA_REQUIRED_USE that need to be added to appropriate ebuild +# metadata variables. +# +# The eclass exports LUA_SINGLE_USEDEP that is suitable for depending +# on other packages using the eclass. Dependencies on packages using +# lua.eclass should be created via lua_gen_cond_dep() function, using +# LUA_USEDEP placeholder. +# +# Please note that packages support multiple Lua implementations +# (using lua.eclass) cannot depend on packages not supporting +# them (using this eclass). +# +# Note that since this eclass always inherits lua-utils as well, in ebuilds +# using the former there is no need to explicitly inherit the latter in order +# to use helper functions such as lua_get_CFLAGS. +# +# @EXAMPLE: +# @CODE +# EAPI=7 +# +# LUA_COMPAT=( lua5-{1..3} ) +# +# inherit lua-single +# +# [...] +# +# REQUIRED_USE="${LUA_REQUIRED_USE}" +# DEPEND="${LUA_DEPS}" +# RDEPEND="${DEPEND} +# $(lua_gen_cond_dep ' +# dev-lua/foo[${LUA_USEDEP}] +# ') +# " +# BDEPEND="virtual/pkgconfig" +# +# # Only neeed if the setup phase has to do more than just call lua-single_pkg_setup +# pkg_setup() { +# lua-single_pkg_setup +# [...] +# } +# +# src_install() { +# emake LUA_VERSION="$(lua_get_version)" install +# } +# @CODE + +case ${EAPI:-0} in + 0|1|2|3|4|5|6) + die "Unsupported EAPI=${EAPI} (too old) for ${ECLASS}" + ;; + 7) + ;; + *) + die "Unsupported EAPI=${EAPI} (unknown) for ${ECLASS}" + ;; +esac + +if [[ ! ${_LUA_SINGLE_R0} ]]; then + +if [[ ${_LUA_R0} ]]; then + die 'lua-single.eclass cannot be used with lua.eclass.' +fi + +inherit lua-utils + +fi + +EXPORT_FUNCTIONS pkg_setup + +# @ECLASS-VARIABLE: LUA_COMPAT +# @REQUIRED +# @PRE_INHERIT +# @DESCRIPTION: +# This variable contains a list of Lua implementations the package +# supports. It must be set before the `inherit' call. It has to be +# an array. +# +# Example: +# @CODE +# LUA_COMPAT=( lua5-1 lua5-2 lua5-3 ) +# @CODE +# +# Please note that you can also use bash brace expansion if you like: +# @CODE +# LUA_COMPAT=( lua5-{1..3} ) +# @CODE + +# @ECLASS-VARIABLE: LUA_COMPAT_OVERRIDE +# @USER_VARIABLE +# @DEFAULT_UNSET +# @DESCRIPTION: +# This variable can be used when working with ebuilds to override +# the in-ebuild LUA_COMPAT. It is a string listing all +# the implementations which package will be built for. It need be +# specified in the calling environment, and not in ebuilds. +# +# It should be noted that in order to preserve metadata immutability, +# LUA_COMPAT_OVERRIDE does not affect IUSE nor dependencies. +# The state of LUA_TARGETS is ignored, and all the implementations +# in LUA_COMPAT_OVERRIDE are built. Dependencies need to be satisfied +# manually. +# +# Example: +# @CODE +# LUA_COMPAT_OVERRIDE='lua5-2' emerge -1v dev-lua/foo +# @CODE + +# @ECLASS-VARIABLE: LUA_REQ_USE +# @DEFAULT_UNSET +# @PRE_INHERIT +# @DESCRIPTION: +# The list of USE flags required to be enabled on the chosen Lua +# implementations, formed as a USE-dependency string. It should be valid +# for all implementations in LUA_COMPAT, so it may be necessary to +# use USE defaults. +# This must be set before calling `inherit'. +# +# Example: +# @CODE +# LUA_REQ_USE="deprecated" +# @CODE +# +# It will cause the Lua dependencies to look like: +# @CODE +# lua_targets_luaX-Y? ( dev-lang/lua:X.Y[deprecated] ) +# @CODE + +# @ECLASS-VARIABLE: LUA_DEPS +# @OUTPUT_VARIABLE +# @DESCRIPTION: +# This is an eclass-generated Lua dependency string for all +# implementations listed in LUA_COMPAT. +# +# Example use: +# @CODE +# RDEPEND="${LUA_DEPS} +# dev-foo/mydep" +# DEPEND="${RDEPEND}" +# @CODE +# +# Example value: +# @CODE +# lua_targets_lua5-1? ( dev-lang/lua:5.1 ) +# lua_targets_lua5-2? ( dev-lang/lua:5.2 ) +# @CODE + +# @ECLASS-VARIABLE: LUA_REQUIRED_USE +# @OUTPUT_VARIABLE +# @DESCRIPTION: +# This is an eclass-generated required-use expression which ensures at +# least one Lua implementation has been enabled. +# +# This expression should be utilized in an ebuild by including it in +# REQUIRED_USE, optionally behind a use flag. +# +# Example use: +# @CODE +# REQUIRED_USE="lua? ( ${LUA_REQUIRED_USE} )" +# @CODE +# +# Example value: +# @CODE +# || ( lua_targets_lua5-1 lua_targets_lua5-2 ) +# @CODE + +# @ECLASS-VARIABLE: LUA_SINGLE_USEDEP +# @OUTPUT_VARIABLE +# @DESCRIPTION: +# This is an eclass-generated USE-dependency string which can be used +# to depend on another lua-single package being built for the same +# Lua implementations. +# +# If you need to depend on a multi-impl (lua.eclass) package, use +# lua_gen_cond_dep with LUA_USEDEP placeholder instead. +# +# Example use: +# @CODE +# RDEPEND="dev-lua/foo[${LUA_SINGLE_USEDEP}]" +# @CODE +# +# Example value: +# @CODE +# lua_single_target_lua5-1(-)? +# @CODE + +# @ECLASS-VARIABLE: LUA_USEDEP +# @OUTPUT_VARIABLE +# @DESCRIPTION: +# This is an eclass-generated USE-dependency string which can be used to +# depend on another Lua package being built for the same Lua +# implementations. +# +# Example use: +# @CODE +# RDEPEND="dev-lua/foo[${LUA_USEDEP}]" +# @CODE +# +# Example value: +# @CODE +# lua_targets_lua5-1(-)?,lua_targets_lua5-2(-)? +# @CODE + +# @FUNCTION: _lua_single_set_globals +# @INTERNAL +# @DESCRIPTION: +# Sets all the global output variables provided by this eclass. +# This function must be called once, in global scope. +_lua_single_set_globals() { + _lua_set_impls + + local flags=( "${_LUA_SUPPORTED_IMPLS[@]/#/lua_single_target_}" ) + + if [[ ${#_LUA_SUPPORTED_IMPLS[@]} -eq 1 ]]; then + # if only one implementation is supported, use IUSE defaults + # to avoid requesting the user to enable it + IUSE="+${flags[0]}" + else + IUSE="${flags[*]}" + fi + + local requse="^^ ( ${flags[*]} )" + local single_flags="${flags[@]/%/(-)?}" + local single_usedep=${single_flags// /,} + + local deps= i LUA_PKG_DEP + for i in "${_LUA_SUPPORTED_IMPLS[@]}"; do + _lua_export "${i}" LUA_PKG_DEP + deps+="lua_single_target_${i}? ( ${LUA_PKG_DEP} ) " + done + + if [[ ${LUA_DEPS+1} ]]; then + if [[ ${LUA_DEPS} != "${deps}" ]]; then + eerror "LUA_DEPS have changed between inherits (LUA_REQ_USE?)!" + eerror "Before: ${LUA_DEPS}" + eerror "Now : ${deps}" + die "LUA_DEPS integrity check failed" + fi + + # these two are formality -- they depend on LUA_COMPAT only + if [[ ${LUA_REQUIRED_USE} != ${requse} ]]; then + eerror "LUA_REQUIRED_USE have changed between inherits!" + eerror "Before: ${LUA_REQUIRED_USE}" + eerror "Now : ${requse}" + die "LUA_REQUIRED_USE integrity check failed" + fi + + if [[ ${LUA_SINGLE_USEDEP} != "${single_usedep}" ]]; then + eerror "LUA_SINGLE_USEDEP have changed between inherits!" + eerror "Before: ${LUA_SINGLE_USEDEP}" + eerror "Now : ${single_usedep}" + die "LUA_SINGLE_USEDEP integrity check failed" + fi + else + LUA_DEPS=${deps} + LUA_REQUIRED_USE=${requse} + LUA_SINGLE_USEDEP=${single_usedep} + LUA_USEDEP='%LUA_USEDEP-NEEDS-TO-BE-USED-IN-LUA_GEN_COND_DEP%' + readonly LUA_DEPS LUA_REQUIRED_USE LUA_SINGLE_USEDEP LUA_USEDEP + fi +} + +_lua_single_set_globals +unset -f _lua_single_set_globals + +if [[ ! ${_LUA_SINGLE_R0} ]]; then + +# @FUNCTION: _lua_gen_usedep +# @USAGE: [<pattern>...] +# @INTERNAL +# @DESCRIPTION: +# Output a USE dependency string for Lua implementations which +# are both in LUA_COMPAT and match any of the patterns passed +# as parameters to the function. +# +# The patterns can be fnmatch-style patterns (matched via bash == operator +# against LUA_COMPAT values). Remember to escape or quote the fnmatch +# patterns to prevent accidental shell filename expansion. +# +# This is an internal function used to implement lua_gen_cond_dep. +_lua_gen_usedep() { + debug-print-function ${FUNCNAME} "${@}" + + local impl matches=() + + _lua_verify_patterns "${@}" + for impl in "${_LUA_SUPPORTED_IMPLS[@]}"; do + if _lua_impl_matches "${impl}" "${@}"; then + matches+=( + "lua_single_target_${impl}(-)?" + ) + fi + done + + [[ ${matches[@]} ]] || die "No supported implementations match lua_gen_usedep patterns: ${@}" + + local out=${matches[@]} + echo "${out// /,}" +} + +# @FUNCTION: _lua_impl_matches +# @USAGE: <impl> [<pattern>...] +# @INTERNAL +# @DESCRIPTION: +# Check whether the specified <impl> matches at least one +# of the patterns following it. Return 0 if it does, 1 otherwise. +# Matches if no patterns are provided. +# +# <impl> can be in LUA_COMPAT or ELUA form. The patterns can be +# fnmatch-style patterns, e.g. 'lua5*', '.. +_lua_impl_matches() { + [[ ${#} -ge 1 ]] || die "${FUNCNAME}: takes at least 1 parameter" + [[ ${#} -eq 1 ]] && return 0 + + local impl=${1} pattern + shift + + for pattern; do + # unify value style to allow lax matching + if [[ ${impl/./-} == ${pattern/./-} ]]; then + return 0 + fi + done + + return 1 +} + +# @FUNCTION: _lua_verify_patterns +# @USAGE: <pattern>... +# @INTERNAL +# @DESCRIPTION: +# Verify whether the patterns passed to the eclass function are correct +# (i.e. can match any valid implementation). Dies on wrong pattern. +_lua_verify_patterns() { + debug-print-function ${FUNCNAME} "${@}" + + local impl pattern + for pattern; do + for impl in "${_LUA_ALL_IMPLS[@]}"; do + [[ ${impl} == ${pattern/./-} ]] && continue 2 + done + + die "Invalid implementation pattern: ${pattern}" + done +} + +# @FUNCTION: lua_gen_cond_dep +# @USAGE: <dependency> [<pattern>...] +# @DESCRIPTION: +# Output a list of <dependency>-ies made conditional to USE flags +# of Lua implementations which are both in LUA_COMPAT and match +# any of the patterns passed as the remaining parameters. +# +# The patterns can be fnmatch-style patterns (matched via bash == operator +# against LUA_COMPAT values). Remember to escape or quote the fnmatch +# patterns to prevent accidental shell filename expansion. +# +# In order to enforce USE constraints on the packages, verbatim +# '${LUA_SINGLE_USEDEP}' and '${LUA_USEDEP}' (quoted!) may +# be placed in the dependency specification. It will get expanded within +# the function into a proper USE dependency string. +# +# Example: +# @CODE +# LUA_COMPAT=( lua5-{1..3} ) +# RDEPEND="$(lua_gen_cond_dep \ +# 'dev-lua/backported_core_module[${LUA_USEDEP}]' lua5-1 lua5-2 )" +# @CODE +# +# It will cause the variable to look like: +# @CODE +# RDEPEND="lua_single_target_lua5-1? ( +# dev-lua/backported_core_module[lua_targets_lua5-1(-)?,...] ) +# lua_single_target_lua5-2? ( +# dev-lua/backported_core_module[lua_targets_lua5-2(-)?,...] )" +# @CODE +lua_gen_cond_dep() { + debug-print-function ${FUNCNAME} "${@}" + + local impl matches=() + + local dep=${1} + shift + + _lua_verify_patterns "${@}" + for impl in "${_LUA_SUPPORTED_IMPLS[@]}"; do + if _lua_impl_matches "${impl}" "${@}"; then + # substitute ${LUA_SINGLE_USEDEP} if used + # (since lua_gen_usedep() will not return + # ${LUA_SINGLE_USEDEP}, the code is run at most once) + if [[ ${dep} == *'${LUA_SINGLE_USEDEP}'* ]]; then + local usedep=$(_lua_gen_usedep "${@}") + dep=${dep//\$\{LUA_SINGLE_USEDEP\}/${usedep}} + fi + local multi_usedep="lua_targets_${impl}(-)" + + local subdep=${dep//\$\{LUA_MULTI_USEDEP\}/${multi_usedep}} + matches+=( "lua_single_target_${impl}? ( + ${subdep//\$\{LUA_USEDEP\}/${multi_usedep}} )" ) + fi + done + + echo "${matches[@]}" +} + +# @FUNCTION: lua_gen_impl_dep +# @USAGE: [<requested-use-flags> [<impl-pattern>...]] +# @DESCRIPTION: +# Output a dependency on Lua implementations with the specified USE +# dependency string appended, or no USE dependency string if called +# without the argument (or with empty argument). If any implementation +# patterns are passed, the output dependencies will be generated only +# for the implementations matching them. +# +# The patterns can be fnmatch-style patterns (matched via bash == operator +# against LUA_COMPAT values). Remember to escape or quote the fnmatch +# patterns to prevent accidental shell filename expansion. +# +# Use this function when you need to request different USE flags +# on the Lua interpreter depending on package's USE flags. If you +# only need a single set of interpreter USE flags, just set +# LUA_REQ_USE and use ${LUA_DEPS} globally. +# +# Example: +# @CODE +# LUA_COMPAT=( lua5-{1..3} ) +# RDEPEND="foo? ( $(lua_gen_impl_dep 'deprecated(+)' lua5-3 ) )" +# @CODE +# +# It will cause the variable to look like: +# @CODE +# RDEPEND="foo? ( +# lua_single_target_lua5-3? ( dev-lang/lua:5.3[deprecated(+)] ) +# )" +# @CODE +lua_gen_impl_dep() { + debug-print-function ${FUNCNAME} "${@}" + + local impl + local matches=() + + local LUA_REQ_USE=${1} + shift + + _lua_verify_patterns "${@}" + for impl in "${_LUA_SUPPORTED_IMPLS[@]}"; do + if _lua_impl_matches "${impl}" "${@}"; then + local LUA_PKG_DEP + _lua_export "${impl}" LUA_PKG_DEP + matches+=( "lua_single_target_${impl}? ( ${LUA_PKG_DEP} )" ) + fi + done + + echo "${matches[@]}" +} + +# @FUNCTION: lua_setup +# @DESCRIPTION: +# Determine what the selected Lua implementation is and set +# the Lua build environment up for it. +lua_setup() { + debug-print-function ${FUNCNAME} "${@}" + + unset ELUA + + # support developer override + if [[ ${LUA_COMPAT_OVERRIDE} ]]; then + local impls=( ${LUA_COMPAT_OVERRIDE} ) + [[ ${#impls[@]} -eq 1 ]] || die "LUA_COMPAT_OVERRIDE must name exactly one implementation for lua-single" + + ewarn "WARNING: LUA_COMPAT_OVERRIDE in effect. The following Lua" + ewarn "implementation will be used:" + ewarn + ewarn " ${LUA_COMPAT_OVERRIDE}" + ewarn + ewarn "Dependencies won't be satisfied, and LUA_SINGLE_TARGET flags will be ignored." + + _lua_export "${impls[0]}" ELUA LUA + _lua_wrapper_setup + einfo "Using ${ELUA} to build" + return + fi + + local impl + for impl in "${_LUA_SUPPORTED_IMPLS[@]}"; do + if use "lua_single_target_${impl}"; then + if [[ ${ELUA} ]]; then + eerror "Your LUA_SINGLE_TARGET setting lists more than a single Lua" + eerror "implementation. Please set it to just one value. If you need" + eerror "to override the value for a single package, please use package.env" + eerror "or an equivalent solution (man 5 portage)." + echo + die "More than one implementation in LUA_SINGLE_TARGET." + fi + + _lua_export "${impl}" ELUA LUA + _lua_wrapper_setup + einfo "Using ${ELUA} to build" + fi + done + + if [[ ! ${ELUA} ]]; then + eerror "No Lua implementation selected for the build. Please set" + eerror "the LUA_SINGLE_TARGET variable in your make.conf to one" + eerror "of the following values:" + eerror + eerror "${_LUA_SUPPORTED_IMPLS[@]}" + echo + die "No supported Lua implementation in LUA_SINGLE_TARGET." + fi +} + +# @FUNCTION: lua-single_pkg_setup +# @DESCRIPTION: +# Runs lua_setup. +lua-single_pkg_setup() { + debug-print-function ${FUNCNAME} "${@}" + + [[ ${MERGE_TYPE} != binary ]] && lua_setup +} + +_LUA_SINGLE_R0=1 +fi diff --git a/eclass/lua-utils.eclass b/eclass/lua-utils.eclass new file mode 100644 index 0000000..0589318 --- /dev/null +++ b/eclass/lua-utils.eclass @@ -0,0 +1,532 @@ +# Copyright 1999-2020 Gentoo Authors +# Distributed under the terms of the GNU General Public License v2 + +# @ECLASS: lua-utils.eclass +# @MAINTAINER: +# William Hubbs <williamh@gentoo.org> +# Marek Szuba <marecki@gentoo.org> +# @AUTHOR: +# Marek Szuba <marecki@gentoo.org> +# Based on python-utils-r1.eclass by Michał Górny <mgorny@gentoo.org> et al. +# @SUPPORTED_EAPIS: 7 +# @BLURB: Utility functions for packages with Lua parts +# @DESCRIPTION: +# A utility eclass providing functions to query Lua implementations, +# install Lua modules and scripts. +# +# This eclass neither sets any metadata variables nor exports any phase +# functions. It can be inherited safely. + +case ${EAPI:-0} in + 0|1|2|3|4|5|6) + die "Unsupported EAPI=${EAPI} (too old) for ${ECLASS}" + ;; + 7) + ;; + *) + die "Unsupported EAPI=${EAPI} (unknown) for ${ECLASS}" + ;; +esac + +if [[ ! ${_LUA_UTILS_R0} ]]; then + +inherit toolchain-funcs + +# @ECLASS-VARIABLE: _LUA_ALL_IMPLS +# @INTERNAL +# @DESCRIPTION: +# All supported Lua implementations, most preferred last +_LUA_ALL_IMPLS=( + luajit + lua5-1 + lua5-2 + lua5-3 + lua5-4 +) +readonly _LUA_ALL_IMPLS + +# @FUNCTION: _lua_set_impls +# @INTERNAL +# @DESCRIPTION: +# Check LUA_COMPAT for well-formedness and validity, then set +# two global variables: +# +# - _LUA_SUPPORTED_IMPLS containing valid implementations supported +# by the ebuild (LUA_COMPAT minus dead implementations), +# +# - and _LUA_UNSUPPORTED_IMPLS containing valid implementations that +# are not supported by the ebuild. +# +# Implementations in both variables are ordered using the pre-defined +# eclass implementation ordering. +# +# This function must only be called once. +_lua_set_impls() { + local i + + if ! declare -p LUA_COMPAT &>/dev/null; then + die 'LUA_COMPAT not declared.' + fi + if [[ $(declare -p LUA_COMPAT) != "declare -a"* ]]; then + die 'LUA_COMPAT must be an array.' + fi + + local supp=() unsupp=() + + for i in "${_LUA_ALL_IMPLS[@]}"; do + if has "${i}" "${LUA_COMPAT[@]}"; then + supp+=( "${i}" ) + else + unsupp+=( "${i}" ) + fi + done + + if [[ ! ${supp[@]} ]]; then + die "No supported implementation in LUA_COMPAT." + fi + + if [[ ${_LUA_SUPPORTED_IMPLS[@]} ]]; then + # set once already, verify integrity + if [[ ${_LUA_SUPPORTED_IMPLS[@]} != ${supp[@]} ]]; then + eerror "Supported impls (LUA_COMPAT) changed between inherits!" + eerror "Before: ${_LUA_SUPPORTED_IMPLS[*]}" + eerror "Now : ${supp[*]}" + die "_LUA_SUPPORTED_IMPLS integrity check failed" + fi + if [[ ${_LUA_UNSUPPORTED_IMPLS[@]} != ${unsupp[@]} ]]; then + eerror "Unsupported impls changed between inherits!" + eerror "Before: ${_LUA_UNSUPPORTED_IMPLS[*]}" + eerror "Now : ${unsupp[*]}" + die "_LUA_UNSUPPORTED_IMPLS integrity check failed" + fi + else + _LUA_SUPPORTED_IMPLS=( "${supp[@]}" ) + _LUA_UNSUPPORTED_IMPLS=( "${unsupp[@]}" ) + readonly _LUA_SUPPORTED_IMPLS _LUA_UNSUPPORTED_IMPLS + fi +} + +# @FUNCTION: _lua_wrapper_setup +# @USAGE: [<path> [<impl>]] +# @INTERNAL +# @DESCRIPTION: +# Create proper Lua executables and pkg-config wrappers +# (if available) in the directory named by <path>. Set up PATH +# and PKG_CONFIG_PATH appropriately. <path> defaults to ${T}/${ELUA}. +# +# The wrappers will be created for implementation named by <impl>, +# or for one named by ${ELUA} if no <impl> passed. +# +# If the named directory contains a lua symlink already, it will +# be assumed to contain proper wrappers already and only environment +# setup will be done. If wrapper update is requested, the directory +# shall be removed first. +_lua_wrapper_setup() { + debug-print-function ${FUNCNAME} "${@}" + + local workdir=${1:-${T}/${ELUA}} + local impl=${2:-${ELUA}} + + [[ ${workdir} ]] || die "${FUNCNAME}: no workdir specified." + [[ ${impl} ]] || die "${FUNCNAME}: no impl nor ELUA specified." + + if [[ ! -x ${workdir}/bin/lua ]]; then + mkdir -p "${workdir}"/{bin,pkgconfig} || die + + # Clean up, in case we were supposed to do a cheap update + rm -f "${workdir}"/bin/lua{,c} || die + rm -f "${workdir}"/pkgconfig/lua.pc || die + + local ELUA LUA + _lua_export "${impl}" ELUA LUA + + # Lua interpreter + ln -s "${EPREFIX}"/usr/bin/${ELUA} "${workdir}"/bin/lua || die + + # Lua compiler, or a stub for it in case of luajit + if [[ ${ELUA} == luajit ]]; then + # Just in case + ln -s "${EPREFIX}"/bin/true "${workdir}"/bin/luac || die + else + ln -s "${EPREFIX}"/usr/bin/${ELUA/a/ac} "${workdir}"/bin/luac || die + fi + + # pkg-config + ln -s "${EPREFIX}"/usr/$(get_libdir)/pkgconfig/${ELUA}.pc \ + "${workdir}"/pkgconfig/lua.pc || die + fi + + # Now, set the environment. + # But note that ${workdir} may be shared with something else, + # and thus already on top of PATH. + if [[ ${PATH##:*} != ${workdir}/bin ]]; then + PATH=${workdir}/bin${PATH:+:${PATH}} + fi + if [[ ${PKG_CONFIG_PATH##:*} != ${workdir}/pkgconfig ]]; then + PKG_CONFIG_PATH=${workdir}/pkgconfig${PKG_CONFIG_PATH:+:${PKG_CONFIG_PATH}} + fi + export PATH PKG_CONFIG_PATH +} + +# @ECLASS-VARIABLE: ELUA +# @DEFAULT_UNSET +# @DESCRIPTION: +# The executable name of the current Lua interpreter. This variable is set +# automatically in functions called by lua_foreach_impl(). +# +# Example value: +# @CODE +# lua5.1 +# @CODE + +# @ECLASS-VARIABLE: LUA +# @DEFAULT_UNSET +# @DESCRIPTION: +# The absolute path to the current Lua interpreter. This variable is set +# automatically in functions called by lua_foreach_impl(). +# +# Example value: +# @CODE +# /usr/bin/lua5.1 +# @CODE + +# @FUNCTION: _lua_get_library_file +# @USAGE: <impl> +# @INTERNAL +# @DESCRIPTION: +# Get the core part (i.e. without the extension) of the library name, +# with path, of the given Lua implementation. +# Used internally by _lua_export(). +_lua_get_library_file() { + local impl="${1}" + local libdir libname + + case ${impl} in + luajit) + libname=lib$($(tc-getPKG_CONFIG) --variable libname ${impl}) || die + ;; + lua*) + libname=lib${impl} + ;; + *) + die "Invalid implementation: ${impl}" + ;; + esac + libdir=$($(tc-getPKG_CONFIG) --variable libdir ${impl}) || die + + debug-print "${FUNCNAME}: libdir = ${libdir}, libname = ${libname}" + echo "${libdir}/${libname}" +} + +# @FUNCTION: _lua_export +# @USAGE: [<impl>] <variables>... +# @INTERNAL +# @DESCRIPTION: +# Set and export the Lua implementation-relevant variables passed +# as parameters. +# +# The optional first parameter may specify the requested Lua +# implementation (either as LUA_TARGETS value, e.g. lua5-2, +# or an ELUA one, e.g. lua5.2). If no implementation passed, +# the current one will be obtained from ${ELUA}. +_lua_export() { + debug-print-function ${FUNCNAME} "${@}" + + local impl var + + case "${1}" in + luajit) + impl=${1} + shift + ;; + lua*) + impl=${1/-/.} + shift + ;; + *) + impl=${ELUA} + if [[ -z ${impl} ]]; then + die "_lua_export called without a Lua implementation and ELUA is unset" + fi + ;; + esac + debug-print "${FUNCNAME}: implementation: ${impl}" + + for var; do + case "${var}" in + ELUA) + export ELUA=${impl} + debug-print "${FUNCNAME}: ELUA = ${ELUA}" + ;; + LUA) + export LUA="${EPREFIX}"/usr/bin/${impl} + debug-print "${FUNCNAME}: LUA = ${LUA}" + ;; + LUA_CFLAGS) + local val + + val=$($(tc-getPKG_CONFIG) --cflags ${impl}) || die + + export LUA_CFLAGS=${val} + debug-print "${FUNCNAME}: LUA_CFLAGS = ${LUA_CFLAGS}" + ;; + LUA_CMOD_DIR) + local val + + val=$($(tc-getPKG_CONFIG) --variable INSTALL_CMOD ${impl}) || die + + export LUA_CMOD_DIR=${val} + debug-print "${FUNCNAME}: LUA_CMOD_DIR = ${LUA_CMOD_DIR}" + ;; + LUA_INCLUDE_DIR) + local val + + val=$($(tc-getPKG_CONFIG) --variable includedir ${impl}) || die + + export LUA_INCLUDE_DIR=${val} + debug-print "${FUNCNAME}: LUA_INCLUDE_DIR = ${LUA_INCLUDE_DIR}" + ;; + LUA_LIBS) + local val + + val=$($(tc-getPKG_CONFIG) --libs ${impl}) || die + + export LUA_LIBS=${val} + debug-print "${FUNCNAME}: LUA_LIBS = ${LUA_LIBS}" + ;; + LUA_LMOD_DIR) + local val + + val=$($(tc-getPKG_CONFIG) --variable INSTALL_LMOD ${impl}) || die + + export LUA_LMOD_DIR=${val} + debug-print "${FUNCNAME}: LUA_LMOD_DIR = ${LUA_LMOD_DIR}" + ;; + LUA_PKG_DEP) + local d + case ${impl} in + luajit) + LUA_PKG_DEP="dev-lang/luajit:=" + ;; + lua*) + LUA_PKG_DEP="dev-lang/lua:${impl#lua}" + ;; + *) + die "Invalid implementation: ${impl}" + ;; + esac + + # use-dep + if [[ ${LUA_REQ_USE} ]]; then + LUA_PKG_DEP+=[${LUA_REQ_USE}] + fi + + export LUA_PKG_DEP + debug-print "${FUNCNAME}: LUA_PKG_DEP = ${LUA_PKG_DEP}" + ;; + LUA_SHARED_LIB) + local val=$(_lua_get_library_file ${impl}) + export LUA_SHARED_LIB="${val}".so + debug-print "${FUNCNAME}: LUA_SHARED_LIB = ${LUA_SHARED_LIB}" + ;; + LUA_VERSION) + local val + + val=$($(tc-getPKG_CONFIG) --modversion ${impl}) || die + + export LUA_VERSION=${val} + debug-print "${FUNCNAME}: LUA_VERSION = ${LUA_VERSION}" + ;; + *) + die "_lua_export: unknown variable ${var}" + ;; + esac + done +} + +# @FUNCTION: lua_enable_tests +# @USAGE: <test-runner> <test-directory> +# @DESCRIPTION: +# Set up IUSE, RESTRICT, BDEPEND and src_test() for running tests +# with the specified test runner. Also copies the current value +# of RDEPEND to test?-BDEPEND. The test-runner argument must be one of: +# +# - busted: dev-lua/busted +# +# Additionally, a second argument can be passed after <test-runner>, +# so <test-runner> will use that directory to search for tests. +# If not passed, a default directory of <test-runner> will be used. +# +# - busted: spec +# +# This function is meant as a helper for common use cases, and it only +# takes care of basic setup. You still need to list additional test +# dependencies manually. If you have uncommon use case, you should +# not use it and instead enable tests manually. +# +# This function must be called in global scope, after RDEPEND has been +# declared. Take care not to overwrite the variables set by it. +lua_enable_tests() { + debug-print-function ${FUNCNAME} "${@}" + + [[ ${#} -ge 1 ]] || die "${FUNCNAME} takes at least one argument: test-runner (test-directory)" + local test_directory + local test_pkg + case ${1} in + busted) + test_directory="${2:-spec}" + test_pkg="dev-lua/busted" + if [[ ! ${_LUA_SINGLE_R0} ]]; then + eval "lua_src_test() { + busted --lua=\"\${ELUA}\" --output=\"plainTerminal\" \"${test_directory}\" || die \"Tests fail with \${ELUA}\" + }" + src_test() { + lua_foreach_impl lua_src_test + } + else + eval "src_test() { + busted --lua=\"\${ELUA}\" --output=\"plainTerminal\" \"${test_directory}\" || die \"Tests fail with \${ELUA}\" + }" + fi + ;; + *) + die "${FUNCNAME}: unsupported argument: ${1}" + esac + + local test_deps=${RDEPEND} + if [[ -n ${test_pkg} ]]; then + if [[ ! ${_LUA_SINGLE_R0} ]]; then + test_deps+=" ${test_pkg}[${LUA_USEDEP}]" + else + test_deps+=" $(lua_gen_cond_dep " + ${test_pkg}[\${LUA_USEDEP}] + ")" + fi + fi + if [[ -n ${test_deps} ]]; then + IUSE+=" test" + RESTRICT+=" !test? ( test )" + BDEPEND+=" test? ( ${test_deps} )" + fi + + # we need to ensure successful return in case we're called last, + # otherwise Portage may wrongly assume sourcing failed + return 0 +} + +# @FUNCTION: lua_get_CFLAGS +# @USAGE: [<impl>] +# @DESCRIPTION: +# Obtain and print the compiler flags for building against Lua, +# for the given implementation. If no implementation is provided, +# ${ELUA} will be used. +# +# Please note that this function requires Lua and pkg-config installed, +# and therefore proper build-time dependencies need be added to the ebuild. +lua_get_CFLAGS() { + debug-print-function ${FUNCNAME} "${@}" + + _lua_export "${@}" LUA_CFLAGS + echo "${LUA_CFLAGS}" +} + +# @FUNCTION: lua_get_cmod_dir +# @USAGE: [<impl>] +# @DESCRIPTION: +# Obtain and print the name of the directory into which compiled Lua +# modules are installed, for the given implementation. If no implementation +# is provided, ${ELUA} will be used. +# +# Please note that this function requires Lua and pkg-config installed, +# and therefore proper build-time dependencies need be added to the ebuild. +lua_get_cmod_dir() { + debug-print-function ${FUNCNAME} "${@}" + + _lua_export "${@}" LUA_CMOD_DIR + echo "${LUA_CMOD_DIR}" +} + +# @FUNCTION: lua_get_include_dir +# @USAGE: [<impl>] +# @DESCRIPTION: +# Obtain and print the name of the directory containing header files +# of the given Lua implementation. If no implementation is provided, +# ${ELUA} will be used. +# +# Please note that this function requires Lua and pkg-config installed, +# and therefore proper build-time dependencies need be added to the ebuild. +lua_get_include_dir() { + debug-print-function ${FUNCNAME} "${@}" + + _lua_export "${@}" LUA_INCLUDE_DIR + echo "${LUA_INCLUDE_DIR}" +} + +# @FUNCTION: lua_get_LIBS +# @USAGE: [<impl>] +# @DESCRIPTION: +# Obtain and print the compiler flags for linking against Lua, +# for the given implementation. If no implementation is provided, +# ${ELUA} will be used. +# +# Please note that this function requires Lua and pkg-config installed, +# and therefore proper build-time dependencies need be added to the ebuild. +lua_get_LIBS() { + debug-print-function ${FUNCNAME} "${@}" + + _lua_export "${@}" LUA_LIBS + echo "${LUA_LIBS}" +} + +# @FUNCTION: lua_get_lmod_dir +# @USAGE: [<impl>] +# @DESCRIPTION: +# Obtain and print the name of the directory into which native-Lua +# modules are installed, for the given implementation. If no implementation +# is provided, ${ELUA} will be used. +# +# Please note that this function requires Lua and pkg-config installed, +# and therefore proper build-time dependencies need be added to the ebuild. +lua_get_lmod_dir() { + debug-print-function ${FUNCNAME} "${@}" + + _lua_export "${@}" LUA_LMOD_DIR + echo "${LUA_LMOD_DIR}" +} + +# @FUNCTION: lua_get_shared_lib +# @USAGE: [<impl>] +# @DESCRIPTION: +# Obtain and print the expected name, with path, of the main shared library +# of the given Lua implementation. If no implementation is provided, +# ${ELUA} will be used. +# +# Note that it is up to the ebuild maintainer to ensure Lua actually +# provides a shared library. +# +# Please note that this function requires Lua and pkg-config installed, +# and therefore proper build-time dependencies need be added to the ebuild. +lua_get_shared_lib() { + debug-print-function ${FUNCNAME} "${@}" + + _lua_export "${@}" LUA_SHARED_LIB + echo "${LUA_SHARED_LIB}" +} + +# @FUNCTION: lua_get_version +# @USAGE: [<impl>] +# @DESCRIPTION: +# Obtain and print the full version number of the given Lua implementation. +# If no implementation is provided, ${ELUA} will be used. +# +# Please note that this function requires Lua and pkg-config installed, +# and therefore proper build-time dependencies need be added to the ebuild. +lua_get_version() { + debug-print-function ${FUNCNAME} "${@}" + + _lua_export "${@}" LUA_VERSION + echo "${LUA_VERSION}" +} + +_LUA_UTILS_R0=1 +fi diff --git a/eclass/lua.eclass b/eclass/lua.eclass new file mode 100644 index 0000000..46d9e84 --- /dev/null +++ b/eclass/lua.eclass @@ -0,0 +1,381 @@ +# Copyright 1999-2020 Gentoo Authors +# Distributed under the terms of the GNU General Public License v2 + +# @ECLASS: lua.eclass +# @MAINTAINER: +# William Hubbs <williamh@gentoo.org> +# Marek Szuba <marecki@gentoo.org> +# @AUTHOR: +# Marek Szuba <marecki@gentoo.org> +# Based on python-r1.eclass by Michał Górny <mgorny@gentoo.org> et al. +# @SUPPORTED_EAPIS: 7 +# @BLURB: A common eclass for Lua packages +# @DESCRIPTION: +# A common eclass providing helper functions to build and install +# packages supporting being installed for multiple Lua implementations. +# +# This eclass sets correct IUSE. Modification of REQUIRED_USE has to +# be done by the author of the ebuild (but LUA_REQUIRED_USE is +# provided for convenience, see below). The eclass exports LUA_DEPS +# and LUA_USEDEP so you can create correct dependencies for your +# package easily. It also provides methods to easily run a command for +# each enabled Lua implementation and duplicate the sources for them. +# +# Note that since this eclass always inherits lua-utils as well, in ebuilds +# using the former there is no need to explicitly inherit the latter in order +# to use helper functions such as lua_get_CFLAGS. +# +# @EXAMPLE: +# @CODE +# EAPI=7 +# +# LUA_COMPAT=( lua5-{1..3} ) +# +# inherit lua +# +# [...] +# +# REQUIRED_USE="${LUA_REQUIRED_USE}" +# DEPEND="${LUA_DEPS}" +# RDEPEND="${DEPEND} +# dev-lua/foo[${LUA_USEDEP}]" +# BDEPEND="virtual/pkgconfig" +# +# lua_src_install() { +# emake LUA_VERSION="$(lua_get_version)" install +# } +# +# src_install() { +# lua_foreach_impl lua_src_install +# } +# @CODE + +case ${EAPI:-0} in + 0|1|2|3|4|5|6) + die "Unsupported EAPI=${EAPI} (too old) for ${ECLASS}" + ;; + 7) + ;; + *) + die "Unsupported EAPI=${EAPI} (unknown) for ${ECLASS}" + ;; +esac + +if [[ ! ${_LUA_R0} ]]; then + +if [[ ${_LUA_SINGLE_R0} ]]; then + die 'lua.eclass cannot be used with lua-single.eclass.' +fi + +inherit multibuild lua-utils + +fi + +# @ECLASS-VARIABLE: LUA_COMPAT +# @REQUIRED +# @PRE_INHERIT +# @DESCRIPTION: +# This variable contains a list of Lua implementations the package +# supports. It must be set before the `inherit' call. It has to be +# an array. +# +# Example: +# @CODE +# LUA_COMPAT=( lua5-1 lua5-2 lua5-3 ) +# @CODE +# +# Please note that you can also use bash brace expansion if you like: +# @CODE +# LUA_COMPAT=( lua5-{1..3} ) +# @CODE + +# @ECLASS-VARIABLE: LUA_COMPAT_OVERRIDE +# @USER_VARIABLE +# @DEFAULT_UNSET +# @DESCRIPTION: +# This variable can be used when working with ebuilds to override +# the in-ebuild LUA_COMPAT. It is a string listing all +# the implementations which package will be built for. It need be +# specified in the calling environment, and not in ebuilds. +# +# It should be noted that in order to preserve metadata immutability, +# LUA_COMPAT_OVERRIDE does not affect IUSE nor dependencies. +# The state of LUA_TARGETS is ignored, and all the implementations +# in LUA_COMPAT_OVERRIDE are built. Dependencies need to be satisfied +# manually. +# +# Example: +# @CODE +# LUA_COMPAT_OVERRIDE='lua5-2' emerge -1v dev-lua/foo +# @CODE + +# @ECLASS-VARIABLE: LUA_REQ_USE +# @DEFAULT_UNSET +# @PRE_INHERIT +# @DESCRIPTION: +# The list of USE flags required to be enabled on the chosen Lua +# implementations, formed as a USE-dependency string. It should be valid +# for all implementations in LUA_COMPAT, so it may be necessary to +# use USE defaults. +# This must be set before calling `inherit'. +# +# Example: +# @CODE +# LUA_REQ_USE="deprecated" +# @CODE +# +# It will cause the Lua dependencies to look like: +# @CODE +# lua_targets_luaX-Y? ( dev-lang/lua:X.Y[deprecated] ) +# @CODE + +# @ECLASS-VARIABLE: BUILD_DIR +# @OUTPUT_VARIABLE +# @DEFAULT_UNSET +# @DESCRIPTION: +# The current build directory. In global scope, it is supposed to +# contain an initial build directory; if unset, it defaults to ${S}. +# +# In functions run by lua_foreach_impl(), the BUILD_DIR is locally +# set to an implementation-specific build directory. That path is +# created through appending a hyphen and the implementation name +# to the final component of the initial BUILD_DIR. +# +# Example value: +# @CODE +# ${WORKDIR}/foo-1.3-lua5-1 +# @CODE + +# @ECLASS-VARIABLE: LUA_DEPS +# @OUTPUT_VARIABLE +# @DESCRIPTION: +# This is an eclass-generated Lua dependency string for all +# implementations listed in LUA_COMPAT. +# +# Example use: +# @CODE +# RDEPEND="${LUA_DEPS} +# dev-foo/mydep" +# DEPEND="${RDEPEND}" +# @CODE +# +# Example value: +# @CODE +# lua_targets_lua5-1? ( dev-lang/lua:5.1 ) +# lua_targets_lua5-2? ( dev-lang/lua:5.2 ) +# @CODE + +# @ECLASS-VARIABLE: LUA_REQUIRED_USE +# @OUTPUT_VARIABLE +# @DESCRIPTION: +# This is an eclass-generated required-use expression which ensures at +# least one Lua implementation has been enabled. +# +# This expression should be utilized in an ebuild by including it in +# REQUIRED_USE, optionally behind a use flag. +# +# Example use: +# @CODE +# REQUIRED_USE="lua? ( ${LUA_REQUIRED_USE} )" +# @CODE +# +# Example value: +# @CODE +# || ( lua_targets_lua5-1 lua_targets_lua5-2 ) +# @CODE + +# @ECLASS-VARIABLE: LUA_USEDEP +# @OUTPUT_VARIABLE +# @DESCRIPTION: +# This is an eclass-generated USE-dependency string which can be used to +# depend on another Lua package being built for the same Lua +# implementations. +# +# Example use: +# @CODE +# RDEPEND="dev-lua/foo[${LUA_USEDEP}]" +# @CODE +# +# Example value: +# @CODE +# lua_targets_lua5-1(-)?,lua_targets_lua5-2(-)? +# @CODE + +if [[ ! ${_LUA_R0} ]]; then + +# @FUNCTION: _lua_validate_useflags +# @INTERNAL +# @DESCRIPTION: +# Enforce the proper setting of LUA_TARGETS, if LUA_COMPAT_OVERRIDE +# is not in effect. If it is, just warn that the flags will be ignored. +_lua_validate_useflags() { + debug-print-function ${FUNCNAME} "${@}" + + if [[ ${LUA_COMPAT_OVERRIDE} ]]; then + if [[ ! ${_LUA_COMPAT_OVERRIDE_WARNED} ]]; then + ewarn "WARNING: LUA_COMPAT_OVERRIDE in effect. The following Lua" + ewarn "implementations will be enabled:" + ewarn + ewarn " ${LUA_COMPAT_OVERRIDE}" + ewarn + ewarn "Dependencies won't be satisfied, and LUA_TARGETS will be ignored." + _LUA_COMPAT_OVERRIDE_WARNED=1 + fi + # we do not use flags with LCO + return + fi + + local i + + for i in "${_LUA_SUPPORTED_IMPLS[@]}"; do + use "lua_targets_${i}" && return 0 + done + + eerror "No Lua implementation selected for the build. Please add one" + eerror "of the following values to your LUA_TARGETS" + eerror "(in make.conf or package.use):" + eerror + eerror "${LUA_COMPAT[@]}" + echo + die "No supported Lua implementation in LUA_TARGETS." +} + +# @FUNCTION: _lua_obtain_impls +# @INTERNAL +# @DESCRIPTION: +# Set up the enabled implementation list. +_lua_obtain_impls() { + _lua_validate_useflags + + if [[ ${LUA_COMPAT_OVERRIDE} ]]; then + MULTIBUILD_VARIANTS=( ${LUA_COMPAT_OVERRIDE} ) + return + fi + + MULTIBUILD_VARIANTS=() + + local impl + for impl in "${_LUA_SUPPORTED_IMPLS[@]}"; do + has "${impl}" "${LUA_COMPAT[@]}" && \ + use "lua_targets_${impl}" && MULTIBUILD_VARIANTS+=( "${impl}" ) + done +} + + +# @FUNCTION: _lua_multibuild_wrapper +# @USAGE: <command> [<args>...] +# @INTERNAL +# @DESCRIPTION: +# Initialize the environment for the Lua implementation selected +# for multibuild. +_lua_multibuild_wrapper() { + debug-print-function ${FUNCNAME} "${@}" + + local -x ELUA LUA + _lua_export "${MULTIBUILD_VARIANT}" ELUA LUA + local -x PATH=${PATH} PKG_CONFIG_PATH=${PKG_CONFIG_PATH} + _lua_wrapper_setup + + "${@}" +} + +# @FUNCTION: lua_copy_sources +# @DESCRIPTION: +# Create a single copy of the package sources for each enabled Lua +# implementation. +# +# The sources are always copied from initial BUILD_DIR (or S if unset) +# to implementation-specific build directory matching BUILD_DIR used by +# lua_foreach_abi(). +lua_copy_sources() { + debug-print-function ${FUNCNAME} "${@}" + + local MULTIBUILD_VARIANTS + _lua_obtain_impls + + multibuild_copy_sources +} + +# @FUNCTION: lua_foreach_impl +# @USAGE: <command> [<args>...] +# @DESCRIPTION: +# Run the given command for each of the enabled Lua implementations. +# If additional parameters are passed, they will be passed through +# to the command. +# +# The function will return 0 status if all invocations succeed. +# Otherwise, the return code from first failing invocation will +# be returned. +# +# For each command being run, ELUA, LUA and BUILD_DIR are set +# locally, and the former two are exported to the command environment. +lua_foreach_impl() { + debug-print-function ${FUNCNAME} "${@}" + + local MULTIBUILD_VARIANTS + _lua_obtain_impls + + multibuild_foreach_variant _lua_multibuild_wrapper "${@}" +} + +_LUA_R0=1 +fi + +# @FUNCTION: _lua_set_globals +# @INTERNAL +# @DESCRIPTION: +# Sets all the global output variables provided by this eclass. +# This function must be called once, in global scope. +_lua_set_globals() { + local deps i LUA_PKG_DEP + + _lua_set_impls + + for i in "${_LUA_SUPPORTED_IMPLS[@]}"; do + _lua_export "${i}" LUA_PKG_DEP + deps+="lua_targets_${i}? ( ${LUA_PKG_DEP} ) " + done + + local flags=( "${_LUA_SUPPORTED_IMPLS[@]/#/lua_targets_}" ) + local optflags=${flags[@]/%/(-)?} + + local requse="|| ( ${flags[*]} )" + local usedep=${optflags// /,} + + if [[ ${LUA_DEPS+1} ]]; then + # IUSE is magical, so we can't really check it + # (but we verify LUA_COMPAT already) + + if [[ ${LUA_DEPS} != "${deps}" ]]; then + eerror "LUA_DEPS have changed between inherits (LUA_REQ_USE?)!" + eerror "Before: ${LUA_DEPS}" + eerror "Now : ${deps}" + die "LUA_DEPS integrity check failed" + fi + + # these two are formality -- they depend on LUA_COMPAT only + if [[ ${LUA_REQUIRED_USE} != ${requse} ]]; then + eerror "LUA_REQUIRED_USE have changed between inherits!" + eerror "Before: ${LUA_REQUIRED_USE}" + eerror "Now : ${requse}" + die "LUA_REQUIRED_USE integrity check failed" + fi + + if [[ ${LUA_USEDEP} != "${usedep}" ]]; then + eerror "LUA_USEDEP have changed between inherits!" + eerror "Before: ${LUA_USEDEP}" + eerror "Now : ${usedep}" + die "LUA_USEDEP integrity check failed" + fi + else + IUSE=${flags[*]} + + LUA_DEPS=${deps} + LUA_REQUIRED_USE=${requse} + LUA_USEDEP=${usedep} + readonly LUA_DEPS LUA_REQUIRED_USE + fi +} + +_lua_set_globals +unset -f _lua_set_globals diff --git a/eclass/mate-desktop.org.eclass b/eclass/mate-desktop.org.eclass new file mode 100644 index 0000000..418f3f8 --- /dev/null +++ b/eclass/mate-desktop.org.eclass @@ -0,0 +1,61 @@ +# Copyright 1999-2017 Gentoo Foundation +# Distributed under the terms of the GNU General Public License v2 + +# @ECLASS: mate-desktop.org.eclass +# @MAINTAINER: +# mate@gentoo.org +# @AUTHOR: +# Authors: NP-Hardass <NP-Hardass@gentoo.org> based upon the gnome.org eclass. +# @SUPPORTED_EAPIS: 6 +# @BLURB: Helper eclass for mate-desktop.org hosted archives +# @DESCRIPTION: +# Provide a default SRC_URI and EGIT_REPO_URI for MATE packages as well as +# exporting some useful values like the MATE_BRANCH + +# EAPIs < 6 are banned. +case "${EAPI:-0}" in + 6) ;; + *) die "EAPI=${EAPI:-0} is not supported" ;; +esac + +if [[ ${PV} == 9999 ]]; then + inherit git-r3 +fi + +inherit versionator + +# @ECLASS-VARIABLE: MATE_TARBALL_SUFFIX +# @INTERNAL +# @DESCRIPTION: +# All projects hosted on mate-desktop.org provide tarballs as tar.xz. +# Undefined in live ebuilds. +[[ ${PV} != 9999 ]] && : ${MATE_TARBALL_SUFFIX:="xz"} + +# @ECLASS-VARIABLE: MATE_DESKTOP_ORG_PN +# @DESCRIPTION: +# Name of the package as hosted on mate-desktop.org. +# Leave unset if package name matches PN. +: ${MATE_DESKTOP_ORG_PN:=$PN} + +# @ECLASS-VARIABLE: MATE_DESKTOP_ORG_PV +# @DESCRIPTION: +# Package version string as listed on mate-desktop.org. +# Leave unset if package version string matches PV. +: ${MATE_DESKTOP_ORG_PV:=$PV} + +# @ECLASS-VARIABLE: MATE_BRANCH +# @DESCRIPTION: +# Major and minor numbers of the version number, unless live. +# If live ebuild, will be set to '9999'. +: ${MATE_BRANCH:=$(get_version_component_range 1-2)} + +# Set SRC_URI or EGIT_REPO_URI based on whether live +if [[ ${PV} == 9999 ]]; then + EGIT_REPO_URI="https://github.com/mate-desktop/${MATE_DESKTOP_ORG_PN}.git" + SRC_URI="" +else + SRC_URI="https://pub.mate-desktop.org/releases/${MATE_BRANCH}/${MATE_DESKTOP_ORG_PN}-${MATE_DESKTOP_ORG_PV}.tar.${MATE_TARBALL_SUFFIX}" +fi + +# Set HOMEPAGE for all ebuilds +HOMEPAGE="https://mate-desktop.org" diff --git a/eclass/mate.eclass b/eclass/mate.eclass new file mode 100644 index 0000000..34d5e47 --- /dev/null +++ b/eclass/mate.eclass @@ -0,0 +1,162 @@ +# Copyright 1999-2020 Gentoo Authors +# Distributed under the terms of the GNU General Public License v2 + +# @ECLASS: mate.eclass +# @MAINTAINER: +# mate@gentoo.org +# @AUTHOR: +# Authors: NP-Hardass <NP-Hardass@gentoo.org> based upon the gnome2 +# and autotools-utils eclasses +# @SUPPORTED_EAPIS: 6 +# @BLURB: Provides phases for MATE based packages. +# @DESCRIPTION: +# Exports portage base functions used by ebuilds written for packages using the +# MATE framework. Occassionally acts as a wrapper to gnome2 due to the +# fact that MATE is a GNOME fork. For additional functions, see gnome2-utils.eclass. + +# Check EAPI only +case "${EAPI:-0}" in + 6) ;; + *) die "EAPI=${EAPI:-0} is not supported" ;; +esac + +# Inherit happens below after declaration of GNOME2_LA_PUNT + +# @ECLASS-VARIABLE: MATE_LA_PUNT +# @DESCRIPTION: +# Available values for MATE_LA_PUNT: +# - "no": will not clean any .la files +# - "yes": will run prune_libtool_files --modules +# - If it is not set, it will run prune_libtool_files +# MATE_LA_PUNT is a stub to GNOME2_LA_PUNT +MATE_LA_PUNT=${MATE_LA_PUNT:-""} +GNOME2_LA_PUNT="${MATE_LA_PUNT}" + +inherit gnome2 autotools mate-desktop.org + +case "${EAPI:-0}" in + 6) EXPORT_FUNCTIONS src_prepare src_configure src_install pkg_preinst pkg_postinst pkg_postrm ;; + *) die "EAPI=${EAPI:-0} is not supported" ;; +esac + +# Autotools requires our MATE m4 files +DEPEND=">=mate-base/mate-common-${MATE_BRANCH}" + +# @FUNCTION: mate_py_cond_func_wrap +# @DESCRIPTION: +# Wraps a function for conditional python use, to run for each +# python implementation in the build directory. +# This function should only be used if the ebuild also inherits the +# python-r1 eclass +mate_py_cond_func_wrap() { + if [[ ! ${_PYTHON_R1} ]]; then + die "This function requires the inheritence of the python-r1 eclass" + fi + if use python; then + python_foreach_impl run_in_build_dir "$@" + else + $@ + fi +} + +# @ECLASS-VARIABLE: MATE_FORCE_AUTORECONF +# @DESCRIPTION: +# Available values for MATE_FORCE_AUTORECONF: +# - true: will always run eautoreconf +# - false: will default to automatic detect +# - If it is not set, it will default to false +: ${MATE_FORCE_AUTORECONF:="false"} + +# @FUNCTION: ematedocize +# @DESCRIPTION: +# A wrapper around mate-doc-common +ematedocize() { + ebegin "Running mate-doc-common --copy" + mate-doc-common --copy || die + eend $? +} + +# @FUNCTION: want_mate_doc +# @DESCRIPTION: +# Returns true/false based on whether eautoreconf should call +# ematedocize +want_mate_doc() { + grep -q USE_COMMON_DOC_BUILD autogen.sh +} + +# @FUNCTION: mate_src_prepare +# @DESCRIPTION: +# Call gnome2_src_prepare to handle environment setup and patching, then +# call eautoreconf if necessary +mate_src_prepare() { + debug-print-function ${FUNCNAME} "$@" + + local force_autoreconf=${MATE_FORCE_AUTORECONF} + [[ ${PV} == 9999 ]] && force_autoreconf="true" + + gen_chksum() { + find '(' -name 'Makefile.am' \ + -o -name 'configure.ac' \ + -o -name 'configure.in' ')' \ + -exec cksum {} + | sort -k2 + } + + local chksum=$(gen_chksum) + + gnome2_src_prepare "$@" + + if [[ "${force_autoreconf}" == "true" ]] || [[ ${chksum} != $(gen_chksum) ]]; then + want_mate_doc && ematedocize + AT_NOELIBTOOLIZE="yes" eautoreconf # gnome2_src_prepare calls elibtoolize + fi +} + +# @FUNCTION: mate_src_configure +# @DESCRIPTION: +# MATE specific configure handling +# Stub to gnome2_src_configure() +mate_src_configure() { + + local mateconf=() + + # Pass --disable-static whenever possible + if ! in_iuse static-libs || ! use static-libs; then + if grep -q "enable-static" "${ECONF_SOURCE:-.}"/configure; then + mateconf+=( --disable-static ) + fi + fi + + gnome2_src_configure "${mateconf[@]}" "$@" +} + +# @FUNCTION: mate_src_install +# @DESCRIPTION: +# MATE specific install. Stub to gnome2_src_install +mate_src_install() { + gnome2_src_install "$@" +} + +# @FUNCTION: mate_pkg_preinst +# @DESCRIPTION: +# Finds Icons, GConf and GSettings schemas for later handling in pkg_postinst +# Stub to gnome2_pkg_preinst +mate_pkg_preinst() { + gnome2_pkg_preinst "$@" +} + +# @FUNCTION: mate_pkg_postinst +# @DESCRIPTION: +# Handle scrollkeeper, GConf, GSettings, Icons, desktop and mime +# database updates. +# Stub to gnome2_pkg_postinst +mate_pkg_postinst() { + gnome2_pkg_postinst "$@" +} + +# @FUNCTION: mate_pkg_postrm +# @DESCRIPTION: +# Handle scrollkeeper, GSettings, Icons, desktop and mime database updates. +# Stub to gnome2_pkg_postrm +mate_pkg_postrm() { + gnome2_pkg_postrm "$@" +} diff --git a/eclass/mercurial.eclass b/eclass/mercurial.eclass new file mode 100644 index 0000000..faf3830 --- /dev/null +++ b/eclass/mercurial.eclass @@ -0,0 +1,203 @@ +# Copyright 1999-2019 Gentoo Authors +# Distributed under the terms of the GNU General Public License v2 + +# @ECLASS: mercurial.eclass +# @MAINTAINER: +# Christoph Junghans <junghans@gentoo.org> +# @AUTHOR: +# Next gen author: Krzysztof Pawlik <nelchael@gentoo.org> +# Original author: Aron Griffis <agriffis@gentoo.org> +# @BLURB: This eclass provides generic mercurial fetching functions +# @DESCRIPTION: +# This eclass provides generic mercurial fetching functions. To fetch sources +# from mercurial repository just set EHG_REPO_URI to correct repository URI. If +# you need to share single repository between several ebuilds set EHG_PROJECT to +# project name in all of them. + +inherit eutils + +EXPORT_FUNCTIONS src_unpack + +PROPERTIES+=" live" + +DEPEND="dev-vcs/mercurial" + +# @ECLASS-VARIABLE: EHG_REPO_URI +# @DESCRIPTION: +# Mercurial repository URI. + +# @ECLASS-VARIABLE: EHG_REVISION +# @DESCRIPTION: +# Create working directory for specified revision, defaults to default. +# +# EHG_REVISION is passed as a value for --updaterev parameter, so it can be more +# than just a revision, please consult `hg help revisions' for more details. +: ${EHG_REVISION:="default"} + +# @ECLASS-VARIABLE: EHG_STORE_DIR +# @DESCRIPTION: +# Mercurial sources store directory. Users may override this in /etc/portage/make.conf +[[ -z "${EHG_STORE_DIR}" ]] && EHG_STORE_DIR="${PORTAGE_ACTUAL_DISTDIR:-${DISTDIR}}/hg-src" + +# @ECLASS-VARIABLE: EHG_PROJECT +# @DESCRIPTION: +# Project name. +# +# This variable default to $PN, but can be changed to allow repository sharing +# between several ebuilds. +[[ -z "${EHG_PROJECT}" ]] && EHG_PROJECT="${PN}" + +# @ECLASS-VARIABLE: EGIT_CHECKOUT_DIR +# @DESCRIPTION: +# The directory to check the hg sources out to. +# +# EHG_CHECKOUT_DIR=${S} + +# @ECLASS-VARIABLE: EHG_QUIET +# @DESCRIPTION: +# Suppress some extra noise from mercurial, set it to 'ON' to be quiet. +: ${EHG_QUIET:="OFF"} +[[ "${EHG_QUIET}" == "ON" ]] && EHG_QUIET_CMD_OPT="--quiet" + +# @ECLASS-VARIABLE: EHG_CONFIG +# @DESCRIPTION: +# Extra config option to hand to hg clone/pull + +# @ECLASS-VARIABLE: EHG_CLONE_CMD +# @DESCRIPTION: +# Command used to perform initial repository clone. +[[ -z "${EHG_CLONE_CMD}" ]] && EHG_CLONE_CMD="hg clone ${EHG_CONFIG:+--config ${EHG_CONFIG}} ${EHG_QUIET_CMD_OPT} --pull --noupdate" + +# @ECLASS-VARIABLE: EHG_PULL_CMD +# @DESCRIPTION: +# Command used to update repository. +[[ -z "${EHG_PULL_CMD}" ]] && EHG_PULL_CMD="hg pull ${EHG_CONFIG:+--config ${EHG_CONFIG}} ${EHG_QUIET_CMD_OPT}" + +# @ECLASS-VARIABLE: EHG_OFFLINE +# @DESCRIPTION: +# Set this variable to a non-empty value to disable the automatic updating of +# a mercurial source tree. This is intended to be set outside the ebuild by +# users. +EHG_OFFLINE="${EHG_OFFLINE:-${EVCS_OFFLINE}}" + +# @FUNCTION: mercurial_fetch +# @USAGE: [repository_uri] [module] [sourcedir] +# @DESCRIPTION: +# Clone or update repository. +# +# If repository URI is not passed it defaults to EHG_REPO_URI, if module is +# empty it defaults to basename of EHG_REPO_URI, sourcedir defaults to +# EHG_CHECKOUT_DIR, which defaults to S. + +mercurial_fetch() { + debug-print-function ${FUNCNAME} "${@}" + + has "${EAPI:-0}" 0 1 2 && ! use prefix && EPREFIX= + + EHG_REPO_URI=${1-${EHG_REPO_URI}} + [[ -z "${EHG_REPO_URI}" ]] && die "EHG_REPO_URI is empty" + + local module="${2-$(basename "${EHG_REPO_URI}")}" + local sourcedir="${3:-${EHG_CHECKOUT_DIR:-${S}}}" + + # Should be set but blank to prevent using $HOME/.hgrc + export HGRCPATH= + + # Check ${EHG_STORE_DIR} directory: + addwrite "$(dirname "${EHG_STORE_DIR}")" || die "addwrite failed" + if [[ ! -d "${EHG_STORE_DIR}" ]]; then + mkdir -p "${EHG_STORE_DIR}" || die "failed to create ${EHG_STORE_DIR}" + chmod -f g+rw "${EHG_STORE_DIR}" || \ + die "failed to chown ${EHG_STORE_DIR}" + fi + + # Create project directory: + mkdir -p "${EHG_STORE_DIR}/${EHG_PROJECT}" || \ + die "failed to create ${EHG_STORE_DIR}/${EHG_PROJECT}" + chmod -f g+rw "${EHG_STORE_DIR}/${EHG_PROJECT}" || \ + echo "Warning: failed to chmod g+rw ${EHG_PROJECT}" + pushd "${EHG_STORE_DIR}/${EHG_PROJECT}" > /dev/null || \ + die "failed to cd to ${EHG_STORE_DIR}/${EHG_PROJECT}" + + # Clone/update repository: + if [[ ! -d "${module}" ]]; then + einfo "Cloning ${EHG_REPO_URI} to ${EHG_STORE_DIR}/${EHG_PROJECT}/${module}" + ${EHG_CLONE_CMD} "${EHG_REPO_URI}" "${module}" || { + rm -rf "${module}" + die "failed to clone ${EHG_REPO_URI}" + } + elif [[ -z "${EHG_OFFLINE}" ]]; then + einfo "Updating ${EHG_STORE_DIR}/${EHG_PROJECT}/${module} from ${EHG_REPO_URI}" + pushd "${module}" > /dev/null || die "failed to cd to ${module}" + ${EHG_PULL_CMD} "${EHG_REPO_URI}" || die "update failed" + popd > /dev/null || die + fi + popd > /dev/null || die + + # Checkout working copy: + einfo "Creating working directory in ${sourcedir} (target revision: ${EHG_REVISION})" + mkdir -p "${sourcedir}" || die "failed to create ${sourcedir}" + hg clone \ + ${EHG_QUIET_CMD_OPT} \ + --updaterev="${EHG_REVISION}" \ + ${EHG_CONFIG:+--config ${EHG_CONFIG}} \ + "${EHG_STORE_DIR}/${EHG_PROJECT}/${module}" \ + "${sourcedir}" || die "hg clone failed" + # An exact revision helps a lot for testing purposes, so have some output... + # id num branch + # fd6e32d61721 6276 default + local HG_REVDATA=($(hg identify -b -i "${sourcedir}")) + export HG_REV_ID=${HG_REVDATA[0]} + local HG_REV_BRANCH=${HG_REVDATA[1]} + einfo "Work directory: ${sourcedir} global id: ${HG_REV_ID} (was ${EHG_REVISION} branch: ${HG_REV_BRANCH}" +} + +# @FUNCTION: mercurial_bootstrap +# @INTERNAL +# @DESCRIPTION: +# Internal function that runs bootstrap command on unpacked source. +mercurial_bootstrap() { + debug-print-function ${FUNCNAME} "$@" + + # @ECLASS-VARIABLE: EHG_BOOTSTRAP + # @DESCRIPTION: + # Command to be executed after checkout and clone of the specified + # repository. + if [[ ${EHG_BOOTSTRAP} ]]; then + pushd "${S}" > /dev/null + einfo "Starting bootstrap" + + if [[ -f ${EHG_BOOTSTRAP} ]]; then + # we have file in the repo which we should execute + debug-print "${FUNCNAME}: bootstraping with file \"${EHG_BOOTSTRAP}\"" + + if [[ -x ${EHG_BOOTSTRAP} ]]; then + eval "./${EHG_BOOTSTRAP}" \ + || die "${FUNCNAME}: bootstrap script failed" + else + eerror "\"${EHG_BOOTSTRAP}\" is not executable." + eerror "Report upstream, or bug ebuild maintainer to remove bootstrap command." + die "\"${EHG_BOOTSTRAP}\" is not executable" + fi + else + # we execute some system command + debug-print "${FUNCNAME}: bootstraping with commands \"${EHG_BOOTSTRAP}\"" + + eval "${EHG_BOOTSTRAP}" \ + || die "${FUNCNAME}: bootstrap commands failed" + fi + + einfo "Bootstrap finished" + popd > /dev/null + fi +} + +# @FUNCTION: mercurial_src_unpack +# @DESCRIPTION: +# The mercurial src_unpack function, which will be exported. +function mercurial_src_unpack { + debug-print-function ${FUNCNAME} "$@" + + mercurial_fetch + mercurial_bootstrap +} diff --git a/eclass/meson.eclass b/eclass/meson.eclass new file mode 100644 index 0000000..67b7ca8 --- /dev/null +++ b/eclass/meson.eclass @@ -0,0 +1,415 @@ +# Copyright 2017-2020 Gentoo Authors +# Distributed under the terms of the GNU General Public License v2 + +# @ECLASS: meson.eclass +# @MAINTAINER: +# William Hubbs <williamh@gentoo.org> +# Mike Gilbert <floppym@gentoo.org> +# @SUPPORTED_EAPIS: 6 7 +# @BLURB: common ebuild functions for meson-based packages +# @DESCRIPTION: +# This eclass contains the default phase functions for packages which +# use the meson build system. +# +# @EXAMPLE: +# Typical ebuild using meson.eclass: +# +# @CODE +# EAPI=6 +# +# inherit meson +# +# ... +# +# src_configure() { +# local emesonargs=( +# $(meson_use qt4) +# $(meson_feature threads) +# $(meson_use bindist official_branding) +# ) +# meson_src_configure +# } +# +# ... +# +# @CODE + +case ${EAPI:-0} in + 6|7) ;; + *) die "EAPI=${EAPI} is not supported" ;; +esac + +if [[ -z ${_MESON_ECLASS} ]]; then + +inherit multiprocessing ninja-utils python-utils-r1 toolchain-funcs + +if [[ ${EAPI} == 6 ]]; then + inherit eapi7-ver +fi + +fi + +EXPORT_FUNCTIONS src_configure src_compile src_test src_install + +if [[ -z ${_MESON_ECLASS} ]]; then +_MESON_ECLASS=1 + +MESON_DEPEND=">=dev-util/meson-0.54.0 + >=dev-util/ninja-1.8.2 + dev-util/meson-format-array +" + +if [[ ${EAPI:-0} == [6] ]]; then + DEPEND=${MESON_DEPEND} +else + BDEPEND=${MESON_DEPEND} +fi + +# @ECLASS-VARIABLE: BUILD_DIR +# @DEFAULT_UNSET +# @DESCRIPTION: +# Build directory, location where all generated files should be placed. +# If this isn't set, it defaults to ${WORKDIR}/${P}-build. + +# @ECLASS-VARIABLE: EMESON_SOURCE +# @DEFAULT_UNSET +# @DESCRIPTION: +# The location of the source files for the project; this is the source +# directory to pass to meson. +# If this isn't set, it defaults to ${S} + +# @VARIABLE: emesonargs +# @DEFAULT_UNSET +# @DESCRIPTION: +# Optional meson arguments as Bash array; this should be defined before +# calling meson_src_configure. + +# @VARIABLE: emesontestargs +# @DEFAULT_UNSET +# @DESCRIPTION: +# Optional meson test arguments as Bash array; this should be defined before +# calling meson_src_test. + +# @VARIABLE: MYMESONARGS +# @DEFAULT_UNSET +# @DESCRIPTION: +# User-controlled environment variable containing arguments to be passed to +# meson in meson_src_configure. + +# @FUNCTION: _meson_env_array +# @INTERNAL +# @DESCRIPTION: +# Parses the command line flags and converts them into an array suitable for +# use in a cross file. +# +# Input: --single-quote=\' --double-quote=\" --dollar=\$ --backtick=\` +# --backslash=\\ --full-word-double="Hello World" +# --full-word-single='Hello World' +# --full-word-backslash=Hello\ World +# --simple --unicode-8=© --unicode-16=𐐷 --unicode-32=𐤅 +# +# Output: ['--single-quote=\'', '--double-quote="', '--dollar=$', +# '--backtick=`', '--backslash=\\', '--full-word-double=Hello World', +# '--full-word-single=Hello World', +# '--full-word-backslash=Hello World', '--simple', '--unicode-8=©', +# '--unicode-16=𐐷', '--unicode-32=𐤅'] +# +_meson_env_array() { + meson-format-array "$@" +} + +# @FUNCTION: _meson_get_machine_info +# @USAGE: <tuple> +# @RETURN: system/cpu_family/cpu variables +# @INTERNAL +# @DESCRIPTION: +# Translate toolchain tuple into machine values for meson. +_meson_get_machine_info() { + local tuple=$1 + + # system roughly corresponds to uname -s (lowercase) + case ${tuple} in + *-aix*) system=aix ;; + *-cygwin*) system=cygwin ;; + *-darwin*) system=darwin ;; + *-freebsd*) system=freebsd ;; + *-linux*) system=linux ;; + mingw*|*-mingw*) system=windows ;; + *-solaris*) system=sunos ;; + esac + + cpu_family=$(tc-arch "${tuple}") + case ${cpu_family} in + amd64) cpu_family=x86_64 ;; + arm64) cpu_family=aarch64 ;; + esac + + # This may require adjustment based on CFLAGS + cpu=${tuple%%-*} +} + +# @FUNCTION: _meson_create_cross_file +# @RETURN: path to cross file +# @INTERNAL +# @DESCRIPTION: +# Creates a cross file. meson uses this to define settings for +# cross-compilers. This function is called from meson_src_configure. +_meson_create_cross_file() { + local system cpu_family cpu + _meson_get_machine_info "${CHOST}" + + local fn=${T}/meson.${CHOST}.${ABI}.ini + + cat > "${fn}" <<-EOF + [binaries] + ar = $(_meson_env_array "$(tc-getAR)") + c = $(_meson_env_array "$(tc-getCC)") + cpp = $(_meson_env_array "$(tc-getCXX)") + fortran = $(_meson_env_array "$(tc-getFC)") + llvm-config = '$(tc-getPROG LLVM_CONFIG llvm-config)' + nm = $(_meson_env_array "$(tc-getNM)") + objc = $(_meson_env_array "$(tc-getPROG OBJC cc)") + objcpp = $(_meson_env_array "$(tc-getPROG OBJCXX c++)") + pkgconfig = '$(tc-getPKG_CONFIG)' + strip = $(_meson_env_array "$(tc-getSTRIP)") + windres = $(_meson_env_array "$(tc-getRC)") + + [properties] + c_args = $(_meson_env_array "${CFLAGS} ${CPPFLAGS}") + c_link_args = $(_meson_env_array "${CFLAGS} ${LDFLAGS}") + cpp_args = $(_meson_env_array "${CXXFLAGS} ${CPPFLAGS}") + cpp_link_args = $(_meson_env_array "${CXXFLAGS} ${LDFLAGS}") + fortran_args = $(_meson_env_array "${FCFLAGS}") + fortran_link_args = $(_meson_env_array "${FCFLAGS} ${LDFLAGS}") + objc_args = $(_meson_env_array "${OBJCFLAGS} ${CPPFLAGS}") + objc_link_args = $(_meson_env_array "${OBJCFLAGS} ${LDFLAGS}") + objcpp_args = $(_meson_env_array "${OBJCXXFLAGS} ${CPPFLAGS}") + objcpp_link_args = $(_meson_env_array "${OBJCXXFLAGS} ${LDFLAGS}") + needs_exe_wrapper = true + sys_root = '${SYSROOT}' + pkg_config_libdir = '${PKG_CONFIG_LIBDIR:-${EPREFIX}/usr/$(get_libdir)/pkgconfig}' + + [host_machine] + system = '${system}' + cpu_family = '${cpu_family}' + cpu = '${cpu}' + endian = '$(tc-endian "${CHOST}")' + EOF + + echo "${fn}" +} + +# @FUNCTION: _meson_create_native_file +# @RETURN: path to native file +# @INTERNAL +# @DESCRIPTION: +# Creates a native file. meson uses this to define settings for +# native compilers. This function is called from meson_src_configure. +_meson_create_native_file() { + local system cpu_family cpu + _meson_get_machine_info "${CBUILD}" + + local fn=${T}/meson.${CBUILD}.${ABI}.ini + + cat > "${fn}" <<-EOF + [binaries] + ar = $(_meson_env_array "$(tc-getBUILD_AR)") + c = $(_meson_env_array "$(tc-getBUILD_CC)") + cpp = $(_meson_env_array "$(tc-getBUILD_CXX)") + fortran = $(_meson_env_array "$(tc-getBUILD_PROG FC gfortran)") + llvm-config = '$(tc-getBUILD_PROG LLVM_CONFIG llvm-config)' + nm = $(_meson_env_array "$(tc-getBUILD_NM)") + objc = $(_meson_env_array "$(tc-getBUILD_PROG OBJC cc)") + objcpp = $(_meson_env_array "$(tc-getBUILD_PROG OBJCXX c++)") + pkgconfig = '$(tc-getBUILD_PKG_CONFIG)' + strip = $(_meson_env_array "$(tc-getBUILD_STRIP)") + windres = $(_meson_env_array "$(tc-getBUILD_PROG RC windres)") + + [properties] + c_args = $(_meson_env_array "${BUILD_CFLAGS} ${BUILD_CPPFLAGS}") + c_link_args = $(_meson_env_array "${BUILD_CFLAGS} ${BUILD_LDFLAGS}") + cpp_args = $(_meson_env_array "${BUILD_CXXFLAGS} ${BUILD_CPPFLAGS}") + cpp_link_args = $(_meson_env_array "${BUILD_CXXFLAGS} ${BUILD_LDFLAGS}") + fortran_args = $(_meson_env_array "${BUILD_FCFLAGS}") + fortran_link_args = $(_meson_env_array "${BUILD_FCFLAGS} ${BUILD_LDFLAGS}") + objc_args = $(_meson_env_array "${BUILD_OBJCFLAGS} ${BUILD_CPPFLAGS}") + objc_link_args = $(_meson_env_array "${BUILD_OBJCFLAGS} ${BUILD_LDFLAGS}") + objcpp_args = $(_meson_env_array "${BUILD_OBJCXXFLAGS} ${BUILD_CPPFLAGS}") + objcpp_link_args = $(_meson_env_array "${BUILD_OBJCXXFLAGS} ${BUILD_LDFLAGS}") + needs_exe_wrapper = false + pkg_config_libdir = '${BUILD_PKG_CONFIG_LIBDIR:-${EPREFIX}/usr/$(get_libdir)/pkgconfig}' + + [build_machine] + system = '${system}' + cpu_family = '${cpu_family}' + cpu = '${cpu}' + endian = '$(tc-endian "${CBUILD}")' + EOF + + echo "${fn}" +} + +# @FUNCTION: meson_use +# @USAGE: <USE flag> [option name] +# @DESCRIPTION: +# Given a USE flag and meson project option, outputs a string like: +# +# -Doption=true +# -Doption=false +# +# If the project option is unspecified, it defaults to the USE flag. +meson_use() { + usex "$1" "-D${2-$1}=true" "-D${2-$1}=false" +} + +# @FUNCTION: meson_feature +# @USAGE: <USE flag> [option name] +# @DESCRIPTION: +# Given a USE flag and meson project option, outputs a string like: +# +# -Doption=enabled +# -Doption=disabled +# +# If the project option is unspecified, it defaults to the USE flag. +meson_feature() { + usex "$1" "-D${2-$1}=enabled" "-D${2-$1}=disabled" +} + +# @FUNCTION: meson_src_configure +# @USAGE: [extra meson arguments] +# @DESCRIPTION: +# This is the meson_src_configure function. +meson_src_configure() { + debug-print-function ${FUNCNAME} "$@" + + local BUILD_CFLAGS=${BUILD_CFLAGS} + local BUILD_CPPFLAGS=${BUILD_CPPFLAGS} + local BUILD_CXXFLAGS=${BUILD_CXXFLAGS} + local BUILD_FCFLAGS=${BUILD_FCFLAGS} + local BUILD_OBJCFLAGS=${BUILD_OBJCFLAGS} + local BUILD_OBJCXXFLAGS=${BUILD_OBJCXXFLAGS} + local BUILD_LDFLAGS=${BUILD_LDFLAGS} + local BUILD_PKG_CONFIG_LIBDIR=${BUILD_PKG_CONFIG_LIBDIR} + local BUILD_PKG_CONFIG_PATH=${BUILD_PKG_CONFIG_PATH} + + if tc-is-cross-compiler; then + : ${BUILD_CFLAGS:=-O1 -pipe} + : ${BUILD_CXXFLAGS:=-O1 -pipe} + : ${BUILD_FCFLAGS:=-O1 -pipe} + : ${BUILD_OBJCFLAGS:=-O1 -pipe} + : ${BUILD_OBJCXXFLAGS:=-O1 -pipe} + else + : ${BUILD_CFLAGS:=${CFLAGS}} + : ${BUILD_CPPFLAGS:=${CPPFLAGS}} + : ${BUILD_CXXFLAGS:=${CXXFLAGS}} + : ${BUILD_FCFLAGS:=${FCFLAGS}} + : ${BUILD_LDFLAGS:=${LDFLAGS}} + : ${BUILD_OBJCFLAGS:=${OBJCFLAGS}} + : ${BUILD_OBJCXXFLAGS:=${OBJCXXFLAGS}} + : ${BUILD_PKG_CONFIG_LIBDIR:=${PKG_CONFIG_LIBDIR}} + : ${BUILD_PKG_CONFIG_PATH:=${PKG_CONFIG_PATH}} + fi + + local mesonargs=( + meson setup + --buildtype plain + --libdir "$(get_libdir)" + --localstatedir "${EPREFIX}/var/lib" + --prefix "${EPREFIX}/usr" + --sysconfdir "${EPREFIX}/etc" + --wrap-mode nodownload + --build.pkg-config-path "${BUILD_PKG_CONFIG_PATH}${BUILD_PKG_CONFIG_PATH:+:}${EPREFIX}/usr/share/pkgconfig" + --pkg-config-path "${PKG_CONFIG_PATH}${PKG_CONFIG_PATH:+:}${EPREFIX}/usr/share/pkgconfig" + --native-file "$(_meson_create_native_file)" + ) + + if tc-is-cross-compiler; then + mesonargs+=( --cross-file "$(_meson_create_cross_file)" ) + fi + + BUILD_DIR="${BUILD_DIR:-${WORKDIR}/${P}-build}" + + # Handle quoted whitespace + eval "local -a MYMESONARGS=( ${MYMESONARGS} )" + + mesonargs+=( + # Arguments from ebuild + "${emesonargs[@]}" + + # Arguments passed to this function + "$@" + + # Arguments from user + "${MYMESONARGS[@]}" + + # Source directory + "${EMESON_SOURCE:-${S}}" + + # Build directory + "${BUILD_DIR}" + ) + + # Used by symbolextractor.py + # https://bugs.gentoo.org/717720 + tc-export NM + tc-getPROG READELF readelf >/dev/null + + # https://bugs.gentoo.org/625396 + python_export_utf8_locale + + # https://bugs.gentoo.org/721786 + local -x BOOST_INCLUDEDIR="${BOOST_INCLUDEDIR-${EPREFIX}/usr/include}" + local -x BOOST_LIBRARYDIR="${BOOST_LIBRARYDIR-${EPREFIX}/usr/$(get_libdir)}" + + ( + export -n {C,CPP,CXX,F,OBJC,OBJCXX,LD}FLAGS PKG_CONFIG_{LIBDIR,PATH} + echo "${mesonargs[@]}" >&2 + "${mesonargs[@]}" + ) || die +} + +# @FUNCTION: meson_src_compile +# @USAGE: [extra ninja arguments] +# @DESCRIPTION: +# This is the meson_src_compile function. +meson_src_compile() { + debug-print-function ${FUNCNAME} "$@" + + eninja -C "${BUILD_DIR}" "$@" +} + +# @FUNCTION: meson_src_test +# @USAGE: [extra meson test arguments] +# @DESCRIPTION: +# This is the meson_src_test function. +meson_src_test() { + debug-print-function ${FUNCNAME} "$@" + + local mesontestargs=( + -C "${BUILD_DIR}" + ) + [[ -n ${NINJAOPTS} || -n ${MAKEOPTS} ]] && + mesontestargs+=( + --num-processes "$(makeopts_jobs ${NINJAOPTS:-${MAKEOPTS}})" + ) + + # Append additional arguments from ebuild + mesontestargs+=("${emesontestargs[@]}") + + set -- meson test "${mesontestargs[@]}" "$@" + echo "$@" >&2 + "$@" || die "tests failed" +} + +# @FUNCTION: meson_src_install +# @USAGE: [extra ninja install arguments] +# @DESCRIPTION: +# This is the meson_src_install function. +meson_src_install() { + debug-print-function ${FUNCNAME} "$@" + + DESTDIR="${D}" eninja -C "${BUILD_DIR}" install "$@" + einstalldocs +} + +fi diff --git a/eclass/mono-env.eclass b/eclass/mono-env.eclass new file mode 100644 index 0000000..51794ed --- /dev/null +++ b/eclass/mono-env.eclass @@ -0,0 +1,44 @@ +# Copyright 1999-2013 Gentoo Foundation +# Distributed under the terms of the GNU General Public License v2 + +# @ECLASS: mono-env.eclass +# @MAINTAINER: +# dotnet@gentoo.org +# @BLURB: Set environment variables commonly used by dotnet packages. +# @DESCRIPTION: +# Set environment variables commonly used by dotnet packages. + +SRC_URI="http://download.mono-project.com/sources/${PN}/${P}.tar.bz2" + +EXPORT_FUNCTIONS pkg_setup + +if [[ ! ${_MONO_ENV} ]]; then + +mono-env_pkg_setup() { + # >=mono-0.92 versions using mcs -pkg:foo-sharp require shared memory, so we set the + # shared dir to ${T} so that ${T}/.wapi can be used during the install process. + export MONO_SHARED_DIR="${T}" + + # export more variables as needed by other dotnet packages + export MONO_REGISTRY_PATH="${T}/registry" + export XDG_DATA_HOME="${T}/data" + + # Building mono, nant and many other dotnet packages is known to fail if LC_ALL + # variable is not set to C. To prevent this all mono related packages will be + # build with LC_ALL=C (see bugs #146424, #149817) + export LC_ALL=C + + # Monodevelop-using applications need this to be set or they will try to create config + # files in the user's ~ dir. + export XDG_CONFIG_HOME="${T}" + + # Fix bug 83020: + # "Access Violations Arise When Emerging Mono-Related Packages with MONO_AOT_CACHE" + unset MONO_AOT_CACHE + + # mono libs can live on /usr/lib as they are not arch specific + QA_MULTILIB_PATHS="usr/lib/" +} + +_MONO_ENV=1 +fi diff --git a/eclass/mono.eclass b/eclass/mono.eclass new file mode 100644 index 0000000..b1dc1e5 --- /dev/null +++ b/eclass/mono.eclass @@ -0,0 +1,81 @@ +# Copyright 1999-2020 Gentoo Authors +# Distributed under the terms of the GNU General Public License v2 + +# @ECLASS: mono.eclass +# @MAINTAINER: +# dotnet@gentoo.org +# @BLURB: common settings and functions for mono and dotnet related packages +# @DEPRECATED: mono-env +# @DESCRIPTION: +# The mono eclass contains common environment settings that are useful for +# dotnet packages. Currently, it provides no functions, just exports +# MONO_SHARED_DIR and sets LC_ALL in order to prevent errors during compilation +# of dotnet packages. + +inherit multilib + +# >=mono-0.92 versions using mcs -pkg:foo-sharp require shared memory, so we set the +# shared dir to ${T} so that ${T}/.wapi can be used during the install process. +export MONO_SHARED_DIR="${T}" + +# Building mono, nant and many other dotnet packages is known to fail if LC_ALL +# variable is not set to C. To prevent this all mono related packages will be +# build with LC_ALL=C (see bugs #146424, #149817) +export LC_ALL=C + +# Monodevelop-using applications need this to be set or they will try to create config +# files in the user's ~ dir. + +export XDG_CONFIG_HOME="${T}" + +# Fix bug 83020: +# "Access Violations Arise When Emerging Mono-Related Packages with MONO_AOT_CACHE" + +unset MONO_AOT_CACHE + +egacinstall() { + use !prefix && has "${EAPI:-0}" 0 1 2 && ED="${D}" + gacutil -i "${1}" \ + -root "${ED}"/usr/$(get_libdir) \ + -gacdir /usr/$(get_libdir) \ + -package ${2:-${GACPN:-${PN}}} \ + || die "installing ${1} into the Global Assembly Cache failed" +} + +mono_multilib_comply() { + use !prefix && has "${EAPI:-0}" 0 1 2 && ED="${D}" + local dir finddirs=() mv_command=${mv_command:-mv} + if [[ -d "${ED}/usr/lib" && "$(get_libdir)" != "lib" ]] + then + if ! [[ -d "${ED}"/usr/"$(get_libdir)" ]] + then + mkdir "${ED}"/usr/"$(get_libdir)" || die "Couldn't mkdir ${ED}/usr/$(get_libdir)" + fi + ${mv_command} "${ED}"/usr/lib/* "${ED}"/usr/"$(get_libdir)"/ || die "Moving files into correct libdir failed" + rm -rf "${ED}"/usr/lib + for dir in "${ED}"/usr/"$(get_libdir)"/pkgconfig "${ED}"/usr/share/pkgconfig + do + + if [[ -d "${dir}" && "$(find "${dir}" -name '*.pc')" != "" ]] + then + pushd "${dir}" &> /dev/null + sed -i -r -e 's:/(lib)([^a-zA-Z0-9]|$):/'"$(get_libdir)"'\2:g' \ + *.pc \ + || die "Sedding some sense into pkgconfig files failed." + popd "${dir}" &> /dev/null + fi + done + if [[ -d "${ED}/usr/bin" ]] + then + for exe in "${ED}/usr/bin"/* + do + if [[ "$(file "${exe}")" == *"shell script text"* ]] + then + sed -r -i -e ":/lib(/|$): s:/lib(/|$):/$(get_libdir)\1:" \ + "${exe}" || die "Sedding some sense into ${exe} failed" + fi + done + fi + + fi +} diff --git a/eclass/mount-boot.eclass b/eclass/mount-boot.eclass new file mode 100644 index 0000000..2b07160 --- /dev/null +++ b/eclass/mount-boot.eclass @@ -0,0 +1,113 @@ +# Copyright 1999-2021 Gentoo Authors +# Distributed under the terms of the GNU General Public License v2 + +# @ECLASS: mount-boot.eclass +# @MAINTAINER: +# base-system@gentoo.org +# @SUPPORTED_EAPIS: 6 7 +# @BLURB: functions for packages that install files into /boot +# @DESCRIPTION: +# This eclass is really only useful for bootloaders. +# +# If the live system has a separate /boot partition configured, then this +# function tries to ensure that it's mounted in rw mode, exiting with an +# error if it can't. It does nothing if /boot isn't a separate partition. + +case ${EAPI:-0} in + 6|7) ;; + *) die "${ECLASS}: EAPI ${EAPI:-0} not supported" ;; +esac + +EXPORT_FUNCTIONS pkg_pretend pkg_preinst pkg_postinst pkg_prerm pkg_postrm + +# @FUNCTION: mount-boot_is_disabled +# @INTERNAL +# @DESCRIPTION: +# Detect whether the current environment/build settings are such that we do not +# want to mess with any mounts. +mount-boot_is_disabled() { + # Since this eclass only deals with /boot, skip things when EROOT is active. + if [[ ${EROOT:-/} != / ]] ; then + return 0 + fi + + # If we're only building a package, then there's no need to check things. + if [[ ${MERGE_TYPE} == buildonly ]] ; then + return 0 + fi + + # The user wants us to leave things be. + if [[ -n ${DONT_MOUNT_BOOT} ]] ; then + return 0 + fi + + # OK, we want to handle things ourselves. + return 1 +} + +# @FUNCTION: mount-boot_check_status +# @INTERNAL +# @DESCRIPTION: +# Check if /boot is sane, i.e., mounted as read-write if on a separate +# partition. Die if conditions are not fulfilled. If nonfatal is used, +# the function will return a non-zero status instead. +mount-boot_check_status() { + # Get out fast if possible. + mount-boot_is_disabled && return 0 + + # note that /dev/BOOT is in the Gentoo default /etc/fstab file + local fstabstate=$(awk '!/^[[:blank:]]*#|^\/dev\/BOOT/ && $2 == "/boot" \ + { print 1; exit }' /etc/fstab || die "awk failed") + + if [[ -z ${fstabstate} ]] ; then + einfo "Assuming you do not have a separate /boot partition." + return 0 + fi + + local procstate=$(awk '$2 == "/boot" { split($4, a, ","); \ + for (i in a) if (a[i] ~ /^r[ow]$/) { print a[i]; break }; exit }' \ + /proc/mounts || die "awk failed") + + if [[ -z ${procstate} ]] ; then + eerror "Your boot partition is not mounted at /boot." + eerror "Please mount it and retry." + die -n "/boot not mounted" + return 1 + fi + + if [[ ${procstate} == ro ]] ; then + eerror "Your boot partition, detected as being mounted at /boot," \ + "is read-only." + eerror "Please remount it as read-write and retry." + die -n "/boot mounted read-only" + return 2 + fi + + einfo "Your boot partition was detected as being mounted at /boot." + einfo "Files will be installed there for ${PN} to function correctly." + return 0 +} + +mount-boot_pkg_pretend() { + mount-boot_check_status +} + +mount-boot_pkg_preinst() { + mount-boot_check_status +} + +mount-boot_pkg_prerm() { + mount-boot_check_status + + if [[ -z ${EPREFIX} ]] \ + && ! ( shopt -s failglob; : "${EROOT}"/boot/.keep* ) 2>/dev/null + then + # Create a .keep file, in case it is shadowed at the mount point + touch "${EROOT}"/boot/.keep 2>/dev/null + fi +} + +# No-op phases for backwards compatibility +mount-boot_pkg_postinst() { :; } + +mount-boot_pkg_postrm() { :; } diff --git a/eclass/mozcoreconf-v5.eclass b/eclass/mozcoreconf-v5.eclass new file mode 100644 index 0000000..d50d944 --- /dev/null +++ b/eclass/mozcoreconf-v5.eclass @@ -0,0 +1,278 @@ +# Copyright 1999-2020 Gentoo Authors +# Distributed under the terms of the GNU General Public License v2 +# +# @ECLASS: mozcoreconf-v5.eclass +# @MAINTAINER: +# Mozilla team <mozilla@gentoo.org> +# @BLURB: core options and configuration functions for mozilla +# @DESCRIPTION: +# +# inherit mozconfig-v6.* or above for mozilla configuration support + +# @ECLASS-VARIABLE: MOZILLA_FIVE_HOME +# @DESCRIPTION: +# This is an eclass-generated variable that defines the rpath that the mozilla +# product will be installed in. Read-only + +if [[ ! ${_MOZCORECONF} ]]; then + +PYTHON_COMPAT=( python2_7 ) +PYTHON_REQ_USE='ncurses,sqlite,ssl,threads' + +inherit multilib toolchain-funcs flag-o-matic python-any-r1 versionator + +IUSE="${IUSE} custom-cflags custom-optimization" + +DEPEND="virtual/pkgconfig + ${PYTHON_DEPS}" + +# @FUNCTION: mozconfig_annotate +# @DESCRIPTION: +# add an annotated line to .mozconfig +# +# Example: +# mozconfig_annotate "building on ultrasparc" --enable-js-ultrasparc +# => ac_add_options --enable-js-ultrasparc # building on ultrasparc +mozconfig_annotate() { + declare reason=$1 x ; shift + [[ $# -gt 0 ]] || die "mozconfig_annotate missing flags for ${reason}\!" + for x in ${*}; do + echo "ac_add_options ${x} # ${reason}" >>.mozconfig + done +} + +# @FUNCTION: mozconfig_use_enable +# @DESCRIPTION: +# add a line to .mozconfig based on a USE-flag +# +# Example: +# mozconfig_use_enable truetype freetype2 +# => ac_add_options --enable-freetype2 # +truetype +mozconfig_use_enable() { + declare flag=$(use_enable "$@") + mozconfig_annotate "$(use $1 && echo +$1 || echo -$1)" "${flag}" +} + +# @FUNCTION: mozconfig_use_with +# @DESCRIPTION: +# add a line to .mozconfig based on a USE-flag +# +# Example: +# mozconfig_use_with kerberos gss-api /usr/$(get_libdir) +# => ac_add_options --with-gss-api=/usr/lib # +kerberos +mozconfig_use_with() { + declare flag=$(use_with "$@") + mozconfig_annotate "$(use $1 && echo +$1 || echo -$1)" "${flag}" +} + +# @FUNCTION: mozconfig_use_extension +# @DESCRIPTION: +# enable or disable an extension based on a USE-flag +# +# Example: +# mozconfig_use_extension gnome gnomevfs +# => ac_add_options --enable-extensions=gnomevfs +mozconfig_use_extension() { + declare minus=$(use $1 || echo -) + mozconfig_annotate "${minus:-+}$1" --enable-extensions=${minus}${2} +} + +moz_pkgsetup() { + # Ensure we use C locale when building + export LANG="C" + export LC_ALL="C" + export LC_MESSAGES="C" + export LC_CTYPE="C" + + # Ensure we use correct toolchain + export HOST_CC="$(tc-getBUILD_CC)" + export HOST_CXX="$(tc-getBUILD_CXX)" + tc-export CC CXX LD PKG_CONFIG + + # Ensure that we have a sane build enviroment + export MOZILLA_CLIENT=1 + export BUILD_OPT=1 + export NO_STATIC_LIB=1 + export USE_PTHREADS=1 + export ALDFLAGS=${LDFLAGS} + # ensure MOZCONFIG is not defined + unset MOZCONFIG + + # set MOZILLA_FIVE_HOME + export MOZILLA_FIVE_HOME="/usr/$(get_libdir)/${PN}" + + # nested configure scripts in mozilla products generate unrecognized options + # false positives when toplevel configure passes downwards. + export QA_CONFIGURE_OPTIONS=".*" + + if [[ $(gcc-major-version) -eq 3 ]]; then + ewarn "Unsupported compiler detected, DO NOT file bugs for" + ewarn "outdated compilers. Bugs opened with gcc-3 will be closed" + ewarn "invalid." + fi + + python-any-r1_pkg_setup +} + +# @FUNCTION: mozconfig_init +# @DESCRIPTION: +# Initialize mozilla configuration and populate with core settings. +# This should be called in src_configure before any other mozconfig_* functions. +mozconfig_init() { + declare enable_optimize pango_version myext x + declare XUL=$([[ ${PN} == xulrunner ]] && echo true || echo false) + declare FF=$([[ ${PN} == firefox ]] && echo true || echo false) + declare SM=$([[ ${PN} == seamonkey ]] && echo true || echo false) + declare TB=$([[ ${PN} == thunderbird ]] && echo true || echo false) + declare WF=$([[ ${PN} == waterfox* ]] && echo true || echo false) + + #################################### + # + # Setup the initial .mozconfig + # See http://www.mozilla.org/build/configure-build.html + # + #################################### + + case ${PN} in + *xulrunner) + cp xulrunner/config/mozconfig .mozconfig \ + || die "cp xulrunner/config/mozconfig failed" ;; + *firefox|waterfox*) + cp browser/config/mozconfig .mozconfig \ + || die "cp browser/config/mozconfig failed" ;; + seamonkey) + # Must create the initial mozconfig to enable application + : >.mozconfig || die "initial mozconfig creation failed" + mozconfig_annotate "" --enable-application=suite ;; + *thunderbird) + # Must create the initial mozconfig to enable application + : >.mozconfig || die "initial mozconfig creation failed" + mozconfig_annotate "" --enable-application=mail ;; + esac + + #################################### + # + # CFLAGS setup and ARCH support + # + #################################### + + # Set optimization level + if [[ $(gcc-major-version) -ge 7 ]]; then + mozconfig_annotate "Workaround known breakage" --enable-optimize=-O2 + elif [[ ${ARCH} == hppa ]]; then + mozconfig_annotate "more than -O0 causes a segfault on hppa" --enable-optimize=-O0 + elif [[ ${ARCH} == x86 ]]; then + mozconfig_annotate "less then -O2 causes a segfault on x86" --enable-optimize=-O2 + elif use custom-optimization || [[ ${ARCH} =~ (alpha|ia64) ]]; then + # Set optimization level based on CFLAGS + if is-flag -O0; then + mozconfig_annotate "from CFLAGS" --enable-optimize=-O0 + elif [[ ${ARCH} == ppc ]] && has_version '>=sys-libs/glibc-2.8'; then + mozconfig_annotate "more than -O1 segfaults on ppc with glibc-2.8" --enable-optimize=-O1 + elif is-flag -O4; then + mozconfig_annotate "from CFLAGS" --enable-optimize=-O4 + elif is-flag -O3; then + mozconfig_annotate "from CFLAGS" --enable-optimize=-O3 + elif is-flag -O1; then + mozconfig_annotate "from CFLAGS" --enable-optimize=-O1 + elif is-flag -Os; then + mozconfig_annotate "from CFLAGS" --enable-optimize=-Os + else + mozconfig_annotate "Gentoo's default optimization" --enable-optimize=-O2 + fi + else + # Enable Mozilla's default + mozconfig_annotate "mozilla default" --enable-optimize + fi + + # Strip optimization so it does not end up in compile string + filter-flags '-O*' + + # Strip over-aggressive CFLAGS + use custom-cflags || strip-flags + + # Additional ARCH support + case "${ARCH}" in + arm) + # Reduce the memory requirements for linking + append-ldflags -Wl,--no-keep-memory -Wl,--reduce-memory-overheads + ;; + alpha) + # Historically we have needed to add -fPIC manually for 64-bit. + # Additionally, alpha should *always* build with -mieee for correct math + # operation + append-flags -fPIC -mieee + ;; + ia64) + # Historically we have needed to add this manually for 64-bit + append-flags -fPIC + ;; + ppc64) + append-flags -fPIC -mminimal-toc + # Reduce the memory requirements for linking + append-ldflags -Wl,--no-keep-memory -Wl,--reduce-memory-overheads + ;; + esac + + # We need to append flags for gcc-6 support + if [[ $(gcc-major-version) -ge 6 ]]; then + append-cxxflags -fno-delete-null-pointer-checks -fno-lifetime-dse -fno-schedule-insns2 + fi + + # Use the MOZILLA_FIVE_HOME for the rpath + append-ldflags -Wl,-rpath="${MOZILLA_FIVE_HOME}",--enable-new-dtags + # Set MOZILLA_FIVE_HOME in mozconfig + mozconfig_annotate '' --with-default-mozilla-five-home=${MOZILLA_FIVE_HOME} + + #################################### + # + # mozconfig setup + # + #################################### + + mozconfig_annotate disable_update_strip \ + --disable-updater \ + --disable-strip \ + --disable-install-strip + + # jemalloc won't build with older glibc + ! has_version ">=sys-libs/glibc-2.4" && mozconfig_annotate "we have old glibc" --disable-jemalloc +} + +# @FUNCTION: mozconfig_final +# @DESCRIPTION: +# Apply EXTRA_ECONF values to .mozconfig +# Display a table describing all configuration options paired +# with reasons, then clean up extensions list. +# This should be called in src_configure at the end of all other mozconfig_* functions. +mozconfig_final() { + declare ac opt hash reason + + # Apply EXTRA_ECONF entries to .mozconfig + if [[ -n ${EXTRA_ECONF} ]]; then + IFS=\! read -a ac <<<${EXTRA_ECONF// --/\!} + for opt in "${ac[@]}"; do + mozconfig_annotate "EXTRA_ECONF" --${opt#--} + done + fi + + echo + echo "==========================================================" + echo "Building ${PF} with the following configuration" + grep ^ac_add_options .mozconfig | while read ac opt hash reason; do + [[ -z ${hash} || ${hash} == \# ]] \ + || die "error reading mozconfig: ${ac} ${opt} ${hash} ${reason}" + printf " %-30s %s\n" "${opt}" "${reason:-mozilla.org default}" + done + echo "==========================================================" + echo + + # Resolve multiple --enable-extensions down to one + declare exts=$(sed -n 's/^ac_add_options --enable-extensions=\([^ ]*\).*/\1/p' \ + .mozconfig | xargs) + sed -i '/^ac_add_options --enable-extensions/d' .mozconfig + echo "ac_add_options --enable-extensions=${exts// /,}" >> .mozconfig +} + +_MOZCORECONF=1 +fi diff --git a/eclass/mozcoreconf-v6.eclass b/eclass/mozcoreconf-v6.eclass new file mode 100644 index 0000000..0dd165d --- /dev/null +++ b/eclass/mozcoreconf-v6.eclass @@ -0,0 +1,287 @@ +# Copyright 1999-2019 Gentoo Authors +# Distributed under the terms of the GNU General Public License v2 +# +# @ECLASS: mozcoreconf-v6.eclass +# @MAINTAINER: +# Mozilla team <mozilla@gentoo.org> +# @BLURB: core options and configuration functions for mozilla +# @DESCRIPTION: +# +# inherit mozconfig-v6.* or above for mozilla configuration support + +# @ECLASS-VARIABLE: MOZILLA_FIVE_HOME +# @DESCRIPTION: +# This is an eclass-generated variable that defines the rpath that the mozilla +# product will be installed in. Read-only + +if [[ ! ${_MOZCORECONF} ]]; then + +inherit multilib toolchain-funcs flag-o-matic python-any-r1 versionator + +IUSE="${IUSE} custom-cflags custom-optimization" + +DEPEND="virtual/pkgconfig + dev-lang/python:2.7[ncurses,sqlite,ssl,threads(+)] + ${PYTHON_DEPS}" + +# @FUNCTION: mozconfig_annotate +# @DESCRIPTION: +# add an annotated line to .mozconfig +# +# Example: +# mozconfig_annotate "building on ultrasparc" --enable-js-ultrasparc +# => ac_add_options --enable-js-ultrasparc # building on ultrasparc +mozconfig_annotate() { + declare reason=$1 x ; shift + [[ $# -gt 0 ]] || die "mozconfig_annotate missing flags for ${reason}\!" + for x in ${*}; do + echo "ac_add_options ${x} # ${reason}" >>.mozconfig + done +} + +# @FUNCTION: mozconfig_use_enable +# @DESCRIPTION: +# add a line to .mozconfig based on a USE-flag +# +# Example: +# mozconfig_use_enable truetype freetype2 +# => ac_add_options --enable-freetype2 # +truetype +mozconfig_use_enable() { + declare flag=$(use_enable "$@") + mozconfig_annotate "$(use $1 && echo +$1 || echo -$1)" "${flag}" +} + +# @FUNCTION: mozconfig_use_with +# @DESCRIPTION: +# add a line to .mozconfig based on a USE-flag +# +# Example: +# mozconfig_use_with kerberos gss-api /usr/$(get_libdir) +# => ac_add_options --with-gss-api=/usr/lib # +kerberos +mozconfig_use_with() { + declare flag=$(use_with "$@") + mozconfig_annotate "$(use $1 && echo +$1 || echo -$1)" "${flag}" +} + +# @FUNCTION: mozconfig_use_extension +# @DESCRIPTION: +# enable or disable an extension based on a USE-flag +# +# Example: +# mozconfig_use_extension gnome gnomevfs +# => ac_add_options --enable-extensions=gnomevfs +mozconfig_use_extension() { + declare minus=$(use $1 || echo -) + mozconfig_annotate "${minus:-+}$1" --enable-extensions=${minus}${2} +} + +moz_pkgsetup() { + # Ensure we use C locale when building + export LANG="C" + export LC_ALL="C" + export LC_MESSAGES="C" + export LC_CTYPE="C" + + # Ensure we use correct toolchain + export HOST_CC="$(tc-getBUILD_CC)" + export HOST_CXX="$(tc-getBUILD_CXX)" + tc-export CC CXX LD PKG_CONFIG AR RANLIB + + # Ensure that we have a sane build enviroment + export MOZILLA_CLIENT=1 + export BUILD_OPT=1 + export NO_STATIC_LIB=1 + export USE_PTHREADS=1 + export ALDFLAGS=${LDFLAGS} + # ensure MOZCONFIG is not defined + unset MOZCONFIG + + # set MOZILLA_FIVE_HOME + export MOZILLA_FIVE_HOME="/usr/$(get_libdir)/${PN}" + + # nested configure scripts in mozilla products generate unrecognized options + # false positives when toplevel configure passes downwards. + export QA_CONFIGURE_OPTIONS=".*" + + python-any-r1_pkg_setup + # workaround to set python3 into PYTHON3 until mozilla doesn't need py2 + if [[ "${PYTHON_COMPAT[@]}" != "${PYTHON_COMPAT[@]#python3*}" ]]; then + export PYTHON3=${PYTHON} + python_export python2_7 PYTHON EPYTHON + fi +} + +# @FUNCTION: mozconfig_init +# @DESCRIPTION: +# Initialize mozilla configuration and populate with core settings. +# This should be called in src_configure before any other mozconfig_* functions. +mozconfig_init() { + declare enable_optimize pango_version myext x + declare XUL=$([[ ${PN} == xulrunner ]] && echo true || echo false) + declare FF=$([[ ${PN} == firefox ]] && echo true || echo false) + declare SM=$([[ ${PN} == seamonkey ]] && echo true || echo false) + declare TB=$([[ ${PN} == thunderbird ]] && echo true || echo false) + declare TRB=$([[ ${PN} == torbrowser ]] && echo true || echo false) + declare WF=$([[ ${PN} == waterfox* ]] && echo true || echo false) + + #################################### + # + # Setup the initial .mozconfig + # See http://www.mozilla.org/build/configure-build.html + # + #################################### + + case ${PN} in + *xulrunner) + cp xulrunner/config/mozconfig .mozconfig \ + || die "cp xulrunner/config/mozconfig failed" ;; + *firefox|waterfox*) + cp browser/config/mozconfig .mozconfig \ + || die "cp browser/config/mozconfig failed" ;; + *torbrowser) + cp browser/config/mozconfig .mozconfig \ + || die "cp browser/config/mozconfig failed" ;; + seamonkey) + # Must create the initial mozconfig to enable application + : >.mozconfig || die "initial mozconfig creation failed" + # NOTE--this is not compatible with mozilla prior to v60 + mozconfig_annotate "" --enable-application=comm/suite ;; + *thunderbird) + # Must create the initial mozconfig to enable application + : >.mozconfig || die "initial mozconfig creation failed" + # NOTE--this is not compatible with mozilla prior to v60 + mozconfig_annotate "" --enable-application=comm/mail ;; + esac + + #################################### + # + # CFLAGS setup and ARCH support + # + #################################### + + # Set optimization level + if [[ $(gcc-major-version) -eq 7 ]]; then + mozconfig_annotate "Workaround known breakage" --enable-optimize=-O2 + elif [[ ${ARCH} == hppa ]]; then + mozconfig_annotate "more than -O0 causes a segfault on hppa" --enable-optimize=-O0 + elif [[ ${ARCH} == x86 ]]; then + mozconfig_annotate "less than -O2 causes a segfault on x86" --enable-optimize=-O2 + elif [[ ${ARCH} == arm ]] && [[ $(gcc-major-version) -ge 6 ]]; then + mozconfig_annotate "less than -O2 causes a breakage on arm with gcc-6" --enable-optimize=-O2 + elif use custom-optimization || [[ ${ARCH} =~ (alpha|ia64) ]]; then + # Set optimization level based on CFLAGS + if is-flag -O0; then + mozconfig_annotate "from CFLAGS" --enable-optimize=-O0 + elif [[ ${ARCH} == ppc ]] && has_version '>=sys-libs/glibc-2.8'; then + mozconfig_annotate "more than -O1 segfaults on ppc with glibc-2.8" --enable-optimize=-O1 + elif is-flag -O4; then + mozconfig_annotate "from CFLAGS" --enable-optimize=-O4 + elif is-flag -O3; then + mozconfig_annotate "from CFLAGS" --enable-optimize=-O3 + elif is-flag -O1; then + mozconfig_annotate "from CFLAGS" --enable-optimize=-O1 + elif is-flag -Os; then + mozconfig_annotate "from CFLAGS" --enable-optimize=-Os + else + mozconfig_annotate "Gentoo's default optimization" --enable-optimize=-O2 + fi + else + # Enable Mozilla's default + mozconfig_annotate "mozilla default" --enable-optimize + fi + + # Strip optimization so it does not end up in compile string + filter-flags '-O*' + + if is-flagq '-g*' ; then + mozconfig_annotate 'elf-hack broken with -g* flags' --disable-elf-hack + fi + + # Strip over-aggressive CFLAGS + use custom-cflags || strip-flags + + # Additional ARCH support + case "${ARCH}" in + arm | ppc64) + # Reduce the memory requirements for linking + if [[ "${PN}" != seamonkey ]] && use clang ; then + # Nothing to do + :; + elif tc-ld-is-gold; then + append-ldflags -Wl,--no-keep-memory + else + append-ldflags -Wl,--no-keep-memory -Wl,--reduce-memory-overheads + fi + ;; + alpha) + # Historically we have needed to add -fPIC manually for 64-bit. + # Additionally, alpha should *always* build with -mieee for correct math + # operation + append-flags -fPIC -mieee + ;; + ia64) + # Historically we have needed to add this manually for 64-bit + append-flags -fPIC + ;; + esac + + # We need to append flags for gcc-6 support + if [[ $(gcc-major-version) -ge 6 ]]; then + append-cxxflags -flifetime-dse=1 + fi + + # Use the MOZILLA_FIVE_HOME for the rpath + append-ldflags -Wl,-rpath="${MOZILLA_FIVE_HOME}",--enable-new-dtags + + #################################### + # + # mozconfig setup + # + #################################### + + mozconfig_annotate disable_update_strip \ + --disable-updater \ + --disable-strip \ + --disable-install-strip + + # jemalloc won't build with older glibc + ! has_version ">=sys-libs/glibc-2.4" && mozconfig_annotate "we have old glibc" --disable-jemalloc +} + +# @FUNCTION: mozconfig_final +# @DESCRIPTION: +# Apply EXTRA_ECONF values to .mozconfig +# Display a table describing all configuration options paired +# with reasons, then clean up extensions list. +# This should be called in src_configure at the end of all other mozconfig_* functions. +mozconfig_final() { + declare ac opt hash reason + + # Apply EXTRA_ECONF entries to .mozconfig + if [[ -n ${EXTRA_ECONF} ]]; then + IFS=\! read -a ac <<<${EXTRA_ECONF// --/\!} + for opt in "${ac[@]}"; do + mozconfig_annotate "EXTRA_ECONF" --${opt#--} + done + fi + + echo + echo "==========================================================" + echo "Building ${PF} with the following configuration" + grep ^ac_add_options .mozconfig | while read ac opt hash reason; do + [[ -z ${hash} || ${hash} == \# ]] \ + || die "error reading mozconfig: ${ac} ${opt} ${hash} ${reason}" + printf " %-30s %s\n" "${opt}" "${reason:-mozilla.org default}" + done + echo "==========================================================" + echo + + # Resolve multiple --enable-extensions down to one + declare exts=$(sed -n 's/^ac_add_options --enable-extensions=\([^ ]*\).*/\1/p' \ + .mozconfig | xargs) + sed -i '/^ac_add_options --enable-extensions/d' .mozconfig + echo "ac_add_options --enable-extensions=${exts// /,}" >> .mozconfig +} + +_MOZCORECONF=1 +fi diff --git a/eclass/mozextension.eclass b/eclass/mozextension.eclass new file mode 100644 index 0000000..c627690 --- /dev/null +++ b/eclass/mozextension.eclass @@ -0,0 +1,125 @@ +# Copyright 1999-2020 Gentoo Authors +# Distributed under the terms of the GNU General Public License v2 +# +# @ECLASS: mozextension.eclass +# @MAINTAINER: +# Mozilla team <mozilla@gentoo.org> +# @BLURB: Install extensions for use in mozilla products. +# +if [[ ! ${_MOZEXTENSION} ]]; then + +# @ECLASS-VARIABLE: MOZEXTENSION_TARGET +# @DESCRIPTION: +# This variable allows the installation path for xpi_install +# to be overridden from the default app-global extensions path. +# Default is empty, which installs to predetermined hard-coded +# paths specified in the eclass. +: ${MOZEXTENSION_TARGET:=""} + +inherit eutils + +DEPEND="app-arch/unzip" + +mozversion_extension_location() { + case ${PN} in + firefox|firefox-bin|palemoon) + if [[ $(get_version_component_range 1) -ge 21 ]] ; then + return 0 + fi + ;; + esac + + return 1 +} + +xpi_unpack() { + local xpi xpiname srcdir + + # Not gonna use ${A} as we are looking for a specific option being passed to function + # You must specify which xpi to use + [[ -z "$*" ]] && die "Nothing passed to the $FUNCNAME command. please pass which xpi to unpack" + + for xpi in "$@"; do + einfo "Unpacking ${xpi} to ${PWD}" + xpiname=$(basename ${xpi%.*}) + + if [[ "${xpi:0:2}" != "./" ]] && [[ "${xpi:0:1}" != "/" ]] ; then + srcdir="${DISTDIR}/" + fi + + [[ -s "${srcdir}${xpi}" ]] || die "${xpi} does not exist" + + case "${xpi##*.}" in + ZIP|zip|jar|xpi) + mkdir "${WORKDIR}/${xpiname}" && \ + unzip -qo "${srcdir}${xpi}" -d "${WORKDIR}/${xpiname}" || die "failed to unpack ${xpi}" + ;; + *) + einfo "unpack ${xpi}: file format not recognized. Ignoring." + ;; + esac + done +} + + +xpi_install() { + local emid + + # You must tell xpi_install which xpi to use + [[ ${#} -ne 1 ]] && die "$FUNCNAME takes exactly one argument, please specify an xpi to unpack" + + x="${1}" + #cd ${x} + # determine id for extension + if [[ -f "${x}"/install.rdf ]]; then + emid="$(sed -n -e '/install-manifest/,$ { /em:id/!d; s/.*[\">]\([^\"<>]*\)[\"<].*/\1/; p; q }' "${x}"/install.rdf)" + [[ -z "${emid}" ]] && die "failed to determine extension id from install.rdf" + elif [[ -f "${x}"/manifest.json ]]; then + emid="$( sed -n 's/.*"id": "\(.*\)".*/\1/p' "${x}"/manifest.json )" + [[ -z "${emid}" ]] && die "failed to determine extension id from manifest.json" + else + die "failed to determine extension id" + fi + + if [[ -n ${MOZEXTENSION_TARGET} ]]; then + insinto "${MOZILLA_FIVE_HOME}"/${MOZEXTENSION_TARGET%/}/${emid} + elif $(mozversion_extension_location) ; then + insinto "${MOZILLA_FIVE_HOME}"/browser/extensions/${emid} + else + insinto "${MOZILLA_FIVE_HOME}"/extensions/${emid} + fi + doins -r "${x}"/* || die "failed to copy extension" +} + +xpi_copy() { + local emid + + # You must tell xpi_install which xpi to use + [[ ${#} -ne 1 ]] && die "$FUNCNAME takes exactly one argument, please specify an xpi to unpack" + + x="${1}" + #cd ${x} + # determine id for extension + if [[ -f "${x}"/install.rdf ]]; then + emid="$(sed -n -e '/install-manifest/,$ { /em:id/!d; s/.*[\">]\([^\"<>]*\)[\"<].*/\1/; p; q }' "${x}"/install.rdf)" + [[ -z "${emid}" ]] && die "failed to determine extension id from install.rdf" + elif [[ -f "${x}"/manifest.json ]]; then + emid="$(sed -n 's/.*"id": "\([^"]*\)".*/\1/p' "${x}"/manifest.json)" + [[ -z "${emid}" ]] && die "failed to determine extension id from manifest.json" + else + die "failed to determine extension id" + fi + + if [[ -n ${MOZEXTENSION_TARGET} ]]; then + insinto "${MOZILLA_FIVE_HOME}"/${MOZEXTENSION_TARGET%/} + elif $(mozversion_extension_location) ; then + insinto "${MOZILLA_FIVE_HOME}"/browser/extensions + else + insinto "${MOZILLA_FIVE_HOME}"/extensions + fi + + newins "${DISTDIR%/}"/${x##*/}.xpi ${emid}.xpi +} + +_MOZEXTENSION=1 +fi diff --git a/eclass/mozlinguas-v2.eclass b/eclass/mozlinguas-v2.eclass new file mode 100644 index 0000000..7795a85 --- /dev/null +++ b/eclass/mozlinguas-v2.eclass @@ -0,0 +1,391 @@ +# Copyright 1999-2015 Gentoo Foundation +# Distributed under the terms of the GNU General Public License v2 + +# @ECLASS: mozlinguas-v2.eclass +# @MAINTAINER: +# mozilla@gentoo.org +# @AUTHOR: +# Nirbheek Chauhan <nirbheek@gentoo.org> +# Ian Stakenvicius <axs@gentoo.org> +# @SUPPORTED_EAPIS: 2 3 4 5 6 +# @BLURB: Handle language packs for mozilla products +# @DESCRIPTION: +# Sets IUSE according to MOZ_LANGS (language packs available). Also exports +# src_unpack, src_compile and src_install for use in ebuilds, and provides +# supporting functions for langpack generation and installation. + +inherit mozextension + +case "${EAPI:-0}" in + 0|1) + die "EAPI ${EAPI:-0} does not support the '->' SRC_URI operator";; + 2|3|4|5|6) + inherit eapi7-ver + EXPORT_FUNCTIONS src_unpack src_compile src_install;; + + *) + die "EAPI ${EAPI} is not supported, contact eclass maintainers";; +esac + +# @ECLASS-VARIABLE: MOZ_LANGS +# @DESCRIPTION: +# Array containing the list of language pack xpis available for +# this release. The list can be updated with scripts/get_langs.sh from the +# mozilla overlay. +: ${MOZ_LANGS:=()} + +# @ECLASS-VARIABLE: MOZ_PV +# @DESCRIPTION: +# Ebuild package version converted to equivalent upstream version. +# Defaults to ${PV}, and should be overridden for alphas, betas, and RCs +: ${MOZ_PV:="${PV}"} + +# @ECLASS-VARIABLE: MOZ_PN +# @DESCRIPTION: +# Ebuild package name converted to equivalent upstream name. +# Defaults to ${PN}, and should be overridden for binary ebuilds. +: ${MOZ_PN:="${PN}"} + +# @ECLASS-VARIABLE: MOZ_P +# @DESCRIPTION: +# Ebuild package name + version converted to upstream equivalent. +# Defaults to ${MOZ_PN}-${MOZ_PV} +: ${MOZ_P:="${MOZ_PN}-${MOZ_PV}"} + +# @ECLASS-VARIABLE: MOZ_FTP_URI +# @DESCRIPTION: +# The ftp URI prefix for the release tarballs and language packs. +: ${MOZ_FTP_URI:=""} + +# @ECLASS-VARIABLE: MOZ_HTTP_URI +# @DESCRIPTION: +# The http URI prefix for the release tarballs and language packs. +: ${MOZ_HTTP_URI:=""} + +# @ECLASS-VARIABLE: MOZ_LANGPACK_HTTP_URI +# @DESCRIPTION: +# An alternative http URI if it differs from official mozilla URI. +# Defaults to whatever MOZ_HTTP_URI was set to. +: ${MOZ_LANGPACK_HTTP_URI:=${MOZ_HTTP_URI}} + +# @ECLASS-VARIABLE: MOZ_LANGPACK_PREFIX +# @DESCRIPTION: +# The relative path till the lang code in the langpack file URI. +# Defaults to ${MOZ_PV}/linux-i686/xpi/ +: ${MOZ_LANGPACK_PREFIX:="${MOZ_PV}/linux-i686/xpi/"} + +# @ECLASS-VARIABLE: MOZ_LANGPACK_SUFFIX +# @DESCRIPTION: +# The suffix after the lang code in the langpack file URI. +# Defaults to '.xpi' +: ${MOZ_LANGPACK_SUFFIX:=".xpi"} + +# @ECLASS-VARIABLE: MOZ_LANGPACK_UNOFFICIAL +# @DESCRIPTION: +# The status of the langpack, used to differentiate within +# Manifests and on Gentoo mirrors as to when the langpacks are +# generated officially by Mozilla or if they were generated +# unofficially by others (ie the Gentoo mozilla team). When +# this var is set, the distfile will have a .unofficial.xpi +# suffix. +: ${MOZ_LANGPACK_UNOFFICIAL:=""} + +# @ECLASS-VARIABLE: MOZ_GENERATE_LANGPACKS +# @DESCRIPTION: +# This flag specifies whether or not the langpacks should be +# generated directly during the build process, rather than +# being downloaded and installed from upstream pre-built +# extensions. Primarily it supports pre-release builds. +# Defaults to empty. +: ${MOZ_GENERATE_LANGPACKS:=""} + +# @ECLASS-VARIABLE: MOZ_L10N_SOURCEDIR +# @DESCRIPTION: +# The path that l10n sources can be found at, once unpacked. +# Defaults to ${WORKDIR}/l10n-sources +: ${MOZ_L10N_SOURCEDIR:="${WORKDIR}/l10n-sources"} + +# @ECLASS-VARIABLE: MOZ_L10N_URI_PREFIX +# @DESCRIPTION: +# The full URI prefix of the distfile for each l10n locale. The +# AB_CD and MOZ_L10N_URI_SUFFIX will be appended to this to complete the +# SRC_URI when MOZ_GENERATE_LANGPACKS is set. If empty, nothing will +# be added to SRC_URI. +# Defaults to empty. +: ${MOZ_L10N_URI_PREFIX:=""} + +# @ECLASS-VARIABLE: MOZ_L10N_URI_SUFFIX +# @DESCRIPTION: +# The suffix of l10n source distfiles. +# Defaults to '.tar.xz' +: ${MOZ_L10N_URI_SUFFIX:=".tar.xz"} + +# @ECLASS-VARIABLE: MOZ_FORCE_UPSTREAM_L10N +# @DESCRIPTION: +# Set this to use upstream langpaks even if the package normally +# shouldn't (ie it is an alpha or beta package) +: ${MOZ_FORCE_UPSTREAM_L10N:=""} + +# @ECLASS-VARIABLE: MOZ_TOO_REGIONALIZED_FOR_L10N +# @INTERNAL +# @DESCRIPTION: +# Upstream identifiers that should not contain region subtags in L10N +MOZ_TOO_REGIONALIZED_FOR_L10N=( fy-NL ga-IE gu-IN hi-IN hy-AM nb-NO nn-NO pa-IN sv-SE ) + +# @ECLASS-VARIABLE: MOZ_INSTALL_L10N_XPIFILE +# @DESCRIPTION: +# Install langpacks as .xpi file instead of unpacked directory. +# Leave unset to install unpacked +: ${MOZ_INSTALL_L10N_XPIFILE:=""} + +# Add l10n_* to IUSE according to available language packs +# No language packs for alphas and betas +if ! [[ -n ${MOZ_GENERATE_LANGPACKS} ]] ; then + if ! [[ ${PV} =~ alpha|beta ]] || { [[ ${PN} == seamonkey ]] && ! [[ ${PV} =~ alpha ]] ; } || [[ -n ${MOZ_FORCE_UPSTREAM_L10N} ]] ; then + [[ -z ${MOZ_FTP_URI} ]] && [[ -z ${MOZ_LANGPACK_HTTP_URI} ]] && die "No URI set to download langpacks, please set one of MOZ_{FTP,HTTP_LANGPACK}_URI" + for x in "${MOZ_LANGS[@]}" ; do + # en and en_US are handled internally + if [[ ${x} == en ]] || [[ ${x} == en-US ]]; then + continue + fi + # strip region subtag if $x is in the list + if has ${x} "${MOZ_TOO_REGIONALIZED_FOR_L10N[@]}" ; then + xflag=${x%%-*} + else + xflag=${x} + fi + SRC_URI+=" l10n_${xflag/[_@]/-}? (" + [[ -n ${MOZ_FTP_URI} ]] && SRC_URI+=" + ${MOZ_FTP_URI}/${MOZ_LANGPACK_PREFIX}${x}${MOZ_LANGPACK_SUFFIX} -> ${MOZ_P}-${x}${MOZ_LANGPACK_UNOFFICIAL:+.unofficial}.xpi" + [[ -n ${MOZ_LANGPACK_HTTP_URI} ]] && SRC_URI+=" + ${MOZ_LANGPACK_HTTP_URI}/${MOZ_LANGPACK_PREFIX}${x}${MOZ_LANGPACK_SUFFIX} -> ${MOZ_P}-${x}${MOZ_LANGPACK_UNOFFICIAL:+.unofficial}.xpi" + SRC_URI+=" )" + IUSE+=" l10n_${xflag/[_@]/-}" + # We used to do some magic if specific/generic locales were missing, but + # we stopped doing that due to bug 325195. + done + fi +else + for x in "${MOZ_LANGS[@]}" ; do + # en and en_US are handled internally + if [[ ${x} == en ]] || [[ ${x} == en-US ]]; then + continue + fi + # strip region subtag if $x is in the list + if has ${x} "${MOZ_TOO_REGIONALIZED_FOR_L10N[@]}" ; then + xflag=${x%%-*} + else + xflag=${x} + fi +# Do NOT grab l10n sources from hg tip at this time, since it is a moving target +# if [[ ${PV} =~ alpha ]]; then +# # Please note that this URI is not deterministic - digest breakage could occur +# SRC_URI+=" l10n_${xflag/[_@]/-}? ( http://hg.mozilla.org/releases/l10n/mozilla-aurora/ach/archive/tip.tar.bz2 -> ${MOZ_P}-l10n-${x}.tar.bz2 )" +# elif [[ ${PV} =~ beta ]] && ! [[ ${PN} == seamonkey ]]; then +# # Please note that this URI is not deterministic - digest breakage could occur +# SRC_URI+=" l10n_${xflag/[_@]/-}? ( http://hg.mozilla.org/releases/l10n/mozilla-beta/ach/archive/tip.tar.bz2 -> ${MOZ_P}-l10n-${x}.tar.bz2 )" +# elif [[ -n ${MOZ_L10N_URI_PREFIX} ]]; then + if [[ -n ${MOZ_L10N_URI_PREFIX} ]]; then + SRC_URI+=" l10n_${xflag/[_@]/-}? ( ${MOZ_L10N_URI_PREFIX}${x}${MOZ_L10N_URI_SUFFIX} )" + fi + IUSE+=" l10n_${xflag/[_@]/-}" + done +fi +unset x xflag + +# @FUNCTION: mozlinguas_export +# @INTERNAL +# @DESCRIPTION: +# Generate the list of language packs called "mozlinguas" +# This list is used to unpack and install the xpi language packs +mozlinguas_export() { + if [[ ${PN} == seamonkey ]] ; then + [[ ${PV} =~ alpha ]] && ! [[ -n ${MOZ_GENERATE_LANGPACKS} ]] && return + else + [[ ${PV} =~ alpha|beta ]] && ! [[ -n ${MOZ_GENERATE_LANGPACKS} ]] && return + fi + local lingua lflag + mozlinguas=() + # Set mozlinguas based on the enabled l10n_* USE flags. + for lingua in "${MOZ_LANGS[@]}"; do + # strip region subtag if $x is in the list + if has ${lingua} en en-US; then + # For mozilla products, en and en_US are handled internally + continue + elif has ${lingua} "${MOZ_TOO_REGIONALIZED_FOR_L10N[@]}" ; then + lflag=${lingua%%-*} + else + lflag=${lingua} + fi + use l10n_${lflag/[_@]/-} && mozlinguas+=( ${lingua} ) + done + # Compatibility code - Check LINGUAS and warn if anything set there isn't enabled via l10n + for lingua in ${LINGUAS}; do + if has ${lingua//[_@]/-} en en-US; then + # For mozilla products, en and en_US are handled internally + continue + # If this language is supported by ${P}, + elif has ${lingua} "${MOZ_LANGS[@]//-/_}"; then + # Warn the language is missing, if it isn't already there + has ${lingua//[_@]/-} "${mozlinguas[@]//[_@]/-}" || \ + ewarn "LINGUAS value ${lingua} is not enabled using L10N use flags" + continue + # For each short lingua that isn't in MOZ_LANGS, + # We used to add *all* long MOZ_LANGS to the mozlinguas list, + # but we stopped doing that due to bug 325195. + else + : + fi + einfo "Sorry, but ${P} does not support the ${lingua} locale in LINGUAS" + done +} + +# @FUNCTION: mozlinguas_src_unpack +# @DESCRIPTION: +# Unpack xpi language packs according to the user's LINGUAS settings +mozlinguas_src_unpack() { + local x + if ! [[ -n ${MOZ_GENERATE_LANGPACKS} ]]; then + mozlinguas_export + for x in "${mozlinguas[@]}"; do + # FIXME: Add support for unpacking xpis to portage + xpi_unpack "${MOZ_P}-${x}${MOZ_LANGPACK_UNOFFICIAL:+.unofficial}.xpi" + done + if [[ "${mozlinguas[*]}" != "" && "${mozlinguas[*]}" != "en" ]]; then + einfo "Selected language packs (first will be default): ${mozlinguas[*]}" + fi + fi +} +# For the phase function export +mozlinguas-v2_src_unpack() { + mozlinguas_src_unpack +} + + +# @FUNCTION: mozlinguas_mozconfig +# @DESCRIPTION: +# if applicable, add the necessary flag to .mozconfig to support +# the generation of locales. Note that this function requires +# mozconfig_annontate to already be declared via an inherit of +# mozconfig or mozcoreconf. +mozlinguas_mozconfig() { + if [[ -n ${MOZ_GENERATE_LANGPACKS} ]]; then + if declare -f mozconfig_annotate >/dev/null ; then + mozconfig_annotate 'for building locales' --with-l10n-base=${MOZ_L10N_SOURCEDIR} + else + die "Could not configure l10n-base, mozconfig_annotate not declared -- missing inherit?" + fi + fi +} + +# @FUNCTION: mozlinguas_src_compile +# @DESCRIPTION: +# if applicable, build the selected locales. +mozlinguas_src_compile() { + if [[ -n ${MOZ_GENERATE_LANGPACKS} ]]; then + # leverage BUILD_OBJ_DIR if set otherwise assume PWD. + local x y targets=( "langpack" ) localedir="${BUILD_OBJ_DIR:-.}" + case ${PN} in + *firefox) + localedir+="/browser/locales" + ;; + seamonkey) + if [[ "$(ver_cut 2)" -gt 53 ]] || { [[ "$(ver_cut 2)" -eq 53 ]] && [[ "$(ver_cut 3)" -ge 6 ]] ; } ; then + localedir+="/comm" + fi + localedir+="/suite/locales" + ;; + *thunderbird) + localedir+="/mail/locales" + targets+=( "calendar-langpack" ) + ;; + *) die "Building locales for ${PN} is not supported." + esac + pushd "${localedir}" > /dev/null || die + mozlinguas_export + for x in "${mozlinguas[@]}"; do for y in "${targets[@]}"; do + emake ${y}-${x} LOCALE_MERGEDIR="./${y}-${x}" + done; done + popd > /dev/null || die + fi +} + +# For the phase function export +mozlinguas-v2_src_compile() { + mozlinguas_src_compile +} + +# @FUNCTION: mozlinguas_xpistage_langpacks +# @DESCRIPTION: +# Add extra langpacks to the xpi-stage dir for prebuilt plugins +# +# First argument is the path to the extension +# Second argument is the prefix of the source (same as first if unspecified) +# Remaining arguments are the modules in the extension that are localized +# (basename of first if unspecified) +# +# Example - installing extra langpacks for lightning: +# src_install() { +# ... # general installation steps +# mozlinguas_xpistage_langpacks \ +# "${BUILD_OBJ_DIR}"/dist/xpi-stage/lightning \ +# "${WORKDIR}"/lightning \ +# lightning calendar +# ... # proceed with installation from the xpi-stage dir +# } + +mozlinguas_xpistage_langpacks() { + local l c modpath="${1}" srcprefix="${1}" modules=( "${1##*/}" ) + shift + if [[ -n ${1} ]] ; then srcprefix="${1}" ; shift ; fi + if [[ -n ${1} ]] ; then modules=( $@ ) ; fi + + mozlinguas_export + mkdir -p "${modpath}/chrome" || die + for l in "${mozlinguas[@]}"; do for c in "${modules[@]}" ; do + if [[ -e "${srcprefix}-${l}/chrome/${c}-${l}" ]]; then + cp -RLp -t "${modpath}/chrome" "${srcprefix}-${l}/chrome/${c}-${l}" || die + grep "locale ${c} ${l} chrome/" "${srcprefix}-${l}/chrome.manifest" \ + >>"${modpath}/chrome.manifest" || die + elif [[ -e "${srcprefix}/chrome/${c}-${l}" ]]; then + cp -RLp -t "${modpath}/chrome" "${srcprefix}/chrome/${c}-${l}" || die + grep "locale ${c} ${l} chrome/" "${srcprefix}/chrome.manifest" \ + >>"${modpath}/chrome.manifest" || die + else + ewarn "Locale ${l} was not found for ${c}, skipping." + fi + done; done +} + +# @FUNCTION: mozlinguas-v2_src_install +# @DESCRIPTION: +# Install xpi language packs according to the user's L10N settings +# NOTE - uses ${BUILD_OBJ_DIR} or PWD if unset, for source-generated langpacks +mozlinguas_src_install() { + local x + mozlinguas_export + if [[ -n ${MOZ_GENERATE_LANGPACKS} ]] && [[ -n ${mozlinguas[*]} ]]; then + local repopath="${WORKDIR}/${PN}-generated-langpacks" + mkdir -p "${repopath}" || die + pushd "${BUILD_OBJ_DIR:-.}"/dist/*/xpi > /dev/null || die + for x in "${mozlinguas[@]}"; do + cp "${MOZ_P}.${x}.langpack.xpi" \ + "${repopath}/${MOZ_P}-${x}${MOZ_LANGPACK_UNOFFICIAL:+.unofficial}.xpi" || die + xpi_unpack "${repopath}/${MOZ_P}-${x}${MOZ_LANGPACK_UNOFFICIAL:+.unofficial}.xpi" + done + popd > /dev/null || die + fi + + for x in "${mozlinguas[@]}"; do + if [[ -n ${MOZ_INSTALL_L10N_XPIFILE} ]]; then + xpi_copy "${WORKDIR}/${MOZ_P}-${x}${MOZ_LANGPACK_UNOFFICIAL:+.unofficial}" + else + xpi_install "${WORKDIR}/${MOZ_P}-${x}${MOZ_LANGPACK_UNOFFICIAL:+.unofficial}" + fi + done +} + +# For the phase function export +mozlinguas-v2_src_install() { + mozlinguas_src_install +} diff --git a/eclass/multibuild.eclass b/eclass/multibuild.eclass new file mode 100644 index 0000000..8f9612b --- /dev/null +++ b/eclass/multibuild.eclass @@ -0,0 +1,276 @@ +# Copyright 1999-2020 Gentoo Authors +# Distributed under the terms of the GNU General Public License v2 + +# @ECLASS: multibuild.eclass +# @MAINTAINER: +# Michał Górny <mgorny@gentoo.org> +# @AUTHOR: +# Author: Michał Górny <mgorny@gentoo.org> +# @SUPPORTED_EAPIS: 4 5 6 7 +# @BLURB: A generic eclass for building multiple variants of packages. +# @DESCRIPTION: +# The multibuild eclass aims to provide a generic framework for building +# multiple 'variants' of a package (e.g. multilib, Python +# implementations). + +case "${EAPI:-0}" in + 0|1|2|3) + die "Unsupported EAPI=${EAPI:-0} (too old) for ${ECLASS}" + ;; + 4|5|6|7) + ;; + *) + die "Unsupported EAPI=${EAPI} (unknown) for ${ECLASS}" + ;; +esac + +if [[ ! ${_MULTIBUILD} ]]; then + +# @ECLASS-VARIABLE: MULTIBUILD_VARIANTS +# @REQUIRED +# @DESCRIPTION: +# An array specifying all enabled variants which multibuild_foreach* +# can execute the process for. +# +# In ebuild, it can be set in global scope. Eclasses should set it +# locally in function scope to support nesting properly. +# +# Example: +# @CODE +# python_foreach_impl() { +# local MULTIBUILD_VARIANTS=( python{2_5,2_6,2_7} ... ) +# multibuild_foreach_variant python_compile +# } +# @CODE + +# @ECLASS-VARIABLE: MULTIBUILD_VARIANT +# @OUTPUT_VARIABLE +# @DESCRIPTION: +# The current variant which the function was executed for. +# +# Example value: +# @CODE +# python2_6 +# @CODE + +# @ECLASS-VARIABLE: MULTIBUILD_ID +# @OUTPUT_VARIABLE +# @DESCRIPTION: +# The unique identifier for a multibuild run. In a simple run, it is +# equal to MULTIBUILD_VARIANT. In a nested multibuild environment, it +# contains the complete selection tree. +# +# It can be used to create variant-unique directories and files. +# +# Example value: +# @CODE +# amd64-double +# @CODE + +# @ECLASS-VARIABLE: BUILD_DIR +# @OUTPUT_VARIABLE +# @DEFAULT_UNSET +# @DESCRIPTION: +# The current build directory. In global scope, it is supposed +# to contain an 'initial' build directory. If unset, ${S} is used. +# +# multibuild_foreach_variant() sets BUILD_DIR locally +# to variant-specific build directories based on the initial value +# of BUILD_DIR. +# +# Example value: +# @CODE +# ${WORKDIR}/foo-1.3-python2_6 +# @CODE + +# @FUNCTION: multibuild_foreach_variant +# @USAGE: [<argv>...] +# @DESCRIPTION: +# Run the passed command repeatedly for each of the enabled package +# variants. +# +# Each of the runs will have variant-specific BUILD_DIR set, and output +# teed to a separate log in ${T}. +# +# The function returns 0 if all commands return 0, or the first non-zero +# exit status otherwise. However, it performs all the invocations +# nevertheless. It is preferred to call 'die' inside of the passed +# function. +multibuild_foreach_variant() { + debug-print-function ${FUNCNAME} "${@}" + + [[ ${MULTIBUILD_VARIANTS} ]] \ + || die "MULTIBUILD_VARIANTS need to be set" + + local bdir=${BUILD_DIR:-${S}} + + # Avoid writing outside WORKDIR if S=${WORKDIR}. + [[ ${bdir%%/} == ${WORKDIR%%/} ]] && bdir=${WORKDIR}/build + + local prev_id=${MULTIBUILD_ID:+${MULTIBUILD_ID}-} + local ret=0 lret=0 v + + debug-print "${FUNCNAME}: initial build_dir = ${bdir}" + + for v in "${MULTIBUILD_VARIANTS[@]}"; do + local MULTIBUILD_VARIANT=${v} + local MULTIBUILD_ID=${prev_id}${v} + local BUILD_DIR=${bdir%%/}-${v} + + _multibuild_run() { + # find the first non-private command + local i=1 + while [[ ${!i} == _* ]]; do + (( i += 1 )) + done + + [[ ${i} -le ${#} ]] && einfo "${v}: running ${@:${i}}" + "${@}" + } + + _multibuild_run "${@}" \ + > >(exec tee -a "${T}/build-${MULTIBUILD_ID}.log") 2>&1 + lret=${?} + done + [[ ${ret} -eq 0 && ${lret} -ne 0 ]] && ret=${lret} + + return ${ret} +} + +# @FUNCTION: multibuild_parallel_foreach_variant +# @USAGE: [<argv>...] +# @DESCRIPTION: +# Run the passed command repeatedly for each of the enabled package +# variants. This used to run the commands in parallel but now it's +# just a deprecated alias to multibuild_foreach_variant. +# +# The function returns 0 if all commands return 0, or the first non-zero +# exit status otherwise. However, it performs all the invocations +# nevertheless. It is preferred to call 'die' inside of the passed +# function. +multibuild_parallel_foreach_variant() { + debug-print-function ${FUNCNAME} "${@}" + + [[ ${EAPI} == [45] ]] || die "${FUNCNAME} is banned in EAPI ${EAPI}" + + multibuild_foreach_variant "${@}" +} + +# @FUNCTION: multibuild_for_best_variant +# @USAGE: [<argv>...] +# @DESCRIPTION: +# Run the passed command once, for the best of the enabled package +# variants. +# +# The run will have a proper, variant-specificBUILD_DIR set, and output +# teed to a separate log in ${T}. +# +# The function returns command exit status. +multibuild_for_best_variant() { + debug-print-function ${FUNCNAME} "${@}" + + [[ ${MULTIBUILD_VARIANTS} ]] \ + || die "MULTIBUILD_VARIANTS need to be set" + + # bash-4.1 can't handle negative subscripts + local MULTIBUILD_VARIANTS=( + "${MULTIBUILD_VARIANTS[$(( ${#MULTIBUILD_VARIANTS[@]} - 1 ))]}" + ) + multibuild_foreach_variant "${@}" +} + +# @FUNCTION: multibuild_copy_sources +# @DESCRIPTION: +# Create per-variant copies of source tree. The source tree is assumed +# to be in ${BUILD_DIR}, or ${S} if the former is unset. The copies will +# be placed in directories matching BUILD_DIRs used by +# multibuild_foreach(). +multibuild_copy_sources() { + debug-print-function ${FUNCNAME} "${@}" + + local _MULTIBUILD_INITIAL_BUILD_DIR=${BUILD_DIR:-${S}} + + einfo "Will copy sources from ${_MULTIBUILD_INITIAL_BUILD_DIR}" + + local cp_args=() + if cp --reflink=auto --version &>/dev/null; then + # enable reflinking if possible to make this faster + cp_args+=( --reflink=auto ) + fi + + _multibuild_create_source_copy() { + einfo "${MULTIBUILD_VARIANT}: copying to ${BUILD_DIR}" + cp -p -R "${cp_args[@]}" \ + "${_MULTIBUILD_INITIAL_BUILD_DIR}" "${BUILD_DIR}" || die + } + + multibuild_foreach_variant _multibuild_create_source_copy +} + +# @FUNCTION: run_in_build_dir +# @USAGE: <argv>... +# @DESCRIPTION: +# Run the given command in the directory pointed by BUILD_DIR. +run_in_build_dir() { + debug-print-function ${FUNCNAME} "${@}" + local ret + + [[ ${#} -ne 0 ]] || die "${FUNCNAME}: no command specified." + [[ ${BUILD_DIR} ]] || die "${FUNCNAME}: BUILD_DIR not set." + + mkdir -p "${BUILD_DIR}" || die + pushd "${BUILD_DIR}" >/dev/null || die + "${@}" + ret=${?} + popd >/dev/null || die + + return ${ret} +} + +# @FUNCTION: multibuild_merge_root +# @USAGE: <src-root> <dest-root> +# @DESCRIPTION: +# Merge the directory tree (fake root) from <src-root> to <dest-root> +# (the real root). Both directories have to be real, absolute paths +# (i.e. including ${D}). Source root will be removed. +multibuild_merge_root() { + local src=${1} + local dest=${2} + + local ret + + if use userland_BSD; then + # Most of BSD variants fail to copy broken symlinks, #447370 + # also, they do not support --version + + tar -C "${src}" -f - -c . \ + | tar -x -f - -C "${dest}" + [[ ${PIPESTATUS[*]} == '0 0' ]] + ret=${?} + else + local cp_args=() + + if cp -a --version &>/dev/null; then + cp_args+=( -a ) + else + cp_args+=( -P -R -p ) + fi + + if cp --reflink=auto --version &>/dev/null; then + # enable reflinking if possible to make this faster + cp_args+=( --reflink=auto ) + fi + + cp "${cp_args[@]}" "${src}"/. "${dest}"/ + ret=${?} + fi + + if [[ ${ret} -ne 0 ]]; then + die "${MULTIBUILD_VARIANT:-(unknown)}: merging image failed." + fi + + rm -rf "${src}" +} + +_MULTIBUILD=1 +fi diff --git a/eclass/multilib-build.eclass b/eclass/multilib-build.eclass new file mode 100644 index 0000000..585364d --- /dev/null +++ b/eclass/multilib-build.eclass @@ -0,0 +1,676 @@ +# Copyright 2013-2020 Gentoo Authors +# Distributed under the terms of the GNU General Public License v2 + +# @ECLASS: multilib-build.eclass +# @MAINTAINER: +# gx86-multilib team <multilib@gentoo.org> +# @AUTHOR: +# Author: Michał Górny <mgorny@gentoo.org> +# @SUPPORTED_EAPIS: 4 5 6 7 +# @BLURB: flags and utility functions for building multilib packages +# @DESCRIPTION: +# The multilib-build.eclass exports USE flags and utility functions +# necessary to build packages for multilib in a clean and uniform +# manner. +# +# Please note that dependency specifications for multilib-capable +# dependencies shall use the USE dependency string in ${MULTILIB_USEDEP} +# to properly request multilib enabled. + +if [[ ! ${_MULTILIB_BUILD} ]]; then + +# EAPI=4 is required for meaningful MULTILIB_USEDEP. +case ${EAPI:-0} in + 4|5|6|7) ;; + *) die "EAPI=${EAPI} is not supported" ;; +esac + +[[ ${EAPI} == [45] ]] && inherit eutils +inherit multibuild multilib + +# @ECLASS-VARIABLE: _MULTILIB_FLAGS +# @INTERNAL +# @DESCRIPTION: +# The list of multilib flags and corresponding ABI values. If the same +# flag is reused for multiple ABIs (e.g. x86 on Linux&FreeBSD), multiple +# ABIs may be separated by commas. +# +# Please contact multilib before modifying this list. This way we can +# ensure that every *preliminary* work is done and the multilib can be +# extended safely. +_MULTILIB_FLAGS=( + abi_x86_32:x86,x86_fbsd,x86_freebsd,x86_linux,x86_macos,x86_solaris + abi_x86_64:amd64,amd64_fbsd,x64_freebsd,amd64_linux,x64_macos,x64_solaris + abi_x86_x32:x32 + abi_mips_n32:n32 + abi_mips_n64:n64 + abi_mips_o32:o32 +# abi_ppc_32:ppc,ppc_aix,ppc_macos +# abi_ppc_64:ppc64 + abi_s390_32:s390 + abi_s390_64:s390x +) +readonly _MULTILIB_FLAGS + +# @ECLASS-VARIABLE: MULTILIB_COMPAT +# @DEFAULT_UNSET +# @DESCRIPTION: +# List of multilib ABIs supported by the ebuild. If unset, defaults to +# all ABIs supported by the eclass. +# +# This variable is intended for use in prebuilt multilib packages that +# can provide binaries only for a limited set of ABIs. If ABIs need to +# be limited due to a bug in source code, package.use.mask is to be used +# instead. Along with MULTILIB_COMPAT, KEYWORDS should contain '-*'. +# +# Note that setting this variable effectively disables support for all +# other ABIs, including other architectures. For example, specifying +# abi_x86_{32,64} disables support for MIPS as well. +# +# The value of MULTILIB_COMPAT determines the value of IUSE. If set, it +# also enables REQUIRED_USE constraints. +# +# Example use: +# @CODE +# # Upstream provides binaries for x86 & amd64 only +# MULTILIB_COMPAT=( abi_x86_{32,64} ) +# @CODE + +# @ECLASS-VARIABLE: MULTILIB_USEDEP +# @OUTPUT_VARIABLE +# @DESCRIPTION: +# The USE-dependency to be used on dependencies (libraries) needing +# to support multilib as well. +# +# Example use: +# @CODE +# RDEPEND="dev-libs/libfoo[${MULTILIB_USEDEP}] +# net-libs/libbar[ssl,${MULTILIB_USEDEP}]" +# @CODE + +# @ECLASS-VARIABLE: MULTILIB_ABI_FLAG +# @OUTPUT_VARIABLE +# @DESCRIPTION: +# The complete ABI name. Resembles the USE flag name. +# +# This is set within multilib_foreach_abi(), +# multilib_parallel_foreach_abi() and multilib-minimal sub-phase +# functions. +# +# It may be null (empty) when the build is done on ABI not controlled +# by a USE flag (e.g. on non-multilib arch or when using multilib +# portage). The build will always be done for a single ABI then. +# +# Example value: +# @CODE +# abi_x86_64 +# @CODE + +_multilib_build_set_globals() { + local flags=( "${_MULTILIB_FLAGS[@]%:*}" ) + + if [[ ${MULTILIB_COMPAT[@]} ]]; then + # Validate MULTILIB_COMPAT and filter out the flags. + local f + for f in "${MULTILIB_COMPAT[@]}"; do + if ! has "${f}" "${flags[@]}"; then + die "Invalid value in MULTILIB_COMPAT: ${f}" + fi + done + + flags=( "${MULTILIB_COMPAT[@]}" ) + + REQUIRED_USE="|| ( ${flags[*]} )" + fi + + local usedeps=${flags[@]/%/(-)?} + + IUSE=${flags[*]} + MULTILIB_USEDEP=${usedeps// /,} + readonly MULTILIB_USEDEP +} +_multilib_build_set_globals +unset -f _multilib_build_set_globals + +# @FUNCTION: multilib_get_enabled_abis +# @DESCRIPTION: +# Return the ordered list of enabled ABIs if multilib builds +# are enabled. The best (most preferred) ABI will come last. +# +# If multilib is disabled, the default ABI will be returned +# in order to enforce consistent testing with multilib code. +multilib_get_enabled_abis() { + debug-print-function ${FUNCNAME} "${@}" + + local pairs=( $(multilib_get_enabled_abi_pairs) ) + echo "${pairs[@]#*.}" +} + +# @FUNCTION: multilib_get_enabled_abi_pairs +# @DESCRIPTION: +# Return the ordered list of enabled <use-flag>.<ABI> pairs +# if multilib builds are enabled. The best (most preferred) +# ABI will come last. +# +# If multilib is disabled, the default ABI will be returned +# along with empty <use-flag>. +multilib_get_enabled_abi_pairs() { + debug-print-function ${FUNCNAME} "${@}" + + local abis=( $(get_all_abis) ) + + local abi i found + for abi in "${abis[@]}"; do + for i in "${_MULTILIB_FLAGS[@]}"; do + local m_abis=${i#*:} m_abi + local m_flag=${i%:*} + + # split on ,; we can't switch IFS for function scope because + # paludis is broken (bug #486592), and switching it locally + # for the split is more complex than cheating like this + for m_abi in ${m_abis//,/ }; do + if [[ ${m_abi} == ${abi} ]] \ + && { [[ ! "${MULTILIB_COMPAT[@]}" ]] || has "${m_flag}" "${MULTILIB_COMPAT[@]}"; } \ + && use "${m_flag}" + then + echo "${m_flag}.${abi}" + found=1 + break 2 + fi + done + done + done + + if [[ ! ${found} ]]; then + # ${ABI} can be used to override the fallback (multilib-portage), + # ${DEFAULT_ABI} is the safe fallback. + local abi=${ABI:-${DEFAULT_ABI}} + + debug-print "${FUNCNAME}: no ABIs enabled, fallback to ${abi}" + debug-print "${FUNCNAME}: ABI=${ABI}, DEFAULT_ABI=${DEFAULT_ABI}" + echo ".${abi}" + fi +} + +# @FUNCTION: _multilib_multibuild_wrapper +# @USAGE: <argv>... +# @INTERNAL +# @DESCRIPTION: +# Initialize the environment for ABI selected for multibuild. +_multilib_multibuild_wrapper() { + debug-print-function ${FUNCNAME} "${@}" + + local ABI=${MULTIBUILD_VARIANT#*.} + local -r MULTILIB_ABI_FLAG=${MULTIBUILD_VARIANT%.*} + + multilib_toolchain_setup "${ABI}" + readonly ABI + "${@}" +} + +# @FUNCTION: multilib_foreach_abi +# @USAGE: <argv>... +# @DESCRIPTION: +# If multilib support is enabled, sets the toolchain up for each +# supported ABI along with the ABI variable and correct BUILD_DIR, +# and runs the given commands with them. +# +# If multilib support is disabled, it just runs the commands. No setup +# is done. +multilib_foreach_abi() { + debug-print-function ${FUNCNAME} "${@}" + + local MULTIBUILD_VARIANTS=( $(multilib_get_enabled_abi_pairs) ) + multibuild_foreach_variant _multilib_multibuild_wrapper "${@}" +} + +# @FUNCTION: multilib_parallel_foreach_abi +# @USAGE: <argv>... +# @DESCRIPTION: +# If multilib support is enabled, sets the toolchain up for each +# supported ABI along with the ABI variable and correct BUILD_DIR, +# and runs the given commands with them. +# +# If multilib support is disabled, it just runs the commands. No setup +# is done. +# +# This function used to run multiple commands in parallel. Now it's just +# a deprecated alias to multilib_foreach_abi. +multilib_parallel_foreach_abi() { + debug-print-function ${FUNCNAME} "${@}" + + local MULTIBUILD_VARIANTS=( $(multilib_get_enabled_abi_pairs) ) + multibuild_foreach_variant _multilib_multibuild_wrapper "${@}" +} + +# @FUNCTION: multilib_for_best_abi +# @USAGE: <argv>... +# @DESCRIPTION: +# Runs the given command with setup for the 'best' (usually native) ABI. +multilib_for_best_abi() { + debug-print-function ${FUNCNAME} "${@}" + + [[ ${EAPI} == [45] ]] || die "${FUNCNAME} is banned in EAPI ${EAPI}, use multilib_is_native_abi() instead" + + eqawarn "QA warning: multilib_for_best_abi() function is deprecated and should" + eqawarn "not be used. The multilib_is_native_abi() check may be used instead." + + local MULTIBUILD_VARIANTS=( $(multilib_get_enabled_abi_pairs) ) + + multibuild_for_best_variant _multilib_multibuild_wrapper "${@}" +} + +# @FUNCTION: multilib_check_headers +# @DESCRIPTION: +# Check whether the header files are consistent between ABIs. +# +# This function needs to be called after each ABI's installation phase. +# It obtains the header file checksums and compares them with previous +# runs (if any). Dies if header files differ. +multilib_check_headers() { + _multilib_header_cksum() { + set -o pipefail + + if [[ -d ${ED%/}/usr/include ]]; then + find "${ED%/}"/usr/include -type f \ + -exec cksum {} + | sort -k2 + fi + } + + local cksum cksum_prev + local cksum_file=${T}/.multilib_header_cksum + cksum=$(_multilib_header_cksum) || die + unset -f _multilib_header_cksum + + if [[ -f ${cksum_file} ]]; then + cksum_prev=$(< "${cksum_file}") || die + + if [[ ${cksum} != ${cksum_prev} ]]; then + echo "${cksum}" > "${cksum_file}.new" || die + + eerror "Header files have changed between ABIs." + + if type -p diff &>/dev/null; then + eerror "$(diff -du "${cksum_file}" "${cksum_file}.new")" + else + eerror "Old checksums in: ${cksum_file}" + eerror "New checksums in: ${cksum_file}.new" + fi + + die "Header checksum mismatch, aborting." + fi + else + echo "${cksum}" > "${cksum_file}" || die + fi +} + +# @FUNCTION: multilib_copy_sources +# @DESCRIPTION: +# Create a single copy of the package sources for each enabled ABI. +# +# The sources are always copied from initial BUILD_DIR (or S if unset) +# to ABI-specific build directory matching BUILD_DIR used by +# multilib_foreach_abi(). +multilib_copy_sources() { + debug-print-function ${FUNCNAME} "${@}" + + local MULTIBUILD_VARIANTS=( $(multilib_get_enabled_abi_pairs) ) + multibuild_copy_sources +} + +# @ECLASS-VARIABLE: MULTILIB_WRAPPED_HEADERS +# @DEFAULT_UNSET +# @DESCRIPTION: +# A list of headers to wrap for multilib support. The listed headers +# will be moved to a non-standard location and replaced with a file +# including them conditionally to current ABI. +# +# This variable has to be a bash array. Paths shall be relative to +# installation root (${ED}), and name regular files. Recursive wrapping +# is not supported. +# +# Please note that header wrapping is *discouraged*. It is preferred to +# install all headers in a subdirectory of libdir and use pkg-config to +# locate the headers. Some C preprocessors will not work with wrapped +# headers. +# +# Example: +# @CODE +# MULTILIB_WRAPPED_HEADERS=( +# /usr/include/foobar/config.h +# ) +# @CODE + +# @ECLASS-VARIABLE: MULTILIB_CHOST_TOOLS +# @DEFAULT_UNSET +# @DESCRIPTION: +# A list of tool executables to preserve for each multilib ABI. +# The listed executables will be renamed to ${CHOST}-${basename}, +# and the native variant will be symlinked to the generic name. +# +# This variable has to be a bash array. Paths shall be relative to +# installation root (${ED}), and name regular files or symbolic +# links to regular files. Recursive wrapping is not supported. +# +# If symbolic link is passed, both symlink path and symlink target +# will be changed. As a result, the symlink target is expected +# to be wrapped as well (either by listing in MULTILIB_CHOST_TOOLS +# or externally). +# +# Please note that tool wrapping is *discouraged*. It is preferred to +# install pkg-config files for each ABI, and require reverse +# dependencies to use that. +# +# Packages that search for tools properly (e.g. using AC_PATH_TOOL +# macro) will find the wrapper executables automatically. Other packages +# will need explicit override of tool paths. +# +# Example: +# @CODE +# MULTILIB_CHOST_TOOLS=( +# /usr/bin/foo-config +# ) +# @CODE + +# @FUNCTION: multilib_prepare_wrappers +# @USAGE: [<install-root>] +# @DESCRIPTION: +# Perform the preparation of all kinds of wrappers for the current ABI. +# This function shall be called once per each ABI, after installing +# the files to be wrapped. +# +# Takes an optional custom <install-root> from which files will be +# used. If no root is specified, uses ${ED}. +# +# The files to be wrapped are specified using separate variables, +# e.g. MULTILIB_WRAPPED_HEADERS. Those variables shall not be changed +# between the successive calls to multilib_prepare_wrappers +# and multilib_install_wrappers. +# +# After all wrappers are prepared, multilib_install_wrappers shall +# be called to commit them to the installation tree. +multilib_prepare_wrappers() { + debug-print-function ${FUNCNAME} "${@}" + + [[ ${#} -le 1 ]] || die "${FUNCNAME}: too many arguments" + + local root=${1:-${ED%/}} + local f + + if [[ ${COMPLETE_MULTILIB} == yes ]]; then + # symlink '${CHOST}-foo -> foo' to support abi-wrapper while + # keeping ${CHOST}-foo calls correct. + + for f in "${MULTILIB_CHOST_TOOLS[@]}"; do + # drop leading slash if it's there + f=${f#/} + + local dir=${f%/*} + local fn=${f##*/} + + ln -s "${fn}" "${root}/${dir}/${CHOST}-${fn}" || die + done + + return + fi + + for f in "${MULTILIB_CHOST_TOOLS[@]}"; do + # drop leading slash if it's there + f=${f#/} + + local dir=${f%/*} + local fn=${f##*/} + + if [[ -L ${root}/${f} ]]; then + # rewrite the symlink target + local target + target=$(readlink "${root}/${f}") || die + local target_dir target_fn=${target##*/} + + [[ ${target} == */* ]] && target_dir=${target%/*} + + ln -f -s "${target_dir+${target_dir}/}${CHOST}-${target_fn}" \ + "${root}/${f}" || die + fi + + mv "${root}/${f}" "${root}/${dir}/${CHOST}-${fn}" || die + + # symlink the native one back + if multilib_is_native_abi; then + ln -s "${CHOST}-${fn}" "${root}/${f}" || die + fi + done + + if [[ ${MULTILIB_WRAPPED_HEADERS[@]} ]]; then + # If abi_flag is unset, then header wrapping is unsupported on + # this ABI. This means the arch doesn't support multilib at all + # -- in this case, the headers are not wrapped and everything + # works as expected. + + if [[ ${MULTILIB_ABI_FLAG} ]]; then + for f in "${MULTILIB_WRAPPED_HEADERS[@]}"; do + # drop leading slash if it's there + f=${f#/} + + if [[ ${f} != usr/include/* ]]; then + die "Wrapping headers outside of /usr/include is not supported at the moment." + fi + # and then usr/include + f=${f#usr/include} + + local dir=${f%/*} + + # Some ABIs may have install less files than others. + if [[ -f ${root}/usr/include${f} ]]; then + local wrapper=${ED%/}/tmp/multilib-include${f} + + if [[ ! -f ${ED%/}/tmp/multilib-include${f} ]]; then + dodir "/tmp/multilib-include${dir}" + # a generic template + cat > "${wrapper}" <<_EOF_ || die +/* This file is auto-generated by multilib-build.eclass + * as a multilib-friendly wrapper. For the original content, + * please see the files that are #included below. + */ + +#if defined(__x86_64__) /* amd64 */ +# if defined(__ILP32__) /* x32 ABI */ +# error "abi_x86_x32 not supported by the package." +# else /* 64-bit ABI */ +# error "abi_x86_64 not supported by the package." +# endif +#elif defined(__i386__) /* plain x86 */ +# error "abi_x86_32 not supported by the package." +#elif defined(__mips__) +# if(_MIPS_SIM == _ABIN32) /* n32 */ +# error "abi_mips_n32 not supported by the package." +# elif(_MIPS_SIM == _ABI64) /* n64 */ +# error "abi_mips_n64 not supported by the package." +# elif(_MIPS_SIM == _ABIO32) /* o32 */ +# error "abi_mips_o32 not supported by the package." +# endif +#elif defined(__sparc__) +# if defined(__arch64__) +# error "abi_sparc_64 not supported by the package." +# else +# error "abi_sparc_32 not supported by the package." +# endif +#elif defined(__s390__) +# if defined(__s390x__) +# error "abi_s390_64 not supported by the package." +# else +# error "abi_s390_32 not supported by the package." +# endif +#elif defined(__powerpc__) || defined(__ppc__) +# if defined(__powerpc64__) || defined(__ppc64__) +# error "abi_ppc_64 not supported by the package." +# else +# error "abi_ppc_32 not supported by the package." +# endif +#elif defined(SWIG) /* https://sourceforge.net/p/swig/bugs/799/ */ +# error "Native ABI not supported by the package." +#else +# error "No ABI matched, please report a bug to bugs.gentoo.org" +#endif +_EOF_ + fi + + if ! grep -q "${MULTILIB_ABI_FLAG} " "${wrapper}" + then + die "Flag ${MULTILIB_ABI_FLAG} not listed in wrapper template. Please report a bug to https://bugs.gentoo.org." + fi + + # $CHOST shall be set by multilib_toolchain_setup + dodir "/tmp/multilib-include/${CHOST}${dir}" + mv "${root}/usr/include${f}" "${ED%/}/tmp/multilib-include/${CHOST}${dir}/" || die + + # Note: match a space afterwards to avoid collision potential. + sed -e "/${MULTILIB_ABI_FLAG} /s&error.*&include <${CHOST}${f}>&" \ + -i "${wrapper}" || die + + # Needed for swig. + if multilib_is_native_abi; then + sed -e "/Native ABI/s&error.*&include <${CHOST}${f}>&" \ + -i "${wrapper}" || die + fi + fi + done + fi + fi +} + +# @FUNCTION: multilib_install_wrappers +# @USAGE: [<install-root>] +# @DESCRIPTION: +# Install the previously-prepared wrappers. This function shall +# be called once, after all wrappers were prepared. +# +# Takes an optional custom <install-root> to which the wrappers will be +# installed. If no root is specified, uses ${ED}. There is no need to +# use the same root as when preparing the wrappers. +# +# The files to be wrapped are specified using separate variables, +# e.g. MULTILIB_WRAPPED_HEADERS. Those variables shall not be changed +# between the calls to multilib_prepare_wrappers +# and multilib_install_wrappers. +multilib_install_wrappers() { + debug-print-function ${FUNCNAME} "${@}" + + [[ ${#} -le 1 ]] || die "${FUNCNAME}: too many arguments" + + [[ ${COMPLETE_MULTILIB} == yes ]] && return + + local root=${1:-${ED}} + + if [[ -d ${ED%/}/tmp/multilib-include ]]; then + multibuild_merge_root \ + "${ED%/}"/tmp/multilib-include "${root}"/usr/include + # it can fail if something else uses /tmp + rmdir "${ED%/}"/tmp &>/dev/null + fi +} + +# @FUNCTION: multilib_is_native_abi +# @DESCRIPTION: +# Determine whether the currently built ABI is the profile native. +# Return true status (0) if that is true, otherwise false (1). +multilib_is_native_abi() { + debug-print-function ${FUNCNAME} "${@}" + + [[ ${#} -eq 0 ]] || die "${FUNCNAME}: too many arguments" + + [[ ${COMPLETE_MULTILIB} == yes || ${ABI} == ${DEFAULT_ABI} ]] +} + +# @FUNCTION: multilib_build_binaries +# @DESCRIPTION: +# Deprecated synonym for multilib_is_native_abi +multilib_build_binaries() { + debug-print-function ${FUNCNAME} "${@}" + + [[ ${EAPI} == [45] ]] || die "${FUNCNAME} is banned in EAPI ${EAPI}, use multilib_is_native_abi() instead" + + eqawarn "QA warning: multilib_build_binaries is deprecated. Please use the equivalent" + eqawarn "multilib_is_native_abi function instead." + + multilib_is_native_abi "${@}" +} + +# @FUNCTION: multilib_native_use_with +# @USAGE: <flag> [<opt-name> [<opt-value>]] +# @DESCRIPTION: +# Output --with configure option alike use_with if USE <flag> is enabled +# and executables are being built (multilib_is_native_abi is true). +# Otherwise, outputs --without configure option. Arguments are the same +# as for use_with in the EAPI. +multilib_native_use_with() { + if multilib_is_native_abi; then + use_with "${@}" + else + echo "--without-${2:-${1}}" + fi +} + +# @FUNCTION: multilib_native_use_enable +# @USAGE: <flag> [<opt-name> [<opt-value>]] +# @DESCRIPTION: +# Output --enable configure option alike use_enable if USE <flag> +# is enabled and executables are being built (multilib_is_native_abi +# is true). Otherwise, outputs --disable configure option. Arguments are +# the same as for use_enable in the EAPI. +multilib_native_use_enable() { + if multilib_is_native_abi; then + use_enable "${@}" + else + echo "--disable-${2:-${1}}" + fi +} + +# @FUNCTION: multilib_native_enable +# @USAGE: <opt-name> [<opt-value>] +# @DESCRIPTION: +# Output --enable configure option if executables are being built +# (multilib_is_native_abi is true). Otherwise, output --disable configure +# option. +multilib_native_enable() { + if multilib_is_native_abi; then + echo "--enable-${1}${2+=${2}}" + else + echo "--disable-${1}" + fi +} + +# @FUNCTION: multilib_native_with +# @USAGE: <opt-name> [<opt-value>] +# @DESCRIPTION: +# Output --with configure option if executables are being built +# (multilib_is_native_abi is true). Otherwise, output --without configure +# option. +multilib_native_with() { + if multilib_is_native_abi; then + echo "--with-${1}${2+=${2}}" + else + echo "--without-${1}" + fi +} + +# @FUNCTION: multilib_native_usex +# @USAGE: <flag> [<true1> [<false1> [<true2> [<false2>]]]] +# @DESCRIPTION: +# Output the concatenation of <true1> (or 'yes' if unspecified) +# and <true2> if USE <flag> is enabled and executables are being built +# (multilib_is_native_abi is true). Otherwise, output the concatenation +# of <false1> (or 'no' if unspecified) and <false2>. Arguments +# are the same as for usex in the EAPI. +# +# Note: in EAPI 4 you need to inherit eutils to use this function. +multilib_native_usex() { + if multilib_is_native_abi; then + usex "${@}" + else + echo "${3-no}${5}" + fi +} + +_MULTILIB_BUILD=1 +fi diff --git a/eclass/multilib-minimal.eclass b/eclass/multilib-minimal.eclass new file mode 100644 index 0000000..136ee3b --- /dev/null +++ b/eclass/multilib-minimal.eclass @@ -0,0 +1,125 @@ +# Copyright 1999-2018 Gentoo Foundation +# Distributed under the terms of the GNU General Public License v2 + +# @ECLASS: multilib-minimal.eclass +# @MAINTAINER: +# Multilib team <multilib@gentoo.org> +# @SUPPORTED_EAPIS: 4 5 6 7 +# @BLURB: wrapper for multilib builds providing convenient multilib_src_* functions +# @DESCRIPTION: +# +# src_configure, src_compile, src_test and src_install are exported. +# +# Use multilib_src_* instead of src_* which runs this phase for +# all enabled ABIs. +# +# multilib-minimal should _always_ go last in inherit order! +# +# If you want to use in-source builds, then you must run +# multilib_copy_sources at the end of src_prepare! +# Also make sure to set correct variables such as +# ECONF_SOURCE=${S} +# +# If you need generic install rules, use multilib_src_install_all function. + + +# EAPI=4 is required for meaningful MULTILIB_USEDEP. +case ${EAPI:-0} in + 4|5|6|7) ;; + *) die "EAPI=${EAPI} is not supported" ;; +esac + + +[[ ${EAPI} == [45] ]] && inherit eutils +inherit multilib-build + +EXPORT_FUNCTIONS src_configure src_compile src_test src_install + + +multilib-minimal_src_configure() { + debug-print-function ${FUNCNAME} "$@" + + multilib-minimal_abi_src_configure() { + debug-print-function ${FUNCNAME} "$@" + + mkdir -p "${BUILD_DIR}" || die + pushd "${BUILD_DIR}" >/dev/null || die + if declare -f multilib_src_configure >/dev/null ; then + multilib_src_configure + else + default_src_configure + fi + popd >/dev/null || die + } + + multilib_foreach_abi multilib-minimal_abi_src_configure +} + +multilib-minimal_src_compile() { + debug-print-function ${FUNCNAME} "$@" + + multilib-minimal_abi_src_compile() { + debug-print-function ${FUNCNAME} "$@" + + pushd "${BUILD_DIR}" >/dev/null || die + if declare -f multilib_src_compile >/dev/null ; then + multilib_src_compile + else + default_src_compile + fi + popd >/dev/null || die + } + + multilib_foreach_abi multilib-minimal_abi_src_compile +} + +multilib-minimal_src_test() { + debug-print-function ${FUNCNAME} "$@" + + multilib-minimal_abi_src_test() { + debug-print-function ${FUNCNAME} "$@" + + pushd "${BUILD_DIR}" >/dev/null || die + if declare -f multilib_src_test >/dev/null ; then + multilib_src_test + else + default_src_test + fi + popd >/dev/null || die + } + + multilib_foreach_abi multilib-minimal_abi_src_test +} + +multilib-minimal_src_install() { + debug-print-function ${FUNCNAME} "$@" + + multilib-minimal_abi_src_install() { + debug-print-function ${FUNCNAME} "$@" + + pushd "${BUILD_DIR}" >/dev/null || die + if declare -f multilib_src_install >/dev/null ; then + multilib_src_install + else + # default_src_install will not work here as it will + # break handling of DOCS wrt #468092 + # so we split up the emake and doc-install part + # this is synced with __eapi4_src_install + if [[ -f Makefile || -f GNUmakefile || -f makefile ]] ; then + emake DESTDIR="${D}" install + fi + fi + + multilib_prepare_wrappers + multilib_check_headers + popd >/dev/null || die + } + multilib_foreach_abi multilib-minimal_abi_src_install + multilib_install_wrappers + + if declare -f multilib_src_install_all >/dev/null ; then + multilib_src_install_all + else + einstalldocs + fi +} diff --git a/eclass/multilib.eclass b/eclass/multilib.eclass new file mode 100644 index 0000000..095e3a4 --- /dev/null +++ b/eclass/multilib.eclass @@ -0,0 +1,555 @@ +# Copyright 1999-2020 Gentoo Authors +# Distributed under the terms of the GNU General Public License v2 + +# @ECLASS: multilib.eclass +# @MAINTAINER: +# toolchain@gentoo.org +# @BLURB: This eclass is for all functions pertaining to handling multilib configurations. +# @DESCRIPTION: +# This eclass is for all functions pertaining to handling multilib configurations. + +if [[ -z ${_MULTILIB_ECLASS} ]]; then +_MULTILIB_ECLASS=1 + +inherit toolchain-funcs + +# Defaults: +export MULTILIB_ABIS=${MULTILIB_ABIS:-"default"} +export DEFAULT_ABI=${DEFAULT_ABI:-"default"} +export CFLAGS_default +export LDFLAGS_default +export CHOST_default=${CHOST_default:-${CHOST}} +export CTARGET_default=${CTARGET_default:-${CTARGET:-${CHOST_default}}} +export LIBDIR_default=${CONF_LIBDIR:-"lib"} +export KERNEL_ABI=${KERNEL_ABI:-${DEFAULT_ABI}} + +# @FUNCTION: has_multilib_profile +# @DESCRIPTION: +# Return true if the current profile is a multilib profile and lists more than +# one abi in ${MULTILIB_ABIS}. When has_multilib_profile returns true, that +# profile should enable the 'multilib' use flag. This is so you can DEPEND on +# a package only for multilib or not multilib. +has_multilib_profile() { + [ -n "${MULTILIB_ABIS}" -a "${MULTILIB_ABIS}" != "${MULTILIB_ABIS/ /}" ] +} + +# @FUNCTION: get_libdir +# @RETURN: the libdir for the selected ABI +# @DESCRIPTION: +# This function simply returns the desired lib directory. With portage +# 2.0.51, we now have support for installing libraries to lib32/lib64 +# to accomidate the needs of multilib systems. It's no longer a good idea +# to assume all libraries will end up in lib. Replace any (sane) instances +# where lib is named directly with $(get_libdir) if possible. +# +# Jeremy Huddleston <eradicator@gentoo.org> (23 Dec 2004): +# Added support for ${ABI} and ${DEFAULT_ABI}. If they're both not set, +# fall back on old behavior. Any profile that has these set should also +# depend on a newer version of portage (not yet released) which uses these +# over CONF_LIBDIR in econf, dolib, etc... +if has "${EAPI:-0}" 0 1 2 3 4 5; then + get_libdir() { + local CONF_LIBDIR + if [ -n "${CONF_LIBDIR_OVERRIDE}" ] ; then + # if there is an override, we want to use that... always. + echo ${CONF_LIBDIR_OVERRIDE} + else + get_abi_LIBDIR + fi + } +fi + +# @FUNCTION: get_abi_var +# @USAGE: <VAR> [ABI] +# @RETURN: returns the value of ${<VAR>_<ABI>} which should be set in make.defaults +# @INTERNAL +# @DESCRIPTION: +# ex: +# CFLAGS=$(get_abi_var CFLAGS sparc32) # CFLAGS=-m32 +# +# Note that the prefered method is to set CC="$(tc-getCC) $(get_abi_CFLAGS)" +# This will hopefully be added to portage soon... +# +# If <ABI> is not specified, ${ABI} is used. +# If <ABI> is not specified and ${ABI} is not defined, ${DEFAULT_ABI} is used. +# If <ABI> is not specified and ${ABI} and ${DEFAULT_ABI} are not defined, we return an empty string. +get_abi_var() { + local flag=$1 + local abi=${2:-${ABI:-${DEFAULT_ABI:-default}}} + local var="${flag}_${abi}" + echo ${!var} +} + +# @FUNCTION: get_abi_CFLAGS +# @USAGE: [ABI] +# @DESCRIPTION: +# Alias for 'get_abi_var CFLAGS' +get_abi_CFLAGS() { get_abi_var CFLAGS "$@"; } + +# @FUNCTION: get_abi_LDFLAGS +# @USAGE: [ABI] +# @DESCRIPTION: +# Alias for 'get_abi_var LDFLAGS' +get_abi_LDFLAGS() { get_abi_var LDFLAGS "$@"; } + +# @FUNCTION: get_abi_CHOST +# @USAGE: [ABI] +# @DESCRIPTION: +# Alias for 'get_abi_var CHOST' +get_abi_CHOST() { get_abi_var CHOST "$@"; } + +# @FUNCTION: get_abi_CTARGET +# @USAGE: [ABI] +# @DESCRIPTION: +# Alias for 'get_abi_var CTARGET' +get_abi_CTARGET() { get_abi_var CTARGET "$@"; } + +# @FUNCTION: get_abi_FAKE_TARGETS +# @USAGE: [ABI] +# @DESCRIPTION: +# Alias for 'get_abi_var FAKE_TARGETS' +get_abi_FAKE_TARGETS() { get_abi_var FAKE_TARGETS "$@"; } + +# @FUNCTION: get_abi_LIBDIR +# @USAGE: [ABI] +# @DESCRIPTION: +# Alias for 'get_abi_var LIBDIR' +get_abi_LIBDIR() { get_abi_var LIBDIR "$@"; } + +# @FUNCTION: get_install_abis +# @DESCRIPTION: +# Return a list of the ABIs we want to install for with +# the last one in the list being the default. +get_install_abis() { + local x order="" + + if [[ -z ${MULTILIB_ABIS} ]] ; then + echo "default" + return 0 + fi + + if [[ ${EMULTILIB_PKG} == "true" ]] ; then + for x in ${MULTILIB_ABIS} ; do + if [[ ${x} != "${DEFAULT_ABI}" ]] ; then + has ${x} ${ABI_DENY} || order="${order} ${x}" + fi + done + has ${DEFAULT_ABI} ${ABI_DENY} || order="${order} ${DEFAULT_ABI}" + + if [[ -n ${ABI_ALLOW} ]] ; then + local ordera="" + for x in ${order} ; do + if has ${x} ${ABI_ALLOW} ; then + ordera="${ordera} ${x}" + fi + done + order=${ordera} + fi + else + order=${DEFAULT_ABI} + fi + + if [[ -z ${order} ]] ; then + die "The ABI list is empty. Are you using a proper multilib profile? Perhaps your USE flags or MULTILIB_ABIS are too restrictive for this package." + fi + + echo ${order} + return 0 +} + +# @FUNCTION: get_all_abis +# @DESCRIPTION: +# Return a list of the ABIs supported by this profile. +# the last one in the list being the default. +get_all_abis() { + local x order="" mvar dvar + + mvar="MULTILIB_ABIS" + dvar="DEFAULT_ABI" + if [[ -n $1 ]] ; then + mvar="$1_${mvar}" + dvar="$1_${dvar}" + fi + + if [[ -z ${!mvar} ]] ; then + echo "default" + return 0 + fi + + for x in ${!mvar}; do + if [[ ${x} != ${!dvar} ]] ; then + order="${order:+${order} }${x}" + fi + done + order="${order:+${order} }${!dvar}" + + echo ${order} + return 0 +} + +# @FUNCTION: get_all_libdirs +# @DESCRIPTION: +# Returns a list of all the libdirs used by this profile. This includes +# those that might not be touched by the current ebuild and always includes +# "lib". +get_all_libdirs() { + local libdirs abi + + for abi in ${MULTILIB_ABIS}; do + libdirs+=" $(get_abi_LIBDIR ${abi})" + done + [[ " ${libdirs} " != *" lib "* ]] && libdirs+=" lib" + + echo "${libdirs}" +} + +# @FUNCTION: is_final_abi +# @DESCRIPTION: +# Return true if ${ABI} is the last ABI on our list (or if we're not +# using the new multilib configuration. This can be used to determine +# if we're in the last (or only) run through src_{unpack,compile,install} +is_final_abi() { + has_multilib_profile || return 0 + set -- $(get_install_abis) + local LAST_ABI=$# + [[ ${!LAST_ABI} == ${ABI} ]] +} + +# @FUNCTION: number_abis +# @DESCRIPTION: +# echo the number of ABIs we will be installing for +number_abis() { + set -- `get_install_abis` + echo $# +} + +# @FUNCTION: get_exeext +# @DESCRIPTION: +# Returns standard executable program suffix (null, .exe, etc.) +# for the current platform identified by CHOST. +# +# Example: +# get_exeext +# Returns: null string (almost everywhere) || .exe (mingw*) || ... +get_exeext() { + case ${CHOST} in + *-cygwin*|mingw*|*-mingw*) echo ".exe";; + esac +} + +# @FUNCTION: get_libname +# @USAGE: [version] +# @DESCRIPTION: +# Returns libname with proper suffix {.so,.dylib,.dll,etc} and optionally +# supplied version for the current platform identified by CHOST. +# +# Example: +# get_libname ${PV} +# Returns: .so.${PV} (ELF) || .${PV}.dylib (MACH) || ... +get_libname() { + local libname + local ver=$1 + case ${CHOST} in + *-cygwin*) libname="dll.a";; # import lib + mingw*|*-mingw*) libname="dll";; + *-darwin*) libname="dylib";; + *-mint*) libname="irrelevant";; + hppa*-hpux*) libname="sl";; + *) libname="so";; + esac + + if [[ -z $* ]] ; then + echo ".${libname}" + else + for ver in "$@" ; do + case ${CHOST} in + *-cygwin*) echo ".${ver}.${libname}";; + *-darwin*) echo ".${ver}.${libname}";; + *-mint*) echo ".${libname}";; + *) echo ".${libname}.${ver}";; + esac + done + fi +} + +# @FUNCTION: get_modname +# @USAGE: +# @DESCRIPTION: +# Returns modulename with proper suffix {.so,.bundle,etc} for the current +# platform identified by CHOST. +# +# Example: +# libfoo$(get_modname) +# Returns: libfoo.so (ELF) || libfoo.bundle (MACH) || ... +get_modname() { + local modname + local ver=$1 + case ${CHOST} in + *-darwin*) modname="bundle";; + *) modname="so";; + esac + + echo ".${modname}" +} + +# This is for the toolchain to setup profile variables when pulling in +# a crosscompiler (and thus they aren't set in the profile). +multilib_env() { + local CTARGET=${1:-${CTARGET}} + local cpu=${CTARGET%%*-} + + if [[ ${CTARGET} = *-musl* ]]; then + # musl has no multilib support and can run only in 'lib': + # - https://bugs.gentoo.org/675954 + # - https://gcc.gnu.org/PR90077 + # - https://github.com/gentoo/musl/issues/245 + : ${MULTILIB_ABIS=default} + : ${DEFAULT_ABI=default} + export MULTILIB_ABIS DEFAULT_ABI + return + fi + + case ${cpu} in + aarch64*) + # Not possible to do multilib with aarch64 and a single toolchain. + export CFLAGS_arm=${CFLAGS_arm-} + case ${cpu} in + aarch64*be) export CHOST_arm="armv8b-${CTARGET#*-}";; + *) export CHOST_arm="armv8l-${CTARGET#*-}";; + esac + CHOST_arm=${CHOST_arm/%-gnu/-gnueabi} + export CTARGET_arm=${CHOST_arm} + export LIBDIR_arm="lib" + + export CFLAGS_arm64=${CFLAGS_arm64-} + export CHOST_arm64=${CTARGET} + export CTARGET_arm64=${CHOST_arm64} + export LIBDIR_arm64="lib64" + + : ${MULTILIB_ABIS=arm64} + : ${DEFAULT_ABI=arm64} + ;; + x86_64*) + export CFLAGS_x86=${CFLAGS_x86--m32} + export CHOST_x86=${CTARGET/x86_64/i686} + CHOST_x86=${CHOST_x86/%-gnux32/-gnu} + export CTARGET_x86=${CHOST_x86} + if [[ ${SYMLINK_LIB} == "yes" ]] ; then + export LIBDIR_x86="lib32" + else + export LIBDIR_x86="lib" + fi + + export CFLAGS_amd64=${CFLAGS_amd64--m64} + export CHOST_amd64=${CTARGET/%-gnux32/-gnu} + export CTARGET_amd64=${CHOST_amd64} + export LIBDIR_amd64="lib64" + + export CFLAGS_x32=${CFLAGS_x32--mx32} + export CHOST_x32=${CTARGET/%-gnu/-gnux32} + export CTARGET_x32=${CHOST_x32} + export LIBDIR_x32="libx32" + + case ${CTARGET} in + *-gnux32) + : ${MULTILIB_ABIS=x32 amd64 x86} + : ${DEFAULT_ABI=x32} + ;; + *) + : ${MULTILIB_ABIS=amd64 x86} + : ${DEFAULT_ABI=amd64} + ;; + esac + ;; + mips64*|mipsisa64*) + export CFLAGS_o32=${CFLAGS_o32--mabi=32} + export CHOST_o32=${CTARGET/mips64/mips} + export CHOST_o32=${CHOST_o32/mipsisa64/mipsisa32} + export CTARGET_o32=${CHOST_o32} + export LIBDIR_o32="lib" + + export CFLAGS_n32=${CFLAGS_n32--mabi=n32} + export CHOST_n32=${CTARGET} + export CTARGET_n32=${CHOST_n32} + export LIBDIR_n32="lib32" + + export CFLAGS_n64=${CFLAGS_n64--mabi=64} + export CHOST_n64=${CTARGET} + export CTARGET_n64=${CHOST_n64} + export LIBDIR_n64="lib64" + + : ${MULTILIB_ABIS=n64 n32 o32} + : ${DEFAULT_ABI=n32} + ;; + powerpc64*) + export CFLAGS_ppc=${CFLAGS_ppc--m32} + export CHOST_ppc=${CTARGET/powerpc64/powerpc} + export CTARGET_ppc=${CHOST_ppc} + export LIBDIR_ppc="lib" + + export CFLAGS_ppc64=${CFLAGS_ppc64--m64} + export CHOST_ppc64=${CTARGET} + export CTARGET_ppc64=${CHOST_ppc64} + export LIBDIR_ppc64="lib64" + + : ${MULTILIB_ABIS=ppc64 ppc} + : ${DEFAULT_ABI=ppc64} + ;; + riscv64*) + export CFLAGS_lp64d=${CFLAGS_lp64d--mabi=lp64d -march=rv64imafdc} + export CHOST_lp64d=${CTARGET} + export CTARGET_lp64d=${CTARGET} + export LIBDIR_lp64d="lib64/lp64d" + + export CFLAGS_lp64=${CFLAGS_lp64--mabi=lp64 -march=rv64imac} + export CHOST_lp64=${CTARGET} + export CTARGET_lp64=${CTARGET} + export LIBDIR_lp64="lib64/lp64" + + export CFLAGS_ilp32d=${CFLAGS_ilp32d--mabi=ilp32d -march=rv32imafdc} + export CHOST_ilp32d=${CTARGET/riscv64/riscv32} + export CTARGET_ilp32d=${CTARGET/riscv64/riscv32} + export LIBDIR_ilp32d="lib32/ilp32d" + + export CFLAGS_ilp32=${CFLAGS_ilp32--mabi=ilp32 -march=rv32imac} + export CHOST_ilp32=${CTARGET/riscv64/riscv32} + export CTARGET_ilp32=${CTARGET/riscv64/riscv32} + export LIBDIR_ilp32="lib32/ilp32" + + : ${MULTILIB_ABIS=lp64d lp64 ilp32d ilp32} + : ${DEFAULT_ABI=lp64d} + ;; + riscv32*) + export CFLAGS_ilp32d=${CFLAGS_ilp32d--mabi=ilp32d} + export CHOST_ilp32d=${CTARGET} + export CTARGET_ilp32d=${CTARGET} + export LIBDIR_ilp32d="lib32/ilp32d" + + export CFLAGS_ilp32=${CFLAGS_ilp32--mabi=ilp32 -march=rv32imac} + export CHOST_ilp32=${CTARGET} + export CTARGET_ilp32=${CTARGET} + export LIBDIR_ilp32="lib32/ilp32" + + : ${MULTILIB_ABIS=ilp32d ilp32} + : ${DEFAULT_ABI=ilp32d} + ;; + s390x*) + export CFLAGS_s390=${CFLAGS_s390--m31} # the 31 is not a typo + export CHOST_s390=${CTARGET/s390x/s390} + export CTARGET_s390=${CHOST_s390} + export LIBDIR_s390="lib" + + export CFLAGS_s390x=${CFLAGS_s390x--m64} + export CHOST_s390x=${CTARGET} + export CTARGET_s390x=${CHOST_s390x} + export LIBDIR_s390x="lib64" + + : ${MULTILIB_ABIS=s390x s390} + : ${DEFAULT_ABI=s390x} + ;; + sparc64*) + export CFLAGS_sparc32=${CFLAGS_sparc32--m32} + export CHOST_sparc32=${CTARGET/sparc64/sparc} + export CTARGET_sparc32=${CHOST_sparc32} + export LIBDIR_sparc32="lib" + + export CFLAGS_sparc64=${CFLAGS_sparc64--m64} + export CHOST_sparc64=${CTARGET} + export CTARGET_sparc64=${CHOST_sparc64} + export LIBDIR_sparc64="lib64" + + : ${MULTILIB_ABIS=sparc64 sparc32} + : ${DEFAULT_ABI=sparc64} + ;; + *) + : ${MULTILIB_ABIS=default} + : ${DEFAULT_ABI=default} + ;; + esac + + export MULTILIB_ABIS DEFAULT_ABI +} + +# @FUNCTION: multilib_toolchain_setup +# @DESCRIPTION: +# Hide multilib details here for packages which are forced to be compiled for a +# specific ABI when run on another ABI (like x86-specific packages on amd64) +multilib_toolchain_setup() { + local v vv + + export ABI=$1 + + local save_restore_variables=( + CBUILD + CHOST + AR + CC + CXX + F77 + FC + LD + NM + OBJDUMP + PKG_CONFIG + RANLIB + READELF + STRINGS + STRIP + PKG_CONFIG_LIBDIR + PKG_CONFIG_PATH + PKG_CONFIG_SYSTEM_INCLUDE_PATH + PKG_CONFIG_SYSTEM_LIBRARY_PATH + ) + + # First restore any saved state we have laying around. + if [[ ${_DEFAULT_ABI_SAVED} == "true" ]] ; then + for v in "${save_restore_variables[@]}" ; do + vv="_abi_saved_${v}" + [[ ${!vv+set} == "set" ]] && export ${v}="${!vv}" || unset ${v} + unset ${vv} + done + unset _DEFAULT_ABI_SAVED + fi + + if [[ ${ABI} != ${DEFAULT_ABI} ]] ; then + # Back that multilib-ass up so we can restore it later + for v in "${save_restore_variables[@]}" ; do + vv="_abi_saved_${v}" + [[ ${!v+set} == "set" ]] && export ${vv}="${!v}" || unset ${vv} + done + export _DEFAULT_ABI_SAVED="true" + + # Set CBUILD only if not cross-compiling. + if [[ ${CBUILD} == "${CHOST}" ]]; then + export CBUILD=$(get_abi_CHOST $1) + fi + + # Set the CHOST native first so that we pick up the native + # toolchain and not a cross-compiler by accident #202811. + # + # Make sure ${save_restore_variables[@]} list matches below. + export CHOST=$(get_abi_CHOST ${DEFAULT_ABI}) + + export AR="$(tc-getAR)" # Avoid 'ar', use '${CHOST}-ar' + export CC="$(tc-getCC) $(get_abi_CFLAGS)" + export CXX="$(tc-getCXX) $(get_abi_CFLAGS)" + export F77="$(tc-getF77) $(get_abi_CFLAGS)" + export FC="$(tc-getFC) $(get_abi_CFLAGS)" + export LD="$(tc-getLD) $(get_abi_LDFLAGS)" + export NM="$(tc-getNM)" # Avoid 'nm', use '${CHOST}-nm' + export OBJDUMP="$(tc-getOBJDUMP)" # Avoid 'objdump', use '${CHOST}-objdump' + export PKG_CONFIG="$(tc-getPKG_CONFIG)" + export RANLIB="$(tc-getRANLIB)" # Avoid 'ranlib', use '${CHOST}-ranlib' + export READELF="$(tc-getREADELF)" # Avoid 'readelf', use '${CHOST}-readelf' + export STRINGS="$(tc-getSTRINGS)" # Avoid 'strings', use '${CHOST}-strings' + export STRIP="$(tc-getSTRIP)" # Avoid 'strip', use '${CHOST}-strip' + + export CHOST=$(get_abi_CHOST $1) + export PKG_CONFIG_LIBDIR=${EPREFIX}/usr/$(get_libdir)/pkgconfig + export PKG_CONFIG_PATH=${EPREFIX}/usr/share/pkgconfig + export PKG_CONFIG_SYSTEM_INCLUDE_PATH=${EPREFIX}/usr/include + export PKG_CONFIG_SYSTEM_LIBRARY_PATH=${EPREFIX}/$(get_libdir):${EPREFIX}/usr/$(get_libdir) + fi +} + +fi diff --git a/eclass/multiprocessing.eclass b/eclass/multiprocessing.eclass new file mode 100644 index 0000000..3e8b2f9 --- /dev/null +++ b/eclass/multiprocessing.eclass @@ -0,0 +1,103 @@ +# Copyright 1999-2017 Gentoo Foundation +# Distributed under the terms of the GNU General Public License v2 + +# @ECLASS: multiprocessing.eclass +# @MAINTAINER: +# base-system@gentoo.org +# @AUTHOR: +# Brian Harring <ferringb@gentoo.org> +# Mike Frysinger <vapier@gentoo.org> +# @BLURB: multiprocessing helper functions +# @DESCRIPTION: +# The multiprocessing eclass contains a suite of utility functions +# that could be helpful to controlling parallel multiple job execution. +# The most common use is processing MAKEOPTS in order to obtain job +# count. +# +# @EXAMPLE: +# +# @CODE +# src_compile() { +# # custom build system that does not support most of MAKEOPTS +# ./mybs -j$(makeopts_jobs) +# } +# @CODE + +if [[ -z ${_MULTIPROCESSING_ECLASS} ]]; then +_MULTIPROCESSING_ECLASS=1 + +# @FUNCTION: get_nproc +# @USAGE: [${fallback:-1}] +# @DESCRIPTION: +# Attempt to figure out the number of processing units available. +# If the value can not be determined, prints the provided fallback +# instead. If no fallback is provided, defaults to 1. +get_nproc() { + local nproc + + # GNU + if type -P nproc &>/dev/null; then + nproc=$(nproc) + fi + + # BSD + if [[ -z ${nproc} ]] && type -P sysctl &>/dev/null; then + nproc=$(sysctl -n hw.ncpu 2>/dev/null) + fi + + # fallback to python2.6+ + # note: this may fail (raise NotImplementedError) + if [[ -z ${nproc} ]] && type -P python &>/dev/null; then + nproc=$(python -c 'import multiprocessing; print(multiprocessing.cpu_count());' 2>/dev/null) + fi + + if [[ -n ${nproc} ]]; then + echo "${nproc}" + else + echo "${1:-1}" + fi +} + +# @FUNCTION: makeopts_jobs +# @USAGE: [${MAKEOPTS}] [${inf:-999}] +# @DESCRIPTION: +# Searches the arguments (defaults to ${MAKEOPTS}) and extracts the jobs number +# specified therein. Useful for running non-make tools in parallel too. +# i.e. if the user has MAKEOPTS=-j9, this will echo "9" -- we can't return the +# number as bash normalizes it to [0, 255]. If the flags haven't specified a +# -j flag, then "1" is shown as that is the default `make` uses. Since there's +# no way to represent infinity, we return ${inf} (defaults to 999) if the user +# has -j without a number. +makeopts_jobs() { + [[ $# -eq 0 ]] && set -- "${MAKEOPTS}" + # This assumes the first .* will be more greedy than the second .* + # since POSIX doesn't specify a non-greedy match (i.e. ".*?"). + local jobs=$(echo " $* " | sed -r -n \ + -e 's:.*[[:space:]](-[a-z]*j|--jobs[=[:space:]])[[:space:]]*([0-9]+).*:\2:p' \ + -e "s:.*[[:space:]](-[a-z]*j|--jobs)[[:space:]].*:${2:-999}:p") + echo ${jobs:-1} +} + +# @FUNCTION: makeopts_loadavg +# @USAGE: [${MAKEOPTS}] [${inf:-999}] +# @DESCRIPTION: +# Searches the arguments (defaults to ${MAKEOPTS}) and extracts the value set +# for load-average. For make and ninja based builds this will mean new jobs are +# not only limited by the jobs-value, but also by the current load - which might +# get excessive due to I/O and not just due to CPU load. +# Be aware that the returned number might be a floating-point number. Test +# whether your software supports that. +# If no limit is specified or --load-average is used without a number, ${inf} +# (defaults to 999) is returned. +makeopts_loadavg() { + [[ $# -eq 0 ]] && set -- "${MAKEOPTS}" + # This assumes the first .* will be more greedy than the second .* + # since POSIX doesn't specify a non-greedy match (i.e. ".*?"). + local lavg=$(echo " $* " | sed -r -n \ + -e 's:.*[[:space:]](-[a-z]*l|--(load-average|max-load)[=[:space:]])[[:space:]]*([0-9]+(\.[0-9]+)?)[[:space:]].*:\3:p' \ + -e "s:.*[[:space:]](-[a-z]*l|--(load-average|max-load))[[:space:]].*:${2:-999}:p") + # Default to ${inf} since the default is to not use a load limit. + echo ${lavg:-${2:-999}} +} + +fi diff --git a/eclass/myspell-r2.eclass b/eclass/myspell-r2.eclass new file mode 100644 index 0000000..2de8d14 --- /dev/null +++ b/eclass/myspell-r2.eclass @@ -0,0 +1,117 @@ +# Copyright 1999-2020 Gentoo Authors +# Distributed under the terms of the GNU General Public License v2 + +# @ECLASS: myspell-r2.eclass +# @MAINTAINER: +# maintainer-needed@gentoo.org +# @AUTHOR: +# Tomáš Chvátal <scarabeus@gentoo.org> +# @BLURB: An eclass to ease the construction of ebuilds for myspell dicts +# @DESCRIPTION: + +EXPORT_FUNCTIONS src_unpack src_install + +# @ECLASS-VARIABLE: MYSPELL_DICT +# @DEFAULT_UNSET +# @DESCRIPTION: +# Array variable containing list of all dictionary files. +# MYSPELL_DICT=( "file.dic" "dir/file2.aff" ) + +# @ECLASS-VARIABLE: MYSPELL_HYPH +# @DESCRIPTION: +# Array variable containing list of all hyphenation files. +# MYSPELL_HYPH=( "file.dic" "dir/file2.dic" ) + +# @ECLASS-VARIABLE: MYSPELL_THES +# @DESCRIPTION: +# Array variable containing list of all thesarus files. +# MYSPELL_THES=( "file.dat" "dir/file2.idx" ) + +# Basically no extra deps needed. +# Unzip is required for .oxt libreoffice extensions +# which are just fancy zip files. +DEPEND="app-arch/unzip" +RDEPEND="" + +# by default this stuff does not have any folder in the pack +S="${WORKDIR}" + +# @FUNCTION: myspell-r2_src_unpack +# @DESCRIPTION: +# Unpack all variants of weird stuff. +# In our case .oxt packs. +myspell-r2_src_unpack() { + debug-print-function ${FUNCNAME} "$@" + + local f + for f in ${A}; do + case ${f} in + *.oxt) + echo ">>> Unpacking "${DISTDIR}/${f}" to ${PWD}" + unzip -qoj ${DISTDIR}/${f} + assert "failed unpacking ${DISTDIR}/${f}" + ;; + *) unpack ${f} ;; + esac + done +} + +# @FUNCTION: myspell-r2_src_install +# @DESCRIPTION: +# Install the dictionaries to the right places. +myspell-r2_src_install() { + debug-print-function ${FUNCNAME} "$@" + + local x target + + # Following the debian directory layout here. + # DICT: /usr/share/hunspell + # THES: /usr/share/mythes + # HYPH: /usr/share/hyphen + # We just need to copy the required files to proper places. + + # TODO: backcompat dosym remove when all dictionaries and libreoffice + # ebuilds in tree use only the new paths + + # Very old installs have hunspell to be symlink to myspell. + # This results in fcked up install/symlink stuff. + if [[ -L "${EPREFIX}/usr/share/hunspell" ]] ; then + eerror "\"${EPREFIX}/usr/share/hunspell\" is a symlink." + eerror "Please remove it so it is created properly as folder" + die "\"${EPREFIX}/usr/share/hunspell\" is a symlink." + fi + + insinto /usr/share/hunspell + for x in "${MYSPELL_DICT[@]}"; do + target="${x##*/}" + newins "${x}" "${target}" || die + dosym ../hunspell/"${target}" /usr/share/myspell/"${target}" || die + done + + insinto /usr/share/mythes + for x in "${MYSPELL_THES[@]}"; do + target="${x##*/}" + newins "${x}" "${target}" || die + dosym ../mythes/"${target}" /usr/share/myspell/"${target}" || die + done + + insinto /usr/share/hyphen + for x in "${MYSPELL_HYPH[@]}"; do + target="${x##*/}" + newins "${x}" "${target}" || die + dosym ../hyphen/"${target}" /usr/share/myspell/"${target}" || die + done + + # Remove licenses as they suffix them with .txt too + rm -rf COPYING* + rm -rf LICENSE* + rm -rf LICENCE* + rm -rf license* + rm -rf licence* + # Readme and so on + for x in *.txt README*; do + if [[ -f ${x} ]]; then + dodoc ${x} || die + fi + done +} diff --git a/eclass/netsurf.eclass b/eclass/netsurf.eclass new file mode 100644 index 0000000..065ed1e --- /dev/null +++ b/eclass/netsurf.eclass @@ -0,0 +1,42 @@ +# Copyright 1999-2020 Gentoo Authors +# Distributed under the terms of the GNU General Public License v2 + +# @ECLASS: netsurf.eclass +# @MAINTAINER: +# maintainer-needed@gentoo.org +# @SUPPORTED_EAPIS: 7 +# @BLURB: Handle buildsystem of www.netsurf-browser.org components +# @DESCRIPTION: +# Handle settings build environment for netsurf build system + +case "${EAPI:-0}" in + 7) ;; + *) die "EAPI=${EAPI} is not supported" ;; +esac + +inherit toolchain-funcs + +# @FUNCTION: netsurf_define_makeconf +# @USAGE: +# @DESCRIPTION: +# This function sets NETSURF_MAKECONF as needed by netsurf build system +netsurf_define_makeconf() { + NETSURF_MAKECONF=( + PREFIX="${EPREFIX}/usr" + NSSHARED="${EPREFIX}/usr/share/netsurf-buildsystem" + LIBDIR="$(get_libdir)" + Q= + CC="$(tc-getCC)" + LD="$(tc-getLD)" + HOST_CC="\$(CC)" + BUILD_CC="$(tc-getBUILD_CC)" + CXX="$(tc-getCXX)" + BUILD_CXX="$(tc-getBUILD_CXX)" + CCOPT= + CCNOOPT= + CCDBG= + LDDBG= + AR="$(tc-getAR)" + WARNFLAGS= + ) +} diff --git a/eclass/ninja-utils.eclass b/eclass/ninja-utils.eclass new file mode 100644 index 0000000..ca8d671 --- /dev/null +++ b/eclass/ninja-utils.eclass @@ -0,0 +1,58 @@ +# Copyright 1999-2018 Gentoo Foundation +# Distributed under the terms of the GNU General Public License v2 + +# @ECLASS: ninja-utils.eclass +# @MAINTAINER: +# Michał Górny <mgorny@gentoo.org> +# Mike Gilbert <floppym@gentoo.org> +# @AUTHOR: +# Michał Górny <mgorny@gentoo.org> +# Mike Gilbert <floppym@gentoo.org> +# @SUPPORTED_EAPIS: 2 4 5 6 7 +# @BLURB: common bits to run dev-util/ninja builder +# @DESCRIPTION: +# This eclass provides a single function -- eninja -- that can be used +# to run the ninja builder alike emake. It does not define any +# dependencies, you need to depend on dev-util/ninja yourself. Since +# ninja is rarely used stand-alone, most of the time this eclass will +# be used indirectly by the eclasses for other build systems (CMake, +# Meson). + +if [[ -z ${_NINJA_UTILS_ECLASS} ]]; then + +case ${EAPI:-0} in + 0|1|3) die "EAPI=${EAPI:-0} is not supported (too old)";; + # copied from cmake-utils + 2|4|5|6|7) ;; + *) die "EAPI=${EAPI} is not yet supported" ;; +esac + +# @ECLASS-VARIABLE: NINJAOPTS +# @DEFAULT_UNSET +# @DESCRIPTION: +# The default set of options to pass to Ninja. Similar to MAKEOPTS, +# supposed to be set in make.conf. If unset, eninja() will convert +# MAKEOPTS instead. + +inherit multiprocessing + +# @FUNCTION: eninja +# @USAGE: [<args>...] +# @DESCRIPTION: +# Call Ninja, passing the NINJAOPTS (or converted MAKEOPTS), followed +# by the supplied arguments. This function dies if ninja fails. Starting +# with EAPI 6, it also supports being called via 'nonfatal'. +eninja() { + local nonfatal_args=() + [[ ${EAPI:-0} != [245] ]] && nonfatal_args+=( -n ) + + if [[ -z ${NINJAOPTS+set} ]]; then + NINJAOPTS="-j$(makeopts_jobs) -l$(makeopts_loadavg "${MAKEOPTS}" 0)" + fi + set -- ninja -v ${NINJAOPTS} "$@" + echo "$@" >&2 + "$@" || die "${nonfatal_args[@]}" "${*} failed" +} + +_NINJA_UTILS_ECLASS=1 +fi diff --git a/eclass/nsplugins.eclass b/eclass/nsplugins.eclass new file mode 100644 index 0000000..0b154c8 --- /dev/null +++ b/eclass/nsplugins.eclass @@ -0,0 +1,79 @@ +# Copyright 1999-2013 Gentoo Foundation +# Distributed under the terms of the GNU General Public License v2 +# +# @ECLASS: nsplugins.eclass +# @MAINTAINER: +# Mozilla Team <mozilla@gentoo.org> +# @AUTHOR: +# Original Author: Martin Schlemmer <azarah@gentoo.org> +# @BLURB: reusable functions for netscape/moz plugin sharing +# @DESCRIPTION: +# Reusable functions that promote sharing of netscape/moz plugins, also provides +# share_plugins_dir function for mozilla applications. + +inherit eutils multilib versionator mozextension + +PLUGINS_DIR="nsbrowser/plugins" + +# This function move the plugin dir in src_install() to +# ${D}/usr/$(get_libdir)/${PLUGIN_DIR}. First argument should be +# the full path (without $D) to old plugin dir. +src_mv_plugins() { + has "${EAPI:-0}" 0 1 2 && ! use prefix && ED="${D}" + + # Move plugins dir. We use keepdir so that it might not be unmerged + # by mistake ... + keepdir /usr/$(get_libdir)/${PLUGINS_DIR} + cp -a "${ED}"/$1/* "${ED}"/usr/$(get_libdir)/${PLUGINS_DIR} + rm -rf "${ED}"/$1 + dosym /usr/$(get_libdir)/${PLUGINS_DIR} $1 +} + +# This function move plugins in pkg_preinst() in old dir to +# ${ROOT}/usr/$(get_libdir)/${PLUGIN_DIR}. First argument should be +# the full path (without $ROOT) to old plugin dir. +pkg_mv_plugins() { + has "${EAPI:-0}" 0 1 2 && ! use prefix && ED="${ROOT}" + + # Move old plugins dir + if [ -d "${ROOT}/$1" -a ! -L "${ROOT}/$1" ] + then + mkdir -p "${EROOT}"/usr/$(get_libdir)/${PLUGINS_DIR} + cp -a "${EROOT}"/$1/* "${EROOT}"/usr/$(get_libdir)/${PLUGINS_DIR} + rm -rf "${EROOT}"/$1 + fi +} + +# This function installs a plugin with dosym to PLUGINS_DIR. +# First argument should be the plugin file. +inst_plugin() { + if [[ -z "${1}" ]]; then + eerror "The plugin file \"${1}\" does not exist." + die "No such file or directory." + fi + + dodir /usr/$(get_libdir)/${PLUGINS_DIR} + dosym ${1} /usr/$(get_libdir)/${PLUGINS_DIR}/$(basename ${1}) +} + +# This function ensures we use proper plugin path for Gentoo. +# This should only be used by mozilla packages. +# ${MOZILLA_FIVE_HOME} must be defined in src_install to support +share_plugins_dir() { + if [[ ${PN} == seamonkey ]] ; then + rm -rf "${D}"${MOZILLA_FIVE_HOME}/plugins \ + || die "failed to remove existing plugins dir" + fi + + if [[ ${PN} == *-bin ]] ; then + PLUGIN_BASE_PATH="/usr/$(get_libdir)" + else + PLUGIN_BASE_PATH=".." + fi + + if $(mozversion_extension_location) ; then + dosym "${PLUGIN_BASE_PATH}/nsbrowser/plugins" "${MOZILLA_FIVE_HOME}/browser/plugins" + else + dosym "${PLUGIN_BASE_PATH}/nsbrowser/plugins" "${MOZILLA_FIVE_HOME}/plugins" + fi +} diff --git a/eclass/nvidia-driver.eclass b/eclass/nvidia-driver.eclass new file mode 100644 index 0000000..65fa909 --- /dev/null +++ b/eclass/nvidia-driver.eclass @@ -0,0 +1,221 @@ +# Copyright 1999-2021 Gentoo Authors +# Distributed under the terms of the GNU General Public License v2 + +# @ECLASS: nvidia-driver.eclass +# @MAINTAINER: +# David Seifert <soap@gentoo.org> +# @AUTHOR: +# Original author: Doug Goldstein <cardoe@gentoo.org> +# @SUPPORTED_EAPIS: 7 +# @BLURB: Provide useful messages for nvidia-drivers +# @DESCRIPTION: +# Provide useful messages for nvidia-drivers based on currently installed +# Nvidia GPU and Linux kernel. + +# @ECLASS-VARIABLE: NV_KV_MAX_PLUS +# @REQUIRED +# @DESCRIPTION: +# Two component version specifier for the strict upper bound on the +# usable kernel version. +# +# Example: +# @CODE +# NV_KV_MAX_PLUS="5.11" +# @CODE +# +# means that only kernels (strictly) below 5.11 are supported by the driver +# in question. + +case ${EAPI:-0} in + [0-6]) die "Unsupported EAPI=${EAPI:-0} (too old) for ${ECLASS}" ;; + 7) ;; + *) die "Unsupported EAPI=${EAPI} (unknown) for ${ECLASS}" ;; +esac + +if [[ ! ${_NVIDIA_DRIVER_ECLASS} ]]; then +_NVIDIA_DRIVER_ECLASS=1 + +inherit readme.gentoo-r1 + +DESCRIPTION="NVIDIA Accelerated Graphics Driver" +HOMEPAGE="https://www.nvidia.com/Download/Find.aspx" +BDEPEND="sys-apps/pciutils" +RESTRICT="bindist mirror test" + +# Variables for readme.gentoo.eclass: +DISABLE_AUTOFORMATTING="yes" +DOC_CONTENTS="You must be in the video group to use the NVIDIA device +For more info, read the docs at +https://www.gentoo.org/doc/en/nvidia-guide.xml#doc_chap3_sect6 + +This ebuild installs a kernel module and X driver. Both must +match explicitly in their version. This means, if you restart +X, you must modprobe -r nvidia before starting it back up + +To use the NVIDIA CUDA/OpenCL, run \"eselect opencl set nvidia\" + +NVIDIA has requested that any bug reports submitted have the +output of nvidia-bug-report.sh included. +" + +# @FUNCTION: nvidia-driver_get_gpu +# @DESCRIPTION: +# Retrieve the PCI device ID for each Nvidia GPU you have +nvidia-driver_get_gpu() { + local NVIDIA_CARD=$( + [[ -x ${BROOT}/usr/sbin/lspci ]] && "${BROOT}"/usr/sbin/lspci -d 10de: -n \ + | awk -F'[: ]' '/ 03[0-9][0-9]: /{print $6}' + ) + + if [[ -n ${NVIDIA_CARD} ]]; then + echo "${NVIDIA_CARD}" + else + echo 0000 + fi +} + +nvidia-driver_get_mask() { + local nvidia_gpus="$(nvidia-driver_get_gpu)" + local nvidia_gpu drv + + for nvidia_gpu in ${nvidia_gpus}; do + # the data below is derived from + # https://us.download.nvidia.com/XFree86/Linux-x86_64/396.18/README/supportedchips.html + + if has ${nvidia_gpu} \ + 0020 0028 0029 002c 002d 00a0 0100 0101 0103 0150 0151 0152 0153; then + echo ">=x11-drivers/nvidia-drivers-72.0.0" + return 0 + fi + + if has ${nvidia_gpu} \ + 0110 0111 0112 0113 0170 0171 0172 0173 0174 0175 0176 0177 0178 0179 017a \ + 017c 017d 0181 0182 0183 0185 0188 018a 018b 018c 01a0 01f0 0200 0201 0202 \ + 0203 0250 0251 0253 0258 0259 025b 0280 0281 0282 0286 0288 0289 028c; then + echo ">=x11-drivers/nvidia-drivers-97.0.0" + return 0 + fi + + if has ${nvidia_gpu} \ + 00fa 00fb 00fc 00fd 00fe 0301 0302 0308 0309 0311 0312 0314 031a 031b 031c \ + 0320 0321 0322 0323 0324 0325 0326 0327 0328 032a 032b 032c 032d 0330 0331 \ + 0332 0333 0334 0338 033f 0341 0342 0343 0344 0347 0348 034c 034e; then + echo ">=x11-drivers/nvidia-drivers-177.0.0" + return 0 + fi + + if has ${nvidia_gpu} \ + 0040 0041 0042 0043 0044 0045 0046 0047 0048 004e 0090 0091 0092 0093 0095 \ + 0098 0099 009d 00c0 00c1 00c2 00c3 00c8 00c9 00cc 00cd 00ce 00f1 00f2 00f3 \ + 00f4 00f5 00f6 00f8 00f9 0140 0141 0142 0143 0144 0145 0146 0147 0148 0149 \ + 014a 014c 014d 014e 014f 0160 0161 0162 0163 0164 0165 0166 0167 0168 0169 \ + 016a 01d0 01d1 01d2 01d3 01d6 01d7 01d8 01da 01db 01dc 01dd 01de 01df 0211 \ + 0212 0215 0218 0221 0222 0240 0241 0242 0244 0245 0247 0290 0291 0292 0293 \ + 0294 0295 0297 0298 0299 029a 029b 029c 029d 029e 029f 02e0 02e1 02e2 02e3 \ + 02e4 038b 0390 0391 0392 0393 0394 0395 0397 0398 0399 039c 039e 03d0 03d1 \ + 03d2 03d5 03d6 0531 0533 053a 053b 053e 07e0 07e1 07e2 07e3 07e5; then + echo ">=x11-drivers/nvidia-drivers-305.0.0" + return 0 + fi + + if has ${nvidia_gpu} \ + 0191 0193 0194 0197 019d 019e 0400 0401 0402 0403 0404 0405 0406 0407 0408 \ + 0409 040a 040b 040c 040d 040e 040f 0410 0420 0421 0422 0423 0424 0425 0426 \ + 0427 0428 0429 042a 042b 042c 042d 042e 042f 05e0 05e1 05e2 05e3 05e6 05e7 \ + 05e7 05e7 05e7 05e7 05e7 05ea 05eb 05ed 05f8 05f9 05fd 05fe 05ff 0600 0601 \ + 0602 0603 0604 0605 0606 0607 0608 0609 0609 060a 060b 060c 060d 060f 0610 \ + 0611 0612 0613 0614 0615 0617 0618 0619 061a 061b 061c 061d 061e 061f 0621 \ + 0622 0623 0625 0626 0627 0628 062a 062b 062c 062d 062e 062e 0630 0631 0632 \ + 0635 0637 0638 063a 0640 0641 0643 0644 0645 0646 0647 0648 0649 0649 064a \ + 064b 064c 0651 0652 0652 0653 0654 0654 0654 0655 0656 0658 0659 065a 065b \ + 065c 06e0 06e1 06e2 06e3 06e4 06e5 06e6 06e7 06e8 06e8 06e9 06ea 06eb 06ec \ + 06ef 06f1 06f8 06f9 06f9 06fa 06fb 06fd 06ff 06ff 0840 0844 0845 0846 0847 \ + 0848 0849 084a 084b 084c 084d 084f 0860 0861 0862 0863 0864 0865 0866 0866 \ + 0867 0868 0869 086a 086c 086d 086e 086f 0870 0871 0872 0872 0873 0873 0874 \ + 0876 087a 087d 087e 087f 08a0 08a2 08a3 08a4 08a5 0a20 0a22 0a23 0a26 0a27 \ + 0a28 0a29 0a2a 0a2b 0a2c 0a2d 0a32 0a34 0a35 0a38 0a3c 0a60 0a62 0a63 0a64 \ + 0a65 0a66 0a67 0a68 0a69 0a6a 0a6c 0a6e 0a6e 0a6f 0a70 0a70 0a70 0a71 0a72 \ + 0a73 0a73 0a73 0a74 0a74 0a75 0a75 0a76 0a78 0a7a 0a7a 0a7a 0a7a 0a7a 0a7a \ + 0a7a 0a7a 0a7a 0a7a 0a7a 0a7c 0ca0 0ca2 0ca3 0ca4 0ca5 0ca7 0ca8 0ca9 0cac \ + 0caf 0cb0 0cb1 0cbc 10c0 10c3 10c5 10d8; then + echo ">=x11-drivers/nvidia-drivers-341.0.0" + return 0 + fi + + if has ${nvidia_gpu} \ + 06c0 06c4 06ca 06cd 06d1 06d2 06d8 06d9 06da 06dc 06dd 06de 06df 0dc0 0dc4 \ + 0dc5 0dc6 0dcd 0dce 0dd1 0dd2 0dd3 0dd6 0dd8 0dda 0de0 0de1 0de2 0de3 0de4 \ + 0de5 0de7 0de8 0de9 0dea 0deb 0dec 0ded 0dee 0def 0df0 0df1 0df2 0df3 0df4 \ + 0df5 0df6 0df7 0df8 0df9 0dfa 0dfc 0e22 0e23 0e24 0e30 0e31 0e3a 0e3b 0f00 \ + 0f01 0f02 0f03 1040 1042 1048 1049 104a 104b 104c 1050 1051 1052 1054 1055 \ + 1056 1057 1058 1059 105a 105b 107c 107d 1080 1081 1082 1084 1086 1087 1088 \ + 1089 108b 1091 1094 1096 109a 109b 1140 1200 1201 1203 1205 1206 1207 1208 \ + 1210 1211 1212 1213 1241 1243 1244 1245 1246 1247 1248 1249 124b 124d 1251; then + echo ">=x11-drivers/nvidia-drivers-391.0.0" + return 0 + fi + done + + return 1 +} + +# @FUNCTION: nvidia-driver_check_gpu +# @DESCRIPTION: +# Prints out a warning if the driver does not work with the installed GPU +nvidia-driver_check_gpu() { + local nvidia_mask=$(nvidia-driver_get_mask) + + if [[ -n ${nvidia_mask} ]]; then + if ver_test "${nvidia_mask##*-}" -lt "${PV}" ; then + ewarn "***** WARNING *****" + ewarn + ewarn "You are currently installing a version of nvidia-drivers that is" + ewarn "known not to work with a GPU you have installed on your system." + ewarn "If this is intentional, please ignore this. If it is not please" + ewarn "perform the following steps:" + ewarn + ewarn "Add the following mask entry to the local package.mask file:" + if [[ -d ${EROOT}/etc/portage/package.mask ]]; then + ewarn "echo \"${nvidia_mask}\" > ${EROOT}/etc/portage/package.mask/nvidia-drivers" + else + ewarn "echo \"${nvidia_mask}\" >> ${EROOT}/etc/portage/package.mask" + fi + ewarn + ewarn "Failure to perform the steps above could result in a non-working" + ewarn "X setup." + ewarn + ewarn "For more information please read:" + ewarn "https://www.nvidia.com/object/IO_32667.html" + fi + fi +} + +nvidia-driver_check_kernel() { + if kernel_is ge ${NV_KV_MAX_PLUS/./ }; then + ewarn "Gentoo supports kernels which are supported by NVIDIA" + ewarn "which are limited to the following kernels:" + ewarn "<sys-kernel/gentoo-sources-${NV_KV_MAX_PLUS}" + ewarn "<sys-kernel/gentoo-kernel-${NV_KV_MAX_PLUS}" + ewarn + ewarn "You are free to apply custom patches via /etc/portage/patches" + ewarn "to provide whatever support you feel is appropriate, but will" + ewarn "not receive support as a result of those changes." + ewarn + ewarn "Do not file a bug report about this." + ewarn + fi + + check_extra_config +} + +nvidia-driver_check() { + # Since Nvidia ships many different series of drivers, we need to give the user + # some kind of guidance as to what version they should install. This tries + # to point the user in the right direction but can't be perfect. check + # nvidia-driver.eclass + nvidia-driver_check_gpu + + use driver && use kernel_linux && nvidia-driver_check_kernel +} + +fi diff --git a/eclass/oasis.eclass b/eclass/oasis.eclass new file mode 100644 index 0000000..bcc46b4 --- /dev/null +++ b/eclass/oasis.eclass @@ -0,0 +1,132 @@ +# Copyright 1999-2020 Gentoo Authors +# Distributed under the terms of the GNU General Public License v2 + +# @ECLASS: oasis.eclass +# @MAINTAINER: +# maintainer-needed@gentoo.org +# @AUTHOR: +# Original Author: Alexis Ballier <aballier@gentoo.org> +# @SUPPORTED_EAPIS: 3 4 5 +# @BLURB: Provides common ebuild phases for oasis-based packages. +# @DESCRIPTION: +# Provides common ebuild phases for oasis-based packages. +# Most of these packages will just have to inherit the eclass, set their +# dependencies and the DOCS variable for base.eclass to install it and be done. +# +# It inherits multilib, findlib, eutils and base eclasses. +# Ebuilds using oasis.eclass must be EAPI>=3. + +# @ECLASS-VARIABLE: OASIS_BUILD_DOCS +# @DESCRIPTION: +# Will make oasis_src_compile build the documentation if this variable is +# defined and the doc useflag is enabled. +# The eclass takes care of setting doc in IUSE but the ebuild should take care +# of the extra dependencies it may need. +# Set before inheriting the eclass. + +# @ECLASS-VARIABLE: OASIS_BUILD_TESTS +# @DESCRIPTION: +# Will make oasis_src_configure enable building the tests if the test useflag is +# enabled. oasis_src_test will then run them. +# Note that you sometimes need to enable this for src_test to be useful, +# sometimes not. It has to be enabled on a per-case basis. +# The eclass takes care of setting test in IUSE but the ebuild should take care +# of the extra dependencies it may need. +# Set before inheriting the eclass. + + +# @ECLASS-VARIABLE: OASIS_NO_DEBUG +# @DESCRIPTION: +# Disable debug useflag usage. Old oasis versions did not support it so we allow +# disabling it in those cases. +# The eclass takes care of setting debug in IUSE. +# Set before inheriting the eclass. + +# @ECLASS-VARIABLE: OASIS_DOC_DIR +# @DESCRIPTION: +# Specify where to install documentation. Default is for ocamldoc HTML. +# Change it before inherit if this is not what you want. +# EPREFIX is automatically prepended. +: ${OASIS_DOC_DIR:="/usr/share/doc/${PF}/html"} + +inherit multilib findlib eutils base + +# Implicitly limited to EAPI 5 or earlier because of base.eclass +case ${EAPI:-0} in + 0|1|2) die "You need at least EAPI-3 to use oasis.eclass";; + 3|4) RDEPEND=">=dev-lang/ocaml-3.12[ocamlopt?]";; + *) RDEPEND=">=dev-lang/ocaml-3.12:=[ocamlopt?]";; +esac + +IUSE="+ocamlopt" +[ -n "${OASIS_NO_DEBUG}" ] || IUSE="${IUSE} debug" +[ -n "${OASIS_BUILD_DOCS}" ] && IUSE="${IUSE} doc" +if [[ -n ${OASIS_BUILD_TESTS} ]]; then + IUSE+=" test" + RESTRICT+=" !test? ( test )" +fi + +DEPEND="${RDEPEND} + dev-ml/ocamlbuild" + +# @FUNCTION: oasis_use_enable +# @USAGE: < useflag > < variable > +# @DESCRIPTION: +# A use_enable-like function for oasis configure variables. +# Outputs '--override variable (true|false)', whether useflag is enabled or +# not. +# Typical usage: $(oasis_use_enable ocamlopt is_native) as an oasis configure +# argument. +oasis_use_enable() { + echo "--override $2 $(usex $1 true false)" +} + +# @FUNCTION: oasis_src_configure +# @DESCRIPTION: +# src_configure phase shared by oasis-based packages. +# Extra arguments may be passed via oasis_configure_opts. +oasis_src_configure() { + local confargs="" + [ -n "${OASIS_BUILD_TESTS}" ] && confargs="${confargs} $(use_enable test tests)" + [ -n "${OASIS_NO_DEBUG}" ] || confargs="${confargs} $(oasis_use_enable debug debug)" + ${OASIS_SETUP_COMMAND:-ocaml setup.ml} -configure \ + --prefix "${ED}/usr" \ + --libdir "${ED}/usr/$(get_libdir)" \ + --docdir "${ED}${OASIS_DOC_DIR}" \ + $(oasis_use_enable ocamlopt is_native) \ + ${confargs} \ + ${oasis_configure_opts} \ + || die +} + +# @FUNCTION: oasis_src_compile +# @DESCRIPTION: +# Builds an oasis-based package. +# Will build documentation if OASIS_BUILD_DOCS is defined and the doc useflag is +# enabled. +oasis_src_compile() { + ${OASIS_SETUP_COMMAND:-ocaml setup.ml} -build || die + if [ -n "${OASIS_BUILD_DOCS}" ] && use doc; then + ocaml setup.ml -doc || die + fi +} + +# @FUNCTION: oasis_src_test +# @DESCRIPTION: +# Runs the testsuite of an oasis-based package. +oasis_src_test() { + LD_LIBRARY_PATH="${S}/_build/lib" ${OASIS_SETUP_COMMAND:-ocaml setup.ml} -test || die +} + +# @FUNCTION: oasis_src_install +# @DESCRIPTION: +# Installs an oasis-based package. +# It calls base_src_install_docs, so will install documentation declared in the +# DOCS variable. +oasis_src_install() { + findlib_src_preinst + ${OASIS_SETUP_COMMAND:-ocaml setup.ml} -install || die + base_src_install_docs +} + +EXPORT_FUNCTIONS src_configure src_compile src_test src_install diff --git a/eclass/office-ext-r1.eclass b/eclass/office-ext-r1.eclass new file mode 100644 index 0000000..a1649ac --- /dev/null +++ b/eclass/office-ext-r1.eclass @@ -0,0 +1,148 @@ +# Copyright 1999-2021 Gentoo Authors +# Distributed under the terms of the GNU General Public License v2 + +# @ECLASS: office-ext-r1.eclass +# @MAINTAINER: +# The office team <office@gentoo.org> +# @AUTHOR: +# Tomáš Chvátal <scarabeus@gentoo.org> +# @SUPPORTED_EAPIS: 5 7 +# @BLURB: Eclass for installing libreoffice extensions +# @DESCRIPTION: +# Eclass for easing maintenance of libreoffice extensions. + +case "${EAPI:-0}" in + 5) inherit eutils multilib ;; + 7) inherit eutils ;; + *) die "EAPI=${EAPI} is not supported" ;; +esac + +EXPORT_FUNCTIONS src_unpack src_install + +# @ECLASS-VARIABLE: OFFICE_REQ_USE +# @DESCRIPTION: +# Useflags required on office implementation for the extension. +# +# Example: +# @CODE +# OFFICE_REQ_USE="java,jemalloc(-)?" +# @CODE +if [[ ${OFFICE_REQ_USE} ]]; then + # Append the brackets for the depend bellow + OFFICE_REQ_USE="[${OFFICE_REQ_USE}]" +fi + +# @ECLASS-VARIABLE: OFFICE_IMPLEMENTATIONS +# @DESCRIPTION: +# List of implementations supported by the extension. +# Some work only for libreoffice and vice versa. +# Default value is all implementations. +# +# Example: +# @CODE +# OFFICE_IMPLEMENTATIONS=( "libreoffice" ) +# @CODE +[[ -z ${OFFICE_IMPLEMENTATIONS} ]] && OFFICE_IMPLEMENTATIONS=( "libreoffice" ) + +# @ECLASS-VARIABLE: OFFICE_EXTENSIONS +# @REQUIRED +# @DESCRIPTION: +# Array containing list of extensions to install. +# +# Example: +# @CODE +# OFFICE_EXTENSIONS=( ${PN}_${PV}.oxt ) +# @CODE +[[ -z ${OFFICE_EXTENSIONS} ]] && die "OFFICE_EXTENSIONS variable is unset." +if [[ "$(declare -p OFFICE_EXTENSIONS 2>/dev/null 2>&1)" != "declare -a"* ]]; then + die "OFFICE_EXTENSIONS variable is not an array." +fi + +# @ECLASS-VARIABLE: OFFICE_EXTENSIONS_LOCATION +# @DESCRIPTION: +# Path to the extensions location. Defaults to ${DISTDIR}. +# +# Example: +# @CODE +# OFFICE_EXTENSIONS_LOCATION="${S}/unpacked/" +# @CODE +: ${OFFICE_EXTENSIONS_LOCATION:=${DISTDIR}} + +IUSE="" +RDEPEND="" + +for i in ${OFFICE_IMPLEMENTATIONS[@]}; do + IUSE+=" office_implementation_${i}" + if [[ ${i} == "libreoffice" ]]; then + RDEPEND+=" + office_implementation_${i}? ( + || ( + app-office/${i}${OFFICE_REQ_USE} + app-office/${i}-bin${OFFICE_REQ_USE} + ) + ) + " + fi +done + +REQUIRED_USE="|| ( " +for i in ${OFFICE_IMPLEMENTATIONS[@]}; do + REQUIRED_USE+=" office_implementation_${i} " +done +REQUIRED_USE+=" )" + +DEPEND="${RDEPEND} + app-arch/unzip +" + +# Most projects actually do not provide any relevant sourcedir as they are oxt. +S="${WORKDIR}" + +# @FUNCTION: office-ext-r1_src_unpack +# @DESCRIPTION: +# Flush the cache after removal of an extension. +office-ext-r1_src_unpack() { + debug-print-function ${FUNCNAME} "$@" + local i + + default + + for i in ${OFFICE_EXTENSIONS[@]}; do + # Unpack the extensions where required and add case for oxt + # which should be most common case for the extensions. + if [[ -f "${OFFICE_EXTENSIONS_LOCATION}/${i}" ]] ; then + case ${i} in + *.oxt) + mkdir -p "${WORKDIR}/${i}/" || die + pushd "${WORKDIR}/${i}/" > /dev/null || die + einfo "Unpacking "${OFFICE_EXTENSIONS_LOCATION}/${i}" to ${PWD}" + unzip -qo ${OFFICE_EXTENSIONS_LOCATION}/${i} + assert "failed unpacking ${OFFICE_EXTENSIONS_LOCATION}/${i}" + popd > /dev/null || die + ;; + *) unpack ${i} ;; + esac + fi + done +} + +# @FUNCTION: office-ext-r1_src_install +# @DESCRIPTION: +# Install the extension source to the proper location. +office-ext-r1_src_install() { + debug-print-function ${FUNCNAME} "$@" + debug-print "Extensions: ${OFFICE_EXTENSIONS[@]}" + + local i j + + for i in ${OFFICE_IMPLEMENTATIONS[@]}; do + if use office_implementation_${i}; then + for j in ${OFFICE_EXTENSIONS[@]}; do + pushd "${WORKDIR}/${j}/" > /dev/null || die + insinto /usr/$(get_libdir)/${i}/share/extensions/${j/.oxt/} + doins -r * + popd > /dev/null || die + done + fi + done +} diff --git a/eclass/opam.eclass b/eclass/opam.eclass new file mode 100644 index 0000000..05ebea5 --- /dev/null +++ b/eclass/opam.eclass @@ -0,0 +1,66 @@ +# Copyright 1999-2020 Gentoo Authors +# Distributed under the terms of the GNU General Public License v2 + +# @ECLASS: opam.eclass +# @MAINTAINER: +# Mark Wright <gienah@gentoo.org> +# @AUTHOR: +# Alexis Ballier <aballier@gentoo.org> +# @SUPPORTED_EAPIS: 5 6 7 +# @BLURB: Provides functions for installing opam packages. +# @DESCRIPTION: +# Provides dependencies on opam and ocaml, opam-install and a default +# src_install for opam-based packages. + +case ${EAPI:-0} in + 5|6|7) ;; + *) die "${ECLASS}: EAPI ${EAPI} not supported" ;; +esac + +# Do not complain about CFLAGS etc since ml projects do not use them. +QA_FLAGS_IGNORED='.*' + +# @ECLASS-VARIABLE: OPAM_INSTALLER_DEP +# @DESCRIPTION: +# Override dependency for OPAM_INSTALLER +: ${OPAM_INSTALLER_DEP:="dev-ml/opam-installer"} + +RDEPEND=">=dev-lang/ocaml-4:=" +case ${EAPI:-0} in + 0|1|2|3|4|5|6) DEPEND="${RDEPEND} ${OPAM_INSTALLER_DEP}";; + *) BDEPEND="${OPAM_INSTALLER_DEP} dev-lang/ocaml"; DEPEND="${RDEPEND}" ;; +esac + +# @ECLASS-VARIABLE: OPAM_INSTALLER +# @DESCRIPTION: +# Eclass can use different opam-installer binary than the one provided in by system. +: ${OPAM_INSTALLER:=opam-installer} + +# @FUNCTION: opam-install +# @USAGE: <list of packages> +# @DESCRIPTION: +# Installs the opam packages given as arguments. For each "${pkg}" element in +# that list, "${pkg}.install" must be readable from current working directory. +opam-install() { + local pkg + for pkg ; do + ${OPAM_INSTALLER} -i \ + --prefix="${ED%/}/usr" \ + --libdir="${D%/}/$(ocamlc -where)" \ + --docdir="${ED%/}/usr/share/doc/${PF}" \ + --mandir="${ED%/}/usr/share/man" \ + "${pkg}.install" || die + done +} + +opam_src_install() { + local pkg="${1:-${PN}}" + opam-install "${pkg}" + # Handle opam putting doc in a subdir + if [ -d "${ED%/}/usr/share/doc/${PF}/${pkg}" ] ; then + mv "${ED%/}/usr/share/doc/${PF}/${pkg}/"* "${ED%/}/usr/share/doc/${PF}/" || die + rmdir "${ED%/}/usr/share/doc/${PF}/${pkg}" || die + fi +} + +EXPORT_FUNCTIONS src_install diff --git a/eclass/openib.eclass b/eclass/openib.eclass new file mode 100644 index 0000000..a36f5cd --- /dev/null +++ b/eclass/openib.eclass @@ -0,0 +1,146 @@ +# Copyright 1999-2020 Gentoo Authors +# Distributed under the terms of the GNU General Public License v2 + +# @ECLASS: openib.eclass +# @AUTHOR: +# Original Author: Alexey Shvetsov <alexxy@gentoo.org> +# @BLURB: Simplify working with OFED packages + +inherit eutils rpm versionator + +EXPORT_FUNCTIONS src_unpack + +HOMEPAGE="https://www.openfabrics.org/" +LICENSE="|| ( GPL-2 BSD-2 )" + +# @ECLASS-VARIABLE: OFED_VER +# @DESCRIPTION: +# Defines OFED version eg 1.4 or 1.4.0.1 + +# @ECLASS-VARIABLE: OFED_RC +# @DESCRIPTION: +# Sets if this version is RC + +# @ECLASS-VARIABLE: OFED_RC_VER +# @DESCRIPTION: +# Sets RC version + + +# @ECLASS-VARIABLE: OFED_SUFFIX +# @DESCRIPTION: +# Defines OFED package suffix eg -1.ofed1.4 + +# @ECLASS-VARIABLE: OFED_SNAPSHOT +# @DESCRIPTION: +# Defines if src tarball is git snapshot + +SLOT="${OFED_VER}" + +# @ECLASS-VARIABLE: OFED_VERSIONS +# @DESCRIPTION: +# Defines array of ofed version supported by eclass + +OFED_VERSIONS=( + "3.5" + "3.12" + ) + +# @FUNCTION: block_other_ofed_versions +# @DESCRIPTION: +# function that creates blockers list for ofed +block_other_ofed_versions() { + local slot + RDEPEND="${RDEPEND} !sys-fabric/${PN}:0" + for slot in ${OFED_VERSIONS[@]}; do + if [[ ${slot} != ${SLOT} ]]; then + RDEPEND+=" !sys-fabric/${PN}:${slot}" + fi + done +} + +OFED_BASE_VER=$(get_version_component_range 1-3 ${OFED_VER}) + +if [ -z $OFED_RC ] ; then + SRC_URI="https://www.openfabrics.org/downloads/OFED/ofed-${OFED_BASE_VER}/OFED-${OFED_VER}.tgz" +else + SRC_URI="https://www.openfabrics.org/downloads/OFED/ofed-${OFED_BASE_VER}/OFED-${OFED_VER}-rc${OFED_RC_VER}.tgz" +fi + +case ${PN} in + ofed) + MY_PN="compat-rdma" + ;; + *) + MY_PN="${PN}" + ;; +esac + +case ${PV} in + *p*) + MY_PV="${PV/p/}" + ;; + *) + MY_PV="${PV}" + ;; +esac + +case ${MY_PN} in + ofa_kernel|compat-rdma) + EXT="tgz" + ;; + *) + EXT="tar.gz" + ;; +esac + +if [ -z ${OFED_SRC_SNAPSHOT} ]; then + S="${WORKDIR}/${MY_PN}-${MY_PV}" +else + S="${WORKDIR}/${MY_PN}-${MY_PV}-${OFED_SUFFIX}" +fi + + +# @FUNCTION: openib_src_unpack +# @DESCRIPTION: +# This function will unpack OFED packages +openib_src_unpack() { + unpack ${A} + if [ -z ${OFED_RC} ]; then + case ${PN} in + ofed) + rpm_unpack "./OFED-${OFED_VER}/SRPMS/${MY_PN}-${OFED_VER}-${OFED_SUFFIX}.src.rpm" + ;; + *) + rpm_unpack "./OFED-${OFED_VER}/SRPMS/${MY_PN}-${MY_PV}-${OFED_SUFFIX}.src.rpm" + ;; + esac + else + case ${PN} in + ofed) + rpm_unpack "./OFED-${OFED_VER}-rc${OFED_RC_VER}/SRPMS/${MY_PN}-${OFED_VER}-${OFED_SUFFIX}.src.rpm" + ;; + *) + rpm_unpack "./OFED-${OFED_VER}-rc${OFED_RC_VER}/SRPMS/${MY_PN}-${MY_PV}-${OFED_SUFFIX}.src.rpm" + ;; + esac + fi + if [ -z ${OFED_SNAPSHOT} ]; then + case ${PN} in + ofed) + unpack ./${MY_PN}-${OFED_VER}.${EXT} + ;; + *) + unpack ./${MY_PN}-${MY_PV}.${EXT} + ;; + esac + else + case ${PN} in + ofed) + unpack ./${MY_PN}-${OFED_VER}-${OFED_SUFFIX}.${EXT} + ;; + *) + unpack ./${MY_PN}-${MY_PV}-${OFED_SUFFIX}.${EXT} + ;; + esac + fi +} diff --git a/eclass/optfeature.eclass b/eclass/optfeature.eclass new file mode 100644 index 0000000..e13fc3e --- /dev/null +++ b/eclass/optfeature.eclass @@ -0,0 +1,66 @@ +# Copyright 1999-2020 Gentoo Authors +# Distributed under the terms of the GNU General Public License v2 + +# @ECLASS: optfeature.eclass +# @MAINTAINER: +# base-system@gentoo.org +# @BLURB: Advertise optional functionality that might be useful to users + +case ${EAPI:-0} in + [0-7]) ;; + *) die "Unsupported EAPI=${EAPI} (unknown) for ${ECLASS}" ;; +esac + +if [[ -z ${_OPTFEATURE_ECLASS} ]]; then +_OPTFEATURE_ECLASS=1 + +# @FUNCTION: optfeature +# @USAGE: <short description> <package atom to match> [other atoms] +# @DESCRIPTION: +# Print out a message suggesting an optional package (or packages) +# not currently installed which provides the described functionality. +# +# The following snippet would suggest app-misc/foo for optional foo support, +# app-misc/bar or app-misc/baz[bar] for optional bar support +# and either both app-misc/a and app-misc/b or app-misc/c for alphabet support. +# @CODE +# optfeature "foo support" app-misc/foo +# optfeature "bar support" app-misc/bar app-misc/baz[bar] +# optfeature "alphabet support" "app-misc/a app-misc/b" app-misc/c +# @CODE +optfeature() { + debug-print-function ${FUNCNAME} "$@" + + local i j msg + local -a arr + local desc=$1 + local flag=0 + shift + for i; do + read -r -d '' -a arr <<<"${i}" + for j in "${arr[@]}"; do + if has_version "${j}"; then + flag=1 + else + flag=0 + break + fi + done + if [[ ${flag} -eq 1 ]]; then + break + fi + done + if [[ ${flag} -eq 0 ]]; then + for i; do + read -r -d '' -a arr <<<"${i}" + msg=" " + for j in "${arr[@]}"; do + msg+=" ${j} and" + done + msg="${msg:0: -4} for ${desc}" + elog "${msg}" + done + fi +} + +fi diff --git a/eclass/out-of-source.eclass b/eclass/out-of-source.eclass new file mode 100644 index 0000000..bbac555 --- /dev/null +++ b/eclass/out-of-source.eclass @@ -0,0 +1,125 @@ +# Copyright 1999-2018 Gentoo Foundation +# Distributed under the terms of the GNU General Public License v2 + +# @ECLASS: out-of-source.eclass +# @MAINTAINER: +# Michał Górny <mgorny@gentoo.org> +# @SUPPORTED_EAPIS: 6 7 +# @BLURB: convenient wrapper to build autotools packages out-of-source +# @DESCRIPTION: +# This eclass provides a minimalistic wrapper interface to easily +# build autotools (and alike) packages out-of-source. It is meant +# to resemble the interface used by multilib-minimal without actually +# requiring the package to be multilib. +# +# For the simplest ebuilds, it is enough to inherit the eclass +# and the new phase functions will automatically build the package +# out-of-source. If you need to redefine one of the default phases +# src_configure() through src_install(), you need to define +# the matching sub-phases: my_src_configure(), my_src_compile(), +# my_src_test() and/or my_src_install(). Those sub-phase functions +# will be run inside the build directory. Additionally, +# my_src_install_all() is provided to perform doc-install and other +# common tasks that are done in source directory. +# +# Example use: +# @CODE +# inherit out-of-source +# +# my_src_configure() { +# econf \ +# --disable-static +# } +# @CODE + +case ${EAPI} in + 6|7);; + *) die "EAPI ${EAPI:-0} unsupported (too old)";; +esac + +EXPORT_FUNCTIONS src_configure src_compile src_test src_install + +if [[ ! ${_OUT_OF_SOURCE_ECLASS} ]]; then + +# @FUNCTION: out-of-source_src_configure +# @DESCRIPTION: +# The default src_configure() implementation establishes a BUILD_DIR, +# sets ECONF_SOURCE to the current directory (usually S), and runs +# my_src_configure() (or the default) inside it. +out-of-source_src_configure() { + debug-print-function ${FUNCNAME} "$@" + + # set some BUILD_DIR if we don't have one yet + : "${BUILD_DIR:=${WORKDIR}/${P}_build}" + local ECONF_SOURCE=${PWD} + + mkdir -p "${BUILD_DIR}" || die + pushd "${BUILD_DIR}" >/dev/null || die + if declare -f my_src_configure >/dev/null ; then + my_src_configure + else + default_src_configure + fi + popd >/dev/null || die +} + +# @FUNCTION: out-of-source_src_compile +# @DESCRIPTION: +# The default src_compile() implementation runs my_src_compile() +# (or the default) inside the build directory. +out-of-source_src_compile() { + debug-print-function ${FUNCNAME} "$@" + + pushd "${BUILD_DIR}" >/dev/null || die + if declare -f my_src_compile >/dev/null ; then + my_src_compile + else + default_src_compile + fi + popd >/dev/null || die +} + +# @FUNCTION: out-of-source_src_test +# @DESCRIPTION: +# The default src_test() implementation runs my_src_test() +# (or the default) inside the build directory. +out-of-source_src_test() { + debug-print-function ${FUNCNAME} "$@" + + pushd "${BUILD_DIR}" >/dev/null || die + if declare -f my_src_test >/dev/null ; then + my_src_test + else + default_src_test + fi + popd >/dev/null || die +} + +# @FUNCTION: out-of-source_src_install +# @DESCRIPTION: +# The default src_install() implementation runs my_src_install() +# (or the 'make install' part of the default) inside the build directory, +# followed by a call to my_src_install_all() (or 'einstalldocs' part +# of the default) in the original working directory. +out-of-source_src_install() { + debug-print-function ${FUNCNAME} "$@" + + pushd "${BUILD_DIR}" >/dev/null || die + if declare -f my_src_install >/dev/null ; then + my_src_install + else + if [[ -f Makefile || -f GNUmakefile || -f makefile ]] ; then + emake DESTDIR="${D}" install + fi + fi + popd >/dev/null || die + + if declare -f my_src_install_all >/dev/null ; then + my_src_install_all + else + einstalldocs + fi +} + +_OUT_OF_SOURCE_ECLASS=1 +fi diff --git a/eclass/pam.eclass b/eclass/pam.eclass new file mode 100644 index 0000000..c9de612 --- /dev/null +++ b/eclass/pam.eclass @@ -0,0 +1,213 @@ +# Copyright 1999-2021 Gentoo Authors +# Distributed under the terms of the GNU General Public License v2 + +# @ECLASS: pam.eclass +# @MAINTAINER: +# Mikle Kolyada <zlogene@gentoo.org> +# @AUTHOR: +# Diego Pettenò <flameeyes@gentoo.org> +# @BLURB: Handles pam related tasks +# @DESCRIPTION: +# This eclass contains functions to install pamd configuration files and +# pam modules. + +if [[ -z ${_PAM_ECLASS} ]]; then +_PAM_ECLASS=1 + +inherit flag-o-matic + +# @FUNCTION: dopamd +# @USAGE: <file> [more files] +# @DESCRIPTION: +# Install pam auth config file in /etc/pam.d +dopamd() { + [[ -z $1 ]] && die "dopamd requires at least one argument" + + if has pam ${IUSE} && ! use pam; then + return 0; + fi + + ( # dont want to pollute calling env + insinto /etc/pam.d + insopts -m 0644 + doins "$@" + ) || die "failed to install $@" + cleanpamd "$@" +} + +# @FUNCTION: newpamd +# @USAGE: <old name> <new name> +# @DESCRIPTION: +# Install pam file <old name> as <new name> in /etc/pam.d +newpamd() { + [[ $# -ne 2 ]] && die "newpamd requires two arguments" + + if has pam ${IUSE} && ! use pam; then + return 0; + fi + + ( # dont want to pollute calling env + insinto /etc/pam.d + insopts -m 0644 + newins "$1" "$2" + ) || die "failed to install $1 as $2" + cleanpamd $2 +} + +# @FUNCTION: dopamsecurity +# @USAGE: <section> <file> [more files] +# @DESCRIPTION: +# Installs the config files in /etc/security/<section>/ +dopamsecurity() { + [[ $# -lt 2 ]] && die "dopamsecurity requires at least two arguments" + + if has pam ${IUSE} && ! use pam; then + return 0 + fi + + ( # dont want to pollute calling env + insinto /etc/security/$1 + insopts -m 0644 + doins "${@:2}" + ) || die "failed to install ${@:2}" +} + +# @FUNCTION: newpamsecurity +# @USAGE: <section> <old name> <new name> +# @DESCRIPTION: +# Installs the config file <old name> as <new name> in /etc/security/<section>/ +newpamsecurity() { + [[ $# -ne 3 ]] && die "newpamsecurity requires three arguments" + + if has pam ${IUSE} && ! use pam; then + return 0; + fi + + ( # dont want to pollute calling env + insinto /etc/security/$1 + insopts -m 0644 + newins "$2" "$3" + ) || die "failed to install $2 as $3" +} + +# @FUNCTION: getpam_mod_dir +# @DESCRIPTION: +# Returns the pam modules' directory for current implementation +getpam_mod_dir() { + if has_version sys-libs/pam; then + PAM_MOD_DIR=/$(get_libdir)/security + else + # Unable to find PAM implementation... defaulting + PAM_MOD_DIR=/$(get_libdir)/security + fi + + echo ${PAM_MOD_DIR} +} + +# @FUNCTION: pammod_hide_symbols +# @DESCRIPTION: +# Hide all non-PAM-used symbols from the module; this function creates a +# simple ld version script that hides all the symbols that are not +# necessary for PAM to load the module, then uses append-flags to make +# sure that it gets used. +pammod_hide_symbols() { + cat - > "${T}"/pam-eclass-pam_symbols.ver <<EOF +{ + global: pam_sm_*; + local: *; +}; +EOF + + append-ldflags -Wl,--version-script="${T}"/pam-eclass-pam_symbols.ver +} + +# @FUNCTION: dopammod +# @USAGE: <file> [more files] +# @DESCRIPTION: +# Install pam module file in the pam modules' dir for current implementation +dopammod() { + [[ -z $1 ]] && die "dopammod requires at least one argument" + + if has pam ${IUSE} && ! use pam; then + return 0; + fi + + exeinto $(getpam_mod_dir) + doexe "$@" || die "failed to install $@" +} + +# @FUNCTION: newpammod +# @USAGE: <old name> <new name> +# @DESCRIPTION: +# Install pam module file <old name> as <new name> in the pam +# modules' dir for current implementation +newpammod() { + [[ $# -ne 2 ]] && die "newpammod requires two arguements" + + if has pam ${IUSE} && ! use pam; then + return 0; + fi + + exeinto $(getpam_mod_dir) + newexe "$1" "$2" || die "failed to install $1 as $2" +} + +# @FUNCTION: pamd_mimic_system +# @USAGE: <pamd file> [auth levels] +# @DESCRIPTION: +# This function creates a pamd file which mimics system-auth file +# for the given levels in the /etc/pam.d directory. +pamd_mimic_system() { + [[ $# -lt 2 ]] && die "pamd_mimic_system requires at least two argments" + pamd_mimic system-auth "$@" +} + +# @FUNCTION: pamd_mimic +# @USAGE: <stack> <pamd file> [auth levels] +# @DESCRIPTION: +# This function creates a pamd file which mimics the given stack +# for the given levels in the /etc/pam.d directory. +pamd_mimic() { + [[ $# -lt 3 ]] && die "pamd_mimic requires at least three argments" + + if has pam ${IUSE} && ! use pam; then + return 0; + fi + + dodir /etc/pam.d + pamdfile=${D}/etc/pam.d/$2 + echo -e "# File autogenerated by pamd_mimic in pam eclass\n\n" >> \ + $pamdfile + + originalstack=$1 + authlevels="auth account password session" + + mimic="\tsubstack\t\t${originalstack}" + + shift; shift + + while [[ -n $1 ]]; do + has $1 ${authlevels} || die "unknown level type" + + echo -e "$1${mimic}" >> ${pamdfile} + + shift + done +} + +# @FUNCTION: cleanpamd +# @USAGE: <pamd file> +# @DESCRIPTION: +# Cleans a pam.d file from modules that might not be present on the system +# where it's going to be installed +cleanpamd() { + while [[ -n $1 ]]; do + if ! has_version sys-libs/pam; then + sed -i -e '/pam_shells\|pam_console/s:^:#:' "${D}/etc/pam.d/$1" + fi + + shift + done +} + +fi diff --git a/eclass/pax-utils.eclass b/eclass/pax-utils.eclass new file mode 100644 index 0000000..1e109c8 --- /dev/null +++ b/eclass/pax-utils.eclass @@ -0,0 +1,190 @@ +# Copyright 1999-2019 Gentoo Authors +# Distributed under the terms of the GNU General Public License v2 + +# @ECLASS: pax-utils.eclass +# @MAINTAINER: +# The Gentoo Linux Hardened Team <hardened@gentoo.org> +# @AUTHOR: +# Author: Kevin F. Quinn <kevquinn@gentoo.org> +# Author: Anthony G. Basile <blueness@gentoo.org> +# @BLURB: functions to provide PaX markings for hardened kernels +# @DESCRIPTION: +# +# This eclass provides support for manipulating PaX markings on ELF binaries, +# whether the system is using legacy PT_PAX markings or the newer XATTR_PAX. +# The eclass wraps the use of paxctl-ng, paxctl, set/getattr and scanelf utilities, +# deciding which to use depending on what's installed on the build host, and +# whether we're working with PT_PAX, XATTR_PAX or both. +# Legacy PT_PAX markings no longer supported. +# +# To control what markings are made, set PAX_MARKINGS in /etc/portage/make.conf +# to contain either "PT", "XT" or "none". The default is none + +if [[ -z ${_PAX_UTILS_ECLASS} ]]; then +_PAX_UTILS_ECLASS=1 + +# @ECLASS-VARIABLE: PAX_MARKINGS +# @DESCRIPTION: +# Control which markings are made: +# PT = PT_PAX markings, XT = XATTR_PAX markings +# Default to none markings. +PAX_MARKINGS=${PAX_MARKINGS:="none"} + +# @FUNCTION: pax-mark +# @USAGE: <flags> <ELF files> +# @RETURN: Shell true if we succeed, shell false otherwise +# @DESCRIPTION: +# Marks <ELF files> with provided PaX <flags> +# +# Flags are passed directly to the utilities unchanged. +# +# @CODE +# p: disable PAGEEXEC P: enable PAGEEXEC +# e: disable EMUTRAMP E: enable EMUTRAMP +# m: disable MPROTECT M: enable MPROTECT +# r: disable RANDMMAP R: enable RANDMMAP +# s: disable SEGMEXEC S: enable SEGMEXEC +# @CODE +# +# Default flags are 'PeMRS', which are the most restrictive settings. Refer +# to https://pax.grsecurity.net/ for details on what these flags are all about. +# +# Please confirm any relaxation of restrictions with the Gentoo Hardened team. +# Either ask on the gentoo-hardened mailing list, or CC/assign +# hardened@gentoo.org on the bug report. +pax-mark() { + local f # loop over paxables + local flags # pax flags + local ret=0 # overall return code of this function + + # Only the actual PaX flags and z are accepted + # 1. The leading '-' is optional + # 2. -C -c only make sense for paxctl, but are unnecessary + # because we progressively do -q -qc -qC + # 3. z is allowed for the default + + flags="${1//[!zPpEeMmRrSs]}" + [[ "${flags}" ]] || return 0 + shift + + # z = default. For XATTR_PAX, the default is no xattr field at all + local dodefault="" + [[ "${flags//[!z]}" ]] && dodefault="yes" + + if has PT ${PAX_MARKINGS}; then + # Uncomment to list all files to be marked + # _pax_list_files einfo "$@" + for f in "$@"; do + + # First try paxctl + if type -p paxctl >/dev/null; then + einfo "PT_PAX marking -${flags} ${f} with paxctl" + # We try modifying the existing PT_PAX_FLAGS header. + paxctl -q${flags} "${f}" >/dev/null 2>&1 && continue + # We no longer try to create/convert a PT_PAX_FLAGS header, bug #590422 + # paxctl -qC${flags} "${f}" >/dev/null 2>&1 && continue + # paxctl -qc${flags} "${f}" >/dev/null 2>&1 && continue + fi + + # Next try paxctl-ng -> this will not create/convert any program headers. + if type -p paxctl-ng >/dev/null && paxctl-ng -L ; then + einfo "PT_PAX marking -${flags} ${f} with paxctl-ng" + flags="${flags//z}" + [[ ${dodefault} == "yes" ]] && paxctl-ng -L -z "${f}" >/dev/null 2>&1 + [[ "${flags}" ]] || continue + paxctl-ng -L -${flags} "${f}" >/dev/null 2>&1 && continue + fi + + # Finally fall back on scanelf. + if type -p scanelf >/dev/null && [[ ${PAX_MARKINGS} != "none" ]]; then + einfo "PT_PAX marking -${flags} ${f} with scanelf" + scanelf -Xxz ${flags} "$f" >/dev/null 2>&1 + # We failed to set PT_PAX flags. + elif [[ ${PAX_MARKINGS} != "none" ]]; then + elog "Failed to set PT_PAX markings -${flags} ${f}." + ret=1 + fi + done + fi + + if has XT ${PAX_MARKINGS}; then + # Uncomment to list all files to be marked + # _pax_list_files einfo "$@" + flags="${flags//z}" + for f in "$@"; do + + # First try paxctl-ng. + if type -p paxctl-ng >/dev/null && paxctl-ng -l ; then + einfo "XATTR_PAX marking -${flags} ${f} with paxctl-ng" + [[ ${dodefault} == "yes" ]] && paxctl-ng -d "${f}" >/dev/null 2>&1 + [[ "${flags}" ]] || continue + paxctl-ng -l -${flags} "${f}" >/dev/null 2>&1 && continue + fi + + # Next try setfattr. + if type -p setfattr >/dev/null; then + [[ "${flags//[!Ee]}" ]] || flags+="e" # bug 447150 + einfo "XATTR_PAX marking -${flags} ${f} with setfattr" + [[ ${dodefault} == "yes" ]] && setfattr -x "user.pax.flags" "${f}" >/dev/null 2>&1 + setfattr -n "user.pax.flags" -v "${flags}" "${f}" >/dev/null 2>&1 && continue + fi + + # We failed to set XATTR_PAX flags. + if [[ ${PAX_MARKINGS} != "none" ]]; then + elog "Failed to set XATTR_PAX markings -${flags} ${f}." + ret=1 + fi + done + fi + + # [[ ${ret} == 1 ]] && elog "Executables may be killed by PaX kernels." + + return ${ret} +} + +# @FUNCTION: list-paxables +# @USAGE: <files> +# @RETURN: Subset of <files> which are ELF executables or shared objects +# @DESCRIPTION: +# Print to stdout all of the <files> that are suitable to have PaX flag +# markings, i.e., filter out the ELF executables or shared objects from a list +# of files. This is useful for passing wild-card lists to pax-mark, although +# in general it is preferable for ebuilds to list precisely which ELFS are to +# be marked. Often not all the ELF installed by a package need remarking. +# @EXAMPLE: +# pax-mark -m $(list-paxables ${S}/{,usr/}bin/*) +list-paxables() { + file "$@" 2> /dev/null | grep -E 'ELF.*(executable|shared object)' | sed -e 's/: .*$//' +} + +# @FUNCTION: host-is-pax +# @RETURN: Shell true if the build process is PaX enabled, shell false otherwise +# @DESCRIPTION: +# This is intended for use where the build process must be modified conditionally +# depending on whether the host is PaX enabled or not. It is not indented to +# determine whether the final binaries need PaX markings. Note: if procfs is +# not mounted on /proc, this returns shell false (e.g. Gentoo/FreeBSD). +host-is-pax() { + grep -qs ^PaX: /proc/self/status +} + + +# INTERNAL FUNCTIONS +# ------------------ +# +# These functions are for use internally by the eclass - do not use +# them elsewhere as they are not supported (i.e. they may be removed +# or their function may change arbitrarily). + +# Display a list of things, one per line, indented a bit, using the +# display command in $1. +_pax_list_files() { + local f cmd + cmd=$1 + shift + for f in "$@"; do + ${cmd} " ${f}" + done +} + +fi diff --git a/eclass/perl-functions.eclass b/eclass/perl-functions.eclass new file mode 100644 index 0000000..e6168a0 --- /dev/null +++ b/eclass/perl-functions.eclass @@ -0,0 +1,588 @@ +# Copyright 1999-2019 Gentoo Authors +# Distributed under the terms of the GNU General Public License v2 + +# @ECLASS: perl-functions.eclass +# @MAINTAINER: +# perl@gentoo.org +# @AUTHOR: +# Seemant Kulleen <seemant@gentoo.org> +# Andreas K. Huettel <dilfridge@gentoo.org> +# Kent Fredric <kentnl@gentoo.org> +# @SUPPORTED_EAPIS: 5 6 7 +# @BLURB: helper functions eclass for perl modules +# @DESCRIPTION: +# The perl-functions eclass is designed to allow easier installation of perl +# modules, and their incorporation into the Gentoo Linux system. +# It provides helper functions, no phases or variable manipulation in +# global scope. + +[[ ${CATEGORY} == "perl-core" ]] && inherit alternatives + +case "${EAPI:-0}" in + 5|6|7) + ;; + *) + die "EAPI=${EAPI} is not supported by perl-functions.eclass" + ;; +esac + +perlinfo_done=false + +# @FUNCTION: perl_set_version +# @DESCRIPTION: +# Extract version information and installation paths from the current Perl +# interpreter. +# +# This sets the following variables: PERL_VERSION, SITE_ARCH, SITE_LIB, +# ARCH_LIB, VENDOR_LIB, VENDOR_ARCH +# +# This function used to be called perlinfo as well. +# +# Example: +# @CODE +# perl_set_version +# echo $PERL_VERSION +# @CODE +perl_set_version() { + debug-print-function $FUNCNAME "$@" + debug-print "$FUNCNAME: perlinfo_done=${perlinfo_done}" + ${perlinfo_done} && return 0 + perlinfo_done=true + + local f version install{{site,vendor}{arch,lib},archlib} + eval "$(perl -V:{version,install{{site,vendor}{arch,lib},archlib}} )" + PERL_VERSION=${version} + SITE_ARCH=${installsitearch} + SITE_LIB=${installsitelib} + ARCH_LIB=${installarchlib} + VENDOR_LIB=${installvendorlib} + VENDOR_ARCH=${installvendorarch} +} + +# @FUNCTION: perl_delete_localpod +# @DESCRIPTION: +# Remove stray perllocal.pod files in the temporary install directory D. +# +# This function used to be called fixlocalpod as well. +perl_delete_localpod() { + debug-print-function $FUNCNAME "$@" + + find "${D}" -type f -name perllocal.pod -delete + find "${D}" -depth -mindepth 1 -type d -empty -delete +} + +# @FUNCTION: perl_fix_osx_extra +# @DESCRIPTION: +# Look through ${S} for AppleDouble encoded files and get rid of them. +perl_fix_osx_extra() { + debug-print-function $FUNCNAME "$@" + + local f + find "${S}" -type f -name "._*" -print0 | while read -rd '' f ; do + einfo "Removing AppleDouble encoded Macintosh file: ${f#${S}/}" + rm -f "${f}" + f=${f#${S}/} + grep -q "${f}" "${S}"/MANIFEST && \ + elog "AppleDouble encoded Macintosh file in MANIFEST: ${f#${S}/}" + done +} + +# @FUNCTION: perl_delete_module_manpages +# @DESCRIPTION: +# Bump off manpages installed by the current module such as *.3pm files as well +# as empty directories. +perl_delete_module_manpages() { + debug-print-function $FUNCNAME "$@" + + if [[ -d "${ED}"/usr/share/man ]] ; then + find "${ED}"/usr/share/man -type f -name "*.3pm" -delete + find "${ED}"/usr/share/man -depth -type d -empty -delete + fi +} + +# @FUNCTION: perl_delete_packlist +# @DESCRIPTION: +# Look through ${D} for .packlist files, empty .bs files and empty directories, +# and get rid of items found. +perl_delete_packlist() { + debug-print-function $FUNCNAME "$@" + perl_set_version + if [[ -d ${D}/${VENDOR_ARCH} ]] ; then + find "${D}/${VENDOR_ARCH}" -type f -a -name .packlist -delete + perl_delete_emptybsdir + fi +} + +# @FUNCTION: perl_delete_emptybsdir +# @DESCRIPTION: +# Look through ${D} for empty .bs files and empty directories, +# and get rid of items found. +perl_delete_emptybsdir() { + debug-print-function $FUNCNAME "$@" + perl_set_version + if [[ -d ${D}/${VENDOR_ARCH} ]] ; then + find "${D}/${VENDOR_ARCH}" -type f \ + -a -name '*.bs' -a -empty -delete + find "${D}" -depth -mindepth 1 -type d -empty -delete + fi +} + +# @FUNCTION: perl_fix_packlist +# @DESCRIPTION: +# Look through ${D} for .packlist text files containing the temporary installation +# folder (i.e. ${D}). If the pattern is found, silently replace it with `/'. +# Remove duplicate entries; then validate all entries in the packlist against ${D} +# and prune entries that do not correspond to installed files. +perl_fix_packlist() { + debug-print-function $FUNCNAME "$@" + + local packlist_temp="${T}/.gentoo_packlist_temp" + find "${D}" -type f -name '.packlist' -print0 | while read -rd '' f ; do + if file "${f}" | grep -q -i " text" ; then + einfo "Fixing packlist file /${f#${D}}" + + # remove the temporary build dir path + sed -i -e "s:${D%/}/:/:g" "${f}" + + # remove duplicate entries + sort -u "${f}" > "${packlist_temp}" + mv "${packlist_temp}" "${f}" + + # remove files that dont exist + cat "${f}" | while read -r entry; do + if [ ! -e "${D}/${entry}" ]; then + einfo "Pruning surplus packlist entry ${entry}" + grep -v -x -F "${entry}" "${f}" > "${packlist_temp}" + mv "${packlist_temp}" "${f}" + fi + done + fi + done +} + +# @FUNCTION: perl_remove_temppath +# @DESCRIPTION: +# Look through ${D} for text files containing the temporary installation +# folder (i.e. ${D}). If the pattern is found, replace it with `/' and warn. +perl_remove_temppath() { + debug-print-function $FUNCNAME "$@" + + find "${D}" -type f -not -name '*.so' -print0 | while read -rd '' f ; do + if file "${f}" | grep -q -i " text" ; then + grep -q "${D}" "${f}" && ewarn "QA: File contains a temporary path ${f}" + sed -i -e "s:${D%/}/:/:g" "${f}" + fi + done +} + +# @FUNCTION: perl_rm_files +# @USAGE: <list of files> +# @DESCRIPTION: +# Remove certain files from a Perl release and remove them from the MANIFEST +# while we're there. +# +# Most useful in src_prepare for nuking bad tests, and is highly recommended +# for any tests like 'pod.t', 'pod-coverage.t' or 'kwalitee.t', as what they +# test is completely irrelevant to end users, and frequently fail simply +# because the authors of Test::Pod... changed their recommendations, and thus +# failures are only useful feedback to Authors, not users. +# +# Removing from MANIFEST also avoids needless log messages warning +# users about files "missing from their kit". +# +# Example: +# @CODE +# src_test() { +# perl_rm_files t/pod{,-coverage}.t +# perl-module_src_test +# } +# @CODE +perl_rm_files() { + debug-print-function $FUNCNAME "$@" + local skipfile="${T}/.gentoo_makefile_skip" + local manifile="${S}/MANIFEST" + local manitemp="${T}/.gentoo_manifest_temp" + oldifs="$IFS" + IFS="\n" + for filename in "$@"; do + einfo "Removing un-needed ${filename}"; + # Remove the file + rm -f "${S}/${filename}" + [[ -e "${manifile}" ]] && echo "${filename}" >> "${skipfile}" + done + if [[ -e "${manifile}" && -e "${skipfile}" ]]; then + einfo "Fixing Manifest" + grep -v -F -f "${skipfile}" "${manifile}" > "${manitemp}" + mv -f -- "${manitemp}" "${manifile}" + rm -- "${skipfile}"; + fi + IFS="$oldifs" +} + +# @FUNCTION: perl_link_duallife_scripts +# @DESCRIPTION: +# Moves files and generates symlinks so dual-life packages installing scripts do not +# lead to file collisions. Mainly for use in pkg_postinst and pkg_postrm, and makes +# only sense for perl-core packages. +perl_link_duallife_scripts() { + debug-print-function $FUNCNAME "$@" + if [[ ${CATEGORY} != perl-core ]] || ! has_version ">=dev-lang/perl-5.8.8-r8" ; then + return 0 + fi + + local i ff + if has "${EBUILD_PHASE:-none}" "postinst" "postrm" ; then + for i in "${DUALLIFESCRIPTS[@]}" ; do + alternatives_auto_makesym "/${i}" "/${i}-[0-9]*" + done + for i in "${DUALLIFEMAN[@]}" ; do + ff=`echo "${EROOT}"/${i%.1}-${PV}-${P}.1*` + ff=${ff##*.1} + alternatives_auto_makesym "/${i}${ff}" "/${i%.1}-[0-9]*" + done + else + pushd "${ED}" > /dev/null + for i in $(find usr/bin -maxdepth 1 -type f 2>/dev/null) ; do + mv ${i}{,-${PV}-${P}} || die + #DUALLIFESCRIPTS[${#DUALLIFESCRIPTS[*]}]=${i##*/} + DUALLIFESCRIPTS[${#DUALLIFESCRIPTS[*]}]=${i} + done + for i in $(find usr/share/man/man1 -maxdepth 1 -type f 2>/dev/null) ; do + mv ${i} ${i%.1}-${PV}-${P}.1 || die + DUALLIFEMAN[${#DUALLIFEMAN[*]}]=${i} + done + popd > /dev/null + fi +} + +# @FUNCTION: perl_check_env +# @DESCRIPTION: +# Checks a blacklist of known-suspect ENV values that can be accidentally set by users +# doing personal perl work, which may accidentally leak into portage and break the +# system perl installaton. +# Dies if any of the suspect fields are found, and tell the user what needs to be unset. +# There's a workaround, but you'll have to read the code for it. +perl_check_env() { + local errored value; + + for i in PERL_MM_OPT PERL5LIB PERL5OPT PERL_MB_OPT PERL_CORE PERLPREFIX; do + # Next unless match + [ -v $i ] || continue; + + # Warn only once, and warn only when one of the bad values are set. + # record failure here. + if [ ${errored:-0} == 0 ]; then + if [ -n "${I_KNOW_WHAT_I_AM_DOING}" ]; then + elog "perl-module.eclass: Suspicious environment values found."; + else + eerror "perl-module.eclass: Suspicious environment values found."; + fi + fi + errored=1 + + # Read ENV Value + value=${!i}; + + # Print ENV name/value pair + if [ -n "${I_KNOW_WHAT_I_AM_DOING}" ]; then + elog " $i=\"$value\""; + else + eerror " $i=\"$value\""; + fi + done + + # Return if there were no failures + [ ${errored:-0} == 0 ] && return; + + # Return if user knows what they're doing + if [ -n "${I_KNOW_WHAT_I_AM_DOING}" ]; then + elog "Continuing anyway, seems you know what you're doing." + return + fi + + eerror "Your environment settings may lead to undefined behavior and/or build failures." + die "Please fix your environment ( ~/.bashrc, package.env, ... ), see above for details." +} + +# @FUNCTION: perl_doexamples +# @USAGE: <list of files or globs> +# @DESCRIPTION: +# Install example files ready-to-run. +# Is called under certain circumstances in perl-module.eclass src_install +# (see the documentation there). +# +# Example: +# @CODE +# src_install() { +# perl-module_src_install +# use examples && perl_doexamples "eg/*" +# } +# @CODE +perl_doexamples() { + debug-print-function $FUNCNAME "$@" + + einfo "Installing examples into /usr/share/doc/${PF}/examples" + + # no compression since we want ready-to-run scripts + docompress -x /usr/share/doc/${PF}/examples + + docinto examples/ + # Lack of quoting here is important in order to support glob expansion + # in DIST_EXAMPLES=( ), which is defined before source extraction occurs + dodoc -r $@ + + # is there a way to undo "docinto" ? +} + +# @FUNCTION: perl_has_module +# @USAGE: <module name> +# @RETURN: 0 if available, non-zero otherwise +# @DESCRIPTION: +# Query the installed system Perl to see if a given module is installed. +# This does **not** load the module in question, only anticipates if it *might* load. +# +# This is primarily for the purposes of dependency weakening so that conditional +# behaviour can be triggered without adding dependencies to portage which would confuse +# a dependency resolver. +# +# returns 'true' if the module is available, returns error if the module is not available +# +# Example: +# @CODE +# perl_has_module "Test::Tester" && echo "Test::Tester installed" +# @CODE + +perl_has_module() { + debug-print-function $FUNCNAME "$@" + + [[ $# -gt 0 ]] || die "${FUNCNAME}: No module name provided" + [[ $# -lt 2 ]] || die "${FUNCNAME}: Too many parameters ($#)" + + perl -we 'my $mn = $ARGV[0]; + $mn =~ s{(::|\x{27})}{/}g; + for(@INC){ + next if ref $_; + exit 0 if -r $_ . q[/] . $mn . q[.pm] + } + exit 1' "$@"; +} + +# @FUNCTION: perl_has_module_version +# @USAGE: <module name> <minimum upstream version> +# @RETURN: 0 if satisfied, non-zero otherwise +# @DESCRIPTION: +# Query the installed system Perl to see if a given module is installed +# and is at least a given version. +# +# This requires more caution to use than perl_has_module as it requires +# loading the module in question to determine version compatibility, +# which can be SLOW, and can have side effects (ie: compilation fails in +# require due to some dependency, resulting in a "Fail") +# +# Also take care to note the module version is a *minimum*, *must* be +# written in upstream versions format and should be a a legal upstream version +# +# returns a true exit code if the module is both available and is at least +# the specified version +# +# Example: +# @CODE +# perl_has_module_version "Test::Tester" "0.017" \ +# && echo "Test::Tester 0.017 or greater installed" +# @CODE +perl_has_module_version() { + debug-print-function $FUNCNAME "$@" + + [[ $# -gt 0 ]] || die "${FUNCNAME}: No module name provided" + [[ $# -gt 1 ]] || die "${FUNCNAME}: No module version provided" + [[ $# -lt 3 ]] || die "${FUNCNAME}: Too many parameters ($#)" + + perl -we 'my $mn = $ARGV[0]; + $mn =~ s{(::|\x{27})}{/}g; + exit ( eval { + require qq[${mn}.pm]; + $ARGV[0]->VERSION($ARGV[1]); + 1 + } ? 0 : 1 )' "$@" +} + +# @FUNCTION: perl_get_module_version +# @USAGE: <module name> +# @RETURN: 0 if module available, non-zero if error +# @DESCRIPTION: +# Query the installed system perl to report the version of the installed +# module. +# +# Note this should be strictly for diagnostic purposes to the end user, +# and may be of selective use in pkg_info to enhance +# emerge --info reports. +# +# Anything that does version comparisons **must not** use the return value +# from this function +# +# Also note that this **must** at least attempt load the module in +# question as part of its operation, and is subsequently prone to SLOWness. +# +# Return codes return error in both compilation-failure and not-installed cases. +# +# Example: +# @CODE +# MODVER=$(perl_get_module_version "Test::Simple") \ +# || die "Test::Simple not installed: $MODVER" +# @CODE + +perl_get_module_version() { + debug-print-function $FUNCNAME "$@" + + [[ $# -gt 0 ]] || die "${FUNCNAME}: No module name provided" + [[ $# -lt 2 ]] || die "${FUNCNAME}: Too many parameters ($#)" + + if ! perl_has_module "$@" ; then + echo "(Not Installed)"; + return 1; + fi + + # Todo: What do we do if require fails? spew to stderr + # or stay silent? + + perl -we 'my $mn = $ARGV[0]; + $mn =~ s{(::|\x{27})}{/}g; + local $@; + eval { require qq[${mn}.pm]; 1 } or do { + print q[(Compilation failed in require)]; + exit 1; + }; + my $stash = \%{ $ARGV[0] . q[::] }; + if ( not exists $stash->{VERSION} ) { + print q[(No VERSION property)]; + exit 0; + } + if ( not defined ${$stash->{VERSION}} ) { + print q[(undef)]; + exit 0; + } + print ${$stash->{VERSION}}; + exit 0; ' "$@" +} + +# @FUNCTION: perl_get_raw_vendorlib +# @DESCRIPTION: +# Convenience function to optimise for a common case without double-handling +# variables everywhere. +# +# Note: Will include EPREFIX where relevant +# +# Example: +# @CODE +# my_raw_vendorlib="$(perl_get_raw_vendorlib)" +# @CODE + +perl_get_raw_vendorlib() { + debug-print-function $FUNCNAME "$@" + + [[ $# -lt 1 ]] || die "${FUNCNAME}: Too many parameters ($#)" + + perl -MConfig \ + -e'exists $Config{$ARGV[0]} || die qq{No such Config key "$ARGV[0]"}; + print $Config{$ARGV[0]}; + exit 0' -- "installvendorlib" || die "Can't extract installvendorlib from Perl Configuration" +} + +# @FUNCTION: perl_get_vendorlib +# @DESCRIPTION: +# Convenience helper for returning Perls' vendor install root +# without EPREFIXing. +# +# Example: +# @CODE +# my_vendorlib="$(perl_get_vendorlib)" +# @CODE + +perl_get_vendorlib() { + debug-print-function $FUNCNAME "$@" + + [[ $# -lt 1 ]] || die "${FUNCNAME}: Too many parameters ($#)" + + # Requires perl 5.14 for /r attribute of s/// + # Just in case somebody out there is stuck in a time warp: upgrade perl first + perl -M5.014 -MConfig \ + -e'exists $Config{$ARGV[0]} || die qq{No such Config key "$ARGV[0]"}; + print $Config{$ARGV[0]} =~ s{\A\Q$ARGV[1]\E}{}r; + exit 0' -- "installvendorlib" "$EPREFIX" || die "Can't extract installvendorlib from Perl Configuration" +} + +# @FUNCTION: perl_domodule +# @USAGE: [-C <target>] [-r] <files> +# @DESCRIPTION: +# Installs files in paths where they can be found in the default +# Perl runtime. +# +# Note: Should only be used in src_install or pkg_preinst +# anywhere else will do the wrong thing or die. +# +# The contents of the <files> list are copied into Perls Vendor library path +# as follows: +# @CODE +# # install perl/File.pm as Samba::File +# pushd perl/ +# perl_domodule -C Samba File.pm +# +# # install perl/ recursively under VENDORLIB/Samba/ +# pushd perl/ +# perl_domodule -C Samba -r . +# @CODE +# +# @CODE +# options: +# -C Target/Name +# The subdirectory relative to the Perl VENDOR_LIB +# to install into. +# +# defaults to "" +# -r +# Install directories recursively ( see doins ) +# files: +# list of .pm files to install to VENDORLIB +# @CODE + +perl_domodule() { + local target_prefix="" + local files=() + local doins_opts=() + + local recursive="false" + local target + local file + + while [[ $# -gt 0 ]] ; do + case $1 in + -C|--target-prefix) + [[ -z "${2}" || "${2:0:1}" == "-" ]] && die "${FUNCNAME}: -C|--target-prefix expects an argument, got \"$2\"!" + target_prefix="${2}"; + shift 2;; + -r) + recursive="true" + shift;; + *) + [[ -z "${1}" || "${1:0:1}" == "-" ]] && die "${FUNCNAME}: Unknown argument \"${1}\"!" + files+=( "${1}" ) + shift 1;; + esac + done + + if [[ "true" == $recursive ]]; then + doins_opts+=( "-r" ) + fi + for file in "${files[@]}"; do + [[ -e "${file}" ]] || die "$FUNCNAME: Argument \"${file}\" is not an existing file" + [[ "false" == ${recursive} && -d "${file}" ]] && die "$FUNCNAME: Argument \"${file}\" is a directory ( needs -r parameter )" + done + + target="$(perl_get_vendorlib)" + + # Extend target if target_prefix is set + [[ -z "${target_prefix}" ]] || target="${target%/}/${target_prefix#/}" + + insinto "/${target#/}" + doins "${doins_opts[@]}" "${files[@]}" +} diff --git a/eclass/perl-module.eclass b/eclass/perl-module.eclass new file mode 100644 index 0000000..7a839bc --- /dev/null +++ b/eclass/perl-module.eclass @@ -0,0 +1,506 @@ +# Copyright 1999-2019 Gentoo Authors +# Distributed under the terms of the GNU General Public License v2 + +# @ECLASS: perl-module.eclass +# @MAINTAINER: +# perl@gentoo.org +# @AUTHOR: +# Seemant Kulleen <seemant@gentoo.org> +# Andreas K. Hüttel <dilfridge@gentoo.org> +# @SUPPORTED_EAPIS: 5 6 7 +# @BLURB: eclass for installing Perl module distributions +# @DESCRIPTION: +# The perl-module eclass is designed to allow easier installation of Perl +# module distributions, and their incorporation into the Gentoo Linux system. +# All exported functions from perl-functions.eclass (inherited here) +# explicitly also belong to the interface of perl-module.eclass. +# If your package does not use any Perl-specific build system (as, e.g., +# ExtUtils::MakeMaker or Module::Build), we recommend to use perl-functions.eclass +# instead. + +case ${EAPI:-0} in + 5) + inherit eutils multiprocessing unpacker perl-functions + PERL_EXPF="src_unpack src_prepare src_configure src_compile src_test src_install" + ;; + 6|7) + inherit multiprocessing perl-functions + PERL_EXPF="src_prepare src_configure src_compile src_test src_install" + ;; + *) + die "EAPI=${EAPI} is not supported by perl-module.eclass" + ;; +esac + +# @ECLASS-VARIABLE: GENTOO_DEPEND_ON_PERL +# @DEFAULT_UNSET +# @DESCRIPTION: +# This variable controls whether a runtime and build time dependency on +# dev-lang/perl is automatically added by the eclass. It defaults to yes. +# Set to no to disable, set to noslotop to add a perl dependency without +# slot operator (EAPI=6). All packages installing into the vendor_perl +# path must use yes here. + +case ${EAPI:-0} in + 5) + [[ ${CATEGORY} == perl-core ]] && \ + PERL_EXPF+=" pkg_postinst pkg_postrm" + + case "${GENTOO_DEPEND_ON_PERL:-yes}" in + yes) + case "${GENTOO_DEPEND_ON_PERL_SUBSLOT:-yes}" in + yes) + DEPEND="dev-lang/perl:=[-build(-)]" + ;; + *) + DEPEND="dev-lang/perl[-build(-)]" + ;; + esac + RDEPEND="${DEPEND}" + ;; + esac + + case "${PERL_EXPORT_PHASE_FUNCTIONS:-yes}" in + yes) + EXPORT_FUNCTIONS ${PERL_EXPF} + ;; + no) + debug-print "PERL_EXPORT_PHASE_FUNCTIONS=no" + ;; + *) + die "PERL_EXPORT_PHASE_FUNCTIONS=${PERL_EXPORT_PHASE_FUNCTIONS} is not supported by perl-module.eclass" + ;; + esac + ;; + 6) + [[ ${CATEGORY} == perl-core ]] && \ + PERL_EXPF+=" pkg_postinst pkg_postrm" + + case "${GENTOO_DEPEND_ON_PERL:-yes}" in + yes) + DEPEND="dev-lang/perl" + RDEPEND="dev-lang/perl:=" + ;; + noslotop) + DEPEND="dev-lang/perl" + RDEPEND="dev-lang/perl" + ;; + esac + + if [[ "${GENTOO_DEPEND_ON_PERL_SUBSLOT:-yes}" != "yes" ]]; then + eerror "GENTOO_DEPEND_ON_PERL_SUBSLOT=no is banned in EAPI=6 and later. If you don't want a slot operator" + die "set GENTOO_DEPEND_ON_PERL=noslotop instead." + fi + + if [[ "${PERL_EXPORT_PHASE_FUNCTIONS}" ]]; then + eerror "PERL_EXPORT_PHASE_FUNCTIONS is banned in EAPI=6 and later. Use perl-module.eclass if you need" + die "phase functions, perl-functions.eclass if not." + fi + + EXPORT_FUNCTIONS ${PERL_EXPF} + ;; + 7) + [[ ${CATEGORY} == perl-core ]] && \ + PERL_EXPF+=" pkg_postinst pkg_postrm" + + case "${GENTOO_DEPEND_ON_PERL:-yes}" in + yes) + DEPEND="dev-lang/perl" + BDEPEND="dev-lang/perl" + RDEPEND="dev-lang/perl:=" + ;; + noslotop) + DEPEND="dev-lang/perl" + BDEPEND="dev-lang/perl" + RDEPEND="dev-lang/perl" + ;; + esac + + if [[ "${GENTOO_DEPEND_ON_PERL_SUBSLOT:-yes}" != "yes" ]]; then + die "GENTOO_DEPEND_ON_PERL_SUBSLOT=no is banned in EAPI=6 and later." + fi + + if [[ "${PERL_EXPORT_PHASE_FUNCTIONS}" ]]; then + die "PERL_EXPORT_PHASE_FUNCTIONS is banned in EAPI=6 and later." + fi + + EXPORT_FUNCTIONS ${PERL_EXPF} + ;; + *) + die "EAPI=${EAPI:-0} is not supported by perl-module.eclass" + ;; +esac + +LICENSE="${LICENSE:-|| ( Artistic GPL-1+ )}" + +# @ECLASS-VARIABLE: DIST_NAME +# @DEFAULT_UNSET +# @DESCRIPTION: +# (EAPI=6 and later) This variable provides a way to override PN for the calculation of S, +# SRC_URI, and HOMEPAGE. If unset, defaults to PN. + +# @ECLASS-VARIABLE: DIST_VERSION +# @DEFAULT_UNSET +# @DESCRIPTION: +# (EAPI=6 and later) This variable provides a way to override PV for the calculation of S and SRC_URI. +# Use it to provide the non-normalized, upstream version number. If unset, defaults to PV. +# Named MODULE_VERSION in EAPI=5. + +# @ECLASS-VARIABLE: DIST_A_EXT +# @DEFAULT_UNSET +# @DESCRIPTION: +# (EAPI=6 and later) This variable provides a way to override the distfile extension for the calculation of +# SRC_URI. If unset, defaults to tar.gz. Named MODULE_A_EXT in EAPI=5. + +# @ECLASS-VARIABLE: DIST_A +# @DEFAULT_UNSET +# @DESCRIPTION: +# (EAPI=6 and later) This variable provides a way to override the distfile name for the calculation of +# SRC_URI. If unset, defaults to ${DIST_NAME}-${DIST_VERSION}.${DIST_A_EXT} Named MODULE_A in EAPI=5. + +# @ECLASS-VARIABLE: DIST_AUTHOR +# @DEFAULT_UNSET +# @DESCRIPTION: +# (EAPI=6 and later) This variable sets the module author name for the calculation of +# SRC_URI. Named MODULE_AUTHOR in EAPI=5. + +# @ECLASS-VARIABLE: DIST_SECTION +# @DEFAULT_UNSET +# @DESCRIPTION: +# (EAPI=6 and later) This variable sets the module section for the calculation of +# SRC_URI. Only required in rare cases for very special snowflakes. +# Named MODULE_SECTION in EAPI=5. + +# @ECLASS-VARIABLE: DIST_EXAMPLES +# @DEFAULT_UNSET +# @DESCRIPTION: +# (EAPI=6 and later) This Bash array allows passing a list of example files to be installed +# in /usr/share/doc/${PF}/examples. If set before inherit, automatically adds +# a use-flag examples, if not you'll have to add the useflag in your ebuild. +# Examples are installed only if the useflag examples exists and is activated. + + +if [[ ${EAPI:-0} == 5 ]]; then + if [[ -n ${MY_PN} || -n ${MY_PV} || -n ${MODULE_VERSION} ]] ; then + : ${MY_P:=${MY_PN:-${PN}}-${MY_PV:-${MODULE_VERSION:-${PV}}}} + S=${MY_S:-${WORKDIR}/${MY_P}} + fi + MODULE_NAME=${MY_PN:-${PN}} + MODULE_P=${MY_P:-${P}} + + [[ -z "${SRC_URI}" && -z "${MODULE_A}" ]] && \ + MODULE_A="${MODULE_P}.${MODULE_A_EXT:-tar.gz}" + [[ -z "${SRC_URI}" && -n "${MODULE_AUTHOR}" ]] && \ + SRC_URI="mirror://cpan/authors/id/${MODULE_AUTHOR:0:1}/${MODULE_AUTHOR:0:2}/${MODULE_AUTHOR}/${MODULE_SECTION:+${MODULE_SECTION}/}${MODULE_A}" + [[ -z "${HOMEPAGE}" ]] && \ + HOMEPAGE="https://metacpan.org/release/${MODULE_NAME}" + + SRC_TEST="skip" +else + DIST_NAME=${DIST_NAME:-${PN}} + DIST_P=${DIST_NAME}-${DIST_VERSION:-${PV}} + S=${WORKDIR}/${DIST_P} + + [[ -z "${SRC_URI}" && -z "${DIST_A}" ]] && \ + DIST_A="${DIST_P}.${DIST_A_EXT:-tar.gz}" + [[ -z "${SRC_URI}" && -n "${DIST_AUTHOR}" ]] && \ + SRC_URI="mirror://cpan/authors/id/${DIST_AUTHOR:0:1}/${DIST_AUTHOR:0:2}/${DIST_AUTHOR}/${DIST_SECTION:+${DIST_SECTION}/}${DIST_A}" + [[ -z "${HOMEPAGE}" ]] && \ + HOMEPAGE="https://metacpan.org/release/${DIST_NAME}" + + [[ -z "${DIST_EXAMPLES}" ]] || IUSE+=" examples" +fi + +SRC_PREP="no" +PREFER_BUILDPL="yes" + +pm_echovar="" + +# @FUNCTION: perl-module_src_unpack +# @DESCRIPTION: +# Unpack the ebuild tarball(s). +# This function is to be called during the ebuild src_unpack() phase. +perl-module_src_unpack() { + debug-print-function $FUNCNAME "$@" + [[ ${EAPI:-0} == 5 ]] || die "perl-module_src_unpack is banned in EAPI=6 or later" + unpacker_src_unpack +} + +# @FUNCTION: perl-module_src_prepare +# @DESCRIPTION: +# Get the ebuild sources ready. +# This function is to be called during the ebuild src_prepare() phase. +perl-module_src_prepare() { + debug-print-function $FUNCNAME "$@" + + if [[ ${EAPI:-0} == 5 ]] ; then + [[ ${PATCHES[@]} ]] && epatch "${PATCHES[@]}" + debug-print "$FUNCNAME: applying user patches" + epatch_user + else + default + fi + + if [[ ${PERL_RM_FILES[@]} ]]; then + debug-print "$FUNCNAME: stripping unneeded files" + perl_rm_files "${PERL_RM_FILES[@]}" + fi + perl_fix_osx_extra +} + +# @FUNCTION: perl-module_src_configure +# @DESCRIPTION: +# Configure the ebuild sources. +# This function is to be called during the ebuild src_configure() phase. +perl-module_src_configure() { + debug-print-function $FUNCNAME "$@" + + if [[ ${EAPI:-0} == 5 && ${SRC_PREP} == yes ]]; then + return 0 + fi + SRC_PREP="yes" + + perl_check_env + + perl_set_version + + [[ -z ${pm_echovar} ]] && export PERL_MM_USE_DEFAULT=1 + # Disable ExtUtils::AutoInstall from prompting + export PERL_EXTUTILS_AUTOINSTALL="--skipdeps" + + if [[ $(declare -p myconf 2>&-) != "declare -a myconf="* ]]; then + local myconf_local=(${myconf}) + else + local myconf_local=("${myconf[@]}") + fi + + if [[ ( ${PREFER_BUILDPL} == yes || ! -f Makefile.PL ) && -f Build.PL ]] ; then + if grep -q '\(use\|require\)\s*Module::Build::Tiny' Build.PL ; then + einfo "Using Module::Build::Tiny" + if [[ ${DEPEND} != *dev-perl/Module-Build-Tiny* && ${PN} != Module-Build-Tiny ]]; then + eerror "QA Notice: The ebuild uses Module::Build::Tiny but doesn't depend on it." + die " Add dev-perl/Module-Build-Tiny to DEPEND!" + fi + else + einfo "Using Module::Build" + if [[ ${DEPEND} != *virtual/perl-Module-Build* && ${DEPEND} != *dev-perl/Module-Build* && ${PN} != Module-Build ]] ; then + eerror "QA Notice: The ebuild uses Module::Build but doesn't depend on it." + die " Add dev-perl/Module-Build to DEPEND!" + fi + fi + set -- \ + --installdirs=vendor \ + --libdoc= \ + --destdir="${D}" \ + --create_packlist=1 \ + "${myconf_local[@]}" + einfo "perl Build.PL" "$@" + perl Build.PL "$@" <<< "${pm_echovar}" \ + || die "Unable to build!" + elif [[ -f Makefile.PL ]] ; then + einfo "Using ExtUtils::MakeMaker" + set -- \ + PREFIX=${EPREFIX}/usr \ + INSTALLDIRS=vendor \ + INSTALLMAN3DIR='none' \ + DESTDIR="${D}" \ + "${myconf_local[@]}" + einfo "perl Makefile.PL" "$@" + perl Makefile.PL "$@" <<< "${pm_echovar}" \ + || die "Unable to build!" + fi + if [[ ! -f Build.PL && ! -f Makefile.PL ]] ; then + einfo "No Make or Build file detected..." + return + fi +} + +# @FUNCTION: perl-module_src_compile +# @DESCRIPTION: +# Compile the ebuild sources. +# This function is to be called during the ebuild src_compile() phase. +perl-module_src_compile() { + debug-print-function $FUNCNAME "$@" + perl_set_version + + if [[ $(declare -p mymake 2>&-) != "declare -a mymake="* ]]; then + local mymake_local=(${mymake}) + else + local mymake_local=("${mymake[@]}") + fi + + if [[ -f Build ]] ; then + ./Build build \ + || die "Compilation failed" + elif [[ -f Makefile ]] ; then + set -- \ + OTHERLDFLAGS="${LDFLAGS}" \ + "${mymake_local[@]}" + einfo "emake" "$@" + emake "$@" \ + || die "Compilation failed" +# OPTIMIZE="${CFLAGS}" \ + fi +} + +# @ECLASS-VARIABLE: DIST_TEST +# @DEFAULT_UNSET +# @DESCRIPTION: +# (EAPI=6 and later) Variable that controls if tests are run in the test phase +# at all, and if yes under which conditions. If unset, defaults to "do parallel" +# If neither "do" nor "parallel" is recognized, tests are skipped. +# (In EAPI=5 the variable is called SRC_TEST, defaults to "skip", and +# recognizes fewer options.) +# The following space-separated keywords are recognized: +# do : run tests +# parallel : run tests in parallel +# verbose : increase test verbosity +# network : do not try to disable network tests + +# @ECLASS-VARIABLE: DIST_TEST_OVERRIDE +# @DEFAULT_UNSET +# @DESCRIPTION: +# (EAPI=6 and later) Variable that controls if tests are run in the test phase +# at all, and if yes under which conditions. It is intended for use in +# make.conf or the environment by ebuild authors during testing, and +# accepts the same values as DIST_TEST. If set, it overrides DIST_TEST +# completely. DO NOT USE THIS IN EBUILDS! + +# @FUNCTION: perl-module_src-test +# @DESCRIPTION: +# This code attempts to work out your threadingness and runs tests +# according to the settings of DIST_TEST using Test::Harness. +perl-module_src_test() { + debug-print-function $FUNCNAME "$@" + local my_test_control + local my_test_verbose + + if [[ ${EAPI:-0} == 5 ]] ; then + my_test_control=${SRC_TEST} + my_test_verbose=${TEST_VERBOSE:-0} + if has 'do' ${my_test_control} || has 'parallel' ${my_test_control} ; then + if has "${my_test_verbose}" 0 && has 'parallel' ${my_test_control} ; then + export HARNESS_OPTIONS=j$(makeopts_jobs) + einfo "Test::Harness Jobs=$(makeopts_jobs)" + fi + else + einfo Skipping tests due to SRC_TEST=${SRC_TEST} + return 0 + fi + else + [[ -n "${DIST_TEST_OVERRIDE}" ]] && ewarn DIST_TEST_OVERRIDE is set to ${DIST_TEST_OVERRIDE} + my_test_control=${DIST_TEST_OVERRIDE:-${DIST_TEST:-do parallel}} + + if ! has 'do' ${my_test_control} && ! has 'parallel' ${my_test_control} ; then + einfo Skipping tests due to DIST_TEST=${my_test_control} + return 0 + fi + + if has verbose ${my_test_control} ; then + my_test_verbose=1 + else + my_test_verbose=0 + fi + + if has parallel ${my_test_control} ; then + export HARNESS_OPTIONS=j$(makeopts_jobs) + einfo "Test::Harness Jobs=$(makeopts_jobs)" + fi + + # this might sometimes work... + if ! has network ${my_test_control} ; then + export NO_NETWORK_TESTING=1 + fi + fi + + perl_set_version + if [[ -f Build ]] ; then + ./Build test verbose=${my_test_verbose} || die "test failed" + elif [[ -f Makefile ]] ; then + emake test TEST_VERBOSE=${my_test_verbose} || die "test failed" + fi +} + +# @FUNCTION: perl-module_src_install +# @DESCRIPTION: +# Install a Perl ebuild. +# This function is to be called during the ebuild src_install() phase. +perl-module_src_install() { + debug-print-function $FUNCNAME "$@" + + perl_set_version + + local f + + if [[ -f Build ]]; then + mytargets="${mytargets:-install}" + mbparams="${mbparams:---pure}" + einfo "./Build ${mytargets} ${mbparams}" + ./Build ${mytargets} ${mbparams} \ + || die "./Build ${mytargets} ${mbparams} failed" + elif [[ -f Makefile ]]; then + case "${CATEGORY}" in + dev-perl|perl-core) mytargets="pure_install" ;; + *) mytargets="install" ;; + esac + if [[ $(declare -p myinst 2>&-) != "declare -a myinst="* ]]; then + local myinst_local=(${myinst}) + else + local myinst_local=("${myinst[@]}") + fi + emake "${myinst_local[@]}" ${mytargets} \ + || die "emake ${myinst_local[@]} ${mytargets} failed" + fi + + perl_delete_module_manpages + perl_delete_localpod + if [[ ${EAPI:-0} == 5 ]] ; then + perl_delete_packlist + else + perl_fix_packlist + perl_delete_emptybsdir + fi + perl_remove_temppath + + for f in Change* CHANGES README* TODO FAQ ${mydoc}; do + [[ -s ${f} ]] && dodoc ${f} + done + + if [[ ${EAPI:-0} != 5 ]] ; then + if in_iuse examples && use examples ; then + [[ ${#DIST_EXAMPLES[@]} -eq 0 ]] || perl_doexamples "${DIST_EXAMPLES[@]}" + fi + fi + + perl_link_duallife_scripts +} + +# @FUNCTION: perl-module_pkg_postinst +# @DESCRIPTION: +# This function is to be called during the pkg_postinst() phase. It only does +# useful things for the perl-core category, where it handles the file renaming and symbolic +# links that prevent file collisions for dual-life packages installing scripts. +# In any other category it immediately exits. +perl-module_pkg_postinst() { + debug-print-function $FUNCNAME "$@" + if [[ ${CATEGORY} != perl-core ]] ; then + eerror "perl-module.eclass: You are calling perl-module_pkg_postinst outside the perl-core category." + die " This does not do anything; the call can be removed." + fi + perl_link_duallife_scripts +} + +# @FUNCTION: perl-module_pkg_postrm +# @DESCRIPTION: +# This function is to be called during the pkg_postrm() phase. It only does +# useful things for the perl-core category, where it handles the file renaming and symbolic +# links that prevent file collisions for dual-life packages installing scripts. +# In any other category it immediately exits. +perl-module_pkg_postrm() { + debug-print-function $FUNCNAME "$@" + if [[ ${CATEGORY} != perl-core ]] ; then + eerror "perl-module.eclass: You are calling perl-module_pkg_postrm outside the perl-core category." + die " This does not do anything; the call can be removed." + fi + perl_link_duallife_scripts +} diff --git a/eclass/php-ext-pecl-r3.eclass b/eclass/php-ext-pecl-r3.eclass new file mode 100644 index 0000000..8df60a3 --- /dev/null +++ b/eclass/php-ext-pecl-r3.eclass @@ -0,0 +1,85 @@ +# Copyright 1999-2016 Gentoo Foundation +# Distributed under the terms of the GNU General Public License v2 + +# @ECLASS: php-ext-pecl-r3.eclass +# @MAINTAINER: +# Gentoo PHP team <php-bugs@gentoo.org> +# @BLURB: A uniform way to install PECL extensions +# @DESCRIPTION: +# This eclass should be used by all dev-php/pecl-* ebuilds as a uniform +# way of installing PECL extensions. For more information about PECL, +# see https://pecl.php.net/ + +# @ECLASS-VARIABLE: PHP_EXT_PECL_PKG +# @DESCRIPTION: +# Set in ebuild before inheriting this eclass if the tarball name +# differs from ${PN/pecl-/} so that SRC_URI and HOMEPAGE get set +# correctly by the eclass. +# +# Setting this variable manually also affects PHP_EXT_NAME and ${S} +# unless you override those in ebuild. If that is not desired, please +# use PHP_EXT_PECL_FILENAME instead. +[[ -z "${PHP_EXT_PECL_PKG}" ]] && PHP_EXT_PECL_PKG="${PN/pecl-/}" + +# @ECLASS-VARIABLE: PHP_EXT_PECL_FILENAME +# @DEFAULT_UNSET +# @DESCRIPTION: +# Set in ebuild before inheriting this eclass if the tarball name +# differs from "${PN/pecl-/}-${PV}.tgz" so that SRC_URI gets set +# correctly by the eclass. +# +# Unlike PHP_EXT_PECL_PKG, setting this variable does not affect +# HOMEPAGE, PHP_EXT_NAME or ${S}. + + +# Set PHP_EXT_NAME for php-ext-source-r3.eclass. +[[ -z "${PHP_EXT_NAME}" ]] && PHP_EXT_NAME="${PHP_EXT_PECL_PKG}" + +# Try to guess the upstream name of the package/version. We only use +# this variable temporarily before unsetting it. +PHP_EXT_PECL_PKG_V="${PHP_EXT_PECL_PKG}-${PV/_/}" + +# It's important that we determine and set $S before we inherit below. +S="${WORKDIR}/${PHP_EXT_PECL_PKG_V}" + +inherit php-ext-source-r3 + +EXPORT_FUNCTIONS src_install src_test + +if [[ -z "${PHP_EXT_PECL_FILENAME}" ]] ; then + SRC_URI="https://pecl.php.net/get/${PHP_EXT_PECL_PKG_V}.tgz" +else + SRC_URI="https://pecl.php.net/get/${PHP_EXT_PECL_FILENAME}" +fi + +# Don't leave this laying around in the environment. +unset PHP_EXT_PECL_PKG_V + +HOMEPAGE="https://pecl.php.net/${PHP_EXT_PECL_PKG}" + + +# @FUNCTION: php-ext-pecl-r3_src_install +# @DESCRIPTION: +# Install a standard PECL package. First we delegate to +# php-ext-source-r3.eclass, and then we attempt to install examples +# found in a standard location. +php-ext-pecl-r3_src_install() { + php-ext-source-r3_src_install + + if in_iuse examples && use examples ; then + dodoc -r examples + fi +} + + +# @FUNCTION: php-ext-pecl-r3_src_test +# @DESCRIPTION: +# Run tests delivered with the PECL package. Phpize will have generated +# a run-tests.php file to be executed by `make test`. We only need to +# force the test suite to run in non-interactive mode. +php-ext-pecl-r3_src_test() { + for slot in $(php_get_slots); do + php_init_slot_env "${slot}" + NO_INTERACTION="yes" emake test + done +} diff --git a/eclass/php-ext-source-r3.eclass b/eclass/php-ext-source-r3.eclass new file mode 100644 index 0000000..b2eae22 --- /dev/null +++ b/eclass/php-ext-source-r3.eclass @@ -0,0 +1,461 @@ +# Copyright 1999-2019 Gentoo Authors +# Distributed under the terms of the GNU General Public License v2 + +# @ECLASS: php-ext-source-r3.eclass +# @MAINTAINER: +# Gentoo PHP team <php-bugs@gentoo.org> +# @SUPPORTED_EAPIS: 6 7 +# @BLURB: Compile and install standalone PHP extensions. +# @DESCRIPTION: +# A unified interface for compiling and installing standalone PHP +# extensions. + +inherit autotools + +EXPORT_FUNCTIONS src_prepare src_configure src_compile src_install src_test + +case ${EAPI:-0} in + 6) inherit eapi7-ver ;; + 7) ;; + *) + die "${ECLASS} is not compatible with EAPI=${EAPI}" +esac + +# @ECLASS-VARIABLE: PHP_EXT_NAME +# @REQUIRED +# @DESCRIPTION: +# The extension name. This must be set, otherwise the eclass dies. +# Only automagically set by php-ext-pecl-r3.eclass, so unless your ebuild +# inherits that eclass, you must set this manually before inherit. +[[ -z "${PHP_EXT_NAME}" ]] && \ + die "no extension name specified for the php-ext-source-r3 eclass" + +# @ECLASS-VARIABLE: PHP_EXT_INI +# @DESCRIPTION: +# Controls whether or not to add a line to php.ini for the extension. +# Defaults to "yes" and should not be changed in most cases. +[[ -z "${PHP_EXT_INI}" ]] && PHP_EXT_INI="yes" + +# @ECLASS-VARIABLE: PHP_EXT_ZENDEXT +# @DESCRIPTION: +# Controls whether the extension is a ZendEngine extension or not. +# Defaults to "no". If you don't know what this is, you don't need it. +[[ -z "${PHP_EXT_ZENDEXT}" ]] && PHP_EXT_ZENDEXT="no" + +# @ECLASS-VARIABLE: USE_PHP +# @REQUIRED +# @DESCRIPTION: +# Lists the PHP slots compatible the extension is compatible with. +# Example: +# @CODE +# USE_PHP="php5-6 php7-0" +# @CODE +[[ -z "${USE_PHP}" ]] && \ + die "USE_PHP is not set for the php-ext-source-r3 eclass" + +# @ECLASS-VARIABLE: PHP_EXT_OPTIONAL_USE +# @DEFAULT_UNSET +# @DESCRIPTION: +# If set, all of the dependencies added by this eclass will be +# conditional on USE=${PHP_EXT_OPTIONAL_USE}. This is needed when +# ebuilds have to inherit this eclass unconditionally, but only +# actually use it when (for example) the user has USE=php. + +# @ECLASS-VARIABLE: PHP_EXT_S +# @DESCRIPTION: +# The relative location of the temporary build directory for the PHP +# extension within the source package. This is useful for packages that +# bundle the PHP extension. Defaults to ${S}. +[[ -z "${PHP_EXT_S}" ]] && PHP_EXT_S="${S}" + +# @ECLASS-VARIABLE: PHP_EXT_SAPIS +# @DESCRIPTION: +# A list of SAPIs for which we will install this extension. Formerly +# called PHPSAPILIST. The default includes every SAPI currently used in +# the tree. +[[ -z "${PHP_EXT_SAPIS}" ]] && PHP_EXT_SAPIS="apache2 cli cgi fpm embed phpdbg" + +# @ECLASS-VARIABLE: PHP_INI_NAME +# @DESCRIPTION: +# An optional file name of the saved ini file minis the ini extension +# This allows ordering of extensions such that one is loaded before +# or after another. Defaults to the PHP_EXT_NAME. +# Example (produces 40-foo.ini file): +# @CODE +# PHP_INI_NAME="40-foo" +# @CODE +: ${PHP_INI_NAME:=${PHP_EXT_NAME}} + +# @ECLASS-VARIABLE: PHP_EXT_NEEDED_USE +# @DEFAULT_UNSET +# @DESCRIPTION: +# A list of USE flags to append to each PHP target selected +# as a valid USE-dependency string. The value should be valid +# for all targets so USE defaults may be necessary. +# Example: +# @CODE +# PHP_EXT_NEEDED_USE="mysql?,pdo,pcre(+)" +# @CODE +# +# The PHP dependencies will result in: +# @CODE +# php_targets_php7-0? ( dev-lang/php:7.0[mysql?,pdo,pcre(+)] ) +# @CODE + + +# Make sure at least one target is installed. First, start a USE +# conditional like "php?", but only when PHP_EXT_OPTIONAL_USE is +# non-null. The option group "|| (..." is always started here. +REQUIRED_USE="${PHP_EXT_OPTIONAL_USE}${PHP_EXT_OPTIONAL_USE:+? ( }|| ( " +PHPDEPEND="${PHP_EXT_OPTIONAL_USE}${PHP_EXT_OPTIONAL_USE:+? ( } " +for _php_target in ${USE_PHP}; do + # Now loop through each USE_PHP target and add the corresponding + # dev-lang/php slot to PHPDEPEND. + IUSE+=" php_targets_${_php_target}" + REQUIRED_USE+="php_targets_${_php_target} " + _php_slot=${_php_target/php} + _php_slot=${_php_slot/-/.} + if [[ ${PHP_EXT_NEEDED_USE} ]] ; then + _php_slot+=[${PHP_EXT_NEEDED_USE}] + fi + PHPDEPEND+=" php_targets_${_php_target}? ( dev-lang/php:${_php_slot} )" +done + +# Don't pollute the environment with our loop variables. +unset _php_slot _php_target + +# Finally, end the optional group that we started before the loop. Close +# the USE-conditional if PHP_EXT_OPTIONAL_USE is non-null. +REQUIRED_USE+=") ${PHP_EXT_OPTIONAL_USE:+ )}" +PHPDEPEND+=" ${PHP_EXT_OPTIONAL_USE:+ )}" +TOOLDEPS="sys-devel/m4 sys-devel/libtool" + +RDEPEND="${PHPDEPEND}" + +case ${EAPI:-0} in + 6) DEPEND="${TOOLDEPS} ${PHPDEPEND}" ;; + 7) DEPEND="${PHPDEPEND}" ; BDEPEND="${TOOLDEPS} ${PHPDEPEND}" ;; +esac + +unset PHPDEPEND TOOLDEPS + +# @ECLASS-VARIABLE: PHP_EXT_SKIP_PHPIZE +# @DEFAULT_UNSET +# @DESCRIPTION: +# By default, we run "phpize" in php-ext-source-r3_src_prepare(). Set +# PHP_EXT_SKIP_PHPIZE="yes" in your ebuild if you do not want to run +# phpize (and the autoreconf that becomes necessary afterwards). + +# @ECLASS-VARIABLE: PHP_EXT_SKIP_PATCHES +# @DEFAULT_UNSET +# @DESCRIPTION: +# By default, we run default_src_prepare to PHP_EXT_S. +# Set PHP_EXT_SKIP_PATCHES="yes" in your ebuild if you +# want to apply patches yourself. + +# @FUNCTION: php-ext-source-r3_src_prepare +# @DESCRIPTION: +# Runs the default src_prepare() for PATCHES/eapply_user() support (optional), +# and for each PHP slot, makes a copy of sources, initializes the environment, +# and calls php-ext-source-r3_phpize(). +php-ext-source-r3_src_prepare() { + local slot orig_s="${PHP_EXT_S}" + if [[ "${PHP_EXT_SKIP_PATCHES}" != 'yes' ]] ; then + pushd "${orig_s}" > /dev/null || die + default + popd > /dev/null || die + fi + for slot in $(php_get_slots); do + cp --recursive --preserve "${orig_s}" "${WORKDIR}/${slot}" || \ + die "failed to copy sources from ${orig_s} to ${WORKDIR}/${slot}" + php_init_slot_env "${slot}" + php-ext-source-r3_phpize + done +} + +# @FUNCTION: php-ext-source-r3_phpize +# @DESCRIPTION: +# Subject to PHP_EXT_SKIP_PHPIZE, this function runs phpize and +# autoreconf in a manner that avoids warnings. +php-ext-source-r3_phpize() { + if [[ "${PHP_EXT_SKIP_PHPIZE}" != 'yes' ]] ; then + # Create configure out of config.m4. We use autotools_run_tool + # to avoid some warnings about WANT_AUTOCONF and + # WANT_AUTOMAKE (see bugs #329071 and #549268). + autotools_run_tool "${PHPIZE}" + + # PHP >=7.4 no longer works with eautoreconf + if ver_test $PHP_CURRENTSLOT -ge 7.4 ; then + rm -fr aclocal.m4 autom4te.cache config.cache \ + configure main/php_config.h.in || die + eautoconf --force + eautoheader + else + # Force libtoolize to run and regenerate autotools files (bug + # #220519). + rm aclocal.m4 || die "failed to remove aclocal.m4" + eautoreconf + fi + fi +} + + +# @ECLASS-VARIABLE: PHP_EXT_ECONF_ARGS +# @DEFAULT_UNSET +# @DESCRIPTION: +# Set this in the ebuild to pass additional configure options to +# econf. Formerly called my_conf. Either a string or an array of +# --flag=value parameters is supported. + +# @FUNCTION: php-ext-source-r3_src_configure +# @DESCRIPTION: +# Takes care of standard configure for PHP extensions (modules). +php-ext-source-r3_src_configure() { + # net-snmp creates these, bug #385403. + addpredict /usr/share/snmp/mibs/.index + addpredict /var/lib/net-snmp/mib_indexes + + # Support either a string or an array for PHP_EXT_ECONF_ARGS. + local econf_args + if [[ -n "${PHP_EXT_ECONF_ARGS}" && $(declare -p PHP_EXT_ECONF_ARGS) == "declare -a"* ]]; then + econf_args=( "${PHP_EXT_ECONF_ARGS[@]}" ) + else + econf_args=( ${PHP_EXT_ECONF_ARGS} ) + fi + + local slot + for slot in $(php_get_slots); do + php_init_slot_env "${slot}" + econf --with-php-config="${PHPCONFIG}" "${econf_args[@]}" + done +} + +# @FUNCTION: php-ext-source-r3_src_compile +# @DESCRIPTION: +# Compile a standard standalone PHP extension. +php-ext-source-r3_src_compile() { + # net-snmp creates these, bug #324739. + addpredict /usr/share/snmp/mibs/.index + addpredict /var/lib/net-snmp/mib_indexes + + # shm extension creates a semaphore file, bug #173574. + addpredict /session_mm_cli0.sem + local slot + for slot in $(php_get_slots); do + php_init_slot_env "${slot}" + emake + done +} + +# @FUNCTION: php-ext-source-r3_src_install +# @DESCRIPTION: +# Install a standard standalone PHP extension. Uses einstalldocs() +# to support the DOCS variable/array. +php-ext-source-r3_src_install() { + local slot + for slot in $(php_get_slots); do + php_init_slot_env "${slot}" + + # Strip $EPREFIX from $EXT_DIR before calling doexe (which + # handles EPREFIX itself). Shared libs are +x by convention, + # although nothing seems to depend on that. + exeinto "${EXT_DIR#$EPREFIX}" + doexe "modules/${PHP_EXT_NAME}.so" + + INSTALL_ROOT="${D}" emake install-headers + done + einstalldocs + php-ext-source-r3_createinifiles +} + +# @FUNCTION: php-ext-source-r3_src_test +# @DESCRIPTION: +# Run tests delivered with the standalone PHP extension. Phpize will have generated +# a run-tests.php file to be executed by `make test`. We only need to +# force the test suite to run in non-interactive mode. +php-ext-source-r3_src_test() { + local slot + for slot in $(php_get_slots); do + php_init_slot_env "${slot}" + NO_INTERACTION="yes" emake test + done +} + +# @FUNCTION: php_get_slots +# @DESCRIPTION: +# Get a list of PHP slots contained in both the ebuild's USE_PHP and the +# user's PHP_TARGETS. +php_get_slots() { + local s="" + local slot + for slot in ${USE_PHP}; do + use php_targets_${slot} && s+=" ${slot/-/.}" + done + echo $s +} + +# @FUNCTION: php_init_slot_env +# @USAGE: <slot> +# @DESCRIPTION: +# Takes a slot name, and initializes some global variables to values +# corresponding to that slot. For example, it sets the path to the "php" +# and "phpize" binaries, which will differ for each slot. This function +# is intended to be called while looping through a list of slots +# obtained from php_get_slots(). +# +# Calling this function will change the working directory to the +# temporary build directory for the given slot. +php_init_slot_env() { + local libdir=$(get_libdir) + local slot="${1}" + + PHPPREFIX="${EPREFIX}/usr/${libdir}/${slot}" + PHPIZE="${PHPPREFIX}/bin/phpize" + PHPCONFIG="${PHPPREFIX}/bin/php-config" + PHPCLI="${PHPPREFIX}/bin/php" + PHPCGI="${PHPPREFIX}/bin/php-cgi" + PHP_PKG="$(best_version =dev-lang/php-${1:3}*)" + + EXT_DIR="$(${PHPCONFIG} --extension-dir 2>/dev/null)" + PHP_CURRENTSLOT=${1:3} + + PHP_EXT_S="${WORKDIR}/${slot}" + cd "${PHP_EXT_S}" || die "failed to change directory to ${PHP_EXT_S}" +} + +# @FUNCTION: php_slot_ini_files +# @USAGE: <slot> +# @INTERNAL +# @DESCRIPTION: +# Output a list of relative paths to INI files for the given +# slot. Usually there will be one INI file per SAPI. +php_slot_ini_files() { + local slot_ini_files="" + local x + for x in ${PHP_EXT_SAPIS} ; do + if [[ -f "${EPREFIX}/etc/php/${x}-${1}/php.ini" ]] ; then + slot_ini_files+=" etc/php/${x}-${1}/ext/${PHP_INI_NAME}.ini" + fi + done + + echo "${slot_ini_files}" +} + +# @FUNCTION: php-ext-source-r3_createinifiles +# @DESCRIPTION: +# Builds INI files for every enabled slot and SAPI. +php-ext-source-r3_createinifiles() { + local slot + for slot in $(php_get_slots); do + php_init_slot_env "${slot}" + + local file + for file in $(php_slot_ini_files "${slot}") ; do + if [[ "${PHP_EXT_INI}" = "yes" ]] ; then + # Add the needed lines to the <ext>.ini files + php-ext-source-r3_addextension "${PHP_EXT_NAME}.so" "${file}" + fi + + if [[ -n "${PHP_EXT_INIFILE}" ]] ; then + cat "${FILESDIR}/${PHP_EXT_INIFILE}" >> "${ED}/${file}" \ + || die "failed to append to ${ED}/${file}" + + einfo "Added contents of ${FILESDIR}/${PHP_EXT_INIFILE}" \ + "to ${file}" + fi + inidir="${file/${PHP_INI_NAME}.ini/}" + inidir="${inidir/ext/ext-active}" + dodir "/${inidir}" + dosym "../ext/${PHP_INI_NAME}.ini" "/${file/ext/ext-active}" + done + done + + # A location where PHP code for this extension can be stored, + # independent of the PHP or extension versions. This will be part of + # PHP's include_path, configured in php.ini. For example, pecl-apcu + # installs an "apc.php" file which you are supposed to load with + # + # require('apcu/apc.php'); + # + PHP_EXT_SHARED_DIR="${EPREFIX}/usr/share/php/${PHP_EXT_NAME}" +} + +# @FUNCTION: php-ext-source-r3_addextension +# @USAGE: <extension-path> <ini-file> +# @INTERNAL +# @DESCRIPTION: +# Add a line to an INI file that will enable the given extension. The +# first parameter is the path to the extension (.so) file, and the +# second parameter is the name of the INI file in which it should be +# loaded. This function determines the setting name (either +# "extension=..." or "zend_extension=...") and then calls +# php-ext-source-r3_addtoinifile to do the actual work. +php-ext-source-r3_addextension() { + local ext_type="extension" + local ext_file="${1}" + + if [[ "${PHP_EXT_ZENDEXT}" = "yes" ]] ; then + ext_type="zend_extension" + ext_file="${EXT_DIR}/${1}" # Zend extensions need the path... + fi + + php-ext-source-r3_addtoinifile "${2}" "${ext_type}" "${ext_file}" +} + +# @FUNCTION: php-ext-source-r3_addtoinifile +# @USAGE: <relative-ini-path> <setting-or-section-name> [setting-value] +# @INTERNAL +# @DESCRIPTION: +# Add a setting=value to one INI file. The first argument is the +# relative path to the INI file. The second argument is the setting +# name, and the third argument is its value. +# +# You can also pass "[Section]" as the second parameter, to create a new +# section in the INI file. In that case, the third parameter (which +# would otherwise be the value of the setting) is ignored. +php-ext-source-r3_addtoinifile() { + local inifile="${WORKDIR}/${1}" + local inidir="${inifile%/*}" + + mkdir -p "${inidir}" || die "failed to create INI directory ${inidir}" + + # Are we adding the name of a section? Assume not by default. + local my_added="${2}=${3}" + if [[ ${2:0:1} == "[" ]] ; then + # Ok, it's a section name. + my_added="${2}" + fi + echo "${my_added}" >> "${inifile}" || die "failed to append to ${inifile}" + einfo "Added '${my_added}' to /${1}" + + insinto "/${1%/*}" + doins "${inifile}" +} + +# @FUNCTION: php-ext-source-r3_addtoinifiles +# @USAGE: <setting-or-section-name> [setting-value] [message] +# @DESCRIPTION: +# Add settings to every php.ini file installed by this extension. +# You can also add new [Section]s -- see the example below. +# +# @CODE +# Add some settings for the extension: +# +# php-ext-source-r3_addtoinifiles "zend_optimizer.optimization_level" "15" +# php-ext-source-r3_addtoinifiles "zend_optimizer.enable_loader" "0" +# php-ext-source-r3_addtoinifiles "zend_optimizer.disable_licensing" "0" +# +# Adding values to a section in php.ini file installed by the extension: +# +# php-ext-source-r3_addtoinifiles "[Debugger]" +# php-ext-source-r3_addtoinifiles "debugger.enabled" "on" +# php-ext-source-r3_addtoinifiles "debugger.profiler_enabled" "on" +# @CODE +php-ext-source-r3_addtoinifiles() { + local slot + for slot in $(php_get_slots); do + for file in $(php_slot_ini_files "${slot}") ; do + php-ext-source-r3_addtoinifile "${file}" "${1}" "${2}" + done + done +} diff --git a/eclass/php-pear-r2.eclass b/eclass/php-pear-r2.eclass new file mode 100644 index 0000000..d388749 --- /dev/null +++ b/eclass/php-pear-r2.eclass @@ -0,0 +1,127 @@ +# Copyright 1999-2020 Gentoo Authors +# Distributed under the terms of the GNU General Public License v2 + +# @ECLASS: php-pear-r2.eclass +# @MAINTAINER: +# Gentoo PHP Team <php-bugs@gentoo.org> +# @AUTHOR: +# Author: Brian Evans <grknight@gentoo.org> +# @SUPPORTED_EAPIS: 6 7 +# @BLURB: Provides means for an easy installation of PEAR packages. +# @DESCRIPTION: +# This eclass provides means for an easy installation of PEAR packages. +# For more information on PEAR, see https://pear.php.net/ +# Note that this eclass doesn't handle dependencies of PEAR packages +# on purpose; please use (R)DEPEND to define them correctly! + +EXPORT_FUNCTIONS src_install pkg_postinst pkg_postrm + +case "${EAPI:-0}" in + 6|7) + ;; + *) + die "Unsupported EAPI=${EAPI} for ${ECLASS}" + ;; +esac + +RDEPEND=">=dev-php/pear-1.8.1" + +# @ECLASS-VARIABLE: PHP_PEAR_PKG_NAME +# @DESCRIPTION: +# Set this if the PEAR package name differs from ${PN/PEAR-/} +# (generally shouldn't be the case). +: ${PHP_PEAR_PKG_NAME:=${PN/PEAR-/}} + +# @ECLASS-VARIABLE: PEAR_PV +# @DESCRIPTION: +# Set in ebuild if the ${PV} breaks SRC_URI for alpha/beta/rc versions +: ${PEAR_PV:=${PV}} + +# @ECLASS-VARIABLE: PEAR-P +# @INTERNAL +# @DESCRIPTION: Combines PHP_PEAR_PKG_NAME and PEAR_PV +PEAR_P="${PHP_PEAR_PKG_NAME}-${PEAR_PV}" + +# @ECLASS-VARIABLE: PHP_PEAR_DOMAIN +# @DESCRIPTION: +# Set in ebuild to the domain name of the channel if not pear.php.net +# When the domain is not pear.php.net, setting the SRC_URI is required +: ${PHP_PEAR_DOMAIN:=pear.php.net} + +# @ECLASS-VARIABLE: PHP_PEAR_CHANNEL +# @DEFAULT_UNSET +# @DESCRIPTION: +# Set in ebuild to the path of channel.xml file which is necessary for +# 3rd party pear channels (besides pear.php.net) to be added to PEAR +# Default is unset to do nothing + +# set default SRC_URI for pear.php.net packages +if [[ "${PHP_PEAR_DOMAIN}" == "pear.php.net" ]] ; then + SRC_URI="https://pear.php.net/get/${PEAR_P}.tgz" +fi + +: ${HOMEPAGE:=https://${PHP_PEAR_DOMAIN}/package/${PHP_PEAR_PKG_NAME}} + +S="${WORKDIR}/${PEAR_P}" + +# @FUNCTION: php-pear-r2_install_packagexml +# @DESCRIPTION: +# Copies the package2.xml or package.xml file and, optionally, the channel.xml +# file to a Gentoo-specific location so that pkg_postinst can install the package +# to the local PEAR database +php-pear-r2_install_packagexml() { + insinto /usr/share/php/.packagexml + if [[ -f "${WORKDIR}/package2.xml" ]] ; then + newins "${WORKDIR}/package2.xml" "${PEAR_P}.xml" + elif [[ -f "${WORKDIR}/package.xml" ]] ; then + newins "${WORKDIR}/package.xml" "${PEAR_P}.xml" + fi + + if [[ -f "${PHP_PEAR_CHANNEL}" ]] ; then + newins "${PHP_PEAR_CHANNEL}" "${PEAR_P}-channel.xml" + fi +} + +# @FUNCTION: php-pear-r2_src_install +# @DESCRIPTION: +# Takes care of standard install for PEAR packages. +# Override src_install if the package installs more than "${PHP_PEAR_PKG_NAME}.php" +# or "${PHP_PEAR_PKG_NAME%%_*}/" as a directory +php-pear-r2_src_install() { + insinto /usr/share/php + [[ -f "${PHP_PEAR_PKG_NAME}.php" ]] && doins "${PHP_PEAR_PKG_NAME}.php" + [[ -d "${PHP_PEAR_PKG_NAME%%_*}" ]] && doins -r "${PHP_PEAR_PKG_NAME%%_*}/" + php-pear-r2_install_packagexml + einstalldocs +} + +# @FUNCTION: php-pear-r2_pkg_postinst +# @DESCRIPTION: +# Register package with the local PEAR database. +php-pear-r2_pkg_postinst() { + # Add unknown channels + if [[ -f "${EROOT%/}/usr/share/php/.packagexml/${PEAR_P}-channel.xml" ]] ; then + "${EROOT%/}/usr/bin/peardev" channel-info "${PHP_PEAR_DOMAIN}" &> /dev/null + if [[ $? -ne 0 ]]; then + "${EROOT%/}/usr/bin/peardev" channel-add \ + "${EROOT%/}/usr/share/php/.packagexml/${PEAR_P}-channel.xml" \ + || einfo "Ignore any errors about existing channels" + fi + fi + + # Register the package from the package{,2}.xml file + # It is not critical to complete so only warn on failure + if [[ -f "${EROOT%/}/usr/share/php/.packagexml/${PEAR_P}.xml" ]] ; then + "${EROOT%/}/usr/bin/peardev" install -nrO --force \ + "${EROOT%/}/usr/share/php/.packagexml/${PEAR_P}.xml" 2> /dev/null \ + || ewarn "Failed to insert package into local PEAR database" + fi +} + +# @FUNCTION: php-pear-r2_pkg_postrm +# @DESCRIPTION: +# Deregister package from the local PEAR database +php-pear-r2_pkg_postrm() { + # Uninstall known dependency + "${EROOT%/}/usr/bin/peardev" uninstall -nrO "${PHP_PEAR_DOMAIN}/${PHP_PEAR_PKG_NAME}" +} diff --git a/eclass/portability.eclass b/eclass/portability.eclass new file mode 100644 index 0000000..333a959 --- /dev/null +++ b/eclass/portability.eclass @@ -0,0 +1,155 @@ +# Copyright 1999-2020 Gentoo Authors +# Distributed under the terms of the GNU General Public License v2 + +# @ECLASS: portability.eclass +# @MAINTAINER: +# base-system@gentoo.org +# @AUTHOR: +# Diego Pettenò <flameeyes@gentoo.org> +# @BLURB: This eclass is created to avoid using non-portable GNUisms inside ebuilds + +if [[ -z ${_PORTABILITY_ECLASS} ]]; then +_PORTABILITY_ECLASS=1 + +# @FUNCTION: treecopy +# @USAGE: <orig1> [orig2 orig3 ....] <dest> +# @RETURN: +# @DESCRIPTION: +# mimic cp --parents copy, but working on BSD userland as well +treecopy() { + local dest=${!#} + local files_count=$# + + while (( $# > 1 )); do + local dirstruct=$(dirname "$1") + mkdir -p "${dest}/${dirstruct}" || die + cp -pPR "$1" "${dest}/${dirstruct}" || die + + shift + done +} + +# @FUNCTION: seq +# @USAGE: [min] <max> [step] +# @RETURN: sequence from min to max regardless of seq command being present on system +# @DESCRIPTION: +# compatibility function that mimes seq command if not available +seq() { + # First try `seq` + local p=$(type -P seq) + if [[ -n ${p} ]] ; then + "${p}" "$@" || die + return $? + fi + + local min max step + case $# in + 1) min=1 max=$1 step=1 ;; + 2) min=$1 max=$2 step=1 ;; + 3) min=$1 max=$3 step=$2 ;; + *) die "seq called with wrong number of arguments" ;; + esac + + # Then try `jot` + p=$(type -P jot) + if [[ -n ${p} ]] ; then + local reps + # BSD userland + if [[ ${step} != 0 ]] ; then + reps=$(( (max - min) / step + 1 )) + else + reps=0 + fi + + jot $reps $min $max $step || die + return $? + fi + + # Screw it, do the output ourselves + while :; do + [[ $max -lt $min && $step -gt 0 ]] && break + [[ $min -lt $max && $step -gt 0 ]] && break + echo $min + : $(( min += step )) + done + return 0 +} + +# @FUNCTION: dlopen_lib +# @USAGE: +# @RETURN: linker flag if needed +# @DESCRIPTION: +# Gets the linker flag to link to dlopen() function +dlopen_lib() { + # - Solaris needs nothing + # - Darwin needs nothing + # - *BSD needs nothing + # - Linux needs -ldl (glibc and uclibc) + # - Interix needs -ldl + case "${CHOST}" in + *-linux-gnu*|*-linux-uclibc|*-interix*) + echo "-ldl" + ;; + esac +} + +# @FUNCTION: get_bmake +# @USAGE: +# @RETURN: system version of make +# @DESCRIPTION: +# Gets the name of the BSD-ish make command (bmake from NetBSD) +# +# This will return make (provided by system packages) for BSD userlands, +# or bsdmake for Darwin userlands and pmake for the rest of userlands, +# both of which are provided by sys-devel/pmake package. +# +# Note: the bsdmake for Darwin userland is with compatibility with MacOSX +# default name. +get_bmake() { + if [[ ${CBUILD:-${CHOST}} == *bsd* ]]; then + echo make + elif [[ ${CBUILD:-${CHOST}} == *darwin* ]]; then + echo bsdmake + else + echo bmake + fi +} + +# @FUNCTION: get_mounts +# @USAGE: +# @RETURN: table of mounts in form "point node fs opts" +# @MAINTAINER: +# @DESCRIPTION: +# Portable method of getting mount names and points. +# Returns as "point node fs options" +# Remember to convert 040 back to a space. +get_mounts() { + local point= node= fs= opts= foo= + + # Linux has /proc/mounts which should always exist + if [[ $(uname -s) == "Linux" ]] ; then + while read node point fs opts foo ; do + echo "${point} ${node} ${fs} ${opts}" + done < /proc/mounts + return + fi + + # OK, pray we have a -p option that outputs mounts in fstab format + # using tabs as the seperator. + # Then pray that there are no tabs in the either. + # Currently only FreeBSD supports this and the other BSDs will + # have to be patched. + # Athough the BSD's may support /proc, they do NOT put \040 in place + # of the spaces and we should not force a /proc either. + local IFS=$'\t' + LC_ALL=C mount -p | while read node point fs foo ; do + opts=${fs#* } + fs=${fs%% *} + echo "${point// /\040} ${node// /\040} ${fs%% *} ${opts// /\040}" + done +} + +_dead_portability_user_funcs() { die "if you really need this, please file a bug for base-system@gentoo.org"; } +is-login-disabled() { _dead_portability_user_funcs; } + +fi diff --git a/eclass/postgres-multi.eclass b/eclass/postgres-multi.eclass new file mode 100644 index 0000000..49d5c6a --- /dev/null +++ b/eclass/postgres-multi.eclass @@ -0,0 +1,176 @@ +# Copyright 1999-2020 Gentoo Authors +# Distributed under the terms of the GNU General Public License v2 + +inherit multibuild postgres +EXPORT_FUNCTIONS pkg_setup src_prepare src_compile src_install src_test + + +# @ECLASS: postgres-multi.eclass +# @MAINTAINER: +# PostgreSQL <pgsql-bugs@gentoo.org> +# @AUTHOR: Aaron W. Swenson <titanofold@gentoo.org> +# @SUPPORTED_EAPIS: 5 6 7 +# @BLURB: An eclass to build PostgreSQL-related packages against multiple slots +# @DESCRIPTION: +# postgres-multi enables ebuilds, particularly PostgreSQL extensions, to +# build and install for one or more PostgreSQL slots as specified by +# POSTGRES_TARGETS use flags. + + +case ${EAPI:-0} in + 5|6|7) ;; + *) die "Unsupported EAPI=${EAPI} (unknown) for ${ECLASS}" ;; +esac + + +# @ECLASS-VARIABLE: POSTGRES_COMPAT +# @REQUIRED +# @DESCRIPTION: +# A Bash array containing a list of compatible PostgreSQL slots as +# defined by the developer. Must be declared before inheriting this +# eclass. Example: +#@CODE +#POSTGRES_COMPAT=( 9.2 9.3 9.4 9.5 9.6 10 ) +#POSTGRES_COMPAT=( 9.{2,3} 9.{4..6} 10 ) # Same as previous +#@CODE +if ! declare -p POSTGRES_COMPAT &>/dev/null; then + die 'Required variable POSTGRES_COMPAT not declared.' +fi + +# @ECLASS-VARIABLE: _POSTGRES_INTERSECT_SLOTS +# @INTERNAL +# @DESCRIPTION: +# A Bash array containing the intersect of POSTGRES_TARGETS and +# POSTGRES_COMPAT. +export _POSTGRES_INTERSECT_SLOTS=( ) + +# @FUNCTION: _postgres-multi_multibuild_wrapper +# @USAGE: <command> [arg ...] +# @INTERNAL +# @DESCRIPTION: +# For the given variant, set the values of the PG_SLOT, PG_CONFIG, and +# PKG_CONFIG_PATH environment variables accordingly and replace any +# appearance of @PG_SLOT@ in the command and arguments with value of +# ${PG_SLOT}. +_postgres-multi_multibuild_wrapper() { + debug-print-function ${FUNCNAME} "${@}" + export PG_SLOT=${MULTIBUILD_VARIANT} + export PG_CONFIG=$(which pg_config${MULTIBUILD_VARIANT//./}) + if [[ -n ${PKG_CONFIG_PATH} ]] ; then + PKG_CONFIG_PATH="$(${PG_CONFIG} --libdir)/pkgconfig:${PKG_CONFIG_PATH}" + else + PKG_CONFIG_PATH="$(${PG_CONFIG} --libdir)/pkgconfig" + fi + export PKG_CONFIG_PATH + + $(echo "${@}" | sed "s/@PG_SLOT@/${PG_SLOT}/g") +} + +# @FUNCTION: postgres-multi_foreach +# @USAGE: <command> [arg ...] +# @DESCRIPTION: +# Run the given command in the package's build directory for each +# PostgreSQL slot in the intersect of POSTGRES_TARGETS and +# POSTGRES_COMPAT. The PG_CONFIG and PKG_CONFIG_PATH environment +# variables are updated on each iteration to point to the matching +# pg_config command and pkg-config metadata files, respectively, for the +# current slot. Any appearance of @PG_SLOT@ in the command or arguments +# will be substituted with the slot (e.g., 9.5) of the current +# iteration. +postgres-multi_foreach() { + local MULTIBUILD_VARIANTS=("${_POSTGRES_INTERSECT_SLOTS[@]}") + + multibuild_foreach_variant \ + _postgres-multi_multibuild_wrapper run_in_build_dir ${@} +} + +# @FUNCTION: postgres-multi_forbest +# @USAGE: <command> [arg ...] +# @DESCRIPTION: +# Run the given command in the package's build directory for the highest +# slot in the intersect of POSTGRES_COMPAT and POSTGRES_TARGETS. The +# PG_CONFIG and PKG_CONFIG_PATH environment variables are set to the +# matching pg_config command and pkg-config metadata files, +# respectively. Any appearance of @PG_SLOT@ in the command or arguments +# will be substituted with the matching slot (e.g., 9.5). +postgres-multi_forbest() { + # POSTGRES_COMPAT is reverse sorted once in postgres.eclass so + # element 0 has the highest slot version. + local MULTIBUILD_VARIANTS=("${_POSTGRES_INTERSECT_SLOTS[0]}") + + multibuild_foreach_variant \ + _postgres-multi_multibuild_wrapper run_in_build_dir ${@} +} + +# @FUNCTION: postgres-multi_pkg_setup +# @DESCRIPTION: +# Initialize internal environment variable(s). This is required if +# pkg_setup() is declared in the ebuild. +postgres-multi_pkg_setup() { + local user_slot + + # _POSTGRES_COMPAT is created in postgres.eclass + for user_slot in "${_POSTGRES_COMPAT[@]}"; do + use "postgres_targets_postgres${user_slot/\./_}" && \ + _POSTGRES_INTERSECT_SLOTS+=( "${user_slot}" ) + done + + if [[ "${#_POSTGRES_INTERSECT_SLOTS[@]}" -eq "0" ]]; then + die "One of the postgres_targets_postgresSL_OT use flags must be enabled" + fi + + einfo "Multibuild variants: ${_POSTGRES_INTERSECT_SLOTS[@]}" +} + +# @FUNCTION: postgres-multi_src_prepare +# @DESCRIPTION: +# Calls eapply_user then copies ${S} into a build directory for each +# intersect of POSTGRES_TARGETS and POSTGRES_COMPAT. +postgres-multi_src_prepare() { + if [[ "${#_POSTGRES_INTERSECT_SLOTS[@]}" -eq "0" ]]; then + eerror "Internal array _POSTGRES_INTERSECT_SLOTS is empty." + die "Did you forget to call postgres-multi_pkg_setup?" + fi + + # Check that the slot has been emerged (Should be prevented by + # Portage, but won't be caught by /usr/bin/ebuild) + local slot + for slot in ${_POSTGRES_INTERSECT_SLOTS[@]} ; do + if [[ -z $(which pg_config${slot/.} 2> /dev/null) ]] ; then + eerror + eerror "postgres_targets_postgres${slot/.} use flag is enabled, but hasn't been emerged." + eerror + die "a postgres_targets use flag is enabled, but not emerged" + fi + done + + case ${EAPI:-0} in + 0|1|2|3|4|5) epatch_user ;; + 6|7) eapply_user ;; + esac + + local MULTIBUILD_VARIANT + local MULTIBUILD_VARIANTS=("${_POSTGRES_INTERSECT_SLOTS[@]}") + multibuild_copy_sources +} + +# @FUNCTION: postgres-multi_src_compile +# @DESCRIPTION: +# Runs `emake' in each build directory +postgres-multi_src_compile() { + postgres-multi_foreach emake +} + +# @FUNCTION: postgres-multi_src_install +# @DESCRIPTION: +# Runs `emake install DESTDIR="${D}"' in each build directory. +postgres-multi_src_install() { + postgres-multi_foreach emake install DESTDIR="${D}" +} + +# @FUNCTION: postgres-multi_src_test +# @DESCRIPTION: +# Runs `emake installcheck' in each build directory. +postgres-multi_src_test() { + postgres-multi_foreach emake installcheck +} diff --git a/eclass/postgres.eclass b/eclass/postgres.eclass new file mode 100644 index 0000000..2e2ac85 --- /dev/null +++ b/eclass/postgres.eclass @@ -0,0 +1,185 @@ +# Copyright 1999-2020 Gentoo Authors +# Distributed under the terms of the GNU General Public License v2 + +inherit user +EXPORT_FUNCTIONS pkg_setup + +# @ECLASS: postgres.eclass +# @MAINTAINER: +# PostgreSQL <pgsql-bugs@gentoo.org> +# @AUTHOR: Aaron W. Swenson <titanofold@gentoo.org> +# @SUPPORTED_EAPIS: 5 6 7 +# @BLURB: An eclass for PostgreSQL-related packages +# @DESCRIPTION: +# This eclass provides common utility functions that many +# PostgreSQL-related packages perform, such as checking that the +# currently selected PostgreSQL slot is within a range, adding a system +# user to the postgres system group, and generating dependencies. + + +case ${EAPI:-0} in + 5|6|7) ;; + *) die "Unsupported EAPI=${EAPI} (unknown) for ${ECLASS}" ;; +esac + +# @ECLASS-VARIABLE: _POSTGRES_ALL_VERSIONS +# @INTERNAL +# @DESCRIPTION: +# List of versions to reverse sort POSTGRES_COMPAT slots + +_POSTGRES_ALL_VERSIONS=( 9999 13 12 11 10 9.6 9.5 9.4 9.3 9.2 ) + + + +# @ECLASS-VARIABLE: POSTGRES_COMPAT +# @DEFAULT_UNSET +# @DESCRIPTION: +# A Bash array containing a list of compatible PostgreSQL slots as +# defined by the developer. If declared, must be declared before +# inheriting this eclass. Example: +#@CODE +#POSTGRES_COMPAT=( 9.2 9.3 9.4 9.5 9.6 10 ) +#POSTGRES_COMPAT=( 9.{2,3} 9.{4..6} 10 ) # Same as previous +#@CODE + +# @ECLASS-VARIABLE: POSTGRES_DEP +# @DESCRIPTION: +# An automatically generated dependency string suitable for use in +# DEPEND and RDEPEND declarations. +POSTGRES_DEP="dev-db/postgresql:=" + +# @ECLASS-VARIABLE: POSTGRES_USEDEP +# @DEFAULT_UNSET +# @DESCRIPTION: +# Add the 2-Style and/or 4-Style use dependencies without brackets to be used +# for POSTGRES_DEP. If declared, must be declared before inheriting this eclass. +declare -p POSTGRES_USEDEP &>/dev/null && POSTGRES_DEP+="[${POSTGRES_USEDEP}]" + +# @ECLASS-VARIABLE: POSTGRES_REQ_USE +# @DEFAULT_UNSET +# @DESCRIPTION: +# An automatically generated REQUIRED_USE-compatible string built upon +# POSTGRES_COMPAT. REQUIRED_USE="... ${POSTGRES_REQ_USE}" is only +# required if the package must build against one of the PostgreSQL slots +# declared in POSTGRES_COMPAT. + +# @ECLASS-VARIABLE: _POSTGRES_COMPAT +# @INTERNAL +# @DESCRIPTION: +# Copy of POSTGRES_COMPAT, reverse sorted +_POSTGRES_COMPAT=() + + +if declare -p POSTGRES_COMPAT &> /dev/null ; then + # Reverse sort the given POSTGRES_COMPAT so that the most recent + # slot is preferred over an older slot. + # -- do we care if dependencies are deterministic by USE flags? + for i in ${_POSTGRES_ALL_VERSIONS[@]} ; do + has ${i} ${POSTGRES_COMPAT[@]} && _POSTGRES_COMPAT+=( ${i} ) + done + + POSTGRES_DEP="" + POSTGRES_REQ_USE=" || (" + for slot in "${_POSTGRES_COMPAT[@]}" ; do + POSTGRES_DEP+=" postgres_targets_postgres${slot/\./_}? ( dev-db/postgresql:${slot}=" + declare -p POSTGRES_USEDEP &>/dev/null && \ + POSTGRES_DEP+="[${POSTGRES_USEDEP}]" + POSTGRES_DEP+=" )" + + IUSE+=" postgres_targets_postgres${slot/\./_}" + POSTGRES_REQ_USE+=" postgres_targets_postgres${slot/\./_}" + done + POSTGRES_REQ_USE+=" )" +fi + + +# @FUNCTION: postgres_check_slot +# @DESCRIPTION: +# Verify that the currently selected PostgreSQL slot is set to one of +# the slots defined in POSTGRES_COMPAT. Automatically dies unless a +# POSTGRES_COMPAT slot is selected. Should be called in pkg_pretend(). +postgres_check_slot() { + if ! declare -p POSTGRES_COMPAT &>/dev/null; then + die 'POSTGRES_COMPAT not declared.' + fi + + # Don't die because we can't run postgresql-config during pretend. + [[ "$EBUILD_PHASE" = "pretend" && -z "$(which postgresql-config 2> /dev/null)" ]] \ + && return 0 + + if has $(postgresql-config show 2> /dev/null) "${POSTGRES_COMPAT[@]}"; then + return 0 + else + eerror "PostgreSQL slot must be set to one of: " + eerror " ${POSTGRES_COMPAT[@]}" + die "Incompatible PostgreSQL slot eselected" + fi +} + +# @FUNCTION: postgres_new_user +# @USAGE: [user [(uid|-1) [(shell|-1) [(homedir|-1) [groups]]]]] +# @DESCRIPTION: +# Creates the "postgres" system group and user -- which is separate from +# the database user -- and, optionally, the developer defined user. There +# are no required parameters. +# +# When given a user to create, it'll be created with the next available +# uid, default shell set to /bin/false, default homedir is /dev/null, +# and added to the "postgres" system group. You can use "-1" to skip any +# parameter except user or groups. +postgres_new_user() { + enewgroup postgres 70 + enewuser postgres 70 /bin/bash /var/lib/postgresql postgres + + if [[ $# -gt 0 ]] ; then + if [[ "$1" = "postgres" ]] ; then + ewarn "Username 'postgres' implied, skipping" + else + local groups=$5 + [[ -n "${groups}" ]] && groups+=",postgres" || groups="postgres" + enewuser "$1" "${2:--1}" "${3:--1}" "${4:--1}" "${groups}" + fi + fi +} + +# @FUNCTION: postgres_pkg_setup +# @DESCRIPTION: +# Initialize environment variable(s) according to the best +# installed version of PostgreSQL that is also in POSTGRES_COMPAT. This +# is required if pkg_setup() is declared in the ebuild. +# Exports PG_SLOT, PG_CONFIG, and PKG_CONFIG_PATH. +postgres_pkg_setup() { + debug-print-function ${FUNCNAME} "${@}" + + local compat_slot + local best_slot + for compat_slot in "${_POSTGRES_COMPAT[@]}"; do + if use "postgres_targets_postgres${compat_slot/\./_}"; then + best_slot="${compat_slot}" + break + fi + done + + if [[ -z "${best_slot}" ]]; then + local flags f + for f in "${_POSTGRES_COMPAT[@]}"; do + flags+=" postgres${f/./_}" + done + + eerror "POSTGRES_TARGETS must contain at least one of:" + eerror " ${flags}" + die "No suitable POSTGRES_TARGETS enabled." + fi + + export PG_SLOT=${best_slot} + export PG_CONFIG=$(which pg_config${best_slot//./}) + + local pg_pkg_config_path="$(${PG_CONFIG} --libdir)/pkgconfig" + if [[ -n "${PKG_CONFIG_PATH}" ]]; then + export PKG_CONFIG_PATH="${pg_pkg_config_path}:${PKG_CONFIG_PATH}" + else + export PKG_CONFIG_PATH="${pg_pkg_config_path}" + fi + + elog "PostgreSQL Target: ${best_slot}" +} diff --git a/eclass/prefix.eclass b/eclass/prefix.eclass new file mode 100644 index 0000000..d00c0d7 --- /dev/null +++ b/eclass/prefix.eclass @@ -0,0 +1,138 @@ +# Copyright 1999-2019 Gentoo Authors +# Distributed under the terms of the GNU General Public License v2 + +# @ECLASS: prefix.eclass +# @MAINTAINER: +# Feel free to contact the Prefix team through <prefix@gentoo.org> if +# you have problems, suggestions or questions. +# @BLURB: Eclass to provide Prefix functionality +# @DESCRIPTION: +# Gentoo Prefix allows users to install into a self defined offset +# located somewhere in the filesystem. Prefix ebuilds require +# additional functions and variables which are defined by this eclass. + +# @ECLASS-VARIABLE: EPREFIX +# @DESCRIPTION: +# The offset prefix of a Gentoo Prefix installation. When Gentoo Prefix +# is not used, ${EPREFIX} should be "". Prefix Portage sets EPREFIX, +# hence this eclass has nothing to do here in that case. +# Note that setting EPREFIX in the environment with Prefix Portage sets +# Portage into cross-prefix mode. +if [[ ! ${EPREFIX+set} ]]; then + export EPREFIX='' +fi + + +# @FUNCTION: eprefixify +# @USAGE: <list of to be eprefixified files> +# @DESCRIPTION: +# replaces @GENTOO_PORTAGE_EPREFIX@ with ${EPREFIX} for the given files, +# dies if no arguments are given, a file does not exist, or changing a +# file failed. +eprefixify() { + [[ $# -lt 1 ]] && die "at least one argument required" + + einfo "Adjusting to prefix ${EPREFIX:-/}" + local x + for x in "$@" ; do + if [[ -e ${x} ]] ; then + ebegin " ${x##*/}" + sed -i -e "s|@GENTOO_PORTAGE_EPREFIX@|${EPREFIX}|g" "${x}" + eend $? || die "failed to eprefixify ${x}" + else + die "${x} does not exist" + fi + done + + return 0 +} + +# @FUNCTION: hprefixify +# @USAGE: [ -w <line match> ] [ -e <extended regex> ] [ -q <quotation char> ] <list of files> +# @DESCRIPTION: +# Tries a set of heuristics to prefixify the given files. Dies if no +# arguments are given, a file does not exist, or changing a file failed. +# +# Additional extended regular expression can be passed by -e or +# environment variable PREFIX_EXTRA_REGEX. The default heuristics can +# be constrained to lines that match a sed expression passed by -w or +# environment variable PREFIX_LINE_MATCH. Quotation characters can be +# specified by -q or environment variable PREFIX_QUOTE_CHAR, unless +# EPREFIX is empty. +# +# @EXAMPLE: +# Only prefixify the 30th line, +# hprefixify -w 30 configure +# Only prefixify lines that contain "PATH", +# hprefixify -w "/PATH/" configure +# Also delete all the /opt/gnu search paths, +# hprefixify -e "/\/opt\/gnu/d" configure +# Quote the inserted EPREFIX +# hprefixify -q '"' etc/profile +hprefixify() { + use prefix || return 0 + + local xl=() x + while [[ $# -gt 0 ]]; do + case $1 in + -e) local PREFIX_EXTRA_REGEX="$2" + shift + ;; + -w) local PREFIX_LINE_MATCH="$2" + shift + ;; + -q) local PREFIX_QUOTE_CHAR="${EPREFIX:+$2}" + shift + ;; + *) + xl+=( "$1" ) + ;; + esac + shift + done + local dirs="/(usr|lib(|[onx]?32|n?64)|etc|bin|sbin|var|opt|run)" \ + eprefix="${PREFIX_QUOTE_CHAR}${EPREFIX}${PREFIX_QUOTE_CHAR}" + + [[ ${#xl[@]} -lt 1 ]] && die "at least one file operand is required" + einfo "Adjusting to prefix ${EPREFIX:-/}" + for x in "${xl[@]}" ; do + if [[ -e ${x} ]] ; then + ebegin " ${x##*/}" + sed -r \ + -e "${PREFIX_LINE_MATCH}s,([^[:alnum:]}\)\.])${dirs},\1${eprefix}/\2,g" \ + -e "${PREFIX_LINE_MATCH}s,^${dirs},${eprefix}/\1," \ + -e "${PREFIX_EXTRA_REGEX}" \ + -i "${x}" + eend $? || die "failed to prefixify ${x}" + else + die "${x} does not exist" + fi + done +} + +# @FUNCTION: prefixify_ro +# @USAGE: <file> +# @DESCRIPTION: +# prefixify a read-only file. +# copies the files to ${T}, prefixies it, echos the new file. +# @EXAMPLE: +# doexe "$(prefixify_ro "${FILESDIR}"/fix_libtool_files.sh)" +# epatch "$(prefixify_ro "${FILESDIR}"/${PN}-4.0.2-path.patch)" +prefixify_ro() { + if [[ -e $1 ]] ; then + local f=${1##*/} + cp "$1" "${T}" || die "failed to copy file" + local x="${T}"/${f} + # redirect to stderr because stdout is used to + # return the prefixified file. + if grep -qs @GENTOO_PORTAGE_EPREFIX@ "${x}" ; then + eprefixify "${T}"/${f} 1>&2 + else + hprefixify "${T}"/${f} 1>&2 + fi + echo "${x}" + else + die "$1 does not exist" + fi +} +# vim: tw=72: diff --git a/eclass/preserve-libs.eclass b/eclass/preserve-libs.eclass new file mode 100644 index 0000000..548c641 --- /dev/null +++ b/eclass/preserve-libs.eclass @@ -0,0 +1,74 @@ +# Copyright 1999-2018 Gentoo Foundation +# Distributed under the terms of the GNU General Public License v2 + +# @ECLASS: preserve-libs.eclass +# @MAINTAINER: +# base-system@gentoo.org +# @BLURB: preserve libraries after SONAME changes + +if [[ -z ${_PRESERVE_LIBS_ECLASS} ]]; then +_PRESERVE_LIBS_ECLASS=1 + +# @FUNCTION: preserve_old_lib +# @USAGE: <libs to preserve> [more libs] +# @DESCRIPTION: +# These functions are useful when a lib in your package changes ABI SONAME. +# An example might be from libogg.so.0 to libogg.so.1. Removing libogg.so.0 +# would break packages that link against it. Most people get around this +# by using the portage SLOT mechanism, but that is not always a relevant +# solution, so instead you can call this from pkg_preinst. See also the +# preserve_old_lib_notify function. +preserve_old_lib() { + if [[ ${EBUILD_PHASE} != "preinst" ]] ; then + eerror "preserve_old_lib() must be called from pkg_preinst() only" + die "Invalid preserve_old_lib() usage" + fi + [[ -z $1 ]] && die "Usage: preserve_old_lib <library to preserve> [more libraries to preserve]" + + # let portage worry about it + has preserve-libs ${FEATURES} && return 0 + + has "${EAPI:-0}" 0 1 2 && local ED=${D} EROOT=${ROOT} + + local lib dir + for lib in "$@" ; do + [[ -e ${EROOT}/${lib} ]] || continue + dir=${lib%/*} + dodir ${dir} || die "dodir ${dir} failed" + cp "${EROOT}"/${lib} "${ED}"/${lib} || die "cp ${lib} failed" + touch "${ED}"/${lib} + done +} + +# @FUNCTION: preserve_old_lib_notify +# @USAGE: <libs to notify> [more libs] +# @DESCRIPTION: +# Spit helpful messages about the libraries preserved by preserve_old_lib. +preserve_old_lib_notify() { + if [[ ${EBUILD_PHASE} != "postinst" ]] ; then + eerror "preserve_old_lib_notify() must be called from pkg_postinst() only" + die "Invalid preserve_old_lib_notify() usage" + fi + + # let portage worry about it + has preserve-libs ${FEATURES} && return 0 + + has "${EAPI:-0}" 0 1 2 && local EROOT=${ROOT} + + local lib notice=0 + for lib in "$@" ; do + [[ -e ${EROOT}/${lib} ]] || continue + if [[ ${notice} -eq 0 ]] ; then + notice=1 + ewarn "Old versions of installed libraries were detected on your system." + ewarn "In order to avoid breaking packages that depend on these old libs," + ewarn "the libraries are not being removed. You need to run revdep-rebuild" + ewarn "in order to remove these old dependencies. If you do not have this" + ewarn "helper program, simply emerge the 'gentoolkit' package." + ewarn + fi + ewarn " # revdep-rebuild --library '${lib}' && rm '${lib}'" + done +} + +fi diff --git a/eclass/python-any-r1.eclass b/eclass/python-any-r1.eclass new file mode 100644 index 0000000..313fe6b --- /dev/null +++ b/eclass/python-any-r1.eclass @@ -0,0 +1,396 @@ +# Copyright 1999-2020 Gentoo Authors +# Distributed under the terms of the GNU General Public License v2 + +# @ECLASS: python-any-r1.eclass +# @MAINTAINER: +# Python team <python@gentoo.org> +# @AUTHOR: +# Author: Michał Górny <mgorny@gentoo.org> +# Based on work of: Krzysztof Pawlik <nelchael@gentoo.org> +# @SUPPORTED_EAPIS: 5 6 7 +# @BLURB: An eclass for packages having build-time dependency on Python. +# @DESCRIPTION: +# A minimal eclass for packages which need any Python interpreter +# installed without a need for explicit choice and invariability. +# This usually involves packages requiring Python at build-time +# but having no other relevance to it. +# +# This eclass provides a minimal PYTHON_DEPS variable with a dependency +# string on any of the supported Python implementations. It also exports +# pkg_setup() which finds the best supported implementation and sets it +# as the active one. +# +# Optionally, you can define a python_check_deps() function. It will +# be called by the eclass with EPYTHON set to each matching Python +# implementation and it is expected to check whether the implementation +# fulfills the package requirements. You can use the locally exported +# PYTHON_USEDEP or PYTHON_SINGLE_USEDEP to check USE-dependencies +# of relevant packages. It should return a true value (0) if the Python +# implementation fulfills the requirements, a false value (non-zero) +# otherwise. +# +# Please note that python-any-r1 will always inherit python-utils-r1 +# as well. Thus, all the functions defined there can be used in the +# packages using python-any-r1, and there is no need ever to inherit +# both. +# +# For more information, please see the Python Guide: +# https://dev.gentoo.org/~mgorny/python-guide/ + +case "${EAPI:-0}" in + [0-4]) die "Unsupported EAPI=${EAPI:-0} (too old) for ${ECLASS}" ;; + [5-7]) ;; + *) die "Unsupported EAPI=${EAPI} (unknown) for ${ECLASS}" ;; +esac + +if [[ ! ${_PYTHON_ANY_R1} ]]; then + +if [[ ${_PYTHON_R1} ]]; then + die 'python-any-r1.eclass can not be used with python-r1.eclass.' +elif [[ ${_PYTHON_SINGLE_R1} ]]; then + die 'python-any-r1.eclass can not be used with python-single-r1.eclass.' +fi + +inherit python-utils-r1 + +fi + +EXPORT_FUNCTIONS pkg_setup + +# @ECLASS-VARIABLE: PYTHON_COMPAT +# @REQUIRED +# @DESCRIPTION: +# This variable contains a list of Python implementations the package +# supports. It must be set before the `inherit' call. It has to be +# an array. +# +# Example: +# @CODE +# PYTHON_COMPAT=( python{2_5,2_6,2_7} ) +# @CODE + +# @ECLASS-VARIABLE: PYTHON_COMPAT_OVERRIDE +# @USER_VARIABLE +# @DEFAULT_UNSET +# @DESCRIPTION: +# This variable can be used when working with ebuilds to override +# the in-ebuild PYTHON_COMPAT. It is a string naming the implementation +# which will be used to build the package. It needs to be specified +# in the calling environment, and not in ebuilds. +# +# It should be noted that in order to preserve metadata immutability, +# PYTHON_COMPAT_OVERRIDE does not affect dependencies. The value of +# EPYTHON and eselect-python preferences are ignored. Dependencies need +# to be satisfied manually. +# +# Example: +# @CODE +# PYTHON_COMPAT_OVERRIDE='pypy' emerge -1v dev-python/bar +# @CODE + +# @ECLASS-VARIABLE: PYTHON_REQ_USE +# @DEFAULT_UNSET +# @DESCRIPTION: +# The list of USEflags required to be enabled on the Python +# implementations, formed as a USE-dependency string. It should be valid +# for all implementations in PYTHON_COMPAT, so it may be necessary to +# use USE defaults. +# +# Example: +# @CODE +# PYTHON_REQ_USE="gdbm,ncurses(-)?" +# @CODE +# +# It will cause the Python dependencies to look like: +# @CODE +# || ( dev-lang/python:X.Y[gdbm,ncurses(-)?] ... ) +# @CODE + +# @ECLASS-VARIABLE: PYTHON_DEPS +# @OUTPUT_VARIABLE +# @DESCRIPTION: +# This is an eclass-generated Python dependency string for all +# implementations listed in PYTHON_COMPAT. +# +# Any of the supported interpreters will satisfy the dependency. +# +# Example use: +# @CODE +# DEPEND="${RDEPEND} +# ${PYTHON_DEPS}" +# @CODE +# +# Example value: +# @CODE +# || ( dev-lang/python:2.7[gdbm] +# dev-lang/python:2.6[gdbm] ) +# @CODE + +# @ECLASS-VARIABLE: PYTHON_USEDEP +# @OUTPUT_VARIABLE +# @DESCRIPTION: +# An eclass-generated USE-dependency string for the currently tested +# implementation. It is set locally for python_check_deps() call. +# +# The generated USE-flag list is compatible with packages using +# python-r1 eclass. For python-single-r1 dependencies, +# use PYTHON_SINGLE_USEDEP. +# +# Example use: +# @CODE +# python_check_deps() { +# has_version "dev-python/foo[${PYTHON_USEDEP}]" +# } +# @CODE +# +# Example value: +# @CODE +# python_targets_python3_7(-),-python_single_target_python3_7(-) +# @CODE + +# @ECLASS-VARIABLE: PYTHON_SINGLE_USEDEP +# @OUTPUT_VARIABLE +# @DESCRIPTION: +# An eclass-generated USE-dependency string for the currently tested +# implementation. It is set locally for python_check_deps() call. +# +# The generated USE-flag list is compatible with packages using +# python-single-r1 eclass. For python-r1 dependencies, +# use PYTHON_USEDEP. +# +# Example use: +# @CODE +# python_check_deps() { +# has_version "dev-python/bar[${PYTHON_SINGLE_USEDEP}]" +# } +# @CODE +# +# Example value: +# @CODE +# python_single_target_python3_7(-) +# @CODE + +_python_any_set_globals() { + local usestr deps i PYTHON_PKG_DEP + [[ ${PYTHON_REQ_USE} ]] && usestr="[${PYTHON_REQ_USE}]" + + _PYTHON_ALLOW_PY27=1 \ + _python_set_impls + + for i in "${_PYTHON_SUPPORTED_IMPLS[@]}"; do + _python_export "${i}" PYTHON_PKG_DEP + + # note: need to strip '=' slot operator for || deps + deps="${PYTHON_PKG_DEP/:0=/:0} ${deps}" + done + deps="|| ( ${deps})" + + if [[ ${PYTHON_DEPS+1} ]]; then + if [[ ${PYTHON_DEPS} != "${deps}" ]]; then + eerror "PYTHON_DEPS have changed between inherits (PYTHON_REQ_USE?)!" + eerror "Before: ${PYTHON_DEPS}" + eerror "Now : ${deps}" + die "PYTHON_DEPS integrity check failed" + fi + else + PYTHON_DEPS=${deps} + readonly PYTHON_DEPS + fi + + if [[ ! ${PYTHON_REQUIRED_USE+1} ]]; then + # fake var to catch mistaken usage + PYTHON_REQUIRED_USE='I-DO-NOT-EXIST-IN-PYTHON-ANY-R1' + readonly PYTHON_REQUIRED_USE + fi +} +_python_any_set_globals +unset -f _python_any_set_globals + +if [[ ! ${_PYTHON_ANY_R1} ]]; then + +# @FUNCTION: python_gen_any_dep +# @USAGE: <dependency-block> +# @DESCRIPTION: +# Generate an any-of dependency that enforces a version match between +# the Python interpreter and Python packages. <dependency-block> needs +# to list one or more dependencies with verbatim '${PYTHON_USEDEP}' +# or '${PYTHON_SINGLE_USEDEP}' references (quoted!) that will get +# expanded inside the function. +# +# This should be used along with an appropriate python_check_deps() +# that checks which of the any-of blocks were matched. +# +# Example use: +# @CODE +# DEPEND="$(python_gen_any_dep ' +# dev-python/foo[${PYTHON_SINGLE_USEDEP}] +# || ( dev-python/bar[${PYTHON_USEDEP}] +# dev-python/baz[${PYTHON_USEDEP}] )')" +# +# python_check_deps() { +# has_version "dev-python/foo[${PYTHON_SINGLE_USEDEP}]" \ +# && { has_version "dev-python/bar[${PYTHON_USEDEP}]" \ +# || has_version "dev-python/baz[${PYTHON_USEDEP}]"; } +# } +# @CODE +# +# Example value: +# @CODE +# || ( +# ( +# dev-lang/python:3.7 +# dev-python/foo[python_single_target_python3_7(-)] +# || ( dev-python/bar[python_targets_python3_7(-),-python_single_target_python3_7(-)] +# dev-python/baz[python_targets_python3_7(-),-python_single_target_python3_7(-)] ) +# ) +# ( +# dev-lang/python:3.8 +# dev-python/foo[python_single_target_python3_8(-)] +# || ( dev-python/bar[python_targets_python3_8(-),-python_single_target_python3_8(-)] +# dev-python/baz[python_targets_python3_8(-),-python_single_target_python3_8(-)] ) +# ) +# ) +# @CODE +python_gen_any_dep() { + debug-print-function ${FUNCNAME} "${@}" + + local depstr=${1} + [[ ${depstr} ]] || die "No dependency string provided" + + local i PYTHON_PKG_DEP out= + for i in "${_PYTHON_SUPPORTED_IMPLS[@]}"; do + local PYTHON_USEDEP="python_targets_${i}(-),-python_single_target_${i}(-)" + local PYTHON_SINGLE_USEDEP="python_single_target_${i}(-)" + _python_export "${i}" PYTHON_PKG_DEP + + local i_depstr=${depstr//\$\{PYTHON_USEDEP\}/${PYTHON_USEDEP}} + i_depstr=${i_depstr//\$\{PYTHON_SINGLE_USEDEP\}/${PYTHON_SINGLE_USEDEP}} + # note: need to strip '=' slot operator for || deps + out="( ${PYTHON_PKG_DEP%=} ${i_depstr} ) ${out}" + done + echo "|| ( ${out})" +} + +# @FUNCTION: _python_EPYTHON_supported +# @USAGE: <epython> +# @INTERNAL +# @DESCRIPTION: +# Check whether the specified implementation is supported by package +# (specified in PYTHON_COMPAT). Calls python_check_deps() if declared. +_python_EPYTHON_supported() { + debug-print-function ${FUNCNAME} "${@}" + + local EPYTHON=${1} + local i=${EPYTHON/./_} + + case "${i}" in + python*|jython*|pypy*) + ;; + *) + ewarn "Invalid EPYTHON: ${EPYTHON}" + return 1 + ;; + esac + + if has "${i}" "${_PYTHON_SUPPORTED_IMPLS[@]}"; then + if python_is_installed "${i}"; then + if declare -f python_check_deps >/dev/null; then + local PYTHON_USEDEP="python_targets_${i}(-),-python_single_target_${i}(-)" + local PYTHON_SINGLE_USEDEP="python_single_target_${i}(-)" + python_check_deps + return ${?} + fi + + return 0 + fi + elif ! has "${i}" "${_PYTHON_ALL_IMPLS[@]}"; then + ewarn "Invalid EPYTHON: ${EPYTHON}" + fi + return 1 +} + +# @FUNCTION: python_setup +# @DESCRIPTION: +# Determine what the best installed (and supported) Python +# implementation is, and set the Python build environment up for it. +# +# This function will call python_check_deps() if defined. +python_setup() { + debug-print-function ${FUNCNAME} "${@}" + + # support developer override + if [[ ${PYTHON_COMPAT_OVERRIDE} ]]; then + local impls=( ${PYTHON_COMPAT_OVERRIDE} ) + [[ ${#impls[@]} -eq 1 ]] || die "PYTHON_COMPAT_OVERRIDE must name exactly one implementation for python-any-r1" + + ewarn "WARNING: PYTHON_COMPAT_OVERRIDE in effect. The following Python" + ewarn "implementation will be used:" + ewarn + ewarn " ${PYTHON_COMPAT_OVERRIDE}" + ewarn + ewarn "Dependencies won't be satisfied, and EPYTHON/eselect-python will be ignored." + + _python_export "${impls[0]}" EPYTHON PYTHON + _python_wrapper_setup + einfo "Using ${EPYTHON} to build" + return + fi + + # first, try ${EPYTHON}... maybe it's good enough for us. + if [[ ${EPYTHON} ]]; then + if _python_EPYTHON_supported "${EPYTHON}"; then + _python_export EPYTHON PYTHON + _python_wrapper_setup + einfo "Using ${EPYTHON} to build" + return + fi + fi + + # then, try eselect-python + local variant i + for variant in '' '--python2' '--python3'; do + i=$(eselect python --show ${variant} 2>/dev/null) + + if [[ ! ${i} ]]; then + # no eselect-python? + break + elif _python_EPYTHON_supported "${i}"; then + _python_export "${i}" EPYTHON PYTHON + _python_wrapper_setup + einfo "Using ${EPYTHON} to build" + return + fi + done + + # fallback to best installed impl. + # (reverse iteration over _PYTHON_SUPPORTED_IMPLS) + for (( i = ${#_PYTHON_SUPPORTED_IMPLS[@]} - 1; i >= 0; i-- )); do + _python_export "${_PYTHON_SUPPORTED_IMPLS[i]}" EPYTHON PYTHON + if _python_EPYTHON_supported "${EPYTHON}"; then + _python_wrapper_setup + einfo "Using ${EPYTHON} to build" + return + fi + done + + eerror "No Python implementation found for the build. This is usually" + eerror "a bug in the ebuild. Please report it to bugs.gentoo.org" + eerror "along with the build log." + echo + die "No supported Python implementation installed." +} + +# @FUNCTION: python-any-r1_pkg_setup +# @DESCRIPTION: +# Runs python_setup during from-source installs. +# +# In a binary package installs is a no-op. If you need Python in pkg_* +# phases of a binary package, call python_setup directly. +python-any-r1_pkg_setup() { + debug-print-function ${FUNCNAME} "${@}" + + [[ ${MERGE_TYPE} != binary ]] && python_setup +} + +_PYTHON_ANY_R1=1 +fi diff --git a/eclass/python-r1.eclass b/eclass/python-r1.eclass new file mode 100644 index 0000000..5cae020 --- /dev/null +++ b/eclass/python-r1.eclass @@ -0,0 +1,868 @@ +# Copyright 1999-2020 Gentoo Authors +# Distributed under the terms of the GNU General Public License v2 + +# @ECLASS: python-r1.eclass +# @MAINTAINER: +# Python team <python@gentoo.org> +# @AUTHOR: +# Author: Michał Górny <mgorny@gentoo.org> +# Based on work of: Krzysztof Pawlik <nelchael@gentoo.org> +# @SUPPORTED_EAPIS: 5 6 7 +# @BLURB: A common, simple eclass for Python packages. +# @DESCRIPTION: +# A common eclass providing helper functions to build and install +# packages supporting being installed for multiple Python +# implementations. +# +# This eclass sets correct IUSE. Modification of REQUIRED_USE has to +# be done by the author of the ebuild (but PYTHON_REQUIRED_USE is +# provided for convenience, see below). python-r1 exports PYTHON_DEPS +# and PYTHON_USEDEP so you can create correct dependencies for your +# package easily. It also provides methods to easily run a command for +# each enabled Python implementation and duplicate the sources for them. +# +# Please note that python-r1 will always inherit python-utils-r1 as +# well. Thus, all the functions defined there can be used +# in the packages using python-r1, and there is no need ever to inherit +# both. +# +# For more information, please see the Python Guide: +# https://dev.gentoo.org/~mgorny/python-guide/ + +case "${EAPI:-0}" in + 0|1|2|3|4) + die "Unsupported EAPI=${EAPI:-0} (too old) for ${ECLASS}" + ;; + 5|6|7) + # EAPI=5 is required for sane USE_EXPAND dependencies + ;; + *) + die "Unsupported EAPI=${EAPI} (unknown) for ${ECLASS}" + ;; +esac + +if [[ ! ${_PYTHON_R1} ]]; then + +if [[ ${_PYTHON_SINGLE_R1} ]]; then + die 'python-r1.eclass can not be used with python-single-r1.eclass.' +elif [[ ${_PYTHON_ANY_R1} ]]; then + die 'python-r1.eclass can not be used with python-any-r1.eclass.' +fi + +[[ ${EAPI} == [45] ]] && inherit eutils +inherit multibuild python-utils-r1 + +fi + +# @ECLASS-VARIABLE: PYTHON_COMPAT +# @REQUIRED +# @DESCRIPTION: +# This variable contains a list of Python implementations the package +# supports. It must be set before the `inherit' call. It has to be +# an array. +# +# Example: +# @CODE +# PYTHON_COMPAT=( python2_7 python3_3 python3_4 ) +# @CODE +# +# Please note that you can also use bash brace expansion if you like: +# @CODE +# PYTHON_COMPAT=( python2_7 python3_{3,4} ) +# @CODE + +# @ECLASS-VARIABLE: PYTHON_COMPAT_OVERRIDE +# @USER_VARIABLE +# @DEFAULT_UNSET +# @DESCRIPTION: +# This variable can be used when working with ebuilds to override +# the in-ebuild PYTHON_COMPAT. It is a string listing all +# the implementations which package will be built for. It need be +# specified in the calling environment, and not in ebuilds. +# +# It should be noted that in order to preserve metadata immutability, +# PYTHON_COMPAT_OVERRIDE does not affect IUSE nor dependencies. +# The state of PYTHON_TARGETS is ignored, and all the implementations +# in PYTHON_COMPAT_OVERRIDE are built. Dependencies need to be satisfied +# manually. +# +# Example: +# @CODE +# PYTHON_COMPAT_OVERRIDE='pypy python3_3' emerge -1v dev-python/foo +# @CODE + +# @ECLASS-VARIABLE: PYTHON_REQ_USE +# @DEFAULT_UNSET +# @DESCRIPTION: +# The list of USEflags required to be enabled on the chosen Python +# implementations, formed as a USE-dependency string. It should be valid +# for all implementations in PYTHON_COMPAT, so it may be necessary to +# use USE defaults. +# +# This should be set before calling `inherit'. +# +# Example: +# @CODE +# PYTHON_REQ_USE="gdbm,ncurses(-)?" +# @CODE +# +# It will cause the Python dependencies to look like: +# @CODE +# python_targets_pythonX_Y? ( dev-lang/python:X.Y[gdbm,ncurses(-)?] ) +# @CODE + +# @ECLASS-VARIABLE: PYTHON_DEPS +# @OUTPUT_VARIABLE +# @DESCRIPTION: +# This is an eclass-generated Python dependency string for all +# implementations listed in PYTHON_COMPAT. +# +# Example use: +# @CODE +# RDEPEND="${PYTHON_DEPS} +# dev-foo/mydep" +# DEPEND="${RDEPEND}" +# @CODE +# +# Example value: +# @CODE +# dev-lang/python-exec:= +# python_targets_python2_7? ( dev-lang/python:2.7[gdbm] ) +# python_targets_pypy? ( dev-python/pypy[gdbm] ) +# @CODE + +# @ECLASS-VARIABLE: PYTHON_USEDEP +# @OUTPUT_VARIABLE +# @DESCRIPTION: +# This is an eclass-generated USE-dependency string which can be used to +# depend on another Python package being built for the same Python +# implementations. +# +# The generate USE-flag list is compatible with packages using python-r1 +# and python-distutils-ng eclasses. It must not be used on packages +# using python.eclass. +# +# Example use: +# @CODE +# RDEPEND="dev-python/foo[${PYTHON_USEDEP}]" +# @CODE +# +# Example value: +# @CODE +# python_targets_python2_7(-)?,python_targets_python3_4(-)? +# @CODE + +# @ECLASS-VARIABLE: PYTHON_SINGLE_USEDEP +# @OUTPUT_VARIABLE +# @DESCRIPTION: +# An eclass-generated USE-dependency string for the currently tested +# implementation. It is set locally for python_check_deps() call. +# +# The generated USE-flag list is compatible with packages using +# python-single-r1 eclass. For python-r1 dependencies, +# use PYTHON_USEDEP. +# +# Example use: +# @CODE +# python_check_deps() { +# has_version "dev-python/bar[${PYTHON_SINGLE_USEDEP}]" +# } +# @CODE +# +# Example value: +# @CODE +# python_single_target_python3_7(-) +# @CODE + +# @ECLASS-VARIABLE: PYTHON_REQUIRED_USE +# @OUTPUT_VARIABLE +# @DESCRIPTION: +# This is an eclass-generated required-use expression which ensures at +# least one Python implementation has been enabled. +# +# This expression should be utilized in an ebuild by including it in +# REQUIRED_USE, optionally behind a use flag. +# +# Example use: +# @CODE +# REQUIRED_USE="python? ( ${PYTHON_REQUIRED_USE} )" +# @CODE +# +# Example value: +# @CODE +# || ( python_targets_python2_7 python_targets_python3_4 ) +# @CODE + +_python_set_globals() { + local deps i PYTHON_PKG_DEP + + _python_set_impls + + for i in "${_PYTHON_SUPPORTED_IMPLS[@]}"; do + _python_export "${i}" PYTHON_PKG_DEP + deps+="python_targets_${i}? ( ${PYTHON_PKG_DEP} ) " + done + + local flags=( "${_PYTHON_SUPPORTED_IMPLS[@]/#/python_targets_}" ) + local optflags=${flags[@]/%/(-)?} + + # A nice QA trick here. Since a python-single-r1 package has to have + # at least one PYTHON_SINGLE_TARGET enabled (REQUIRED_USE), + # the following check will always fail on those packages. Therefore, + # it should prevent developers from mistakenly depending on packages + # not supporting multiple Python implementations. + + local flags_st=( "${_PYTHON_SUPPORTED_IMPLS[@]/#/-python_single_target_}" ) + optflags+=,${flags_st[@]/%/(-)} + local requse="|| ( ${flags[*]} )" + local usedep=${optflags// /,} + + # 1) well, python-exec would suffice as an RDEP + # but no point in making this overcomplex, BDEP doesn't hurt anyone + # 2) python-exec should be built with all targets forced anyway + # but if new targets were added, we may need to force a rebuild + deps+=">=dev-lang/python-exec-2:=[${usedep}]" + + if [[ ${PYTHON_DEPS+1} ]]; then + # IUSE is magical, so we can't really check it + # (but we verify PYTHON_COMPAT already) + + if [[ ${PYTHON_DEPS} != "${deps}" ]]; then + eerror "PYTHON_DEPS have changed between inherits (PYTHON_REQ_USE?)!" + eerror "Before: ${PYTHON_DEPS}" + eerror "Now : ${deps}" + die "PYTHON_DEPS integrity check failed" + fi + + # these two are formality -- they depend on PYTHON_COMPAT only + if [[ ${PYTHON_REQUIRED_USE} != ${requse} ]]; then + eerror "PYTHON_REQUIRED_USE have changed between inherits!" + eerror "Before: ${PYTHON_REQUIRED_USE}" + eerror "Now : ${requse}" + die "PYTHON_REQUIRED_USE integrity check failed" + fi + + if [[ ${PYTHON_USEDEP} != "${usedep}" ]]; then + eerror "PYTHON_USEDEP have changed between inherits!" + eerror "Before: ${PYTHON_USEDEP}" + eerror "Now : ${usedep}" + die "PYTHON_USEDEP integrity check failed" + fi + else + IUSE=${flags[*]} + + PYTHON_DEPS=${deps} + PYTHON_REQUIRED_USE=${requse} + PYTHON_USEDEP=${usedep} + readonly PYTHON_DEPS PYTHON_REQUIRED_USE + fi +} +_python_set_globals +unset -f _python_set_globals + +if [[ ! ${_PYTHON_R1} ]]; then + +# @FUNCTION: _python_validate_useflags +# @INTERNAL +# @DESCRIPTION: +# Enforce the proper setting of PYTHON_TARGETS, if PYTHON_COMPAT_OVERRIDE +# is not in effect. If it is, just warn that the flags will be ignored. +_python_validate_useflags() { + debug-print-function ${FUNCNAME} "${@}" + + if [[ ${PYTHON_COMPAT_OVERRIDE} ]]; then + if [[ ! ${_PYTHON_COMPAT_OVERRIDE_WARNED} ]]; then + ewarn "WARNING: PYTHON_COMPAT_OVERRIDE in effect. The following Python" + ewarn "implementations will be enabled:" + ewarn + ewarn " ${PYTHON_COMPAT_OVERRIDE}" + ewarn + ewarn "Dependencies won't be satisfied, and PYTHON_TARGETS will be ignored." + _PYTHON_COMPAT_OVERRIDE_WARNED=1 + fi + # we do not use flags with PCO + return + fi + + local i + + for i in "${_PYTHON_SUPPORTED_IMPLS[@]}"; do + use "python_targets_${i}" && return 0 + done + + eerror "No Python implementation selected for the build. Please add one" + eerror "of the following values to your PYTHON_TARGETS (in make.conf):" + eerror + eerror "${PYTHON_COMPAT[@]}" + echo + die "No supported Python implementation in PYTHON_TARGETS." +} + +# @FUNCTION: _python_gen_usedep +# @USAGE: [<pattern>...] +# @INTERNAL +# @DESCRIPTION: +# Output a USE dependency string for Python implementations which +# are both in PYTHON_COMPAT and match any of the patterns passed +# as parameters to the function. +# +# The patterns can be either fnmatch-style patterns (matched via bash +# == operator against PYTHON_COMPAT values) or '-2' / '-3' to indicate +# appropriately all enabled Python 2/3 implementations (alike +# python_is_python3). Remember to escape or quote the fnmatch patterns +# to prevent accidental shell filename expansion. +# +# This is an internal function used to implement python_gen_cond_dep +# and deprecated python_gen_usedep. +_python_gen_usedep() { + debug-print-function ${FUNCNAME} "${@}" + + local impl matches=() + + _python_verify_patterns "${@}" + for impl in "${_PYTHON_SUPPORTED_IMPLS[@]}"; do + if _python_impl_matches "${impl}" "${@}"; then + matches+=( + "python_targets_${impl}(-)?" + "-python_single_target_${impl}(-)" + ) + fi + done + + [[ ${matches[@]} ]] || die "No supported implementations match python_gen_usedep patterns: ${@}" + + local out=${matches[@]} + echo "${out// /,}" +} + +# @FUNCTION: python_gen_usedep +# @USAGE: <pattern> [...] +# @DESCRIPTION: +# DEPRECATED. Please use python_gen_cond_dep instead. +# +# Output a USE dependency string for Python implementations which +# are both in PYTHON_COMPAT and match any of the patterns passed +# as parameters to the function. +# +# The patterns can be either fnmatch-style patterns (matched via bash +# == operator against PYTHON_COMPAT values) or '-2' / '-3' to indicate +# appropriately all enabled Python 2/3 implementations (alike +# python_is_python3). Remember to escape or quote the fnmatch patterns +# to prevent accidental shell filename expansion. +# +# When all implementations are requested, please use ${PYTHON_USEDEP} +# instead. Please also remember to set an appropriate REQUIRED_USE +# to avoid ineffective USE flags. +# +# Example: +# @CODE +# PYTHON_COMPAT=( python{2_7,3_4} ) +# DEPEND="doc? ( dev-python/epydoc[$(python_gen_usedep 'python2*')] )" +# @CODE +# +# It will cause the dependency to look like: +# @CODE +# DEPEND="doc? ( dev-python/epydoc[python_targets_python2_7?] )" +# @CODE +python_gen_usedep() { + debug-print-function ${FUNCNAME} "${@}" + + # output only once, during some reasonable phase + # (avoid spamming cache regen runs) + if [[ ${EBUILD_PHASE} == setup ]]; then + eqawarn "python_gen_usedep() is deprecated. Please use python_gen_cond_dep instead." + fi + _python_gen_usedep "${@}" +} + +# @FUNCTION: python_gen_useflags +# @USAGE: [<pattern>...] +# @DESCRIPTION: +# Output a list of USE flags for Python implementations which +# are both in PYTHON_COMPAT and match any of the patterns passed +# as parameters to the function. +# +# The patterns can be either fnmatch-style patterns (matched via bash +# == operator against PYTHON_COMPAT values) or '-2' / '-3' to indicate +# appropriately all enabled Python 2/3 implementations (alike +# python_is_python3). Remember to escape or quote the fnmatch patterns +# to prevent accidental shell filename expansion. +# +# Example: +# @CODE +# PYTHON_COMPAT=( python{2_7,3_4} ) +# REQUIRED_USE="doc? ( || ( $(python_gen_useflags python2*) ) )" +# @CODE +# +# It will cause the variable to look like: +# @CODE +# REQUIRED_USE="doc? ( || ( python_targets_python2_7 ) )" +# @CODE +python_gen_useflags() { + debug-print-function ${FUNCNAME} "${@}" + + local impl matches=() + + _python_verify_patterns "${@}" + for impl in "${_PYTHON_SUPPORTED_IMPLS[@]}"; do + if _python_impl_matches "${impl}" "${@}"; then + matches+=( "python_targets_${impl}" ) + fi + done + + echo "${matches[@]}" +} + +# @FUNCTION: python_gen_cond_dep +# @USAGE: <dependency> [<pattern>...] +# @DESCRIPTION: +# Output a list of <dependency>-ies made conditional to USE flags +# of Python implementations which are both in PYTHON_COMPAT and match +# any of the patterns passed as the remaining parameters. +# +# The patterns can be either fnmatch-style patterns (matched via bash +# == operator against PYTHON_COMPAT values) or '-2' / '-3' to indicate +# appropriately all enabled Python 2/3 implementations (alike +# python_is_python3). Remember to escape or quote the fnmatch patterns +# to prevent accidental shell filename expansion. +# +# In order to enforce USE constraints on the packages, verbatim +# '${PYTHON_USEDEP}' (quoted!) may be placed in the dependency +# specification. It will get expanded within the function into a proper +# USE dependency string. +# +# Example: +# @CODE +# PYTHON_COMPAT=( python{2_7,3_{3,4}} pypy ) +# RDEPEND="$(python_gen_cond_dep \ +# 'dev-python/unittest2[${PYTHON_USEDEP}]' python2_7 pypy )" +# @CODE +# +# It will cause the variable to look like: +# @CODE +# RDEPEND="python_targets_python2_7? ( +# dev-python/unittest2[python_targets_python2_7?] ) +# python_targets_pypy? ( +# dev-python/unittest2[python_targets_pypy?] )" +# @CODE +python_gen_cond_dep() { + debug-print-function ${FUNCNAME} "${@}" + + local impl matches=() + local dep=${1} + shift + + _python_verify_patterns "${@}" + for impl in "${_PYTHON_SUPPORTED_IMPLS[@]}"; do + if _python_impl_matches "${impl}" "${@}"; then + # substitute ${PYTHON_USEDEP} if used + # (since python_gen_usedep() will not return ${PYTHON_USEDEP} + # the code is run at most once) + if [[ ${dep} == *'${PYTHON_USEDEP}'* ]]; then + local usedep=$(_python_gen_usedep "${@}") + dep=${dep//\$\{PYTHON_USEDEP\}/${usedep}} + fi + + matches+=( "python_targets_${impl}? ( ${dep} )" ) + fi + done + + echo "${matches[@]}" +} + +# @FUNCTION: python_gen_impl_dep +# @USAGE: [<requested-use-flags> [<impl-pattern>...]] +# @DESCRIPTION: +# Output a dependency on Python implementations with the specified USE +# dependency string appended, or no USE dependency string if called +# without the argument (or with empty argument). If any implementation +# patterns are passed, the output dependencies will be generated only +# for the implementations matching them. +# +# The patterns can be either fnmatch-style patterns (matched via bash +# == operator against PYTHON_COMPAT values) or '-2' / '-3' to indicate +# appropriately all enabled Python 2/3 implementations (alike +# python_is_python3). Remember to escape or quote the fnmatch patterns +# to prevent accidental shell filename expansion. +# +# Use this function when you need to request different USE flags +# on the Python interpreter depending on package's USE flags. If you +# only need a single set of interpreter USE flags, just set +# PYTHON_REQ_USE and use ${PYTHON_DEPS} globally. +# +# Example: +# @CODE +# PYTHON_COMPAT=( python{2_7,3_{3,4}} pypy ) +# RDEPEND="foo? ( $(python_gen_impl_dep 'xml(+)') )" +# @CODE +# +# It will cause the variable to look like: +# @CODE +# RDEPEND="foo? ( +# python_targets_python2_7? ( +# dev-lang/python:2.7[xml(+)] ) +# python_targets_pypy? ( +# dev-python/pypy[xml(+)] ) )" +# @CODE +python_gen_impl_dep() { + debug-print-function ${FUNCNAME} "${@}" + + local impl matches=() + local PYTHON_REQ_USE=${1} + shift + + _python_verify_patterns "${@}" + for impl in "${_PYTHON_SUPPORTED_IMPLS[@]}"; do + if _python_impl_matches "${impl}" "${@}"; then + local PYTHON_PKG_DEP + _python_export "${impl}" PYTHON_PKG_DEP + matches+=( "python_targets_${impl}? ( ${PYTHON_PKG_DEP} )" ) + fi + done + + echo "${matches[@]}" +} + +# @FUNCTION: python_gen_any_dep +# @USAGE: <dependency-block> [<impl-pattern>...] +# @DESCRIPTION: +# Generate an any-of dependency that enforces a version match between +# the Python interpreter and Python packages. <dependency-block> needs +# to list one or more dependencies with verbatim '${PYTHON_USEDEP}' +# or '${PYTHON_SINGLE_USEDEP}' references (quoted!) that will get +# expanded inside the function. Optionally, patterns may be specified +# to restrict the dependency to a subset of Python implementations +# supported by the ebuild. +# +# The patterns can be either fnmatch-style patterns (matched via bash +# == operator against PYTHON_COMPAT values) or '-2' / '-3' to indicate +# appropriately all enabled Python 2/3 implementations (alike +# python_is_python3). Remember to escape or quote the fnmatch patterns +# to prevent accidental shell filename expansion. +# +# This should be used along with an appropriate python_check_deps() +# that checks which of the any-of blocks were matched, and python_setup +# call that enables use of the matched implementation. +# +# Example use: +# @CODE +# DEPEND="$(python_gen_any_dep ' +# dev-python/foo[${PYTHON_SINGLE_USEDEP}] +# || ( dev-python/bar[${PYTHON_USEDEP}] +# dev-python/baz[${PYTHON_USEDEP}] )' -2)" +# +# python_check_deps() { +# has_version "dev-python/foo[${PYTHON_SINGLE_USEDEP}]" \ +# && { has_version "dev-python/bar[${PYTHON_USEDEP}]" \ +# || has_version "dev-python/baz[${PYTHON_USEDEP}]"; } +# } +# +# src_compile() { +# python_foreach_impl usual_code +# +# # some common post-build task that requires Python 2 +# python_setup -2 +# emake frobnicate +# } +# @CODE +# +# Example value: +# @CODE +# || ( +# ( +# dev-lang/python:3.7 +# dev-python/foo[python_single_target_python3_7(-)] +# || ( dev-python/bar[python_targets_python3_7(-),-python_single_target_python3_7(-)] +# dev-python/baz[python_targets_python3_7(-),-python_single_target_python3_7(-)] ) +# ) +# ( +# dev-lang/python:3.8 +# dev-python/foo[python_single_target_python3_8(-)] +# || ( dev-python/bar[python_targets_python3_8(-),-python_single_target_python3_8(-)] +# dev-python/baz[python_targets_python3_8(-),-python_single_target_python3_8(-)] ) +# ) +# ) +# @CODE +python_gen_any_dep() { + debug-print-function ${FUNCNAME} "${@}" + + local depstr=${1} + [[ ${depstr} ]] || die "No dependency string provided" + shift + + local i PYTHON_PKG_DEP out= + _python_verify_patterns "${@}" + for i in "${_PYTHON_SUPPORTED_IMPLS[@]}"; do + if _python_impl_matches "${i}" "${@}"; then + local PYTHON_USEDEP="python_targets_${i}(-),-python_single_target_${i}(-)" + local PYTHON_SINGLE_USEDEP="python_single_target_${i}(-)" + _python_export "${i}" PYTHON_PKG_DEP + + local i_depstr=${depstr//\$\{PYTHON_USEDEP\}/${PYTHON_USEDEP}} + i_depstr=${i_depstr//\$\{PYTHON_SINGLE_USEDEP\}/${PYTHON_SINGLE_USEDEP}} + # note: need to strip '=' slot operator for || deps + out="( ${PYTHON_PKG_DEP/:0=/:0} ${i_depstr} ) ${out}" + fi + done + echo "|| ( ${out})" +} + +# @ECLASS-VARIABLE: BUILD_DIR +# @OUTPUT_VARIABLE +# @DEFAULT_UNSET +# @DESCRIPTION: +# The current build directory. In global scope, it is supposed to +# contain an initial build directory; if unset, it defaults to ${S}. +# +# In functions run by python_foreach_impl(), the BUILD_DIR is locally +# set to an implementation-specific build directory. That path is +# created through appending a hyphen and the implementation name +# to the final component of the initial BUILD_DIR. +# +# Example value: +# @CODE +# ${WORKDIR}/foo-1.3-python2_7 +# @CODE + +# @FUNCTION: python_copy_sources +# @DESCRIPTION: +# Create a single copy of the package sources for each enabled Python +# implementation. +# +# The sources are always copied from initial BUILD_DIR (or S if unset) +# to implementation-specific build directory matching BUILD_DIR used by +# python_foreach_abi(). +python_copy_sources() { + debug-print-function ${FUNCNAME} "${@}" + + local MULTIBUILD_VARIANTS + _python_obtain_impls + + multibuild_copy_sources +} + +# @FUNCTION: _python_obtain_impls +# @INTERNAL +# @DESCRIPTION: +# Set up the enabled implementation list. +_python_obtain_impls() { + _python_validate_useflags + + if [[ ${PYTHON_COMPAT_OVERRIDE} ]]; then + MULTIBUILD_VARIANTS=( ${PYTHON_COMPAT_OVERRIDE} ) + return + fi + + MULTIBUILD_VARIANTS=() + + local impl + for impl in "${_PYTHON_SUPPORTED_IMPLS[@]}"; do + has "${impl}" "${PYTHON_COMPAT[@]}" && \ + use "python_targets_${impl}" && MULTIBUILD_VARIANTS+=( "${impl}" ) + done +} + +# @FUNCTION: _python_multibuild_wrapper +# @USAGE: <command> [<args>...] +# @INTERNAL +# @DESCRIPTION: +# Initialize the environment for Python implementation selected +# for multibuild. +_python_multibuild_wrapper() { + debug-print-function ${FUNCNAME} "${@}" + + local -x EPYTHON PYTHON + local -x PATH=${PATH} PKG_CONFIG_PATH=${PKG_CONFIG_PATH} + _python_export "${MULTIBUILD_VARIANT}" EPYTHON PYTHON + _python_wrapper_setup + + "${@}" +} + +# @FUNCTION: python_foreach_impl +# @USAGE: <command> [<args>...] +# @DESCRIPTION: +# Run the given command for each of the enabled Python implementations. +# If additional parameters are passed, they will be passed through +# to the command. +# +# The function will return 0 status if all invocations succeed. +# Otherwise, the return code from first failing invocation will +# be returned. +# +# For each command being run, EPYTHON, PYTHON and BUILD_DIR are set +# locally, and the former two are exported to the command environment. +python_foreach_impl() { + debug-print-function ${FUNCNAME} "${@}" + + local MULTIBUILD_VARIANTS + _python_obtain_impls + + multibuild_foreach_variant _python_multibuild_wrapper "${@}" +} + +# @FUNCTION: python_setup +# @USAGE: [<impl-pattern>...] +# @DESCRIPTION: +# Find the best (most preferred) Python implementation that is suitable +# for running common Python code. Set the Python build environment up +# for that implementation. This function has two modes of operation: +# pure and any-of dep. +# +# The pure mode is used if python_check_deps() function is not declared. +# In this case, an implementation is considered suitable if it is +# supported (in PYTHON_COMPAT), enabled (via USE flags) and matches +# at least one of the patterns passed (or '*' if no patterns passed). +# +# Implementation restrictions in the pure mode need to be accompanied +# by appropriate REQUIRED_USE constraints. Otherwise, the eclass may +# fail at build time due to unsatisfied dependencies. +# +# The any-of dep mode is used if python_check_deps() is declared. +# In this mode, an implementation is considered suitable if it is +# supported, matches at least one of the patterns and python_check_deps() +# has successful return code. USE flags are not considered. +# +# The python_check_deps() function in the any-of mode needs to be +# accompanied by appropriate any-of dependencies. +# +# The patterns can be either fnmatch-style patterns (matched via bash +# == operator against PYTHON_COMPAT values) or '-2' / '-3' to indicate +# appropriately all enabled Python 2/3 implementations (alike +# python_is_python3). Remember to escape or quote the fnmatch patterns +# to prevent accidental shell filename expansion. +# +# This function needs to be used when Python is being called outside +# of python_foreach_impl calls (e.g. for shared processes like doc +# building). python_foreach_impl sets up the build environment itself. +# +# Pure mode example: +# @CODE +# DEPEND="doc? ( dev-python/epydoc[$(python_gen_usedep 'python2*')] )" +# REQUIRED_USE="doc? ( $(python_gen_useflags 'python2*') )" +# +# src_compile() { +# #... +# if use doc; then +# python_setup 'python2*' +# make doc +# fi +# } +# @CODE +# +# Any-of mode example: +# @CODE +# DEPEND="doc? ( +# $(python_gen_any_dep 'dev-python/epydoc[${PYTHON_USEDEP}]' 'python2*') )" +# +# python_check_deps() { +# has_version "dev-python/epydoc[${PYTHON_USEDEP}]" +# } +# +# src_compile() { +# #... +# if use doc; then +# python_setup 'python2*' +# make doc +# fi +# } +# @CODE +python_setup() { + debug-print-function ${FUNCNAME} "${@}" + + _python_validate_useflags + local pycompat=( "${PYTHON_COMPAT[@]}" ) + if [[ ${PYTHON_COMPAT_OVERRIDE} ]]; then + pycompat=( ${PYTHON_COMPAT_OVERRIDE} ) + fi + + local has_check_deps + declare -f python_check_deps >/dev/null && has_check_deps=1 + + # (reverse iteration -- newest impl first) + local found + _python_verify_patterns "${@}" + for (( i = ${#_PYTHON_SUPPORTED_IMPLS[@]} - 1; i >= 0; i-- )); do + local impl=${_PYTHON_SUPPORTED_IMPLS[i]} + + # check PYTHON_COMPAT[_OVERRIDE] + has "${impl}" "${pycompat[@]}" || continue + + # match USE flags only if override is not in effect + # and python_check_deps() is not defined + if [[ ! ${PYTHON_COMPAT_OVERRIDE} && ! ${has_check_deps} ]]; then + use "python_targets_${impl}" || continue + fi + + # check patterns + _python_impl_matches "${impl}" "${@}" || continue + + _python_export "${impl}" EPYTHON PYTHON + + # if python_check_deps() is declared, switch into any-of mode + if [[ ${has_check_deps} ]]; then + # first check if the interpreter is installed + python_is_installed "${impl}" || continue + # then run python_check_deps + local PYTHON_USEDEP="python_targets_${impl}(-),-python_single_target_${impl}(-)" + local PYTHON_SINGLE_USEDEP="python_single_target_${impl}(-)" + python_check_deps || continue + fi + + found=1 + break + done + + if [[ ! ${found} ]]; then + eerror "${FUNCNAME}: none of the enabled implementation matched the patterns." + eerror " patterns: ${@-'(*)'}" + eerror "Likely a REQUIRED_USE constraint (possibly USE-conditional) is missing." + eerror " suggested: || ( \$(python_gen_useflags ${@}) )" + eerror "(remember to quote all the patterns with '')" + die "${FUNCNAME}: no enabled implementation satisfy requirements" + fi + + _python_wrapper_setup + einfo "Using ${EPYTHON} in global scope" +} + +# @FUNCTION: python_replicate_script +# @USAGE: <path>... +# @DESCRIPTION: +# Copy the given script to variants for all enabled Python +# implementations, then replace it with a symlink to the wrapper. +# +# All specified files must start with a 'python' shebang. A file not +# having a matching shebang will be refused. +python_replicate_script() { + debug-print-function ${FUNCNAME} "${@}" + + _python_replicate_script() { + local _PYTHON_FIX_SHEBANG_QUIET=1 + + local PYTHON_SCRIPTDIR + _python_export PYTHON_SCRIPTDIR + + ( + exeopts -m 0755 + exeinto "${PYTHON_SCRIPTDIR#${EPREFIX}}" + doexe "${files[@]}" + ) + + python_fix_shebang -q \ + "${files[@]/*\//${D%/}/${PYTHON_SCRIPTDIR}/}" + } + + local files=( "${@}" ) + python_foreach_impl _python_replicate_script + unset -f _python_replicate_script + + # install the wrappers + local f + for f; do + _python_ln_rel "${ED%/}/usr/lib/python-exec/python-exec2" "${f}" || die + done +} + +_PYTHON_R1=1 +fi diff --git a/eclass/python-single-r1.eclass b/eclass/python-single-r1.eclass new file mode 100644 index 0000000..dc03237 --- /dev/null +++ b/eclass/python-single-r1.eclass @@ -0,0 +1,529 @@ +# Copyright 1999-2020 Gentoo Authors +# Distributed under the terms of the GNU General Public License v2 + +# @ECLASS: python-single-r1.eclass +# @MAINTAINER: +# Python team <python@gentoo.org> +# @AUTHOR: +# Author: Michał Górny <mgorny@gentoo.org> +# Based on work of: Krzysztof Pawlik <nelchael@gentoo.org> +# @SUPPORTED_EAPIS: 5 6 7 +# @BLURB: An eclass for Python packages not installed for multiple implementations. +# @DESCRIPTION: +# An extension of the python-r1 eclass suite for packages which +# don't support being installed for multiple Python implementations. +# This mostly includes tools embedding Python and packages using foreign +# build systems. +# +# This eclass sets correct IUSE. It also provides PYTHON_DEPS +# and PYTHON_REQUIRED_USE that need to be added to appropriate ebuild +# metadata variables. +# +# The eclass exports PYTHON_SINGLE_USEDEP that is suitable for depending +# on other packages using the eclass. Dependencies on packages using +# python-r1 should be created via python_gen_cond_dep() function, +# using PYTHON_USEDEP placeholder. +# +# Please note that packages support multiple Python implementations +# (using python-r1 eclass) can not depend on packages not supporting +# them (using this eclass). +# +# Please note that python-single-r1 will always inherit python-utils-r1 +# as well. Thus, all the functions defined there can be used +# in the packages using python-single-r1, and there is no need ever +# to inherit both. +# +# For more information, please see the Python Guide: +# https://dev.gentoo.org/~mgorny/python-guide/ + +case "${EAPI:-0}" in + 0|1|2|3|4) + die "Unsupported EAPI=${EAPI:-0} (too old) for ${ECLASS}" + ;; + 5|6|7) + # EAPI=5 is required for sane USE_EXPAND dependencies + ;; + *) + die "Unsupported EAPI=${EAPI} (unknown) for ${ECLASS}" + ;; +esac + +if [[ ! ${_PYTHON_SINGLE_R1} ]]; then + +if [[ ${_PYTHON_R1} ]]; then + die 'python-single-r1.eclass can not be used with python-r1.eclass.' +elif [[ ${_PYTHON_ANY_R1} ]]; then + die 'python-single-r1.eclass can not be used with python-any-r1.eclass.' +fi + +inherit python-utils-r1 + +fi + +EXPORT_FUNCTIONS pkg_setup + +# @ECLASS-VARIABLE: PYTHON_COMPAT +# @REQUIRED +# @DESCRIPTION: +# This variable contains a list of Python implementations the package +# supports. It must be set before the `inherit' call. It has to be +# an array. +# +# Example: +# @CODE +# PYTHON_COMPAT=( python2_7 python3_3 python3_4 ) +# @CODE +# +# Please note that you can also use bash brace expansion if you like: +# @CODE +# PYTHON_COMPAT=( python2_7 python3_{3,4} ) +# @CODE + +# @ECLASS-VARIABLE: PYTHON_COMPAT_OVERRIDE +# @USER_VARIABLE +# @DEFAULT_UNSET +# @DESCRIPTION: +# This variable can be used when working with ebuilds to override +# the in-ebuild PYTHON_COMPAT. It is a string naming the implementation +# which package will be built for. It needs to be specified +# in the calling environment, and not in ebuilds. +# +# It should be noted that in order to preserve metadata immutability, +# PYTHON_COMPAT_OVERRIDE does not affect IUSE nor dependencies. +# The state of PYTHON_SINGLE_TARGET is ignored, and the implementation +# in PYTHON_COMPAT_OVERRIDE is built instead. Dependencies need to be +# satisfied manually. +# +# Example: +# @CODE +# PYTHON_COMPAT_OVERRIDE='pypy' emerge -1v dev-python/bar +# @CODE + +# @ECLASS-VARIABLE: PYTHON_REQ_USE +# @DEFAULT_UNSET +# @DESCRIPTION: +# The list of USEflags required to be enabled on the chosen Python +# implementations, formed as a USE-dependency string. It should be valid +# for all implementations in PYTHON_COMPAT, so it may be necessary to +# use USE defaults. +# +# This should be set before calling `inherit'. +# +# Example: +# @CODE +# PYTHON_REQ_USE="gdbm,ncurses(-)?" +# @CODE +# +# It will cause the Python dependencies to look like: +# @CODE +# python_single_target_pythonX_Y? ( dev-lang/python:X.Y[gdbm,ncurses(-)?] ) +# @CODE + +# @ECLASS-VARIABLE: PYTHON_DEPS +# @OUTPUT_VARIABLE +# @DESCRIPTION: +# This is an eclass-generated Python dependency string for all +# implementations listed in PYTHON_COMPAT. +# +# The dependency string is conditional on PYTHON_SINGLE_TARGET. +# +# Example use: +# @CODE +# RDEPEND="${PYTHON_DEPS} +# dev-foo/mydep" +# DEPEND="${RDEPEND}" +# @CODE +# +# Example value: +# @CODE +# dev-lang/python-exec:= +# python_single_target_python2_7? ( dev-lang/python:2.7[gdbm] ) +# python_single_target_pypy? ( dev-python/pypy[gdbm] ) +# @CODE + +# @ECLASS-VARIABLE: PYTHON_SINGLE_USEDEP +# @OUTPUT_VARIABLE +# @DESCRIPTION: +# This is an eclass-generated USE-dependency string which can be used to +# depend on another python-single-r1 package being built for the same +# Python implementations. +# +# If you need to depend on a multi-impl (python-r1) package, use +# python_gen_cond_dep with PYTHON_USEDEP placeholder instead. +# +# Example use: +# @CODE +# RDEPEND="dev-python/foo[${PYTHON_SINGLE_USEDEP}]" +# @CODE +# +# Example value: +# @CODE +# python_single_target_python3_4(-)? +# @CODE + +# @ECLASS-VARIABLE: PYTHON_USEDEP +# @OUTPUT_VARIABLE +# @DESCRIPTION: +# This is a placeholder variable supported by python_gen_cond_dep, +# in order to depend on python-r1 packages built for the same Python +# implementations. +# +# Example use: +# @CODE +# RDEPEND="$(python_gen_cond_dep ' +# dev-python/foo[${PYTHON_USEDEP}] +# ')" +# @CODE +# +# Example value: +# @CODE +# python_targets_python3_4(-) +# @CODE + +# @ECLASS-VARIABLE: PYTHON_MULTI_USEDEP +# @OUTPUT_VARIABLE +# @DESCRIPTION: +# This is a backwards-compatibility placeholder. Use PYTHON_USEDEP +# instead. + +# @ECLASS-VARIABLE: PYTHON_REQUIRED_USE +# @OUTPUT_VARIABLE +# @DESCRIPTION: +# This is an eclass-generated required-use expression which ensures +# that exactly one PYTHON_SINGLE_TARGET value has been enabled. +# +# This expression should be utilized in an ebuild by including it in +# REQUIRED_USE, optionally behind a use flag. +# +# Example use: +# @CODE +# REQUIRED_USE="python? ( ${PYTHON_REQUIRED_USE} )" +# @CODE +# +# Example value: +# @CODE +# ^^ ( python_single_target_python2_7 python_single_target_python3_3 ) +# @CODE + +_python_single_set_globals() { + _python_set_impls + + local flags=( "${_PYTHON_SUPPORTED_IMPLS[@]/#/python_single_target_}" ) + + if [[ ${#_PYTHON_SUPPORTED_IMPLS[@]} -eq 1 ]]; then + # if only one implementation is supported, use IUSE defaults + # to avoid requesting the user to enable it + IUSE="+${flags[0]}" + else + IUSE="${flags[*]}" + fi + + local requse="^^ ( ${flags[*]} )" + local single_flags="${flags[@]/%/(-)?}" + local single_usedep=${single_flags// /,} + + local deps= i PYTHON_PKG_DEP + for i in "${_PYTHON_SUPPORTED_IMPLS[@]}"; do + _python_export "${i}" PYTHON_PKG_DEP + # 1) well, python-exec would suffice as an RDEP + # but no point in making this overcomplex, BDEP doesn't hurt anyone + # 2) python-exec should be built with all targets forced anyway + # but if new targets were added, we may need to force a rebuild + deps+="python_single_target_${i}? ( + ${PYTHON_PKG_DEP} + >=dev-lang/python-exec-2:=[python_targets_${i}] + ) " + done + + if [[ ${PYTHON_DEPS+1} ]]; then + if [[ ${PYTHON_DEPS} != "${deps}" ]]; then + eerror "PYTHON_DEPS have changed between inherits (PYTHON_REQ_USE?)!" + eerror "Before: ${PYTHON_DEPS}" + eerror "Now : ${deps}" + die "PYTHON_DEPS integrity check failed" + fi + + # these two are formality -- they depend on PYTHON_COMPAT only + if [[ ${PYTHON_REQUIRED_USE} != ${requse} ]]; then + eerror "PYTHON_REQUIRED_USE have changed between inherits!" + eerror "Before: ${PYTHON_REQUIRED_USE}" + eerror "Now : ${requse}" + die "PYTHON_REQUIRED_USE integrity check failed" + fi + + if [[ ${PYTHON_SINGLE_USEDEP} != "${single_usedep}" ]]; then + eerror "PYTHON_SINGLE_USEDEP have changed between inherits!" + eerror "Before: ${PYTHON_SINGLE_USEDEP}" + eerror "Now : ${single_usedep}" + die "PYTHON_SINGLE_USEDEP integrity check failed" + fi + else + PYTHON_DEPS=${deps} + PYTHON_REQUIRED_USE=${requse} + PYTHON_USEDEP='%PYTHON_USEDEP-NEEDS-TO-BE-USED-IN-PYTHON_GEN_COND_DEP%' + PYTHON_SINGLE_USEDEP=${single_usedep} + readonly PYTHON_DEPS PYTHON_REQUIRED_USE PYTHON_SINGLE_USEDEP \ + PYTHON_USEDEP + fi +} +_python_single_set_globals +unset -f _python_single_set_globals + +if [[ ! ${_PYTHON_SINGLE_R1} ]]; then + +# @FUNCTION: _python_gen_usedep +# @USAGE: [<pattern>...] +# @INTERNAL +# @DESCRIPTION: +# Output a USE dependency string for Python implementations which +# are both in PYTHON_COMPAT and match any of the patterns passed +# as parameters to the function. +# +# The patterns can be either fnmatch-style patterns (matched via bash +# == operator against PYTHON_COMPAT values) or '-2' / '-3' to indicate +# appropriately all enabled Python 2/3 implementations (alike +# python_is_python3). Remember to escape or quote the fnmatch patterns +# to prevent accidental shell filename expansion. +# +# This is an internal function used to implement python_gen_cond_dep. +_python_gen_usedep() { + debug-print-function ${FUNCNAME} "${@}" + + local impl matches=() + + _python_verify_patterns "${@}" + for impl in "${_PYTHON_SUPPORTED_IMPLS[@]}"; do + if _python_impl_matches "${impl}" "${@}"; then + matches+=( + "python_single_target_${impl}(-)?" + ) + fi + done + + [[ ${matches[@]} ]] || die "No supported implementations match python_gen_usedep patterns: ${@}" + + local out=${matches[@]} + echo "${out// /,}" +} + +# @FUNCTION: python_gen_useflags +# @USAGE: [<pattern>...] +# @DESCRIPTION: +# Output a list of USE flags for Python implementations which +# are both in PYTHON_COMPAT and match any of the patterns passed +# as parameters to the function. +# +# The patterns can be either fnmatch-style patterns (matched via bash +# == operator against PYTHON_COMPAT values) or '-2' / '-3' to indicate +# appropriately all enabled Python 2/3 implementations (alike +# python_is_python3). Remember to escape or quote the fnmatch patterns +# to prevent accidental shell filename expansion. +# +# Example: +# @CODE +# PYTHON_COMPAT=( python{2_7,3_4} ) +# REQUIRED_USE="doc? ( ^^ ( $(python_gen_useflags 'python2*') ) )" +# @CODE +# +# It will cause the variable to look like: +# @CODE +# REQUIRED_USE="doc? ( ^^ ( python_single_target_python2_7 ) )" +# @CODE +python_gen_useflags() { + debug-print-function ${FUNCNAME} "${@}" + + local impl matches=() + + _python_verify_patterns "${@}" + for impl in "${_PYTHON_SUPPORTED_IMPLS[@]}"; do + if _python_impl_matches "${impl}" "${@}"; then + matches+=( "python_single_target_${impl}" ) + fi + done + + echo "${matches[@]}" +} + +# @FUNCTION: python_gen_cond_dep +# @USAGE: <dependency> [<pattern>...] +# @DESCRIPTION: +# Output a list of <dependency>-ies made conditional to USE flags +# of Python implementations which are both in PYTHON_COMPAT and match +# any of the patterns passed as the remaining parameters. +# +# The patterns can be either fnmatch-style patterns (matched via bash +# == operator against PYTHON_COMPAT values) or '-2' / '-3' to indicate +# appropriately all enabled Python 2/3 implementations (alike +# python_is_python3). Remember to escape or quote the fnmatch patterns +# to prevent accidental shell filename expansion. +# +# In order to enforce USE constraints on the packages, verbatim +# '${PYTHON_SINGLE_USEDEP}' and '${PYTHON_USEDEP}' (quoted!) may +# be placed in the dependency specification. It will get expanded within +# the function into a proper USE dependency string. +# +# Example: +# @CODE +# PYTHON_COMPAT=( python{2_7,3_{3,4}} pypy ) +# RDEPEND="$(python_gen_cond_dep \ +# 'dev-python/unittest2[${PYTHON_USEDEP}]' python2_7 pypy )" +# @CODE +# +# It will cause the variable to look like: +# @CODE +# RDEPEND="python_single_target_python2_7? ( +# dev-python/unittest2[python_targets_python2_7(-)?,...] ) +# python_single_target_pypy? ( +# dev-python/unittest2[python_targets_pypy(-)?,...] )" +# @CODE +python_gen_cond_dep() { + debug-print-function ${FUNCNAME} "${@}" + + local impl matches=() + + local dep=${1} + shift + + _python_verify_patterns "${@}" + for impl in "${_PYTHON_SUPPORTED_IMPLS[@]}"; do + if _python_impl_matches "${impl}" "${@}"; then + # substitute ${PYTHON_SINGLE_USEDEP} if used + # (since python_gen_usedep() will not return + # ${PYTHON_SINGLE_USEDEP}, the code is run at most once) + if [[ ${dep} == *'${PYTHON_SINGLE_USEDEP}'* ]]; then + local usedep=$(_python_gen_usedep "${@}") + dep=${dep//\$\{PYTHON_SINGLE_USEDEP\}/${usedep}} + fi + local multi_usedep="python_targets_${impl}(-)" + + local subdep=${dep//\$\{PYTHON_MULTI_USEDEP\}/${multi_usedep}} + matches+=( "python_single_target_${impl}? ( + ${subdep//\$\{PYTHON_USEDEP\}/${multi_usedep}} )" ) + fi + done + + echo "${matches[@]}" +} + +# @FUNCTION: python_gen_impl_dep +# @USAGE: [<requested-use-flags> [<impl-pattern>...]] +# @DESCRIPTION: +# Output a dependency on Python implementations with the specified USE +# dependency string appended, or no USE dependency string if called +# without the argument (or with empty argument). If any implementation +# patterns are passed, the output dependencies will be generated only +# for the implementations matching them. +# +# The patterns can be either fnmatch-style patterns (matched via bash +# == operator against PYTHON_COMPAT values) or '-2' / '-3' to indicate +# appropriately all enabled Python 2/3 implementations (alike +# python_is_python3). Remember to escape or quote the fnmatch patterns +# to prevent accidental shell filename expansion. +# +# Use this function when you need to request different USE flags +# on the Python interpreter depending on package's USE flags. If you +# only need a single set of interpreter USE flags, just set +# PYTHON_REQ_USE and use ${PYTHON_DEPS} globally. +# +# Example: +# @CODE +# PYTHON_COMPAT=( python{2_7,3_{3,4}} pypy ) +# RDEPEND="foo? ( $(python_gen_impl_dep 'xml(+)') )" +# @CODE +# +# It will cause the variable to look like: +# @CODE +# RDEPEND="foo? ( +# python_single_target_python2_7? ( +# dev-lang/python:2.7[xml(+)] ) +# python_single_target_pypy? ( +# dev-python/pypy[xml(+)] ) )" +# @CODE +python_gen_impl_dep() { + debug-print-function ${FUNCNAME} "${@}" + + local impl + local matches=() + + local PYTHON_REQ_USE=${1} + shift + + _python_verify_patterns "${@}" + for impl in "${_PYTHON_SUPPORTED_IMPLS[@]}"; do + if _python_impl_matches "${impl}" "${@}"; then + local PYTHON_PKG_DEP + _python_export "${impl}" PYTHON_PKG_DEP + matches+=( "python_single_target_${impl}? ( ${PYTHON_PKG_DEP} )" ) + fi + done + + echo "${matches[@]}" +} + +# @FUNCTION: python_setup +# @DESCRIPTION: +# Determine what the selected Python implementation is and set +# the Python build environment up for it. +python_setup() { + debug-print-function ${FUNCNAME} "${@}" + + unset EPYTHON + + # support developer override + if [[ ${PYTHON_COMPAT_OVERRIDE} ]]; then + local impls=( ${PYTHON_COMPAT_OVERRIDE} ) + [[ ${#impls[@]} -eq 1 ]] || die "PYTHON_COMPAT_OVERRIDE must name exactly one implementation for python-single-r1" + + ewarn "WARNING: PYTHON_COMPAT_OVERRIDE in effect. The following Python" + ewarn "implementation will be used:" + ewarn + ewarn " ${PYTHON_COMPAT_OVERRIDE}" + ewarn + ewarn "Dependencies won't be satisfied, and PYTHON_SINGLE_TARGET flags will be ignored." + + _python_export "${impls[0]}" EPYTHON PYTHON + _python_wrapper_setup + einfo "Using ${EPYTHON} to build" + return + fi + + local impl + for impl in "${_PYTHON_SUPPORTED_IMPLS[@]}"; do + if use "python_single_target_${impl}"; then + if [[ ${EPYTHON} ]]; then + eerror "Your PYTHON_SINGLE_TARGET setting lists more than a single Python" + eerror "implementation. Please set it to just one value. If you need" + eerror "to override the value for a single package, please use package.env" + eerror "or an equivalent solution (man 5 portage)." + echo + die "More than one implementation in PYTHON_SINGLE_TARGET." + fi + + _python_export "${impl}" EPYTHON PYTHON + _python_wrapper_setup + einfo "Using ${EPYTHON} to build" + fi + done + + if [[ ! ${EPYTHON} ]]; then + eerror "No Python implementation selected for the build. Please set" + eerror "the PYTHON_SINGLE_TARGET variable in your make.conf to one" + eerror "of the following values:" + eerror + eerror "${_PYTHON_SUPPORTED_IMPLS[@]}" + echo + die "No supported Python implementation in PYTHON_SINGLE_TARGET." + fi +} + +# @FUNCTION: python-single-r1_pkg_setup +# @DESCRIPTION: +# Runs python_setup. +python-single-r1_pkg_setup() { + debug-print-function ${FUNCNAME} "${@}" + + [[ ${MERGE_TYPE} != binary ]] && python_setup +} + +_PYTHON_SINGLE_R1=1 +fi diff --git a/eclass/python-utils-r1.eclass b/eclass/python-utils-r1.eclass new file mode 100644 index 0000000..dcc441b --- /dev/null +++ b/eclass/python-utils-r1.eclass @@ -0,0 +1,1450 @@ +# Copyright 1999-2021 Gentoo Authors +# Distributed under the terms of the GNU General Public License v2 + +# @ECLASS: python-utils-r1.eclass +# @MAINTAINER: +# Python team <python@gentoo.org> +# @AUTHOR: +# Author: Michał Górny <mgorny@gentoo.org> +# Based on work of: Krzysztof Pawlik <nelchael@gentoo.org> +# @SUPPORTED_EAPIS: 5 6 7 +# @BLURB: Utility functions for packages with Python parts. +# @DESCRIPTION: +# A utility eclass providing functions to query Python implementations, +# install Python modules and scripts. +# +# This eclass does not set any metadata variables nor export any phase +# functions. It can be inherited safely. +# +# For more information, please see the Python Guide: +# https://dev.gentoo.org/~mgorny/python-guide/ + +case "${EAPI:-0}" in + [0-4]) die "Unsupported EAPI=${EAPI:-0} (too old) for ${ECLASS}" ;; + [5-7]) ;; + *) die "Unsupported EAPI=${EAPI} (unknown) for ${ECLASS}" ;; +esac + +if [[ ${_PYTHON_ECLASS_INHERITED} ]]; then + die 'python-r1 suite eclasses can not be used with python.eclass.' +fi + +if [[ ! ${_PYTHON_UTILS_R1} ]]; then + +[[ ${EAPI} == 5 ]] && inherit eutils multilib +inherit toolchain-funcs + +# @ECLASS-VARIABLE: _PYTHON_ALL_IMPLS +# @INTERNAL +# @DESCRIPTION: +# All supported Python implementations, most preferred last. +_PYTHON_ALL_IMPLS=( + pypy3 + python3_7 python3_8 python3_9 +) +readonly _PYTHON_ALL_IMPLS + +# @ECLASS-VARIABLE: _PYTHON_HISTORICAL_IMPLS +# @INTERNAL +# @DESCRIPTION: +# All historical Python implementations that are no longer supported. +_PYTHON_HISTORICAL_IMPLS=( + jython2_7 + pypy pypy1_{8,9} pypy2_0 + python2_{5..7} + python3_{1..6} +) +readonly _PYTHON_HISTORICAL_IMPLS + +# @ECLASS-VARIABLE: PYTHON_COMPAT_NO_STRICT +# @INTERNAL +# @DESCRIPTION: +# Set to a non-empty value in order to make eclass tolerate (ignore) +# unknown implementations in PYTHON_COMPAT. +# +# This is intended to be set by the user when using ebuilds that may +# have unknown (newer) implementations in PYTHON_COMPAT. The assumption +# is that the ebuilds are intended to be used within multiple contexts +# which can involve revisions of this eclass that support a different +# set of Python implementations. + +# @FUNCTION: _python_verify_patterns +# @USAGE: <pattern>... +# @INTERNAL +# @DESCRIPTION: +# Verify whether the patterns passed to the eclass function are correct +# (i.e. can match any valid implementation). Dies on wrong pattern. +_python_verify_patterns() { + debug-print-function ${FUNCNAME} "${@}" + + local impl pattern + for pattern; do + [[ ${pattern} == -[23] ]] && continue + + for impl in "${_PYTHON_ALL_IMPLS[@]}" "${_PYTHON_HISTORICAL_IMPLS[@]}" + do + [[ ${impl} == ${pattern/./_} ]] && continue 2 + done + + die "Invalid implementation pattern: ${pattern}" + done +} + +# @FUNCTION: _python_set_impls +# @INTERNAL +# @DESCRIPTION: +# Check PYTHON_COMPAT for well-formedness and validity, then set +# two global variables: +# +# - _PYTHON_SUPPORTED_IMPLS containing valid implementations supported +# by the ebuild (PYTHON_COMPAT - dead implementations), +# +# - and _PYTHON_UNSUPPORTED_IMPLS containing valid implementations that +# are not supported by the ebuild. +# +# Implementations in both variables are ordered using the pre-defined +# eclass implementation ordering. +# +# This function must be called once in global scope by an eclass +# utilizing PYTHON_COMPAT. +_python_set_impls() { + local i + + if ! declare -p PYTHON_COMPAT &>/dev/null; then + die 'PYTHON_COMPAT not declared.' + fi + if [[ $(declare -p PYTHON_COMPAT) != "declare -a"* ]]; then + die 'PYTHON_COMPAT must be an array.' + fi + if [[ ! ${PYTHON_COMPAT_NO_STRICT} ]]; then + for i in "${PYTHON_COMPAT[@]}"; do + # check for incorrect implementations + # we're using pattern matching as an optimization + # please keep them in sync with _PYTHON_ALL_IMPLS + # and _PYTHON_HISTORICAL_IMPLS + case ${i} in + jython2_7|pypy|pypy1_[89]|pypy2_0|pypy3|python2_[5-7]|python3_[1-9]) + ;; + *) + if has "${i}" "${_PYTHON_ALL_IMPLS[@]}" \ + "${_PYTHON_HISTORICAL_IMPLS[@]}" + then + die "Mis-synced patterns in _python_set_impls: missing ${i}" + else + die "Invalid implementation in PYTHON_COMPAT: ${i}" + fi + esac + done + fi + + local supp=() unsupp=() + + for i in "${_PYTHON_ALL_IMPLS[@]}"; do + if has "${i}" "${PYTHON_COMPAT[@]}"; then + supp+=( "${i}" ) + else + unsupp+=( "${i}" ) + fi + done + + if [[ ! ${supp[@]} ]]; then + # special-case python2_7 for python-any-r1 + if [[ ${_PYTHON_ALLOW_PY27} ]] && has python2_7 "${PYTHON_COMPAT[@]}" + then + supp+=( python2_7 ) + else + die "No supported implementation in PYTHON_COMPAT." + fi + fi + + if [[ ${_PYTHON_SUPPORTED_IMPLS[@]} ]]; then + # set once already, verify integrity + if [[ ${_PYTHON_SUPPORTED_IMPLS[@]} != ${supp[@]} ]]; then + eerror "Supported impls (PYTHON_COMPAT) changed between inherits!" + eerror "Before: ${_PYTHON_SUPPORTED_IMPLS[*]}" + eerror "Now : ${supp[*]}" + die "_PYTHON_SUPPORTED_IMPLS integrity check failed" + fi + if [[ ${_PYTHON_UNSUPPORTED_IMPLS[@]} != ${unsupp[@]} ]]; then + eerror "Unsupported impls changed between inherits!" + eerror "Before: ${_PYTHON_UNSUPPORTED_IMPLS[*]}" + eerror "Now : ${unsupp[*]}" + die "_PYTHON_UNSUPPORTED_IMPLS integrity check failed" + fi + else + _PYTHON_SUPPORTED_IMPLS=( "${supp[@]}" ) + _PYTHON_UNSUPPORTED_IMPLS=( "${unsupp[@]}" ) + readonly _PYTHON_SUPPORTED_IMPLS _PYTHON_UNSUPPORTED_IMPLS + fi +} + +# @FUNCTION: _python_impl_matches +# @USAGE: <impl> [<pattern>...] +# @INTERNAL +# @DESCRIPTION: +# Check whether the specified <impl> matches at least one +# of the patterns following it. Return 0 if it does, 1 otherwise. +# Matches if no patterns are provided. +# +# <impl> can be in PYTHON_COMPAT or EPYTHON form. The patterns can be +# either: +# a) fnmatch-style patterns, e.g. 'python2*', 'pypy'... +# b) '-2' to indicate all Python 2 variants (= !python_is_python3) +# c) '-3' to indicate all Python 3 variants (= python_is_python3) +_python_impl_matches() { + [[ ${#} -ge 1 ]] || die "${FUNCNAME}: takes at least 1 parameter" + [[ ${#} -eq 1 ]] && return 0 + + local impl=${1} pattern + shift + + for pattern; do + if [[ ${pattern} == -2 ]]; then + python_is_python3 "${impl}" || return 0 + elif [[ ${pattern} == -3 ]]; then + python_is_python3 "${impl}" && return 0 + return + # unify value style to allow lax matching + elif [[ ${impl/./_} == ${pattern/./_} ]]; then + return 0 + fi + done + + return 1 +} + +# @ECLASS-VARIABLE: PYTHON +# @DEFAULT_UNSET +# @DESCRIPTION: +# The absolute path to the current Python interpreter. +# +# This variable is set automatically in the following contexts: +# +# python-r1: Set in functions called by python_foreach_impl() or after +# calling python_setup(). +# +# python-single-r1: Set after calling python-single-r1_pkg_setup(). +# +# distutils-r1: Set within any of the python sub-phase functions. +# +# Example value: +# @CODE +# /usr/bin/python2.7 +# @CODE + +# @ECLASS-VARIABLE: EPYTHON +# @DEFAULT_UNSET +# @DESCRIPTION: +# The executable name of the current Python interpreter. +# +# This variable is set automatically in the following contexts: +# +# python-r1: Set in functions called by python_foreach_impl() or after +# calling python_setup(). +# +# python-single-r1: Set after calling python-single-r1_pkg_setup(). +# +# distutils-r1: Set within any of the python sub-phase functions. +# +# Example value: +# @CODE +# python2.7 +# @CODE + +# @FUNCTION: python_export +# @USAGE: [<impl>] <variables>... +# @INTERNAL +# @DESCRIPTION: +# Backwards compatibility function. The relevant API is now considered +# private, please use python_get* instead. +python_export() { + debug-print-function ${FUNCNAME} "${@}" + + eqawarn "python_export() is part of private eclass API." + eqawarn "Please call python_get*() instead." + + _python_export "${@}" +} + +# @FUNCTION: _python_export +# @USAGE: [<impl>] <variables>... +# @INTERNAL +# @DESCRIPTION: +# Set and export the Python implementation-relevant variables passed +# as parameters. +# +# The optional first parameter may specify the requested Python +# implementation (either as PYTHON_TARGETS value, e.g. python2_7, +# or an EPYTHON one, e.g. python2.7). If no implementation passed, +# the current one will be obtained from ${EPYTHON}. +# +# The variables which can be exported are: PYTHON, EPYTHON, +# PYTHON_SITEDIR. They are described more completely in the eclass +# variable documentation. +_python_export() { + debug-print-function ${FUNCNAME} "${@}" + + local impl var + + case "${1}" in + python*|jython*) + impl=${1/_/.} + shift + ;; + pypy|pypy3) + impl=${1} + shift + ;; + *) + impl=${EPYTHON} + if [[ -z ${impl} ]]; then + die "_python_export called without a python implementation and EPYTHON is unset" + fi + ;; + esac + debug-print "${FUNCNAME}: implementation: ${impl}" + + for var; do + case "${var}" in + EPYTHON) + export EPYTHON=${impl} + debug-print "${FUNCNAME}: EPYTHON = ${EPYTHON}" + ;; + PYTHON) + export PYTHON=${EPREFIX}/usr/bin/${impl} + debug-print "${FUNCNAME}: PYTHON = ${PYTHON}" + ;; + PYTHON_SITEDIR) + [[ -n ${PYTHON} ]] || die "PYTHON needs to be set for ${var} to be exported, or requested before it" + # sysconfig can't be used because: + # 1) pypy doesn't give site-packages but stdlib + # 2) jython gives paths with wrong case + PYTHON_SITEDIR=$("${PYTHON}" -c 'import distutils.sysconfig; print(distutils.sysconfig.get_python_lib())') || die + export PYTHON_SITEDIR + debug-print "${FUNCNAME}: PYTHON_SITEDIR = ${PYTHON_SITEDIR}" + ;; + PYTHON_INCLUDEDIR) + [[ -n ${PYTHON} ]] || die "PYTHON needs to be set for ${var} to be exported, or requested before it" + PYTHON_INCLUDEDIR=$("${PYTHON}" -c 'import distutils.sysconfig; print(distutils.sysconfig.get_python_inc())') || die + export PYTHON_INCLUDEDIR + debug-print "${FUNCNAME}: PYTHON_INCLUDEDIR = ${PYTHON_INCLUDEDIR}" + + # Jython gives a non-existing directory + if [[ ! -d ${PYTHON_INCLUDEDIR} ]]; then + die "${impl} does not install any header files!" + fi + ;; + PYTHON_LIBPATH) + [[ -n ${PYTHON} ]] || die "PYTHON needs to be set for ${var} to be exported, or requested before it" + PYTHON_LIBPATH=$("${PYTHON}" -c 'import os.path, sysconfig; print(os.path.join(sysconfig.get_config_var("LIBDIR"), sysconfig.get_config_var("LDLIBRARY")) if sysconfig.get_config_var("LDLIBRARY") else "")') || die + export PYTHON_LIBPATH + debug-print "${FUNCNAME}: PYTHON_LIBPATH = ${PYTHON_LIBPATH}" + + if [[ ! ${PYTHON_LIBPATH} ]]; then + die "${impl} lacks a (usable) dynamic library" + fi + ;; + PYTHON_CFLAGS) + local val + + case "${impl}" in + python*) + # python-2.7, python-3.2, etc. + val=$($(tc-getPKG_CONFIG) --cflags ${impl/n/n-}) || die + ;; + *) + die "${impl}: obtaining ${var} not supported" + ;; + esac + + export PYTHON_CFLAGS=${val} + debug-print "${FUNCNAME}: PYTHON_CFLAGS = ${PYTHON_CFLAGS}" + ;; + PYTHON_LIBS) + local val + + case "${impl}" in + python2*|python3.6|python3.7*) + # python* up to 3.7 + val=$($(tc-getPKG_CONFIG) --libs ${impl/n/n-}) || die + ;; + python*) + # python3.8+ + val=$($(tc-getPKG_CONFIG) --libs ${impl/n/n-}-embed) || die + ;; + *) + die "${impl}: obtaining ${var} not supported" + ;; + esac + + export PYTHON_LIBS=${val} + debug-print "${FUNCNAME}: PYTHON_LIBS = ${PYTHON_LIBS}" + ;; + PYTHON_CONFIG) + local flags val + + case "${impl}" in + python*) + [[ -n ${PYTHON} ]] || die "PYTHON needs to be set for ${var} to be exported, or requested before it" + flags=$("${PYTHON}" -c 'import sysconfig; print(sysconfig.get_config_var("ABIFLAGS") or "")') || die + val=${PYTHON}${flags}-config + ;; + *) + die "${impl}: obtaining ${var} not supported" + ;; + esac + + export PYTHON_CONFIG=${val} + debug-print "${FUNCNAME}: PYTHON_CONFIG = ${PYTHON_CONFIG}" + ;; + PYTHON_PKG_DEP) + local d + case ${impl} in + python2.7) + PYTHON_PKG_DEP='>=dev-lang/python-2.7.5-r2:2.7';; + python*) + PYTHON_PKG_DEP="dev-lang/python:${impl#python}";; + pypy) + PYTHON_PKG_DEP='>=dev-python/pypy-7.3.0:0=';; + pypy3) + PYTHON_PKG_DEP='>=dev-python/pypy3-7.3.0:0=';; + *) + die "Invalid implementation: ${impl}" + esac + + # use-dep + if [[ ${PYTHON_REQ_USE} ]]; then + PYTHON_PKG_DEP+=[${PYTHON_REQ_USE}] + fi + + export PYTHON_PKG_DEP + debug-print "${FUNCNAME}: PYTHON_PKG_DEP = ${PYTHON_PKG_DEP}" + ;; + PYTHON_SCRIPTDIR) + local dir + export PYTHON_SCRIPTDIR=${EPREFIX}/usr/lib/python-exec/${impl} + debug-print "${FUNCNAME}: PYTHON_SCRIPTDIR = ${PYTHON_SCRIPTDIR}" + ;; + *) + die "_python_export: unknown variable ${var}" + esac + done +} + +# @FUNCTION: python_get_sitedir +# @USAGE: [<impl>] +# @DESCRIPTION: +# Obtain and print the 'site-packages' path for the given +# implementation. If no implementation is provided, ${EPYTHON} will +# be used. +python_get_sitedir() { + debug-print-function ${FUNCNAME} "${@}" + + _python_export "${@}" PYTHON_SITEDIR + echo "${PYTHON_SITEDIR}" +} + +# @FUNCTION: python_get_includedir +# @USAGE: [<impl>] +# @DESCRIPTION: +# Obtain and print the include path for the given implementation. If no +# implementation is provided, ${EPYTHON} will be used. +python_get_includedir() { + debug-print-function ${FUNCNAME} "${@}" + + _python_export "${@}" PYTHON_INCLUDEDIR + echo "${PYTHON_INCLUDEDIR}" +} + +# @FUNCTION: python_get_library_path +# @USAGE: [<impl>] +# @DESCRIPTION: +# Obtain and print the Python library path for the given implementation. +# If no implementation is provided, ${EPYTHON} will be used. +# +# Please note that this function can be used with CPython only. Use +# in another implementation will result in a fatal failure. +python_get_library_path() { + debug-print-function ${FUNCNAME} "${@}" + + _python_export "${@}" PYTHON_LIBPATH + echo "${PYTHON_LIBPATH}" +} + +# @FUNCTION: python_get_CFLAGS +# @USAGE: [<impl>] +# @DESCRIPTION: +# Obtain and print the compiler flags for building against Python, +# for the given implementation. If no implementation is provided, +# ${EPYTHON} will be used. +# +# Please note that this function can be used with CPython only. +# It requires Python and pkg-config installed, and therefore proper +# build-time dependencies need be added to the ebuild. +python_get_CFLAGS() { + debug-print-function ${FUNCNAME} "${@}" + + _python_export "${@}" PYTHON_CFLAGS + echo "${PYTHON_CFLAGS}" +} + +# @FUNCTION: python_get_LIBS +# @USAGE: [<impl>] +# @DESCRIPTION: +# Obtain and print the compiler flags for linking against Python, +# for the given implementation. If no implementation is provided, +# ${EPYTHON} will be used. +# +# Please note that this function can be used with CPython only. +# It requires Python and pkg-config installed, and therefore proper +# build-time dependencies need be added to the ebuild. +python_get_LIBS() { + debug-print-function ${FUNCNAME} "${@}" + + _python_export "${@}" PYTHON_LIBS + echo "${PYTHON_LIBS}" +} + +# @FUNCTION: python_get_PYTHON_CONFIG +# @USAGE: [<impl>] +# @DESCRIPTION: +# Obtain and print the PYTHON_CONFIG location for the given +# implementation. If no implementation is provided, ${EPYTHON} will be +# used. +# +# Please note that this function can be used with CPython only. +# It requires Python installed, and therefore proper build-time +# dependencies need be added to the ebuild. +python_get_PYTHON_CONFIG() { + debug-print-function ${FUNCNAME} "${@}" + + _python_export "${@}" PYTHON_CONFIG + echo "${PYTHON_CONFIG}" +} + +# @FUNCTION: python_get_scriptdir +# @USAGE: [<impl>] +# @DESCRIPTION: +# Obtain and print the script install path for the given +# implementation. If no implementation is provided, ${EPYTHON} will +# be used. +python_get_scriptdir() { + debug-print-function ${FUNCNAME} "${@}" + + _python_export "${@}" PYTHON_SCRIPTDIR + echo "${PYTHON_SCRIPTDIR}" +} + +# @FUNCTION: _python_ln_rel +# @USAGE: <from> <to> +# @INTERNAL +# @DESCRIPTION: +# Create a relative symlink. +_python_ln_rel() { + debug-print-function ${FUNCNAME} "${@}" + + local target=${1} + local symname=${2} + + local tgpath=${target%/*}/ + local sympath=${symname%/*}/ + local rel_target= + + while [[ ${sympath} ]]; do + local tgseg= symseg= + + while [[ ! ${tgseg} && ${tgpath} ]]; do + tgseg=${tgpath%%/*} + tgpath=${tgpath#${tgseg}/} + done + + while [[ ! ${symseg} && ${sympath} ]]; do + symseg=${sympath%%/*} + sympath=${sympath#${symseg}/} + done + + if [[ ${tgseg} != ${symseg} ]]; then + rel_target=../${rel_target}${tgseg:+${tgseg}/} + fi + done + rel_target+=${tgpath}${target##*/} + + debug-print "${FUNCNAME}: ${symname} -> ${target}" + debug-print "${FUNCNAME}: rel_target = ${rel_target}" + + ln -fs "${rel_target}" "${symname}" +} + +# @FUNCTION: python_optimize +# @USAGE: [<directory>...] +# @DESCRIPTION: +# Compile and optimize Python modules in specified directories (absolute +# paths). If no directories are provided, the default system paths +# are used (prepended with ${D}). +python_optimize() { + debug-print-function ${FUNCNAME} "${@}" + + if [[ ${EBUILD_PHASE} == pre* || ${EBUILD_PHASE} == post* ]]; then + eerror "The new Python eclasses expect the compiled Python files to" + eerror "be controlled by the Package Manager. For this reason," + eerror "the python_optimize function can be used only during src_* phases" + eerror "(src_install most commonly) and not during pkg_* phases." + echo + die "python_optimize is not to be used in pre/post* phases" + fi + + [[ ${EPYTHON} ]] || die 'No Python implementation set (EPYTHON is null).' + + local PYTHON=${PYTHON} + [[ ${PYTHON} ]] || _python_export PYTHON + [[ -x ${PYTHON} ]] || die "PYTHON (${PYTHON}) is not executable" + + # default to sys.path + if [[ ${#} -eq 0 ]]; then + local f + while IFS= read -r -d '' f; do + # 1) accept only absolute paths + # (i.e. skip '', '.' or anything like that) + # 2) skip paths which do not exist + # (python2.6 complains about them verbosely) + + if [[ ${f} == /* && -d ${D%/}${f} ]]; then + set -- "${D%/}${f}" "${@}" + fi + done < <("${PYTHON}" -c 'import sys; print("".join(x + "\0" for x in sys.path))' || die) + + debug-print "${FUNCNAME}: using sys.path: ${*/%/;}" + fi + + local d + for d; do + # make sure to get a nice path without // + local instpath=${d#${D%/}} + instpath=/${instpath##/} + + case "${EPYTHON}" in + python2.7|python3.[34]) + "${PYTHON}" -m compileall -q -f -d "${instpath}" "${d}" + "${PYTHON}" -OO -m compileall -q -f -d "${instpath}" "${d}" + ;; + python*|pypy3) + # both levels of optimization are separate since 3.5 + "${PYTHON}" -m compileall -q -f -d "${instpath}" "${d}" + "${PYTHON}" -O -m compileall -q -f -d "${instpath}" "${d}" + "${PYTHON}" -OO -m compileall -q -f -d "${instpath}" "${d}" + ;; + *) + "${PYTHON}" -m compileall -q -f -d "${instpath}" "${d}" + ;; + esac + done +} + +# @FUNCTION: python_scriptinto +# @USAGE: <new-path> +# @DESCRIPTION: +# Set the directory to which files passed to python_doexe(), +# python_doscript(), python_newexe() and python_newscript() +# are going to be installed. The new value needs to be relative +# to the installation root (${ED}). +# +# If not set explicitly, the directory defaults to /usr/bin. +# +# Example: +# @CODE +# src_install() { +# python_scriptinto /usr/sbin +# python_foreach_impl python_doscript foo +# } +# @CODE +python_scriptinto() { + debug-print-function ${FUNCNAME} "${@}" + + python_scriptroot=${1} +} + +# @FUNCTION: python_doexe +# @USAGE: <files>... +# @DESCRIPTION: +# Install the given executables into the executable install directory, +# for the current Python implementation (${EPYTHON}). +# +# The executable will be wrapped properly for the Python implementation, +# though no shebang mangling will be performed. +python_doexe() { + debug-print-function ${FUNCNAME} "${@}" + + local f + for f; do + python_newexe "${f}" "${f##*/}" + done +} + +# @FUNCTION: python_newexe +# @USAGE: <path> <new-name> +# @DESCRIPTION: +# Install the given executable into the executable install directory, +# for the current Python implementation (${EPYTHON}). +# +# The executable will be wrapped properly for the Python implementation, +# though no shebang mangling will be performed. It will be renamed +# to <new-name>. +python_newexe() { + debug-print-function ${FUNCNAME} "${@}" + + [[ ${EPYTHON} ]] || die 'No Python implementation set (EPYTHON is null).' + [[ ${#} -eq 2 ]] || die "Usage: ${FUNCNAME} <path> <new-name>" + + local wrapd=${python_scriptroot:-/usr/bin} + + local f=${1} + local newfn=${2} + + local scriptdir=$(python_get_scriptdir) + local d=${scriptdir#${EPREFIX}} + + ( + dodir "${wrapd}" + exeopts -m 0755 + exeinto "${d}" + newexe "${f}" "${newfn}" || return ${?} + ) + + # install the wrapper + _python_ln_rel "${ED%/}"/usr/lib/python-exec/python-exec2 \ + "${ED%/}/${wrapd}/${newfn}" || die + + # don't use this at home, just call python_doscript() instead + if [[ ${_PYTHON_REWRITE_SHEBANG} ]]; then + python_fix_shebang -q "${ED%/}/${d}/${newfn}" + fi +} + +# @FUNCTION: python_doscript +# @USAGE: <files>... +# @DESCRIPTION: +# Install the given scripts into the executable install directory, +# for the current Python implementation (${EPYTHON}). +# +# All specified files must start with a 'python' shebang. The shebang +# will be converted, and the files will be wrapped properly +# for the Python implementation. +# +# Example: +# @CODE +# src_install() { +# python_foreach_impl python_doscript ${PN} +# } +# @CODE +python_doscript() { + debug-print-function ${FUNCNAME} "${@}" + + local _PYTHON_REWRITE_SHEBANG=1 + python_doexe "${@}" +} + +# @FUNCTION: python_newscript +# @USAGE: <path> <new-name> +# @DESCRIPTION: +# Install the given script into the executable install directory +# for the current Python implementation (${EPYTHON}), and name it +# <new-name>. +# +# The file must start with a 'python' shebang. The shebang will be +# converted, and the file will be wrapped properly for the Python +# implementation. It will be renamed to <new-name>. +# +# Example: +# @CODE +# src_install() { +# python_foreach_impl python_newscript foo.py foo +# } +# @CODE +python_newscript() { + debug-print-function ${FUNCNAME} "${@}" + + local _PYTHON_REWRITE_SHEBANG=1 + python_newexe "${@}" +} + +# @FUNCTION: python_moduleinto +# @USAGE: <new-path> +# @DESCRIPTION: +# Set the Python module install directory for python_domodule(). +# The <new-path> can either be an absolute target system path (in which +# case it needs to start with a slash, and ${ED} will be prepended to +# it) or relative to the implementation's site-packages directory +# (then it must not start with a slash). The relative path can be +# specified either using the Python package notation (separated by dots) +# or the directory notation (using slashes). +# +# When not set explicitly, the modules are installed to the top +# site-packages directory. +# +# In the relative case, the exact path is determined directly +# by each python_doscript/python_newscript function. Therefore, +# python_moduleinto can be safely called before establishing the Python +# interpreter and/or a single call can be used to set the path correctly +# for multiple implementations, as can be seen in the following example. +# +# Example: +# @CODE +# src_install() { +# python_moduleinto bar +# # installs ${PYTHON_SITEDIR}/bar/baz.py +# python_foreach_impl python_domodule baz.py +# } +# @CODE +python_moduleinto() { + debug-print-function ${FUNCNAME} "${@}" + + python_moduleroot=${1} +} + +# @FUNCTION: python_domodule +# @USAGE: <files>... +# @DESCRIPTION: +# Install the given modules (or packages) into the current Python module +# installation directory. The list can mention both modules (files) +# and packages (directories). All listed files will be installed +# for all enabled implementations, and compiled afterwards. +# +# Example: +# @CODE +# src_install() { +# # (${PN} being a directory) +# python_foreach_impl python_domodule ${PN} +# } +# @CODE +python_domodule() { + debug-print-function ${FUNCNAME} "${@}" + + [[ ${EPYTHON} ]] || die 'No Python implementation set (EPYTHON is null).' + + local d + if [[ ${python_moduleroot} == /* ]]; then + # absolute path + d=${python_moduleroot} + else + # relative to site-packages + local sitedir=$(python_get_sitedir) + d=${sitedir#${EPREFIX}}/${python_moduleroot//.//} + fi + + ( + insopts -m 0644 + insinto "${d}" + doins -r "${@}" || return ${?} + ) + + python_optimize "${ED%/}/${d}" +} + +# @FUNCTION: python_doheader +# @USAGE: <files>... +# @DESCRIPTION: +# Install the given headers into the implementation-specific include +# directory. This function is unconditionally recursive, i.e. you can +# pass directories instead of files. +# +# Example: +# @CODE +# src_install() { +# python_foreach_impl python_doheader foo.h bar.h +# } +# @CODE +python_doheader() { + debug-print-function ${FUNCNAME} "${@}" + + [[ ${EPYTHON} ]] || die 'No Python implementation set (EPYTHON is null).' + + local includedir=$(python_get_includedir) + local d=${includedir#${EPREFIX}} + + ( + insopts -m 0644 + insinto "${d}" + doins -r "${@}" || return ${?} + ) +} + +# @FUNCTION: python_wrapper_setup +# @USAGE: [<path> [<impl>]] +# @DESCRIPTION: +# Backwards compatibility function. The relevant API is now considered +# private, please use python_setup instead. +python_wrapper_setup() { + debug-print-function ${FUNCNAME} "${@}" + + eqawarn "python_wrapper_setup() is part of private eclass API." + eqawarn "Please call python_setup() instead." + + _python_wrapper_setup "${@}" +} + +# @FUNCTION: _python_wrapper_setup +# @USAGE: [<path> [<impl>]] +# @INTERNAL +# @DESCRIPTION: +# Create proper 'python' executable and pkg-config wrappers +# (if available) in the directory named by <path>. Set up PATH +# and PKG_CONFIG_PATH appropriately. <path> defaults to ${T}/${EPYTHON}. +# +# The wrappers will be created for implementation named by <impl>, +# or for one named by ${EPYTHON} if no <impl> passed. +# +# If the named directory contains a python symlink already, it will +# be assumed to contain proper wrappers already and only environment +# setup will be done. If wrapper update is requested, the directory +# shall be removed first. +_python_wrapper_setup() { + debug-print-function ${FUNCNAME} "${@}" + + local workdir=${1:-${T}/${EPYTHON}} + local impl=${2:-${EPYTHON}} + + [[ ${workdir} ]] || die "${FUNCNAME}: no workdir specified." + [[ ${impl} ]] || die "${FUNCNAME}: no impl nor EPYTHON specified." + + if [[ ! -x ${workdir}/bin/python ]]; then + _python_check_dead_variables + + mkdir -p "${workdir}"/{bin,pkgconfig} || die + + # Clean up, in case we were supposed to do a cheap update. + rm -f "${workdir}"/bin/python{,2,3}{,-config} || die + rm -f "${workdir}"/bin/2to3 || die + rm -f "${workdir}"/pkgconfig/python{2,3}{,-embed}.pc || die + + local EPYTHON PYTHON + _python_export "${impl}" EPYTHON PYTHON + + local pyver pyother + if python_is_python3; then + pyver=3 + pyother=2 + else + pyver=2 + pyother=3 + fi + + # Python interpreter + # note: we don't use symlinks because python likes to do some + # symlink reading magic that breaks stuff + # https://bugs.gentoo.org/show_bug.cgi?id=555752 + cat > "${workdir}/bin/python" <<-_EOF_ || die + #!/bin/sh + exec "${PYTHON}" "\${@}" + _EOF_ + cp "${workdir}/bin/python" "${workdir}/bin/python${pyver}" || die + chmod +x "${workdir}/bin/python" "${workdir}/bin/python${pyver}" || die + + local nonsupp=( "python${pyother}" "python${pyother}-config" ) + + # CPython-specific + if [[ ${EPYTHON} == python* ]]; then + cat > "${workdir}/bin/python-config" <<-_EOF_ || die + #!/bin/sh + exec "${PYTHON}-config" "\${@}" + _EOF_ + cp "${workdir}/bin/python-config" \ + "${workdir}/bin/python${pyver}-config" || die + chmod +x "${workdir}/bin/python-config" \ + "${workdir}/bin/python${pyver}-config" || die + + # Python 2.6+. + ln -s "${PYTHON/python/2to3-}" "${workdir}"/bin/2to3 || die + + # Python 2.7+. + ln -s "${EPREFIX}"/usr/$(get_libdir)/pkgconfig/${EPYTHON/n/n-}.pc \ + "${workdir}"/pkgconfig/python${pyver}.pc || die + + # Python 3.8+. + if [[ ${EPYTHON} != python[23].[67] ]]; then + ln -s "${EPREFIX}"/usr/$(get_libdir)/pkgconfig/${EPYTHON/n/n-}-embed.pc \ + "${workdir}"/pkgconfig/python${pyver}-embed.pc || die + fi + else + nonsupp+=( 2to3 python-config "python${pyver}-config" ) + fi + + local x + for x in "${nonsupp[@]}"; do + cat >"${workdir}"/bin/${x} <<-_EOF_ || die + #!/bin/sh + echo "${ECLASS}: ${FUNCNAME}: ${x} is not supported by ${EPYTHON} (PYTHON_COMPAT)" >&2 + exit 127 + _EOF_ + chmod +x "${workdir}"/bin/${x} || die + done + fi + + # Now, set the environment. + # But note that ${workdir} may be shared with something else, + # and thus already on top of PATH. + if [[ ${PATH##:*} != ${workdir}/bin ]]; then + PATH=${workdir}/bin${PATH:+:${PATH}} + fi + if [[ ${PKG_CONFIG_PATH##:*} != ${workdir}/pkgconfig ]]; then + PKG_CONFIG_PATH=${workdir}/pkgconfig${PKG_CONFIG_PATH:+:${PKG_CONFIG_PATH}} + fi + export PATH PKG_CONFIG_PATH +} + +# @FUNCTION: python_is_python3 +# @USAGE: [<impl>] +# @DESCRIPTION: +# Check whether <impl> (or ${EPYTHON}) is a Python3k variant +# (i.e. uses syntax and stdlib of Python 3.*). +# +# Returns 0 (true) if it is, 1 (false) otherwise. +python_is_python3() { + local impl=${1:-${EPYTHON}} + [[ ${impl} ]] || die "python_is_python3: no impl nor EPYTHON" + + [[ ${impl} == python3* || ${impl} == pypy3 ]] +} + +# @FUNCTION: python_is_installed +# @USAGE: [<impl>] +# @DESCRIPTION: +# Check whether the interpreter for <impl> (or ${EPYTHON}) is installed. +# Uses has_version with a proper dependency string. +# +# Returns 0 (true) if it is, 1 (false) otherwise. +python_is_installed() { + local impl=${1:-${EPYTHON}} + [[ ${impl} ]] || die "${FUNCNAME}: no impl nor EPYTHON" + local hasv_args=() + + case ${EAPI} in + 5|6) + hasv_args+=( --host-root ) + ;; + *) + hasv_args+=( -b ) + ;; + esac + + local PYTHON_PKG_DEP + _python_export "${impl}" PYTHON_PKG_DEP + has_version "${hasv_args[@]}" "${PYTHON_PKG_DEP}" +} + +# @FUNCTION: python_fix_shebang +# @USAGE: [-f|--force] [-q|--quiet] <path>... +# @DESCRIPTION: +# Replace the shebang in Python scripts with the current Python +# implementation (EPYTHON). If a directory is passed, works recursively +# on all Python scripts. +# +# Only files having a 'python*' shebang will be modified. Files with +# other shebang will either be skipped when working recursively +# on a directory or treated as error when specified explicitly. +# +# Shebangs matching explicitly current Python version will be left +# unmodified. Shebangs requesting another Python version will be treated +# as fatal error, unless --force is given. +# +# --force causes the function to replace even shebangs that require +# incompatible Python version. --quiet causes the function not to list +# modified files verbosely. +python_fix_shebang() { + debug-print-function ${FUNCNAME} "${@}" + + [[ ${EPYTHON} ]] || die "${FUNCNAME}: EPYTHON unset (pkg_setup not called?)" + + local force quiet + while [[ ${@} ]]; do + case "${1}" in + -f|--force) force=1; shift;; + -q|--quiet) quiet=1; shift;; + --) shift; break;; + *) break;; + esac + done + + [[ ${1} ]] || die "${FUNCNAME}: no paths given" + + local path f + for path; do + local any_correct any_fixed is_recursive + + [[ -d ${path} ]] && is_recursive=1 + + while IFS= read -r -d '' f; do + local shebang i + local error= from= + + # note: we can't ||die here since read will fail if file + # has no newline characters + IFS= read -r shebang <"${f}" + + # First, check if it's shebang at all... + if [[ ${shebang} == '#!'* ]]; then + local split_shebang=() + read -r -a split_shebang <<<${shebang} || die + + # Match left-to-right in a loop, to avoid matching random + # repetitions like 'python2.7 python2'. + for i in "${split_shebang[@]}"; do + case "${i}" in + *"${EPYTHON}") + debug-print "${FUNCNAME}: in file ${f#${D%/}}" + debug-print "${FUNCNAME}: shebang matches EPYTHON: ${shebang}" + + # Nothing to do, move along. + any_correct=1 + from=${EPYTHON} + break + ;; + *python|*python[23]) + debug-print "${FUNCNAME}: in file ${f#${D%/}}" + debug-print "${FUNCNAME}: rewriting shebang: ${shebang}" + + if [[ ${i} == *python2 ]]; then + from=python2 + if [[ ! ${force} ]]; then + python_is_python3 "${EPYTHON}" && error=1 + fi + elif [[ ${i} == *python3 ]]; then + from=python3 + if [[ ! ${force} ]]; then + python_is_python3 "${EPYTHON}" || error=1 + fi + else + from=python + fi + break + ;; + *python[23].[0123456789]|*pypy|*pypy3|*jython[23].[0123456789]) + # Explicit mismatch. + if [[ ! ${force} ]]; then + error=1 + else + case "${i}" in + *python[23].[0123456789]) + from="python[23].[0123456789]";; + *pypy) + from="pypy";; + *pypy3) + from="pypy3";; + *jython[23].[0123456789]) + from="jython[23].[0123456789]";; + *) + die "${FUNCNAME}: internal error in 2nd pattern match";; + esac + fi + break + ;; + esac + done + fi + + if [[ ! ${error} && ! ${from} ]]; then + # Non-Python shebang. Allowed in recursive mode, + # disallowed when specifying file explicitly. + [[ ${is_recursive} ]] && continue + error=1 + fi + + if [[ ! ${quiet} ]]; then + einfo "Fixing shebang in ${f#${D%/}}." + fi + + if [[ ! ${error} ]]; then + # We either want to match ${from} followed by space + # or at end-of-string. + if [[ ${shebang} == *${from}" "* ]]; then + sed -i -e "1s:${from} :${EPYTHON} :" "${f}" || die + else + sed -i -e "1s:${from}$:${EPYTHON}:" "${f}" || die + fi + any_fixed=1 + else + eerror "The file has incompatible shebang:" + eerror " file: ${f#${D%/}}" + eerror " current shebang: ${shebang}" + eerror " requested impl: ${EPYTHON}" + die "${FUNCNAME}: conversion of incompatible shebang requested" + fi + done < <(find -H "${path}" -type f -print0 || die) + + if [[ ! ${any_fixed} ]]; then + local cmd=eerror + [[ ${EAPI} == 5 ]] && cmd=eqawarn + + "${cmd}" "QA warning: ${FUNCNAME}, ${path#${D%/}} did not match any fixable files." + if [[ ${any_correct} ]]; then + "${cmd}" "All files have ${EPYTHON} shebang already." + else + "${cmd}" "There are no Python files in specified directory." + fi + + [[ ${cmd} == eerror ]] && die "${FUNCNAME} did not match any fixable files (QA warning fatal in EAPI ${EAPI})" + fi + done +} + +# @FUNCTION: _python_check_locale_sanity +# @USAGE: <locale> +# @RETURN: 0 if sane, 1 otherwise +# @INTERNAL +# @DESCRIPTION: +# Check whether the specified locale sanely maps between lowercase +# and uppercase ASCII characters. +_python_check_locale_sanity() { + local -x LC_ALL=${1} + local IFS= + + local lc=( {a..z} ) + local uc=( {A..Z} ) + local input="${lc[*]}${uc[*]}" + + local output=$(tr '[:lower:][:upper:]' '[:upper:][:lower:]' <<<"${input}") + [[ ${output} == "${uc[*]}${lc[*]}" ]] +} + +# @FUNCTION: python_export_utf8_locale +# @RETURN: 0 on success, 1 on failure. +# @DESCRIPTION: +# Attempts to export a usable UTF-8 locale in the LC_CTYPE variable. Does +# nothing if LC_ALL is defined, or if the current locale uses a UTF-8 charmap. +# This may be used to work around the quirky open() behavior of python3. +python_export_utf8_locale() { + debug-print-function ${FUNCNAME} "${@}" + + # If the locale program isn't available, just return. + type locale >/dev/null || return 0 + + if [[ $(locale charmap) != UTF-8 ]]; then + # Try English first, then everything else. + local lang locales="C.UTF-8 en_US.UTF-8 en_GB.UTF-8 $(locale -a)" + + for lang in ${locales}; do + if [[ $(LC_ALL=${lang} locale charmap 2>/dev/null) == UTF-8 ]]; then + if _python_check_locale_sanity "${lang}"; then + export LC_CTYPE=${lang} + if [[ -n ${LC_ALL} ]]; then + export LC_NUMERIC=${LC_ALL} + export LC_TIME=${LC_ALL} + export LC_COLLATE=${LC_ALL} + export LC_MONETARY=${LC_ALL} + export LC_MESSAGES=${LC_ALL} + export LC_PAPER=${LC_ALL} + export LC_NAME=${LC_ALL} + export LC_ADDRESS=${LC_ALL} + export LC_TELEPHONE=${LC_ALL} + export LC_MEASUREMENT=${LC_ALL} + export LC_IDENTIFICATION=${LC_ALL} + export LC_ALL= + fi + return 0 + fi + fi + done + + ewarn "Could not find a UTF-8 locale. This may trigger build failures in" + ewarn "some python packages. Please ensure that a UTF-8 locale is listed in" + ewarn "/etc/locale.gen and run locale-gen." + return 1 + fi + + return 0 +} + +# @FUNCTION: build_sphinx +# @USAGE: <directory> +# @DESCRIPTION: +# Build HTML documentation using dev-python/sphinx in the specified +# <directory>. Takes care of disabling Intersphinx and appending +# to HTML_DOCS. +# +# If <directory> is relative to the current directory, care needs +# to be taken to run einstalldocs from the same directory +# (usually ${S}). +build_sphinx() { + debug-print-function ${FUNCNAME} "${@}" + [[ ${#} -eq 1 ]] || die "${FUNCNAME} takes 1 arg: <directory>" + + local dir=${1} + + sed -i -e 's:^intersphinx_mapping:disabled_&:' \ + "${dir}"/conf.py || die + # not all packages include the Makefile in pypi tarball + sphinx-build -b html -d "${dir}"/_build/doctrees "${dir}" \ + "${dir}"/_build/html || die + + HTML_DOCS+=( "${dir}/_build/html/." ) +} + +# -- python.eclass functions -- + +_python_check_dead_variables() { + local v + + for v in PYTHON_DEPEND PYTHON_USE_WITH{,_OR,_OPT} {RESTRICT,SUPPORT}_PYTHON_ABIS + do + if [[ ${!v} ]]; then + die "${v} is invalid for python-r1 suite, please take a look @ https://wiki.gentoo.org/wiki/Project:Python/Python.eclass_conversion#Ebuild_head" + fi + done + + for v in PYTHON_{CPPFLAGS,CFLAGS,CXXFLAGS,LDFLAGS} + do + if [[ ${!v} ]]; then + die "${v} is invalid for python-r1 suite, please take a look @ https://wiki.gentoo.org/wiki/Project:Python/Python.eclass_conversion#PYTHON_CFLAGS" + fi + done + + for v in PYTHON_TESTS_RESTRICTED_ABIS PYTHON_EXPORT_PHASE_FUNCTIONS \ + PYTHON_VERSIONED_{SCRIPTS,EXECUTABLES} PYTHON_NONVERSIONED_EXECUTABLES + do + if [[ ${!v} ]]; then + die "${v} is invalid for python-r1 suite" + fi + done + + for v in DISTUTILS_USE_SEPARATE_SOURCE_DIRECTORIES DISTUTILS_SETUP_FILES \ + DISTUTILS_GLOBAL_OPTIONS DISTUTILS_SRC_TEST PYTHON_MODNAME + do + if [[ ${!v} ]]; then + die "${v} is invalid for distutils-r1, please take a look @ https://wiki.gentoo.org/wiki/Project:Python/Python.eclass_conversion#${v}" + fi + done + + if [[ ${DISTUTILS_DISABLE_TEST_DEPENDENCY} ]]; then + die "${v} is invalid for distutils-r1, please take a look @ https://wiki.gentoo.org/wiki/Project:Python/Python.eclass_conversion#DISTUTILS_SRC_TEST" + fi + + # python.eclass::progress + for v in PYTHON_BDEPEND PYTHON_MULTIPLE_ABIS PYTHON_ABI_TYPE \ + PYTHON_RESTRICTED_ABIS PYTHON_TESTS_FAILURES_TOLERANT_ABIS \ + PYTHON_CFFI_MODULES_GENERATION_COMMANDS + do + if [[ ${!v} ]]; then + die "${v} is invalid for python-r1 suite" + fi + done +} + +python_pkg_setup() { + die "${FUNCNAME}() is invalid for python-r1 suite, please take a look @ https://wiki.gentoo.org/wiki/Project:Python/Python.eclass_conversion#pkg_setup" +} + +python_convert_shebangs() { + die "${FUNCNAME}() is invalid for python-r1 suite, please take a look @ https://wiki.gentoo.org/wiki/Project:Python/Python.eclass_conversion#python_convert_shebangs" +} + +python_clean_py-compile_files() { + die "${FUNCNAME}() is invalid for python-r1 suite" +} + +python_clean_installation_image() { + die "${FUNCNAME}() is invalid for python-r1 suite" +} + +python_execute_function() { + die "${FUNCNAME}() is invalid for python-r1 suite, please take a look @ https://wiki.gentoo.org/wiki/Project:Python/Python.eclass_conversion#python_execute_function" +} + +python_generate_wrapper_scripts() { + die "${FUNCNAME}() is invalid for python-r1 suite" +} + +python_merge_intermediate_installation_images() { + die "${FUNCNAME}() is invalid for python-r1 suite" +} + +python_set_active_version() { + die "${FUNCNAME}() is invalid for python-r1 suite, please take a look @ https://wiki.gentoo.org/wiki/Project:Python/Python.eclass_conversion#pkg_setup" +} + +python_need_rebuild() { + die "${FUNCNAME}() is invalid for python-r1 suite" +} + +PYTHON() { + die "${FUNCNAME}() is invalid for python-r1 suite, please take a look @ https://wiki.gentoo.org/wiki/Project:Python/Python.eclass_conversion#.24.28PYTHON.29.2C_.24.7BEPYTHON.7D" +} + +python_get_implementation() { + die "${FUNCNAME}() is invalid for python-r1 suite" +} + +python_get_implementational_package() { + die "${FUNCNAME}() is invalid for python-r1 suite" +} + +python_get_libdir() { + die "${FUNCNAME}() is invalid for python-r1 suite" +} + +python_get_library() { + die "${FUNCNAME}() is invalid for python-r1 suite" +} + +python_get_version() { + die "${FUNCNAME}() is invalid for python-r1 suite" +} + +python_get_implementation_and_version() { + die "${FUNCNAME}() is invalid for python-r1 suite" +} + +python_execute_nosetests() { + die "${FUNCNAME}() is invalid for python-r1 suite" +} + +python_execute_py.test() { + die "${FUNCNAME}() is invalid for python-r1 suite" +} + +python_execute_trial() { + die "${FUNCNAME}() is invalid for python-r1 suite" +} + +python_enable_pyc() { + die "${FUNCNAME}() is invalid for python-r1 suite" +} + +python_disable_pyc() { + die "${FUNCNAME}() is invalid for python-r1 suite" +} + +python_mod_optimize() { + die "${FUNCNAME}() is invalid for python-r1 suite, please take a look @ https://wiki.gentoo.org/wiki/Project:Python/Python.eclass_conversion#Python_byte-code_compilation" +} + +python_mod_cleanup() { + die "${FUNCNAME}() is invalid for python-r1 suite, please take a look @ https://wiki.gentoo.org/wiki/Project:Python/Python.eclass_conversion#Python_byte-code_compilation" +} + +# python.eclass::progress + +python_abi_depend() { + die "${FUNCNAME}() is invalid for python-r1 suite" +} + +python_install_executables() { + die "${FUNCNAME}() is invalid for python-r1 suite" +} + +python_get_extension_module_suffix() { + die "${FUNCNAME}() is invalid for python-r1 suite" +} + +python_byte-compile_modules() { + die "${FUNCNAME}() is invalid for python-r1 suite" +} + +python_clean_byte-compiled_modules() { + die "${FUNCNAME}() is invalid for python-r1 suite" +} + +python_generate_cffi_modules() { + die "${FUNCNAME}() is invalid for python-r1 suite" +} + +_PYTHON_UTILS_R1=1 +fi diff --git a/eclass/qmail.eclass b/eclass/qmail.eclass new file mode 100644 index 0000000..21f317f --- /dev/null +++ b/eclass/qmail.eclass @@ -0,0 +1,511 @@ +# Copyright 1999-2020 Gentoo Authors +# Distributed under the terms of the GNU General Public License v2 + +# @ECLASS: qmail.eclass +# @MAINTAINER: +# qmail-bugs@gentoo.org +# @BLURB: common qmail functions + +inherit flag-o-matic toolchain-funcs fixheadtails + +# hardcoded paths +QMAIL_HOME="/var/qmail" +TCPRULES_DIR="/etc/tcprules.d" +SUPERVISE_DIR="/var/qmail/supervise" + +# source files and directories +GENQMAIL_F=genqmail-${GENQMAIL_PV}.tar.bz2 +GENQMAIL_S="${WORKDIR}"/genqmail-${GENQMAIL_PV} + +QMAIL_SPP_F=qmail-spp-${QMAIL_SPP_PV}.tar.gz +QMAIL_SPP_S="${WORKDIR}"/qmail-spp-${QMAIL_SPP_PV} + +# @FUNCTION: primes +# @USAGE: <min> <max> +# @DESCRIPTION: +# Prints a list of primes between min and max inclusive +# Note: this functions gets very slow when used with large numbers. +primes() { + local min=${1} max=${2} + local result= primelist=2 i p + + [[ ${min} -le 2 ]] && result="${result} 2" + + for ((i = 3; i <= max; i += 2)) + do + for p in ${primelist} + do + [[ $[i % p] == 0 || $[p * p] -gt ${i} ]] && \ + break + done + if [[ $[i % p] != 0 ]] + then + primelist="${primelist} ${i}" + [[ ${i} -ge ${min} ]] && \ + result="${result} ${i}" + fi + done + + echo ${result} +} + +# @FUNCTION: is_prima +# @USAGE: <number> +# @DESCRIPTION: +# Checks wether a number is a prime number +is_prime() { + local number=${1} i + for i in $(primes ${number} ${number}) + do + [[ ${i} == ${number} ]] && return 0 + done + return 1 +} + +dospp() { + insinto "${QMAIL_HOME}"/plugins/ + insopts -o root -g "${GROUP_ROOT}" -m 0755 + newins $1 ${2:-$(basename $1)} +} + +# @FUNCTION: dosupervise +# @USAGE: <service> [<runfile> <logfile>] +# @DESCRIPTION: +# Install runfiles for services and logging to supervise directory +dosupervise() { + local service=$1 + local runfile=${2:-${service}} logfile=${3:-${service}-log} + [[ -z "${service}" ]] && die "no service given" + + insopts -o root -g "${GROUP_ROOT}" -m 0755 + diropts -o root -g "${GROUP_ROOT}" -m 0755 + + dodir ${SUPERVISE_DIR}/${service}{,/log} + fperms +t ${SUPERVISE_DIR}/${service}{,/log} + + insinto ${SUPERVISE_DIR}/${service} + newins ${runfile} run + + insinto ${SUPERVISE_DIR}/${service}/log + newins ${logfile} run +} + +# @FUNCTION: qmail_set_cc +# @DESCRIPTION: +# The following commands patch the conf-{cc,ld} files to use the user's +# specified CFLAGS and LDFLAGS. These rather complex commands are needed +# because a user supplied patch might apply changes to these files, too. +# See bug #165981. +qmail_set_cc() { + local cc=$(head -n 1 ./conf-cc | sed -e "s#^g\?cc\s\+\(-O2\)\?#$(tc-getCC) #") + local ld=$(head -n 1 ./conf-ld | sed -e "s#^g\?cc\s\+\(-s\)\?#$(tc-getCC) #") + + echo "${cc} ${CFLAGS} ${CPPFLAGS}" > ./conf-cc || die 'Patching conf-cc failed.' + echo "${ld} ${LDFLAGS}" > ./conf-ld || die 'Patching conf-ld failed.' + sed -e "s#'ar #'$(tc-getAR) #" -e "s#'ranlib #'$(tc-getRANLIB) #" -i make-makelib.sh +} + +genqmail_src_unpack() { + cd "${WORKDIR}" + [[ -n ${GENQMAIL_PV} ]] && unpack "${GENQMAIL_F}" +} + +qmail_spp_src_unpack() { + cd "${WORKDIR}" + [[ -n ${QMAIL_SPP_PV} ]] && unpack "${QMAIL_SPP_F}" +} + +# @FUNCTION: qmail_src_postunpack +# @DESCRIPTION: +# Unpack common config files, and set built configuration (CFLAGS, LDFLAGS, etc) +qmail_src_postunpack() { + cd "${S}" + + qmail_set_cc + + mysplit=${QMAIL_CONF_SPLIT:-23} + is_prime ${mysplit} || die "QMAIL_CONF_SPLIT is not a prime number." + einfo "Using conf-split value of ${mysplit}." + echo -n ${mysplit} > "${S}"/conf-split +} + +qmail_src_compile() { + cd "${S}" + emake it man "$@" || die "make failed" +} + +qmail_spp_src_compile() { + cd "${GENQMAIL_S}"/spp/ + emake || die "make spp failed" +} + +qmail_base_install() { + einfo "Setting up basic directory hierarchy" + diropts -o root -g qmail -m 755 + keepdir "${QMAIL_HOME}"/{,bin,control} + keepdir "${QMAIL_HOME}"/users + diropts -o alias -g qmail -m 755 + keepdir "${QMAIL_HOME}"/alias + + einfo "Adding env.d entry for qmail" + doenvd "${GENQMAIL_S}"/conf/99qmail + + einfo "Installing all qmail software" + insinto "${QMAIL_HOME}"/bin + + insopts -o root -g qmail -m 755 + doins bouncesaying condredirect config-fast datemail except forward maildir2mbox \ + maildirmake mailsubj predate preline qbiff \ + qmail-{inject,qmqpc,qmqpd,qmtpd,qread,qstat,smtpd,tcpok,tcpto,showctl} \ + qreceipt sendmail tcp-env + + # obsolete tools, install if they are still present + for i in elq maildirwatch pinq qail qsmhook; do + [[ -x ${i} ]] && doins ${i} + done + + use pop3 && doins qmail-pop3d + + insopts -o root -g qmail -m 711 + doins qmail-{clean,getpw,local,pw2u,remote,rspawn,send} splogger + use pop3 && doins qmail-popup + + insopts -o root -g qmail -m 700 + doins qmail-{lspawn,newmrh,newu,start} + + insopts -o qmailq -g qmail -m 4711 + doins qmail-queue + + declare -F qmail_base_install_hook >/dev/null && \ + qmail_base_install_hook +} + +qmail_config_install() { + einfo "Installing stock configuration files" + insinto "${QMAIL_HOME}"/control + insopts -o root -g "${GROUP_ROOT}" -m 644 + doins "${GENQMAIL_S}"/control/{conf-*,defaultdelivery} + + einfo "Installing configuration sanity checker and launcher" + insinto "${QMAIL_HOME}"/bin + insopts -o root -g "${GROUP_ROOT}" -m 644 + doins "${GENQMAIL_S}"/control/qmail-config-system + + declare -F qmail_config_install_hook >/dev/null && \ + qmail_config_install_hook +} + +qmail_man_install() { + einfo "Installing manpages and documentation" + + into /usr + doman *.[1578] + dodoc BLURB* INSTALL* PIC* README* REMOVE* \ + SENDMAIL* TEST* THANKS* VERSION* + # notqmail converted the files to markdown + if [ -f CHANGES ]; then + dodoc CHANGES FAQ SECURITY THOUGHTS UPGRADE + else + dodoc CHANGES.md FAQ.md SECURITY.md THOUGHTS.md UPGRADE.md + fi + + declare -F qmail_man_install_hook >/dev/null && \ + qmail_man_install_hook +} + +qmail_sendmail_install() { + einfo "Installing sendmail replacement" + diropts -m 755 + dodir /usr/sbin /usr/lib + + dosym "${QMAIL_HOME}"/bin/sendmail /usr/sbin/sendmail + dosym "${QMAIL_HOME}"/bin/sendmail /usr/lib/sendmail + + declare -F qmail_sendmail_install_hook >/dev/null && \ + qmail_sendmail_install_hook +} + +qmail_maildir_install() { + # use the correct maildirmake + # the courier-imap one has some extensions that are nicer + MAILDIRMAKE="${D}${QMAIL_HOME}/bin/maildirmake" + [[ -e /usr/bin/maildirmake ]] && \ + MAILDIRMAKE="/usr/bin/maildirmake" + + einfo "Setting up the default aliases" + diropts -o alias -g qmail -m 700 + "${MAILDIRMAKE}" "${D}${QMAIL_HOME}"/alias/.maildir + keepdir "${QMAIL_HOME}"/alias/.maildir/{cur,new,tmp} + + for i in "${QMAIL_HOME}"/alias/.qmail-{mailer-daemon,postmaster,root}; do + if [[ ! -f "${ROOT}${i}" ]]; then + touch "${D}${i}" + fowners alias:qmail "${i}" + fi + done + + einfo "Setting up default maildirs in the account skeleton" + diropts -o root -g "${GROUP_ROOT}" -m 755 + insinto /etc/skel + insopts -o root -g "${GROUP_ROOT}" -m 644 + newins "${GENQMAIL_S}"/control/defaultdelivery .qmail.sample + "${MAILDIRMAKE}" "${D}"/etc/skel/.maildir + keepdir /etc/skel/.maildir/{cur,new,tmp} + + declare -F qmail_maildir_install_hook >/dev/null && \ + qmail_maildir_install_hook +} + +qmail_tcprules_install() { + dodir "${TCPRULES_DIR}" + insinto "${TCPRULES_DIR}" + insopts -o root -g "${GROUP_ROOT}" -m 0644 + doins "${GENQMAIL_S}"/tcprules/Makefile.qmail + doins "${GENQMAIL_S}"/tcprules/tcp.qmail-* + use ssl && use pop3 || rm -f "${D}${TCPRULES_DIR}"/tcp.qmail-pop3sd +} + +qmail_supervise_install_one() { + dosupervise ${1} + diropts -o qmaill -g "${GROUP_ROOT}" -m 755 + keepdir /var/log/qmail/${1} +} + +qmail_supervise_install() { + einfo "Installing supervise scripts" + + cd "${GENQMAIL_S}"/supervise + + for i in qmail-{send,smtpd,qmtpd,qmqpd}; do + qmail_supervise_install_one ${i} + done + + if use pop3; then + qmail_supervise_install_one qmail-pop3d + use ssl && qmail_supervise_install_one qmail-pop3sd + fi + + declare -F qmail_supervise_install_hook >/dev/null && \ + qmail_supervise_install_hook +} + +qmail_spp_install() { + einfo "Installing qmail-spp configuration files" + insinto "${QMAIL_HOME}"/control/ + insopts -o root -g "${GROUP_ROOT}" -m 0644 + doins "${GENQMAIL_S}"/spp/smtpplugins + + einfo "Installing qmail-spp plugins" + keepdir "${QMAIL_HOME}"/plugins/ + for i in authlog mfdnscheck ifauthnext tarpit; do + dospp "${GENQMAIL_S}"/spp/${i} + done + + declare -F qmail_spp_install_hook >/dev/null && \ + qmail_spp_install_hook +} + +qmail_ssl_install() { + use gencertdaily && \ + CRON_FOLDER=cron.daily || \ + CRON_FOLDER=cron.hourly + + einfo "Installing SSL Certificate creation script" + insinto "${QMAIL_HOME}"/control + insopts -o root -g "${GROUP_ROOT}" -m 0644 + doins "${GENQMAIL_S}"/ssl/servercert.cnf + + insinto "${QMAIL_HOME}"/bin + insopts -o root -g "${GROUP_ROOT}" -m 0755 + doins "${GENQMAIL_S}"/ssl/mkservercert + + einfo "Installing RSA key generation cronjob" + insinto /etc/${CRON_FOLDER} + insopts -o root -g "${GROUP_ROOT}" -m 0755 + doins "${GENQMAIL_S}"/ssl/qmail-genrsacert.sh + + keepdir "${QMAIL_HOME}"/control/tlshosts + + declare -F qmail_ssl_install_hook >/dev/null && \ + qmail_ssl_install_hook +} + +qmail_src_install() { + export GROUP_ROOT="$(id -gn root)" + qmail_base_install + qmail_config_install + qmail_man_install + qmail_sendmail_install + qmail_maildir_install + qmail_tcprules_install + qmail_supervise_install + + use qmail-spp && qmail_spp_install + use ssl && qmail_ssl_install +} + +qmail_queue_setup() { + if use highvolume; then + myconf="--bigtodo" + else + myconf="--no-bigtodo" + fi + + mysplit=${QMAIL_CONF_SPLIT:-23} + is_prime ${mysplit} || die "QMAIL_CONF_SPLIT is not a prime number." + + einfo "Setting up the message queue hierarchy" + /usr/bin/queue-repair.py --create ${myconf} \ + --split ${mysplit} \ + "${ROOT}${QMAIL_HOME}" >/dev/null || \ + die 'queue-repair failed' +} + +qmail_rootmail_fixup() { + local TMPCMD="ln -sf ${QMAIL_HOME}/alias/.maildir/ ${ROOT}/root/.maildir" + + if [[ -d "${ROOT}"/root/.maildir && ! -L "${ROOT}"/root/.maildir ]] ; then + elog "Previously the qmail ebuilds created /root/.maildir/ but not" + elog "every mail was delivered there. If the directory does not" + elog "contain any mail, please delete it and run:" + elog "${TMPCMD}" + else + ${TMPCMD} + fi + + chown -R alias:qmail "${ROOT}${QMAIL_HOME}"/alias/.maildir 2>/dev/null +} + +qmail_tcprules_fixup() { + mkdir -p "${TCPRULES_DIR}" + local POP_FILES= + use pop3 && POP_FILES="pop3 pop3.cdb" + for f in {smtp,qmtp,qmqp}{,.cdb} ${POP_FILES}; do + old="/etc/tcp.${f}" + new="${TCPRULES_DIR}/tcp.qmail-${f}" + fail=0 + if [[ -f "${old}" && ! -f "${new}" ]]; then + einfo "Moving ${old} to ${new}" + cp "${old}" "${new}" || fail=1 + else + fail=1 + fi + if [[ "${fail}" = 1 && -f "${old}" ]]; then + eerror "Error moving ${old} to ${new}, be sure to check the" + eerror "configuration! You may have already moved the files," + eerror "in which case you can delete ${old}" + fi + done +} + +qmail_tcprules_build() { + for f in tcp.qmail-{smtp,qmtp,qmqp,pop3,pop3s}; do + # please note that we don't check if it exists + # as we want it to make the cdb files anyway! + src="${ROOT}${TCPRULES_DIR}/${f}" + cdb="${ROOT}${TCPRULES_DIR}/${f}.cdb" + tmp="${ROOT}${TCPRULES_DIR}/.${f}.tmp" + [[ -e "${src}" ]] && tcprules "${cdb}" "${tmp}" < "${src}" + done +} + +qmail_config_notice() { + elog + elog "To setup ${PN} to run out-of-the-box on your system, run:" + elog "emerge --config =${CATEGORY}/${PF}" +} + +qmail_supervise_config_notice() { + elog + elog "To start qmail at boot you have to add svscan to your startup" + elog "and create the following links:" + elog "ln -s ${SUPERVISE_DIR}/qmail-send /service/qmail-send" + elog "ln -s ${SUPERVISE_DIR}/qmail-smtpd /service/qmail-smtpd" + elog + if use pop3; then + elog "To start the pop3 server as well, create the following link:" + elog "ln -s ${SUPERVISE_DIR}/qmail-pop3d /service/qmail-pop3d" + elog + if use ssl; then + elog "To start the pop3s server as well, create the following link:" + elog "ln -s ${SUPERVISE_DIR}/qmail-pop3sd /service/qmail-pop3sd" + elog + fi + fi + elog "Additionally, the QMTP and QMQP protocols are supported, " + elog "and can be started as:" + elog "ln -s ${SUPERVISE_DIR}/qmail-qmtpd /service/qmail-qmtpd" + elog "ln -s ${SUPERVISE_DIR}/qmail-qmqpd /service/qmail-qmqpd" + elog + elog "Additionally, if you wish to run qmail right now, you should " + elog "run this before anything else:" + elog "source /etc/profile" +} + +qmail_config_fast() { + if [[ ${ROOT} = / ]]; then + local host=$(hostname --fqdn) + + if [[ -z "${host}" ]]; then + eerror + eerror "Cannot determine your fully-qualified hostname" + eerror "Please setup your /etc/hosts as described in" + eerror "https://www.gentoo.org/doc/en/handbook/handbook-x86.xml?part=1&chap=8#doc_chap2_sect4" + eerror + die "cannot determine FQDN" + fi + + if [[ ! -f "${ROOT}${QMAIL_HOME}"/control/me ]]; then + "${ROOT}${QMAIL_HOME}"/bin/config-fast ${host} + fi + else + ewarn "Skipping some configuration as it MUST be run on the final host" + fi +} + +qmail_tcprules_config() { + local localips ip tcpstring line proto f + + einfo "Accepting relaying by default from all ips configured on this machine." + + # Start with iproute2 as ifconfig is deprecated, and ifconfig does not handle + # additional addresses added via iproute2. + # Note: We have to strip off the packed netmask w/e.g. 192.168.0.2/24 + localips=$(ip address show 2>/dev/null | awk '$1 == "inet" {print $2}' | sed 's:/.*::') + if [[ -z ${localips} ]] ; then + # Hello old friend. Maybe you can tell us at least something. + localips=$(ifconfig | awk '$1 == "inet" {print $2}') + fi + + tcpstring=':allow,RELAYCLIENT="",RBLSMTPD=""' + + for ip in ${localips}; do + line="${ip}${tcpstring}" + for proto in smtp qmtp qmqp; do + f="${EROOT}${TCPRULES_DIR}/tcp.qmail-${proto}" + egrep -qs "${line}" "${f}" || echo "${line}" >> "${f}" + done + done +} + +qmail_ssl_generate() { + CRON_FOLDER=cron.hourly + use gencertdaily && CRON_FOLDER=cron.daily + + ebegin "Generating RSA keys for SSL/TLS, this can take some time" + "${ROOT}"/etc/${CRON_FOLDER}/qmail-genrsacert.sh + eend $? + + einfo "Creating a self-signed ssl-certificate:" + "${ROOT}${QMAIL_HOME}"/bin/mkservercert + + einfo "If you want to have a properly signed certificate " + einfo "instead, do the following:" + # space at the end of the string because of the current implementation + # of einfo + einfo "openssl req -new -nodes -out req.pem \\ " + einfo " -config ${QMAIL_HOME}/control/servercert.cnf \\ " + einfo " -keyout ${QMAIL_HOME}/control/servercert.pem" + einfo "Send req.pem to your CA to obtain signed_req.pem, and do:" + einfo "cat signed_req.pem >> ${QMAIL_HOME}/control/servercert.pem" +} diff --git a/eclass/qmake-utils.eclass b/eclass/qmake-utils.eclass new file mode 100644 index 0000000..0d49eb9 --- /dev/null +++ b/eclass/qmake-utils.eclass @@ -0,0 +1,174 @@ +# Copyright 1999-2020 Gentoo Authors +# Distributed under the terms of the GNU General Public License v2 + +# @ECLASS: qmake-utils.eclass +# @MAINTAINER: +# qt@gentoo.org +# @AUTHOR: +# Davide Pesavento <pesa@gentoo.org> +# @SUPPORTED_EAPIS: 7 +# @BLURB: Common functions for qmake-based packages. +# @DESCRIPTION: +# Utility eclass providing wrapper functions for Qt5 qmake. +# +# This eclass does not set any metadata variables nor export any phase +# functions. It can be inherited safely. + +if [[ -z ${_QMAKE_UTILS_ECLASS} ]]; then +_QMAKE_UTILS_ECLASS=1 + +case ${EAPI} in + 7) ;; + *) die "EAPI=${EAPI:-0} is not supported" ;; +esac + +inherit toolchain-funcs + +# @FUNCTION: _qmake-utils_banned_func +# @INTERNAL +# @DESCRIPTION: +# Banned functions are banned. +_qmake-utils_banned_func() { + die "${FUNCNAME[1]} is banned in EAPI 7 and later" +} + +# @FUNCTION: qt4_get_bindir +# @INTERNAL +# @DESCRIPTION: +# Banned. +qt4_get_bindir() { + _qmake-utils_banned_func +} + +# @FUNCTION: qt4_get_headerdir +# @INTERNAL +# @DESCRIPTION: +# Banned. +qt4_get_headerdir() { + _qmake-utils_banned_func +} + +# @FUNCTION: qt4_get_libdir +# @INTERNAL +# @DESCRIPTION: +# Banned. +qt4_get_libdir() { + _qmake-utils_banned_func +} + +# @FUNCTION: qt4_get_mkspecsdir +# @INTERNAL +# @DESCRIPTION: +# Banned. +qt4_get_mkspecsdir() { + _qmake-utils_banned_func +} + +# @FUNCTION: qt4_get_plugindir +# @INTERNAL +# @DESCRIPTION: +# Banned. +qt4_get_plugindir() { + _qmake-utils_banned_func +} + +# @FUNCTION: qt5_get_bindir +# @DESCRIPTION: +# Echoes the directory where Qt5 binaries are installed. +# EPREFIX is already prepended to the returned path. +qt5_get_bindir() { + echo ${EPREFIX}$(qt5_get_libdir)/qt5/bin +} + +# @FUNCTION: qt5_get_headerdir +# @DESCRIPTION: +# Echoes the directory where Qt5 headers are installed. +qt5_get_headerdir() { + echo /usr/include/qt5 +} + +# @FUNCTION: qt5_get_libdir +# @DESCRIPTION: +# Echoes the directory where Qt5 libraries are installed. +qt5_get_libdir() { + echo /usr/$(get_libdir) +} + +# @FUNCTION: qt5_get_mkspecsdir +# @DESCRIPTION: +# Echoes the directory where Qt5 mkspecs are installed. +qt5_get_mkspecsdir() { + echo $(qt5_get_libdir)/qt5/mkspecs +} + +# @FUNCTION: qt5_get_plugindir +# @DESCRIPTION: +# Echoes the directory where Qt5 plugins are installed. +qt5_get_plugindir() { + echo $(qt5_get_libdir)/qt5/plugins +} + +# @FUNCTION: qmake-utils_find_pro_file +# @INTERNAL +# @DESCRIPTION: +# Banned. +qmake-utils_find_pro_file() { + _qmake-utils_banned_func +} + +# @FUNCTION: eqmake4 +# @INTERNAL +# @DESCRIPTION: +# Banned. +eqmake4() { + _qmake-utils_banned_func +} + +# @FUNCTION: eqmake5 +# @USAGE: [arguments for qmake] +# @DESCRIPTION: +# Wrapper for Qt5's qmake. All arguments are passed to qmake. +# +# For recursive build systems, i.e. those based on the subdirs template, +# you should run eqmake5 on the top-level project file only, unless you +# have a valid reason to do otherwise. During the building, qmake will +# be automatically re-invoked with the right arguments on every directory +# specified inside the top-level project file. +eqmake5() { + debug-print-function ${FUNCNAME} "$@" + + ebegin "Running qmake" + + "$(qt5_get_bindir)"/qmake \ + -makefile \ + QMAKE_AR="$(tc-getAR) cqs" \ + QMAKE_CC="$(tc-getCC)" \ + QMAKE_LINK_C="$(tc-getCC)" \ + QMAKE_LINK_C_SHLIB="$(tc-getCC)" \ + QMAKE_CXX="$(tc-getCXX)" \ + QMAKE_LINK="$(tc-getCXX)" \ + QMAKE_LINK_SHLIB="$(tc-getCXX)" \ + QMAKE_OBJCOPY="$(tc-getOBJCOPY)" \ + QMAKE_RANLIB= \ + QMAKE_STRIP= \ + QMAKE_CFLAGS="${CFLAGS}" \ + QMAKE_CFLAGS_RELEASE= \ + QMAKE_CFLAGS_DEBUG= \ + QMAKE_CXXFLAGS="${CXXFLAGS}" \ + QMAKE_CXXFLAGS_RELEASE= \ + QMAKE_CXXFLAGS_DEBUG= \ + QMAKE_LFLAGS="${LDFLAGS}" \ + QMAKE_LFLAGS_RELEASE= \ + QMAKE_LFLAGS_DEBUG= \ + "$@" + + if ! eend $? ; then + echo + eerror "Running qmake has failed! (see above for details)" + eerror "This shouldn't happen - please send a bug report to https://bugs.gentoo.org/" + echo + die "eqmake5 failed" + fi +} + +fi diff --git a/eclass/qt5-build.eclass b/eclass/qt5-build.eclass new file mode 100644 index 0000000..6698b69 --- /dev/null +++ b/eclass/qt5-build.eclass @@ -0,0 +1,934 @@ +# Copyright 1999-2021 Gentoo Authors +# Distributed under the terms of the GNU General Public License v2 + +# @ECLASS: qt5-build.eclass +# @MAINTAINER: +# qt@gentoo.org +# @AUTHOR: +# Davide Pesavento <pesa@gentoo.org> +# @SUPPORTED_EAPIS: 7 +# @BLURB: Eclass for Qt5 split ebuilds. +# @DESCRIPTION: +# This eclass contains various functions that are used when building Qt5. +# Requires EAPI 7. + +if [[ ${CATEGORY} != dev-qt ]]; then + die "qt5-build.eclass is only to be used for building Qt 5" +fi + +case ${EAPI} in + 7) : ;; + *) die "qt5-build.eclass: unsupported EAPI=${EAPI:-0}" ;; +esac + +# @ECLASS-VARIABLE: QT5_MODULE +# @PRE_INHERIT +# @DESCRIPTION: +# The upstream name of the module this package belongs to. Used for +# SRC_URI and EGIT_REPO_URI. Must be set before inheriting the eclass. +: ${QT5_MODULE:=${PN}} + +# @ECLASS-VARIABLE: QT5_TARGET_SUBDIRS +# @DEFAULT_UNSET +# @DESCRIPTION: +# Array variable containing the source directories that should be built. +# All paths must be relative to ${S}. + +# @ECLASS-VARIABLE: QT5_GENTOO_CONFIG +# @DEFAULT_UNSET +# @DESCRIPTION: +# Array of <useflag:feature:macro> triplets that are evaluated in src_install +# to generate the per-package list of enabled QT_CONFIG features and macro +# definitions, which are then merged together with all other Qt5 packages +# installed on the system to obtain the global qconfig.{h,pri} files. + +# @ECLASS-VARIABLE: QT5_GENTOO_PRIVATE_CONFIG +# @DEFAULT_UNSET +# @DESCRIPTION: +# Array of <useflag:feature> pairs that are evaluated in src_install +# to generate the per-package list of enabled QT.global_private features, +# which are then merged together with all other Qt5 packages installed on the +# system to obtain the global qmodule.pri file. + +# @ECLASS-VARIABLE: VIRTUALX_REQUIRED +# @DESCRIPTION: +# For proper description see virtualx.eclass man page. +# Here we redefine default value to be manual, if your package needs virtualx +# for tests you should proceed with setting VIRTUALX_REQUIRED=test. +: ${VIRTUALX_REQUIRED:=manual} + +inherit estack flag-o-matic toolchain-funcs virtualx + +HOMEPAGE="https://www.qt.io/" +LICENSE="|| ( GPL-2 GPL-3 LGPL-3 ) FDL-1.3" +SLOT=5/$(ver_cut 1-2) + +QT5_MINOR_VERSION=$(ver_cut 2) +readonly QT5_MINOR_VERSION + +case ${PV} in + 5.??.9999) + # git stable branch + QT5_BUILD_TYPE="live" + EGIT_BRANCH=${PV%.9999} + ;; + *_alpha*|*_beta*|*_rc*) + # development release + QT5_BUILD_TYPE="release" + MY_P=${QT5_MODULE}-everywhere-src-${PV/_/-} + SRC_URI="https://download.qt.io/development_releases/qt/${PV%.*}/${PV/_/-}/submodules/${MY_P}.tar.xz" + S=${WORKDIR}/${MY_P} + ;; + *) + # official stable release + QT5_BUILD_TYPE="release" + MY_P=${QT5_MODULE}-everywhere-src-${PV} + SRC_URI="https://download.qt.io/official_releases/qt/${PV%.*}/${PV}/submodules/${MY_P}.tar.xz" + S=${WORKDIR}/${MY_P} + ;; +esac +readonly QT5_BUILD_TYPE + +EGIT_REPO_URI=( + "https://code.qt.io/qt/${QT5_MODULE}.git" + "https://github.com/qt/${QT5_MODULE}.git" +) +[[ ${QT5_BUILD_TYPE} == live ]] && inherit git-r3 + +# @ECLASS-VARIABLE: QT5_BUILD_DIR +# @OUTPUT_VARIABLE +# @DESCRIPTION: +# Build directory for out-of-source builds. +: ${QT5_BUILD_DIR:=${S}_build} + +IUSE="debug test" + +if [[ ${QT5_BUILD_TYPE} == release ]]; then + RESTRICT+=" test" # bug 457182 +else + RESTRICT+=" !test? ( test )" +fi + +BDEPEND=" + dev-lang/perl + virtual/pkgconfig +" +if [[ ${PN} != qttest ]]; then + DEPEND+=" test? ( ~dev-qt/qttest-$(ver_cut 1-3) )" +fi + +###### Phase functions ###### + +EXPORT_FUNCTIONS src_unpack src_prepare src_configure src_compile src_install src_test pkg_postinst pkg_postrm + +# @FUNCTION: qt5-build_src_unpack +# @DESCRIPTION: +# Unpacks the sources. +qt5-build_src_unpack() { + # bug 307861 + if [[ ${PN} == qtwebengine ]]; then + eshopts_push -s extglob + if is-flagq '-g?(gdb)?([1-9])'; then + ewarn + ewarn "You have enabled debug info (probably have -g or -ggdb in your CFLAGS/CXXFLAGS)." + ewarn "You may experience really long compilation times and/or increased memory usage." + ewarn "If compilation fails, please try removing -g/-ggdb before reporting a bug." + ewarn + fi + eshopts_pop + fi + + case ${QT5_BUILD_TYPE} in + live) git-r3_src_unpack ;& + release) default ;; + esac +} + +# @FUNCTION: qt5-build_src_prepare +# @DESCRIPTION: +# Prepares the environment and patches the sources if necessary. +qt5-build_src_prepare() { + qt5_prepare_env + + if [[ ${QT5_MODULE} == qtbase ]]; then + qt5_symlink_tools_to_build_dir + + # Avoid unnecessary qmake recompilations + sed -i -e "/Creating qmake/i if [ '!' -e \"\$outpath/bin/qmake\" ]; then" \ + -e '/echo "Done."/a fi' configure || die "sed failed (skip qmake bootstrap)" + + # Respect CC, CXX, *FLAGS, MAKEOPTS and EXTRA_EMAKE when bootstrapping qmake + sed -i -e "/outpath\/qmake\".*\"\$MAKE\")/ s|)| \ + ${MAKEOPTS} ${EXTRA_EMAKE} 'CC=$(tc-getCC)' 'CXX=$(tc-getCXX)' \ + 'QMAKE_CFLAGS=${CFLAGS}' 'QMAKE_CXXFLAGS=${CXXFLAGS}' 'QMAKE_LFLAGS=${LDFLAGS}'&|" \ + -e 's/\(setBootstrapVariable\s\+\|EXTRA_C\(XX\)\?FLAGS=.*\)QMAKE_C\(XX\)\?FLAGS_\(DEBUG\|RELEASE\).*/:/' \ + configure || die "sed failed (respect env for qmake build)" + sed -i -e '/^CPPFLAGS\s*=/ s/-g //' \ + qmake/Makefile.unix || die "sed failed (CPPFLAGS for qmake build)" + + # Respect CXX in bsymbolic_functions, fvisibility, precomp, and a few other tests + sed -i -e "/^QMAKE_CONF_COMPILER=/ s:=.*:=\"$(tc-getCXX)\":" \ + configure || die "sed failed (QMAKE_CONF_COMPILER)" + + # Respect build variables in configure tests (bug #639494) + sed -i -e "s|\"\$outpath/bin/qmake\" \"\$relpathMangled\" -- \"\$@\"|& $(qt5_qmake_args) |" configure || die + fi + + default +} + +# @FUNCTION: qt5-build_src_configure +# @DESCRIPTION: +# Runs qmake in the target directories. For packages +# in qtbase, ./configure is also run before qmake. +qt5-build_src_configure() { + if [[ ${QT5_MODULE} == qtbase ]]; then + qt5_base_configure + fi + if [[ ${QT5_MODULE} == qttools ]] && [[ -z ${QT5_TARGET_SUBDIRS[@]} ]]; then + qt5_tools_configure + fi + + qt5_foreach_target_subdir qt5_qmake +} + +# @FUNCTION: qt5-build_src_compile +# @DESCRIPTION: +# Runs emake in the target directories. +qt5-build_src_compile() { + qt5_foreach_target_subdir emake +} + +# @FUNCTION: qt5-build_src_test +# @DESCRIPTION: +# Runs tests in the target directories. +qt5-build_src_test() { + # disable broken cmake tests (bug 474004) + local myqmakeargs=("${myqmakeargs[@]}" -after SUBDIRS-=cmake SUBDIRS-=installed_cmake) + + qt5_foreach_target_subdir qt5_qmake + qt5_foreach_target_subdir emake + + # create a custom testrunner script that correctly sets + # LD_LIBRARY_PATH before executing the given test + local testrunner=${QT5_BUILD_DIR}/gentoo-testrunner + cat > "${testrunner}" <<-_EOF_ || die + #!/bin/sh + export LD_LIBRARY_PATH="${QT5_BUILD_DIR}/lib:${QT5_LIBDIR}" + "\$@" + _EOF_ + chmod +x "${testrunner}" + + set -- qt5_foreach_target_subdir emake TESTRUNNER="'${testrunner}'" check + if [[ ${VIRTUALX_REQUIRED} == test ]]; then + virtx "$@" + else + "$@" + fi +} + +# @FUNCTION: qt5-build_src_install +# @DESCRIPTION: +# Runs emake install in the target directories. +qt5-build_src_install() { + qt5_foreach_target_subdir emake INSTALL_ROOT="${D}" install + + if [[ ${PN} == qtcore ]]; then + pushd "${QT5_BUILD_DIR}" >/dev/null || die + + set -- emake INSTALL_ROOT="${D}" \ + sub-qmake-qmake-aux-pro-install_subtargets \ + install_{syncqt,mkspecs} + + einfo "Running $*" + "$@" + + popd >/dev/null || die + + # install an empty Gentoo/gentoo-qconfig.h in ${D} + # so that it's placed under package manager control + > "${T}"/gentoo-qconfig.h + ( + insinto "${QT5_HEADERDIR#${EPREFIX}}"/Gentoo + doins "${T}"/gentoo-qconfig.h + ) + + # include gentoo-qconfig.h at the beginning of QtCore/qconfig.h + sed -i -e '1i #include <Gentoo/gentoo-qconfig.h>\n' \ + "${D}${QT5_HEADERDIR}"/QtCore/qconfig.h \ + || die "sed failed (qconfig.h)" + + # install qtchooser configuration file + cat > "${T}/qt5-${CHOST}.conf" <<-_EOF_ || die + ${QT5_BINDIR} + ${QT5_LIBDIR} + _EOF_ + + ( + insinto /etc/xdg/qtchooser + doins "${T}/qt5-${CHOST}.conf" + ) + + # convenience symlinks + dosym qt5-"${CHOST}".conf /etc/xdg/qtchooser/5.conf + dosym qt5-"${CHOST}".conf /etc/xdg/qtchooser/qt5.conf + # TODO bug 522646: write an eselect module to manage default.conf + dosym qt5.conf /etc/xdg/qtchooser/default.conf + fi + + qt5_install_module_config + + # prune libtool files + find "${D}" -name '*.la' -type f -delete || die +} + +# @FUNCTION: qt5-build_pkg_postinst +# @DESCRIPTION: +# Regenerate configuration after installation or upgrade/downgrade. +qt5-build_pkg_postinst() { + qt5_regenerate_global_configs +} + +# @FUNCTION: qt5-build_pkg_postrm +# @DESCRIPTION: +# Regenerate configuration when a module is completely removed. +qt5-build_pkg_postrm() { + if [[ -z ${REPLACED_BY_VERSION} && ${PN} != qtcore ]]; then + qt5_regenerate_global_configs + fi +} + + +###### Public helpers ###### + +# @FUNCTION: qt_use +# @USAGE: <flag> [feature] [enableval] +# @DESCRIPTION: +# <flag> is the name of a flag in IUSE. +# +# Outputs "-${enableval}-${feature}" if <flag> is enabled, "-no-${feature}" +# otherwise. If [feature] is not specified, <flag> is used in its place. +# If [enableval] is not specified, the "-${enableval}" prefix is omitted. +qt_use() { + [[ $# -ge 1 ]] || die "${FUNCNAME}() requires at least one argument" + + usex "$1" "${3:+-$3}-${2:-$1}" "-no-${2:-$1}" +} + +# @FUNCTION: qt_use_compile_test +# @USAGE: <flag> [config] +# @DESCRIPTION: +# <flag> is the name of a flag in IUSE. +# [config] is the argument of qtCompileTest, defaults to <flag>. +# +# This function is useful to disable optional dependencies that are checked +# at qmake-time using the qtCompileTest() function. If <flag> is disabled, +# the compile test is skipped and the dependency is assumed to be unavailable, +# i.e. the corresponding feature will be disabled. Note that all invocations +# of this function must happen before calling qt5-build_src_configure. +qt_use_compile_test() { + [[ $# -ge 1 ]] || die "${FUNCNAME}() requires at least one argument" + + if ! use "$1"; then + mkdir -p "${QT5_BUILD_DIR}" || die + echo "CONFIG += done_config_${2:-$1}" >> "${QT5_BUILD_DIR}"/.qmake.cache || die + fi +} + +# @FUNCTION: qt_use_disable_config +# @USAGE: <flag> <config> <files...> +# @DESCRIPTION: +# <flag> is the name of a flag in IUSE. +# <config> is the (lowercase) name of a Qt5 config entry. +# <files...> is a list of one or more qmake project files. +# +# This function patches <files> to treat <config> as disabled +# when <flag> is disabled, otherwise it does nothing. +# This can be useful to avoid an automagic dependency when the config entry +# is enabled on the system but the corresponding USE flag is disabled. +qt_use_disable_config() { + [[ $# -ge 3 ]] || die "${FUNCNAME}() requires at least three arguments" + + local flag=$1 + local config=$2 + shift 2 + + if ! use "${flag}"; then + echo "$@" | xargs sed -i -e "s/qtConfig(${config})/false/g" || die + fi +} + +# @FUNCTION: qt_use_disable_mod +# @USAGE: <flag> <module> <files...> +# @DESCRIPTION: +# <flag> is the name of a flag in IUSE. +# <module> is the (lowercase) name of a Qt5 module. +# <files...> is a list of one or more qmake project files. +# +# This function patches <files> to treat <module> as not installed +# when <flag> is disabled, otherwise it does nothing. +# This can be useful to avoid an automagic dependency when the module +# is present on the system but the corresponding USE flag is disabled. +qt_use_disable_mod() { + [[ $# -ge 3 ]] || die "${FUNCNAME}() requires at least three arguments" + + local flag=$1 + local module=$2 + shift 2 + + if ! use "${flag}"; then + echo "$@" | xargs sed -i -e "s/qtHaveModule(${module})/false/g" || die + fi +} + + +###### Internal functions ###### + +# @FUNCTION: qt5_prepare_env +# @INTERNAL +# @DESCRIPTION: +# Prepares the environment for building Qt. +qt5_prepare_env() { + # setup installation directories + # note: keep paths in sync with qmake-utils.eclass + QT5_PREFIX=${EPREFIX}/usr + QT5_HEADERDIR=${QT5_PREFIX}/include/qt5 + QT5_LIBDIR=${QT5_PREFIX}/$(get_libdir) + QT5_ARCHDATADIR=${QT5_PREFIX}/$(get_libdir)/qt5 + QT5_BINDIR=${QT5_ARCHDATADIR}/bin + QT5_PLUGINDIR=${QT5_ARCHDATADIR}/plugins + QT5_LIBEXECDIR=${QT5_ARCHDATADIR}/libexec + QT5_IMPORTDIR=${QT5_ARCHDATADIR}/imports + QT5_QMLDIR=${QT5_ARCHDATADIR}/qml + QT5_DATADIR=${QT5_PREFIX}/share/qt5 + QT5_DOCDIR=${QT5_PREFIX}/share/qt5-doc + QT5_TRANSLATIONDIR=${QT5_DATADIR}/translations + QT5_EXAMPLESDIR=${QT5_DATADIR}/examples + QT5_TESTSDIR=${QT5_DATADIR}/tests + QT5_SYSCONFDIR=${EPREFIX}/etc/xdg + readonly QT5_PREFIX QT5_HEADERDIR QT5_LIBDIR QT5_ARCHDATADIR \ + QT5_BINDIR QT5_PLUGINDIR QT5_LIBEXECDIR QT5_IMPORTDIR \ + QT5_QMLDIR QT5_DATADIR QT5_DOCDIR QT5_TRANSLATIONDIR \ + QT5_EXAMPLESDIR QT5_TESTSDIR QT5_SYSCONFDIR + + if [[ ${QT5_MODULE} == qtbase ]]; then + # see mkspecs/features/qt_config.prf + export QMAKEMODULES="${QT5_BUILD_DIR}/mkspecs/modules:${S}/mkspecs/modules:${QT5_ARCHDATADIR}/mkspecs/modules" + fi +} + +# @FUNCTION: qt5_foreach_target_subdir +# @INTERNAL +# @DESCRIPTION: +# Executes the command given as argument from inside each directory +# listed in QT5_TARGET_SUBDIRS. Handles autotests subdirs automatically. +qt5_foreach_target_subdir() { + [[ -z ${QT5_TARGET_SUBDIRS[@]} ]] && QT5_TARGET_SUBDIRS=("") + + local subdir= + for subdir in "${QT5_TARGET_SUBDIRS[@]}"; do + if [[ ${EBUILD_PHASE} == test ]]; then + subdir=tests/auto${subdir#src} + [[ -d ${S}/${subdir} ]] || continue + fi + + local msg="Running $* ${subdir:+in ${subdir}}" + einfo "${msg}" + + mkdir -p "${QT5_BUILD_DIR}/${subdir}" || die -n || return $? + pushd "${QT5_BUILD_DIR}/${subdir}" >/dev/null || die -n || return $? + + "$@" || die -n "${msg} failed" || return $? + + popd >/dev/null || die -n || return $? + done +} + +# @FUNCTION: qt5_symlink_tools_to_build_dir +# @INTERNAL +# @DESCRIPTION: +# Symlinks qmake and a few other tools to QT5_BUILD_DIR, +# so that they can be used when building other modules. +qt5_symlink_tools_to_build_dir() { + local tool= tools=() + if [[ ${PN} != qtcore ]]; then + tools+=(qmake moc rcc qlalr) + [[ ${PN} != qtdbus ]] && tools+=(qdbuscpp2xml qdbusxml2cpp) + [[ ${PN} != qtwidgets ]] && tools+=(uic) + fi + + mkdir -p "${QT5_BUILD_DIR}"/bin || die + pushd "${QT5_BUILD_DIR}"/bin >/dev/null || die + + for tool in "${tools[@]}"; do + [[ -e ${QT5_BINDIR}/${tool} ]] || continue + ln -s "${QT5_BINDIR}/${tool}" . || die "failed to symlink ${tool}" + done + + popd >/dev/null || die +} + +# @FUNCTION: qt5_base_configure +# @INTERNAL +# @DESCRIPTION: +# Runs ./configure for modules belonging to qtbase. +qt5_base_configure() { + # setup toolchain variables used by configure + tc-export AR CC CXX OBJDUMP RANLIB STRIP + export LD="$(tc-getCXX)" + + # bug 633838 + unset QMAKESPEC XQMAKESPEC QMAKEPATH QMAKEFEATURES + + # configure arguments + local conf=( + # installation paths + -prefix "${QT5_PREFIX}" + -bindir "${QT5_BINDIR}" + -headerdir "${QT5_HEADERDIR}" + -libdir "${QT5_LIBDIR}" + -archdatadir "${QT5_ARCHDATADIR}" + -plugindir "${QT5_PLUGINDIR}" + -libexecdir "${QT5_LIBEXECDIR}" + -importdir "${QT5_IMPORTDIR}" + -qmldir "${QT5_QMLDIR}" + -datadir "${QT5_DATADIR}" + -docdir "${QT5_DOCDIR}" + -translationdir "${QT5_TRANSLATIONDIR}" + -sysconfdir "${QT5_SYSCONFDIR}" + -examplesdir "${QT5_EXAMPLESDIR}" + -testsdir "${QT5_TESTSDIR}" + + # force appropriate compiler + $(if use kernel_FreeBSD; then + if tc-is-gcc; then + echo -platform freebsd-g++ + elif tc-is-clang; then + echo -platform freebsd-clang + fi + fi) + $(if use kernel_linux; then + if tc-is-gcc; then + echo -platform linux-g++ + elif tc-is-clang; then + echo -platform linux-clang + fi + fi) + + # configure in release mode by default, + # override via the CONFIG qmake variable + -release + -no-separate-debug-info + + # no need to forcefully build host tools in optimized mode, + # just follow the overall debug/release build type + -no-optimized-tools + + # licensing stuff + -opensource -confirm-license + + # autodetect the highest supported version of the C++ standard + #-c++std <c++11|c++14|c++1z> + + # build shared libraries + -shared + + # disabling accessibility is not recommended by upstream, as + # it will break QStyle and may break other internal parts of Qt + -accessibility + + # disable all SQL drivers by default, override in qtsql + -no-sql-db2 -no-sql-ibase -no-sql-mysql -no-sql-oci -no-sql-odbc + -no-sql-psql -no-sql-sqlite -no-sql-sqlite2 -no-sql-tds + + # MIPS DSP instruction set extensions + $(is-flagq -mno-dsp && echo -no-mips_dsp) + $(is-flagq -mno-dspr2 && echo -no-mips_dspr2) + + # use pkg-config to detect include and library paths + -pkg-config + + # prefer system libraries (only common hard deps here) + -system-zlib + -system-pcre + -system-doubleconversion + + # disable everything to prevent automagic deps (part 1) + -no-mtdev + -no-journald -no-syslog + -no-libpng -no-libjpeg + -no-freetype -no-harfbuzz + -no-openssl -no-libproxy + -no-feature-gssapi + -no-xcb-xlib + + # bug 672340 + -no-xkbcommon + -no-bundled-xcb-xinput + + # cannot use -no-gif because there is no way to override it later + #-no-gif + + # always enable glib event loop support + -glib + + # disable everything to prevent automagic deps (part 2) + -no-gtk + + # exclude examples and tests from default build + -nomake examples + -nomake tests + -no-compile-examples + + # disable rpath on non-prefix (bugs 380415 and 417169) + $(usex prefix '' -no-rpath) + + # print verbose information about each configure test + -verbose + + # disable everything to prevent automagic deps (part 3) + -no-cups -no-evdev -no-tslib -no-icu -no-fontconfig -no-dbus + + # let portage handle stripping + -no-strip + + # precompiled headers can cause problems on hardened, so turn them off + -no-pch + + # link-time code generation is not something we want to enable by default + -no-ltcg + + # reduced relocations cause major breakage on at least arm and ppc, so + # don't specify anything and let the configure figure out if they are + # supported; see also https://bugreports.qt.io/browse/QTBUG-36129 + #-reduce-relocations + + # use the system linker (gold will be selected automagically otherwise) + $(tc-ld-is-gold && echo -use-gold-linker || echo -no-use-gold-linker) + + # disable all platform plugins by default, override in qtgui + -no-xcb -no-eglfs -no-kms -no-gbm -no-directfb -no-linuxfb + + # always enable session management support: it doesn't need extra deps + # at configure time and turning it off is dangerous, see bug 518262 + -sm + + # typedef qreal to double (warning: changing this flag breaks the ABI) + -qreal double + + # disable OpenGL and EGL support by default, override in qtgui, + # qtopengl, qtprintsupport and qtwidgets + -no-opengl -no-egl + + # disable libinput-based generic plugin by default, override in qtgui + -no-libinput + + # respect system proxies by default: it's the most natural + # setting, and it'll become the new upstream default in 5.8 + -system-proxies + + # do not build with -Werror + -no-warnings-are-errors + + # enable in respective modules to avoid poisoning QT.global_private.enabled_features + -no-gui -no-widgets + + # QTBUG-76521, default will change to zstd in Qt6 + -no-zstd + + # module-specific options + "${myconf[@]}" + ) + + pushd "${QT5_BUILD_DIR}" >/dev/null || die + + einfo "Configuring with: ${conf[@]}" + "${S}"/configure "${conf[@]}" || die "configure failed" + + # a forwarding header is no longer created since 5.8, causing the system + # config to always be used. bug 599636 + # ${S}/include does not exist in live sources + local basedir="${S}/" + [[ ${QT5_BUILD_TYPE} == live ]] && basedir="" + cp src/corelib/global/qconfig.h "${basedir}"include/QtCore/ || die + + popd >/dev/null || die + +} + +# @FUNCTION: qt5_tools_configure +# @INTERNAL +# @DESCRIPTION: +# Disables modules other than ${PN} belonging to qttools. +qt5_tools_configure() { + # configure arguments + local qmakeargs=( + -- + # not packaged in Gentoo + -no-feature-distancefieldgenerator + -no-feature-kmap2qmap + -no-feature-macdeployqt + -no-feature-makeqpf + -no-feature-qev + -no-feature-qtattributionsscanner + -no-feature-windeployqt + -no-feature-winrtrunner + ) + + local i + for i in assistant designer linguist pixeltool qdbus qdoc qtdiag qtpaths qtplugininfo; do + [[ ${PN} == ${i} ]] || qmakeargs+=( -no-feature-${i} ) + done + + # allow the ebuild to override what we set here + myqmakeargs=( "${qmakeargs[@]}" "${myqmakeargs[@]}" ) +} + +# @FUNCTION: qt5_qmake_args +# @INTERNAL +# @DESCRIPTION: +# Helper function to get the various toolchain-related variables. +qt5_qmake_args() { + echo \ + QMAKE_AR=\"$(tc-getAR)\" \ + QMAKE_CC=\"$(tc-getCC)\" \ + QMAKE_LINK_C=\"$(tc-getCC)\" \ + QMAKE_LINK_C_SHLIB=\"$(tc-getCC)\" \ + QMAKE_CXX=\"$(tc-getCXX)\" \ + QMAKE_LINK=\"$(tc-getCXX)\" \ + QMAKE_LINK_SHLIB=\"$(tc-getCXX)\" \ + QMAKE_OBJCOPY=\"$(tc-getOBJCOPY)\" \ + QMAKE_RANLIB= \ + QMAKE_STRIP=\"$(tc-getSTRIP)\" \ + QMAKE_CFLAGS=\"${CFLAGS}\" \ + QMAKE_CFLAGS_RELEASE= \ + QMAKE_CFLAGS_DEBUG= \ + QMAKE_CXXFLAGS=\"${CXXFLAGS}\" \ + QMAKE_CXXFLAGS_RELEASE= \ + QMAKE_CXXFLAGS_DEBUG= \ + QMAKE_LFLAGS=\"${LDFLAGS}\" \ + QMAKE_LFLAGS_RELEASE= \ + QMAKE_LFLAGS_DEBUG= +} + +# @FUNCTION: qt5_qmake +# @INTERNAL +# @DESCRIPTION: +# Helper function that runs qmake in the current target subdir. +# Intended to be called by qt5_foreach_target_subdir(). +qt5_qmake() { + local projectdir=${PWD/#${QT5_BUILD_DIR}/${S}} + local qmakepath= + if [[ ${QT5_MODULE} == qtbase ]]; then + qmakepath=${QT5_BUILD_DIR}/bin + else + qmakepath=${QT5_BINDIR} + fi + + "${qmakepath}"/qmake \ + "${projectdir}" \ + CONFIG+=$(usex debug debug release) \ + CONFIG-=$(usex debug release debug) \ + QMAKE_AR="$(tc-getAR) cqs" \ + QMAKE_CC="$(tc-getCC)" \ + QMAKE_LINK_C="$(tc-getCC)" \ + QMAKE_LINK_C_SHLIB="$(tc-getCC)" \ + QMAKE_CXX="$(tc-getCXX)" \ + QMAKE_LINK="$(tc-getCXX)" \ + QMAKE_LINK_SHLIB="$(tc-getCXX)" \ + QMAKE_OBJCOPY="$(tc-getOBJCOPY)" \ + QMAKE_RANLIB= \ + QMAKE_STRIP="$(tc-getSTRIP)" \ + QMAKE_CFLAGS="${CFLAGS}" \ + QMAKE_CFLAGS_RELEASE= \ + QMAKE_CFLAGS_DEBUG= \ + QMAKE_CXXFLAGS="${CXXFLAGS}" \ + QMAKE_CXXFLAGS_RELEASE= \ + QMAKE_CXXFLAGS_DEBUG= \ + QMAKE_LFLAGS="${LDFLAGS}" \ + QMAKE_LFLAGS_RELEASE= \ + QMAKE_LFLAGS_DEBUG= \ + "${myqmakeargs[@]}" \ + || die "qmake failed (${projectdir#${S}/})" +} + +# @FUNCTION: qt5_install_module_config +# @INTERNAL +# @DESCRIPTION: +# Creates and installs gentoo-specific ${PN}-qconfig.{h,pri} and +# ${PN}-qmodule.pri files. +qt5_install_module_config() { + local x qconfig_add= qconfig_remove= qprivateconfig_add= qprivateconfig_remove= + + > "${T}"/${PN}-qconfig.h + > "${T}"/${PN}-qconfig.pri + > "${T}"/${PN}-qmodule.pri + + # generate qconfig_{add,remove} and ${PN}-qconfig.h + for x in "${QT5_GENTOO_CONFIG[@]}"; do + local flag=${x%%:*} + x=${x#${flag}:} + local feature=${x%%:*} + x=${x#${feature}:} + local macro=${x} + macro=$(tr 'a-z-' 'A-Z_' <<< "${macro}") + + if [[ -z ${flag} ]] || { [[ ${flag} != '!' ]] && use ${flag}; }; then + [[ -n ${feature} ]] && qconfig_add+=" ${feature}" + [[ -n ${macro} ]] && echo "#define QT_${macro}" >> "${T}"/${PN}-qconfig.h + else + [[ -n ${feature} ]] && qconfig_remove+=" ${feature}" + [[ -n ${macro} ]] && echo "#define QT_NO_${macro}" >> "${T}"/${PN}-qconfig.h + fi + done + + # install ${PN}-qconfig.h + [[ -s ${T}/${PN}-qconfig.h ]] && ( + insinto "${QT5_HEADERDIR#${EPREFIX}}"/Gentoo + doins "${T}"/${PN}-qconfig.h + ) + + # generate and install ${PN}-qconfig.pri + [[ -n ${qconfig_add} ]] && echo "QCONFIG_ADD=${qconfig_add}" >> "${T}"/${PN}-qconfig.pri + [[ -n ${qconfig_remove} ]] && echo "QCONFIG_REMOVE=${qconfig_remove}" >> "${T}"/${PN}-qconfig.pri + [[ -s ${T}/${PN}-qconfig.pri ]] && ( + insinto "${QT5_ARCHDATADIR#${EPREFIX}}"/mkspecs/gentoo + doins "${T}"/${PN}-qconfig.pri + ) + + # generate qprivateconfig + for x in "${QT5_GENTOO_PRIVATE_CONFIG[@]}"; do + local flag=${x%%:*} + x=${x#${flag}:} + local feature=${x%%:*} + x=${x#${feature}:} + + if [[ -z ${flag} ]] || { [[ ${flag} != '!' ]] && use ${flag}; }; then + [[ -n ${feature} ]] && qprivateconfig_add+=" ${feature}" + else + [[ -n ${feature} ]] && qprivateconfig_remove+=" ${feature}" + fi + done + + # generate and install ${PN}-qmodule.pri + [[ -n ${qprivateconfig_add} ]] && echo "QT.global_private.enabled_features = ${qprivateconfig_add}" >> "${T}"/${PN}-qmodule.pri + [[ -n ${qprivateconfig_remove} ]] && echo "QT.global_private.disabled_features = ${qprivateconfig_remove}" >> "${T}"/${PN}-qmodule.pri + [[ -s ${T}/${PN}-qmodule.pri ]] && ( + insinto "${QT5_ARCHDATADIR#${EPREFIX}}"/mkspecs/gentoo + doins "${T}"/${PN}-qmodule.pri + ) + + # install the original {qconfig,qmodule}.pri from qtcore + [[ ${PN} == qtcore ]] && ( + insinto "${QT5_ARCHDATADIR#${EPREFIX}}"/mkspecs/gentoo + newins "${D}${QT5_ARCHDATADIR}"/mkspecs/qconfig.pri qconfig-qtcore.pri + newins "${D}${QT5_ARCHDATADIR}"/mkspecs/qmodule.pri qmodule-qtcore.pri + ) +} + +# @FUNCTION: qt5_regenerate_global_configs +# @INTERNAL +# @DESCRIPTION: +# Generates Gentoo-specific qconfig.{h,pri} and qmodule.pri according to the +# build configuration. +# Don't call die here because dying in pkg_post{inst,rm} only makes things worse. +qt5_regenerate_global_configs() { + einfo "Regenerating gentoo-qconfig.h" + + find "${ROOT}${QT5_HEADERDIR}"/Gentoo \ + -name '*-qconfig.h' -a \! -name 'gentoo-qconfig.h' -type f \ + -execdir cat '{}' + | sort -u > "${T}"/gentoo-qconfig.h + + [[ -s ${T}/gentoo-qconfig.h ]] || ewarn "Generated gentoo-qconfig.h is empty" + cp "${T}"/gentoo-qconfig.h "${ROOT}${QT5_HEADERDIR}"/Gentoo/gentoo-qconfig.h \ + || eerror "Failed to install new gentoo-qconfig.h" + + einfo "Updating QT_CONFIG in qconfig.pri" + + local qconfig_pri=${ROOT}${QT5_ARCHDATADIR}/mkspecs/qconfig.pri + local qconfig_pri_orig=${ROOT}${QT5_ARCHDATADIR}/mkspecs/gentoo/qconfig-qtcore.pri + if [[ -f ${qconfig_pri} ]]; then + local x qconfig_add= qconfig_remove= + local qt_config new_qt_config= + if [[ -f ${qconfig_pri_orig} ]]; then + qt_config=$(sed -n 's/^QT_CONFIG\s*+=\s*//p' "${qconfig_pri_orig}") + else + qt_config=$(sed -n 's/^QT_CONFIG\s*+=\s*//p' "${qconfig_pri}") + fi + + # generate list of QT_CONFIG entries from the existing list, + # appending QCONFIG_ADD and excluding QCONFIG_REMOVE + eshopts_push -s nullglob + for x in "${ROOT}${QT5_ARCHDATADIR}"/mkspecs/gentoo/*-qconfig.pri; do + qconfig_add+=" $(sed -n 's/^QCONFIG_ADD=\s*//p' "${x}")" + qconfig_remove+=" $(sed -n 's/^QCONFIG_REMOVE=\s*//p' "${x}")" + done + eshopts_pop + for x in ${qt_config} ${qconfig_add}; do + if ! has "${x}" ${new_qt_config} ${qconfig_remove}; then + new_qt_config+=" ${x}" + fi + done + + # now replace the existing QT_CONFIG with the generated list + sed -i -e "s/^QT_CONFIG\s*+=.*/QT_CONFIG +=${new_qt_config}/" \ + "${qconfig_pri}" || eerror "Failed to sed QT_CONFIG in ${qconfig_pri}" + else + ewarn "${qconfig_pri} does not exist or is not a regular file" + fi + + einfo "Updating QT.global_private in qmodule.pri" + + local qmodule_pri=${ROOT}${QT5_ARCHDATADIR}/mkspecs/qmodule.pri + local qmodule_pri_orig=${ROOT}${QT5_ARCHDATADIR}/mkspecs/gentoo/qmodule-qtcore.pri + if [[ -f ${qmodule_pri} && -f ${qmodule_pri_orig} ]]; then + local x + local qprivateconfig_enabled= qprivateconfig_disabled= + local qprivateconfig_orig_enabled= qprivateconfig_orig_disabled= + local new_qprivateconfig_enabled= new_qprivateconfig_disabled= + + # generate lists of QT.global_private.{dis,en}abled_features + qprivateconfig_orig_enabled="$(sed -n 's/^QT.global_private.enabled_features\s=\s*//p' "${qmodule_pri_orig}")" + qprivateconfig_orig_disabled="$(sed -n 's/^QT.global_private.disabled_features\s=\s*//p' "${qmodule_pri_orig}")" + eshopts_push -s nullglob + for x in "${ROOT}${QT5_ARCHDATADIR}"/mkspecs/gentoo/*-qmodule.pri; do + qprivateconfig_enabled+=" $(sed -n 's/^QT.global_private.enabled_features\s=\s*//p' "${x}")" + qprivateconfig_disabled+=" $(sed -n 's/^QT.global_private.disabled_features\s=\s*//p' "${x}")" + done + eshopts_pop + + # anything enabled is enabled, but anything disabled is + # only disabled if it isn't enabled somewhere else. + # this is because we need to forcibly disable some stuff + # in qtcore to support split qtbase. + new_qprivateconfig_enabled=${qprivateconfig_enabled} + for x in ${qprivateconfig_disabled}; do + if ! has "${x}" ${qprivateconfig_enabled}; then + new_qprivateconfig_disabled+=" ${x}" + fi + done + + # check all items from the original qtcore qmodule.pri, + # and add them to the appropriate list if not overridden + # elsewhere + for x in ${qprivateconfig_orig_enabled}; do + if ! has "${x}" ${new_qprivateconfig_enabled} ${new_qprivateconfig_disabled}; then + new_qprivateconfig_enabled+=" ${x}" + fi + done + for x in ${qprivateconfig_orig_disabled}; do + if ! has "${x}" ${new_qprivateconfig_enabled} ${new_qprivateconfig_disabled}; then + new_qprivateconfig_disabled+=" ${x}" + fi + done + + # now replace the existing QT.global_private.{dis,en}abled_features + # with the generated list + sed \ + -e "s/^QT.global_private.enabled_features\s*=.*/QT.global_private.enabled_features =${new_qprivateconfig_enabled}/" \ + -e "s/^QT.global_private.disabled_features\s*=.*/QT.global_private.disabled_features =${new_qprivateconfig_disabled}/" \ + -i "${qmodule_pri}" || eerror "Failed to sed QT.global_private.enabled_features in ${qmodule_pri}" + else + ewarn "${qmodule_pri} or ${qmodule_pri_orig} does not exist or is not a regular file" + fi +} diff --git a/eclass/readme.gentoo-r1.eclass b/eclass/readme.gentoo-r1.eclass new file mode 100644 index 0000000..dfa3b52 --- /dev/null +++ b/eclass/readme.gentoo-r1.eclass @@ -0,0 +1,108 @@ +# Copyright 1999-2018 Gentoo Foundation +# Distributed under the terms of the GNU General Public License v2 + +# @ECLASS: readme.gentoo-r1.eclass +# @MAINTAINER: +# Pacho Ramos <pacho@gentoo.org> +# @AUTHOR: +# Author: Pacho Ramos <pacho@gentoo.org> +# @SUPPORTED_EAPIS: 4 5 6 7 +# @BLURB: install a doc file shown via elog messages +# @DESCRIPTION: +# An eclass for installing a README.gentoo doc file recording tips +# shown via elog messages. With this eclass, those elog messages will only be +# shown at first package installation and a file for later reviewing will be +# installed under /usr/share/doc/${PF} +# +# You need to call readme.gentoo_create_doc in src_install phase and +# readme.gentoo_print_elog in pkg_postinst + +if [[ -z ${_README_GENTOO_ECLASS} ]]; then +_README_GENTOO_ECLASS=1 + +case "${EAPI:-0}" in + 0|1|2|3) + die "Unsupported EAPI=${EAPI:-0} (too old) for ${ECLASS}" + ;; + 4|5|6|7) + ;; + *) + die "Unsupported EAPI=${EAPI} (unknown) for ${ECLASS}" + ;; +esac + +# @ECLASS-VARIABLE: DISABLE_AUTOFORMATTING +# @DEFAULT_UNSET +# @DESCRIPTION: +# If non-empty, DOC_CONTENTS information will be strictly respected, +# not getting it automatically formatted by fmt. If empty, it will +# rely on fmt for formatting and 'echo -e' options to tweak lines a bit. + +# @ECLASS-VARIABLE: FORCE_PRINT_ELOG +# @DEFAULT_UNSET +# @DESCRIPTION: +# If non-empty this variable forces elog messages to be printed. + +# @ECLASS-VARIABLE: README_GENTOO_SUFFIX +# @DESCRIPTION: +# If you want to specify a suffix for README.gentoo file please export it. +: ${README_GENTOO_SUFFIX:=""} + +# @FUNCTION: readme.gentoo_create_doc +# @DESCRIPTION: +# Create doc file with ${DOC_CONTENTS} variable (preferred) and, if not set, +# look for "${FILESDIR}/README.gentoo" contents. You can use +# ${FILESDIR}/README.gentoo-${SLOT} also. +# Usually called at src_install phase. +readme.gentoo_create_doc() { + debug-print-function ${FUNCNAME} "${@}" + + if [[ -n "${DOC_CONTENTS}" ]]; then + if [[ -n "${DISABLE_AUTOFORMATTING}" ]]; then + echo "${DOC_CONTENTS}" > "${T}"/README.gentoo || die + else + local saved_flags=$- + set -f # disable filename expansion in echo arguments + echo -e ${DOC_CONTENTS} | fold -s -w 70 \ + | sed 's/[[:space:]]*$//' > "${T}"/README.gentoo + assert + set +f -${saved_flags} + fi + elif [[ -f "${FILESDIR}/README.gentoo-${SLOT%/*}" ]]; then + cp "${FILESDIR}/README.gentoo-${SLOT%/*}" "${T}"/README.gentoo || die + elif [[ -f "${FILESDIR}/README.gentoo${README_GENTOO_SUFFIX}" ]]; then + cp "${FILESDIR}/README.gentoo${README_GENTOO_SUFFIX}" "${T}"/README.gentoo || die + else + die "You are not specifying README.gentoo contents!" + fi + + dodoc "${T}"/README.gentoo + README_GENTOO_DOC_VALUE=$(< "${T}/README.gentoo") +} + +# @FUNCTION: readme.gentoo_print_elog +# @DESCRIPTION: +# Print elog messages with "${T}"/README.gentoo contents. They will be +# shown only when package is installed at first time. +# Usually called at pkg_postinst phase. +# +# If you want to show them always, please set FORCE_PRINT_ELOG to a non empty +# value in your ebuild before this function is called. +# This can be useful when, for example, DOC_CONTENTS is modified, then, you can +# rely on specific REPLACING_VERSIONS handling in your ebuild to print messages +# when people update from versions still providing old message. +readme.gentoo_print_elog() { + debug-print-function ${FUNCNAME} "${@}" + + if [[ -z "${README_GENTOO_DOC_VALUE}" ]]; then + die "readme.gentoo_print_elog invoked without matching readme.gentoo_create_doc call!" + elif ! [[ -n "${REPLACING_VERSIONS}" ]] || [[ -n "${FORCE_PRINT_ELOG}" ]]; then + echo -e "${README_GENTOO_DOC_VALUE}" | while read -r ELINE; do elog "${ELINE}"; done + elog "" + elog "(Note: Above message is only printed the first time package is" + elog "installed. Please look at ${EPREFIX}/usr/share/doc/${PF}/README.gentoo*" + elog "for future reference)" + fi +} + +fi diff --git a/eclass/readme.gentoo.eclass b/eclass/readme.gentoo.eclass new file mode 100644 index 0000000..fdb2d60 --- /dev/null +++ b/eclass/readme.gentoo.eclass @@ -0,0 +1,140 @@ +# Copyright 1999-2020 Gentoo Authors +# Distributed under the terms of the GNU General Public License v2 + +# @ECLASS: readme.gentoo.eclass +# @MAINTAINER: +# Pacho Ramos <pacho@gentoo.org> +# @AUTHOR: +# Author: Pacho Ramos <pacho@gentoo.org> +# @SUPPORTED_EAPIS: 4 5 +# @BLURB: install a doc file shown via elog messages +# @DESCRIPTION: +# An eclass for installing a README.gentoo doc file recording tips +# shown via elog messages. With this eclass, those elog messages will only be +# shown at first package installation and a file for later reviewing will be +# installed under /usr/share/doc/${PF} +# +# This eclass is DEPRECATED. Please use readme.gentoo-r1 instead. + +if [[ -z ${_README_GENTOO_ECLASS} ]]; then +_README_GENTOO_ECLASS=1 + +inherit estack eutils + +case "${EAPI:-0}" in + 0|1|2|3) + die "Unsupported EAPI=${EAPI:-0} (too old) for ${ECLASS}" + ;; + 4|5) + # EAPI>=4 is required for REPLACING_VERSIONS preventing us + # from needing to export another pkg_preinst phase to save has_version + # result. Also relies on EAPI >=4 default src_install phase. + EXPORT_FUNCTIONS src_install pkg_postinst + ;; + 6) + die "Unsupported EAPI=${EAPI} for ${ECLASS}" + die "Please migrate to readme.gentoo-r1.eclass and note that" + die "it stops to export any ebuild phases and, then, you will" + die "need to ensure readme.gentoo_create_doc is called in" + die "src_install and readme.gentoo_print_elog in pkg_postinst" + ;; + *) + die "Unsupported EAPI=${EAPI} (unknown) for ${ECLASS}" + ;; +esac + +# @ECLASS-VARIABLE: DISABLE_AUTOFORMATTING +# @DEFAULT_UNSET +# @DESCRIPTION: +# If non-empty, DOC_CONTENTS information will be strictly respected, +# not getting it automatically formatted by fmt. If empty, it will +# rely on fmt for formatting and 'echo -e' options to tweak lines a bit. + +# @ECLASS-VARIABLE: FORCE_PRINT_ELOG +# @DEFAULT_UNSET +# @DESCRIPTION: +# If non-empty this variable forces elog messages to be printed. + +# @ECLASS-VARIABLE: README_GENTOO_SUFFIX +# @DESCRIPTION: +# If you want to specify a suffix for README.gentoo file please export it. +: ${README_GENTOO_SUFFIX:=""} + +# @FUNCTION: readme.gentoo_create_doc +# @DESCRIPTION: +# Create doc file with ${DOC_CONTENTS} variable (preferred) and, if not set, +# look for "${FILESDIR}/README.gentoo" contents. You can use +# ${FILESDIR}/README.gentoo-${SLOT} also. +# Usually called at src_install phase. +readme.gentoo_create_doc() { + debug-print-function ${FUNCNAME} "${@}" + + if [[ -n "${DOC_CONTENTS}" ]]; then + eshopts_push + set -f + if [[ -n "${DISABLE_AUTOFORMATTING}" ]]; then + echo "${DOC_CONTENTS}" > "${T}"/README.gentoo + else + echo -e ${DOC_CONTENTS} | fold -s -w 70 \ + | sed 's/[[:space:]]*$//' > "${T}"/README.gentoo + fi + eshopts_pop + elif [[ -f "${FILESDIR}/README.gentoo-${SLOT%/*}" ]]; then + cp "${FILESDIR}/README.gentoo-${SLOT%/*}" "${T}"/README.gentoo || die + elif [[ -f "${FILESDIR}/README.gentoo${README_GENTOO_SUFFIX}" ]]; then + cp "${FILESDIR}/README.gentoo${README_GENTOO_SUFFIX}" "${T}"/README.gentoo || die + else + die "You are not specifying README.gentoo contents!" + fi + + dodoc "${T}"/README.gentoo + README_GENTOO_DOC_VALUE=$(< "${T}/README.gentoo") +} + +# @FUNCTION: readme.gentoo_print_elog +# @DESCRIPTION: +# Print elog messages with "${T}"/README.gentoo contents. They will be +# shown only when package is installed at first time. +# Usually called at pkg_postinst phase. +# +# If you want to show them always, please set FORCE_PRINT_ELOG to a non empty +# value in your ebuild before this function is called. +# This can be useful when, for example, DOC_CONTENTS is modified, then, you can +# rely on specific REPLACING_VERSIONS handling in your ebuild to print messages +# when people update from versions still providing old message. +readme.gentoo_print_elog() { + debug-print-function ${FUNCNAME} "${@}" + + eqawarn "${CATEGORY}/${PN} is using the deprecated readme.gentoo.eclass." + eqawarn "Please use readme.gentoo-r1 instead." + + if [[ -z "${README_GENTOO_DOC_VALUE}" ]]; then + die "readme.gentoo_print_elog invoked without matching readme.gentoo_create_doc call!" + elif ! [[ -n "${REPLACING_VERSIONS}" ]] || [[ -n "${FORCE_PRINT_ELOG}" ]]; then + echo -e "${README_GENTOO_DOC_VALUE}" | while read -r ELINE; do elog "${ELINE}"; done + elog "" + elog "(Note: Above message is only printed the first time package is" + elog "installed. Please look at ${EPREFIX}/usr/share/doc/${PF}/README.gentoo*" + elog "for future reference)" + fi +} + + +# @FUNCTION: readme.gentoo_src_install +# @DESCRIPTION: +# Install generated doc file automatically. +readme.gentoo_src_install() { + debug-print-function ${FUNCNAME} "${@}" + default + readme.gentoo_create_doc +} + +# @FUNCTION: readme.gentoo_pkg_postinst +# @DESCRIPTION: +# Show elog messages from from just generated doc file. +readme.gentoo_pkg_postinst() { + debug-print-function ${FUNCNAME} "${@}" + readme.gentoo_print_elog +} + +fi diff --git a/eclass/rebar.eclass b/eclass/rebar.eclass new file mode 100644 index 0000000..7f71290 --- /dev/null +++ b/eclass/rebar.eclass @@ -0,0 +1,261 @@ +# Copyright 1999-2020 Gentoo Authors +# Distributed under the terms of the GNU General Public License v2 + +# @ECLASS: rebar.eclass +# @MAINTAINER: +# maintainer-needed@gentoo.org +# @AUTHOR: +# Amadeusz Żołnowski <aidecoe@gentoo.org> +# @SUPPORTED_EAPIS: 6 +# @BLURB: Build Erlang/OTP projects using dev-util/rebar. +# @DESCRIPTION: +# An eclass providing functions to build Erlang/OTP projects using +# dev-util/rebar. +# +# rebar is a tool which tries to resolve dependencies itself which is by +# cloning remote git repositories. Dependant projects are usually expected to +# be in sub-directory 'deps' rather than looking at system Erlang lib +# directory. Projects relying on rebar usually don't have 'install' make +# targets. The eclass workarounds some of these problems. It handles +# installation in a generic way for Erlang/OTP structured projects. + +case "${EAPI:-0}" in + 0|1|2|3|4|5) + die "Unsupported EAPI=${EAPI:-0} (too old) for ${ECLASS}" + ;; + 6) + ;; + *) + die "Unsupported EAPI=${EAPI} (unknown) for ${ECLASS}" + ;; +esac + +EXPORT_FUNCTIONS src_prepare src_compile src_test src_install + +RDEPEND="dev-lang/erlang:=" +DEPEND="${RDEPEND} + dev-util/rebar + >=sys-apps/gawk-4.1" + +# @ECLASS-VARIABLE: REBAR_APP_SRC +# @DESCRIPTION: +# Relative path to .app.src description file. +REBAR_APP_SRC="${REBAR_APP_SRC-src/${PN}.app.src}" + +# @FUNCTION: get_erl_libs +# @RETURN: the path to Erlang lib directory +# @DESCRIPTION: +# Get the full path without EPREFIX to Erlang lib directory. +get_erl_libs() { + echo "/usr/$(get_libdir)/erlang/lib" +} + +# @FUNCTION: _rebar_find_dep +# @INTERNAL +# @USAGE: <project_name> +# @RETURN: full path with EPREFIX to a Erlang package/project on success, +# code 1 when dependency is not found and code 2 if multiple versions of +# dependency are found. +# @DESCRIPTION: +# Find a Erlang package/project by name in Erlang lib directory. Project +# directory is usually suffixed with version. It is matched to '<project_name>' +# or '<project_name>-*'. +_rebar_find_dep() { + local pn="$1" + local p + local result + + pushd "${EPREFIX}$(get_erl_libs)" >/dev/null || return 1 + for p in ${pn} ${pn}-*; do + if [[ -d ${p} ]]; then + # Ensure there's at most one matching. + [[ ${result} ]] && return 2 + result="${p}" + fi + done + popd >/dev/null || die + + [[ ${result} ]] || return 1 + echo "${result}" +} + +# @FUNCTION: rebar_disable_coverage +# @USAGE: [<rebar_config>] +# @DESCRIPTION: +# Disable coverage in rebar.config. This is a workaround for failing coverage. +# Coverage is not relevant in this context, so there's no harm to disable it, +# although the issue should be fixed. +rebar_disable_coverage() { + debug-print-function ${FUNCNAME} "${@}" + + local rebar_config="${1:-rebar.config}" + + sed -e 's/{cover_enabled, true}/{cover_enabled, false}/' \ + -i "${rebar_config}" \ + || die "failed to disable coverage in ${rebar_config}" +} + +# @FUNCTION: erebar +# @USAGE: <targets> +# @DESCRIPTION: +# Run rebar with verbose flag. Die on failure. +erebar() { + debug-print-function ${FUNCNAME} "${@}" + + (( $# > 0 )) || die "erebar: at least one target is required" + + local -x ERL_LIBS="${EPREFIX}$(get_erl_libs)" + [[ ${1} == eunit ]] && local -x ERL_LIBS="." + + rebar -v skip_deps=true "$@" || die -n "rebar $@ failed" +} + +# @FUNCTION: rebar_fix_include_path +# @USAGE: <project_name> [<rebar_config>] +# @DESCRIPTION: +# Fix path in rebar.config to 'include' directory of dependant project/package, +# so it points to installation in system Erlang lib rather than relative 'deps' +# directory. +# +# <rebar_config> is optional. Default is 'rebar.config'. +# +# The function dies on failure. +rebar_fix_include_path() { + debug-print-function ${FUNCNAME} "${@}" + + local pn="$1" + local rebar_config="${2:-rebar.config}" + local erl_libs="${EPREFIX}$(get_erl_libs)" + local p + + p="$(_rebar_find_dep "${pn}")" \ + || die "failed to unambiguously resolve dependency of '${pn}'" + + gawk -i inplace \ + -v erl_libs="${erl_libs}" -v pn="${pn}" -v p="${p}" ' +/^{[[:space:]]*erl_opts[[:space:]]*,/, /}[[:space:]]*\.$/ { + pattern = "\"(./)?deps/" pn "/include\""; + if (match($0, "{i,[[:space:]]*" pattern "[[:space:]]*}")) { + sub(pattern, "\"" erl_libs "/" p "/include\""); + } + print $0; + next; +} +1 +' "${rebar_config}" || die "failed to fix include paths in ${rebar_config} for '${pn}'" +} + +# @FUNCTION: rebar_remove_deps +# @USAGE: [<rebar_config>] +# @DESCRIPTION: +# Remove dependencies list from rebar.config and deceive build rules that any +# dependencies are already fetched and built. Otherwise rebar tries to fetch +# dependencies and compile them. +# +# <rebar_config> is optional. Default is 'rebar.config'. +# +# The function dies on failure. +rebar_remove_deps() { + debug-print-function ${FUNCNAME} "${@}" + + local rebar_config="${1:-rebar.config}" + + mkdir -p "${S}/deps" && :>"${S}/deps/.got" && :>"${S}/deps/.built" || die + gawk -i inplace ' +/^{[[:space:]]*deps[[:space:]]*,/, /}[[:space:]]*\.$/ { + if ($0 ~ /}[[:space:]]*\.$/) { + print "{deps, []}."; + } + next; +} +1 +' "${rebar_config}" || die "failed to remove deps from ${rebar_config}" +} + +# @FUNCTION: rebar_set_vsn +# @USAGE: [<version>] +# @DESCRIPTION: +# Set version in project description file if it's not set. +# +# <version> is optional. Default is PV stripped from version suffix. +# +# The function dies on failure. +rebar_set_vsn() { + debug-print-function ${FUNCNAME} "${@}" + + local version="${1:-${PV%_*}}" + + sed -e "s/vsn, git/vsn, \"${version}\"/" \ + -i "${S}/${REBAR_APP_SRC}" \ + || die "failed to set version in src/${PN}.app.src" +} + +# @FUNCTION: rebar_src_prepare +# @DESCRIPTION: +# Prevent rebar from fetching and compiling dependencies. Set version in +# project description file if it's not set. +# +# Existence of rebar.config is optional, but file description file must exist +# at 'src/${PN}.app.src'. +rebar_src_prepare() { + debug-print-function ${FUNCNAME} "${@}" + + default + rebar_set_vsn + if [[ -f rebar.config ]]; then + rebar_disable_coverage + rebar_remove_deps + fi +} + +# @FUNCTION: rebar_src_configure +# @DESCRIPTION: +# Configure with ERL_LIBS set. +rebar_src_configure() { + debug-print-function ${FUNCNAME} "${@}" + + local -x ERL_LIBS="${EPREFIX}$(get_erl_libs)" + default +} + +# @FUNCTION: rebar_src_compile +# @DESCRIPTION: +# Compile project with rebar. +rebar_src_compile() { + debug-print-function ${FUNCNAME} "${@}" + + erebar compile +} + +# @FUNCTION: rebar_src_test +# @DESCRIPTION: +# Run unit tests. +rebar_src_test() { + debug-print-function ${FUNCNAME} "${@}" + + erebar eunit +} + +# @FUNCTION: rebar_src_install +# @DESCRIPTION: +# Install BEAM files, include headers, executables and native libraries. +# Install standard docs like README or defined in DOCS variable. +# +# Function expects that project conforms to Erlang/OTP structure. +rebar_src_install() { + debug-print-function ${FUNCNAME} "${@}" + + local bin + local dest="$(get_erl_libs)/${P}" + + insinto "${dest}" + doins -r ebin + [[ -d include ]] && doins -r include + [[ -d bin ]] && for bin in bin/*; do dobin "$bin"; done + + if [[ -d priv ]]; then + cp -pR priv "${ED}${dest}/" || die "failed to install priv/" + fi + + einstalldocs +} diff --git a/eclass/ros-catkin.eclass b/eclass/ros-catkin.eclass new file mode 100644 index 0000000..2779a03 --- /dev/null +++ b/eclass/ros-catkin.eclass @@ -0,0 +1,229 @@ +# Copyright 1999-2020 Gentoo Authors +# Distributed under the terms of the GNU General Public License v2 + +# @ECLASS: ros-catkin.eclass +# @MAINTAINER: +# ros@gentoo.org +# @AUTHOR: +# Alexis Ballier <aballier@gentoo.org> +# @SUPPORTED_EAPIS: 5 6 7 +# @BLURB: Template eclass for catkin based ROS packages. +# @DESCRIPTION: +# Provides function for building ROS packages on Gentoo. +# It supports selectively building messages, single-python installation, live ebuilds (git only). + +case "${EAPI:-0}" in + 0|1|2|3|4|5|6) + die "EAPI='${EAPI}' is not supported" + ;; + *) + ;; +esac + +# @ECLASS-VARIABLE: ROS_REPO_URI +# @DESCRIPTION: +# URL of the upstream repository. Usually on github. +# Serves for fetching tarballs, live ebuilds and inferring the meta-package name. +EGIT_REPO_URI="${ROS_REPO_URI}" + +# @ECLASS-VARIABLE: ROS_SUBDIR +# @DEFAULT_UNSET +# @DESCRIPTION: +# Subdir in which current packages is located. +# Usually, a repository contains several packages, hence a typical value is: +# ROS_SUBDIR=${PN} + +# @ECLASS-VARIABLE: CATKIN_IN_SOURCE_BUILD +# @DEFAULT_UNSET +# @DESCRIPTION: +# Set to enable in-source build. + +SCM="" +if [ "${PV#9999}" != "${PV}" ] ; then + SCM="git-r3" +fi + +# ROS only really works with one global python version and the target +# version depends on the release. Noetic targets 3.7 and 3.8. +# py3.9 or later are ok to add there as long as dev-ros/* have their deps satisfied. +PYTHON_COMPAT=( python3_{7,8} ) + +inherit ${SCM} python-single-r1 cmake flag-o-matic + +REQUIRED_USE="${PYTHON_REQUIRED_USE}" + +IUSE="test" +RESTRICT="!test? ( test )" +RDEPEND="${PYTHON_DEPS}" +DEPEND="${RDEPEND} + $(python_gen_cond_dep "dev-util/catkin[\${PYTHON_USEDEP}]") + $(python_gen_cond_dep "dev-python/empy[\${PYTHON_USEDEP}]") +" + +# @ECLASS-VARIABLE: CATKIN_HAS_MESSAGES +# @DESCRIPTION: +# Set it to a non-empty value before inherit to tell the eclass the package has messages to build. +# Messages will be built based on ROS_MESSAGES USE_EXPANDed variable. + +# @ECLASS-VARIABLE: CATKIN_MESSAGES_TRANSITIVE_DEPS +# @DESCRIPTION: +# Some messages have dependencies on other messages. +# In that case, CATKIN_MESSAGES_TRANSITIVE_DEPS should contain a space-separated list of atoms +# representing those dependencies. The eclass uses it to ensure proper dependencies on these packages. +if [ -n "${CATKIN_HAS_MESSAGES}" ] ; then + IUSE="${IUSE} +ros_messages_python +ros_messages_cxx ros_messages_eus ros_messages_lisp ros_messages_nodejs" + RDEPEND="${RDEPEND} + ros_messages_cxx? ( dev-ros/gencpp:=[${PYTHON_SINGLE_USEDEP}] ) + ros_messages_eus? ( dev-ros/geneus:=[${PYTHON_SINGLE_USEDEP}] ) + ros_messages_python? ( dev-ros/genpy:=[${PYTHON_SINGLE_USEDEP}] ) + ros_messages_lisp? ( dev-ros/genlisp:=[${PYTHON_SINGLE_USEDEP}] ) + ros_messages_nodejs? ( dev-ros/gennodejs:=[${PYTHON_SINGLE_USEDEP}] ) + dev-ros/message_runtime + " + DEPEND="${DEPEND} ${RDEPEND} + dev-ros/message_generation + dev-ros/genmsg[${PYTHON_SINGLE_USEDEP}] + " + if [ -n "${CATKIN_MESSAGES_TRANSITIVE_DEPS}" ] ; then + for i in ${CATKIN_MESSAGES_TRANSITIVE_DEPS} ; do + ds="${i}[ros_messages_python(-)?,ros_messages_cxx(-)?,ros_messages_lisp(-)?,ros_messages_eus(-)?,ros_messages_nodejs(-)?] ros_messages_python? ( ${i}[${PYTHON_SINGLE_USEDEP}] )" + RDEPEND="${RDEPEND} ${ds}" + DEPEND="${DEPEND} ${ds}" + done + fi +fi + +# @ECLASS-VARIABLE: CATKIN_MESSAGES_CXX_USEDEP +# @DESCRIPTION: +# Use it as cat/pkg[${CATKIN_MESSAGES_CXX_USEDEP}] to indicate a dependency on the C++ messages of cat/pkg. +CATKIN_MESSAGES_CXX_USEDEP="ros_messages_cxx(-)" + +# @ECLASS-VARIABLE: CATKIN_MESSAGES_PYTHON_USEDEP +# @DESCRIPTION: +# Use it as cat/pkg[${CATKIN_MESSAGES_PYTHON_USEDEP}] to indicate a dependency on the Python messages of cat/pkg. +CATKIN_MESSAGES_PYTHON_USEDEP="ros_messages_python(-),${PYTHON_SINGLE_USEDEP}" + +# @ECLASS-VARIABLE: CATKIN_MESSAGES_LISP_USEDEP +# @DESCRIPTION: +# Use it as cat/pkg[${CATKIN_MESSAGES_LISP_USEDEP}] to indicate a dependency on the Common-Lisp messages of cat/pkg. +CATKIN_MESSAGES_LISP_USEDEP="ros_messages_lisp(-)" + +# @ECLASS-VARIABLE: CATKIN_MESSAGES_EUS_USEDEP +# @DESCRIPTION: +# Use it as cat/pkg[${CATKIN_MESSAGES_EUS_USEDEP}] to indicate a dependency on the EusLisp messages of cat/pkg. +CATKIN_MESSAGES_EUS_USEDEP="ros_messages_eus(-)" + +# @ECLASS-VARIABLE: CATKIN_MESSAGES_NODEJS_USEDEP +# @DESCRIPTION: +# Use it as cat/pkg[${CATKIN_MESSAGES_NODEJS_USEDEP}] to indicate a dependency on the nodejs messages of cat/pkg. +CATKIN_MESSAGES_NODEJS_USEDEP="ros_messages_nodejs(-)" + +if [ "${PV#9999}" != "${PV}" ] ; then + SRC_URI="" + KEYWORDS="" + S=${WORKDIR}/${P}/${ROS_SUBDIR} +else + SRC_URI="${ROS_REPO_URI}/archive/${VER_PREFIX}${PV%_*}${VER_SUFFIX}.tar.gz -> ${ROS_REPO_URI##*/}-${PV}.tar.gz" + S=${WORKDIR}/${VER_PREFIX}${ROS_REPO_URI##*/}-${PV}${VER_SUFFIX}/${ROS_SUBDIR} +fi + +HOMEPAGE="https://wiki.ros.org/${PN} ${ROS_REPO_URI}" + +# @FUNCTION: ros-catkin_src_prepare +# @DESCRIPTION: +# Calls cmake_src_prepare (so that PATCHES array is handled there) and initialises the workspace +# by installing a recursive CMakeLists.txt to handle bundles. +ros-catkin_src_prepare() { + # If no multibuild, just use cmake IN_SOURCE support + [ -n "${CATKIN_IN_SOURCE_BUILD}" ] && export CMAKE_IN_SOURCE_BUILD=yes + + cmake_src_prepare + + if [ ! -f "${S}/CMakeLists.txt" ] ; then + catkin_init_workspace || die + fi + + # Most packages require C++11 these days. Do it here, in src_prepare so that + # ebuilds can override it in src_configure. + append-cxxflags '-std=c++14' +} + +# @VARIABLE: mycatkincmakeargs +# @DEFAULT_UNSET +# @DESCRIPTION: +# Optional cmake defines as a bash array. Should be defined before calling +# src_configure. + +# @FUNCTION: ros-catkin_src_configure +# @DESCRIPTION: +# Configures a catkin-based package. +ros-catkin_src_configure() { + export CATKIN_PREFIX_PATH="${EPREFIX}/usr" + export ROS_ROOT="${EPREFIX}/usr/share/ros" + export ROS_PYTHON_VERSION="${EPYTHON#python}" + + if [ -n "${CATKIN_HAS_MESSAGES}" ] ; then + ROS_LANG_DISABLE="" + use ros_messages_cxx || ROS_LANG_DISABLE="${ROS_LANG_DISABLE}:gencpp" + use ros_messages_eus || ROS_LANG_DISABLE="${ROS_LANG_DISABLE}:geneus" + use ros_messages_lisp || ROS_LANG_DISABLE="${ROS_LANG_DISABLE}:genlisp" + use ros_messages_python || ROS_LANG_DISABLE="${ROS_LANG_DISABLE}:genpy" + use ros_messages_nodejs || ROS_LANG_DISABLE="${ROS_LANG_DISABLE}:gennodejs" + export ROS_LANG_DISABLE + fi + + local mycmakeargs=( + "-DCATKIN_ENABLE_TESTING=$(usex test)" + "-DCATKIN_BUILD_BINARY_PACKAGE=ON" + "-DCATKIN_PREFIX_PATH=${SYSROOT:-${EROOT}}/usr" + "${mycatkincmakeargs[@]}" + ) + + local sitedir="$(python_get_sitedir)" + mycmakeargs+=( + -DPYTHON_EXECUTABLE="${PYTHON}" + -DPYTHON_INSTALL_DIR="${sitedir#${EPREFIX}/usr/}" + ) + if [ -n "${CATKIN_IN_SOURCE_BUILD}" ] ; then + export CMAKE_USE_DIR="${BUILD_DIR}" + fi + + cmake_src_configure "${@}" +} + +# @FUNCTION: ros-catkin_src_compile +# @DESCRIPTION: +# Builds a catkin-based package. +ros-catkin_src_compile() { + cmake_src_compile "${@}" +} + +# @FUNCTION: ros-catkin_src_test +# @DESCRIPTION: +# Run the tests of a catkin-based package. +ros-catkin_src_test() { + cd "${BUILD_DIR}" || die + + # Regenerate env for tests, PYTHONPATH is not set properly otherwise... + if [ -f catkin_generated/generate_cached_setup.py ] ; then + einfo "Regenerating setup_cached.sh for tests" + ${PYTHON:-python} catkin_generated/generate_cached_setup.py || die + fi + + nonfatal cmake_build tests + cmake_src_test "${@}" +} + +# @FUNCTION: ros-catkin_src_install +# @DESCRIPTION: +# Installs a catkin-based package. +ros-catkin_src_install() { + if [ -n "${CATKIN_IN_SOURCE_BUILD}" ] ; then + export CMAKE_USE_DIR="${BUILD_DIR}" + fi + + cmake_src_install "${@}" + python_optimize +} + +EXPORT_FUNCTIONS src_prepare src_configure src_compile src_test src_install diff --git a/eclass/rpm.eclass b/eclass/rpm.eclass new file mode 100644 index 0000000..d27f0a3 --- /dev/null +++ b/eclass/rpm.eclass @@ -0,0 +1,129 @@ +# Copyright 1999-2020 Gentoo Authors +# Distributed under the terms of the GNU General Public License v2 + +# @ECLASS: rpm.eclass +# @MAINTAINER: +# base-system@gentoo.org +# @BLURB: convenience class for extracting RPMs + +inherit estack eutils + +case "${EAPI:-0}" in + [0-6]) DEPEND=">=app-arch/rpm2targz-9.0.0.3g" ;; + *) BDEPEND=">=app-arch/rpm2targz-9.0.0.3g" ;; +esac + +# @FUNCTION: rpm_unpack +# @USAGE: <rpms> +# @DESCRIPTION: +# Unpack the contents of the specified rpms like the unpack() function. +rpm_unpack() { + [[ $# -eq 0 ]] && set -- ${A} + local a + for a in "$@" ; do + echo ">>> Unpacking ${a} to ${PWD}" + if [[ ${a} == ./* ]] ; then + : nothing to do -- path is local + elif [[ ${a} == ${DISTDIR}/* ]] ; then + ewarn 'QA: do not use ${DISTDIR} with rpm_unpack -- it is added for you' + elif [[ ${a} == /* ]] ; then + ewarn 'QA: do not use full paths with rpm_unpack -- use ./ paths instead' + else + a="${DISTDIR}/${a}" + fi + rpm2tar -O "${a}" | tar xf - || die "failure unpacking ${a}" + done +} + +# @FUNCTION: srcrpm_unpack +# @USAGE: <rpms> +# @DESCRIPTION: +# Unpack the contents of the specified rpms like the unpack() function as well +# as any archives that it might contain. Note that the secondary archive +# unpack isn't perfect in that it simply unpacks all archives in the working +# directory (with the assumption that there weren't any to start with). +srcrpm_unpack() { + [[ $# -eq 0 ]] && set -- ${A} + rpm_unpack "$@" + + # no .src.rpm files, then nothing to do + [[ "$* " != *".src.rpm " ]] && return 0 + + eshopts_push -s nullglob + + # unpack everything + local a + for a in *.tar.{gz,bz2,xz} *.t{gz,bz2,xz,pxz} *.zip *.ZIP ; do + unpack "./${a}" + rm -f "${a}" + done + + eshopts_pop + + return 0 +} + +# @FUNCTION: rpm_src_unpack +# @DESCRIPTION: +# Automatically unpack all archives in ${A} including rpms. If one of the +# archives in a source rpm, then the sub archives will be unpacked as well. +rpm_src_unpack() { + local a + for a in ${A} ; do + case ${a} in + *.rpm) srcrpm_unpack "${a}" ;; + *) unpack "${a}" ;; + esac + done +} + +# @FUNCTION: rpm_spec_epatch +# @USAGE: [spec] +# @DESCRIPTION: +# Read the specified spec (defaults to ${PN}.spec) and attempt to apply +# all the patches listed in it. If the spec does funky things like moving +# files around, well this won't handle that. +rpm_spec_epatch() { + local p spec=$1 + local dir + + if [[ -z ${spec} ]] ; then + # search likely places for the spec file + for spec in "${PWD}" "${S}" "${WORKDIR}" ; do + spec+="/${PN}.spec" + [[ -e ${spec} ]] && break + done + fi + [[ ${spec} == */* ]] \ + && dir=${spec%/*} \ + || dir= + + ebegin "Applying patches from ${spec}" + + grep '^%patch' "${spec}" | \ + while read line ; do + # expand the %patch line + set -- ${line} + p=$1 + shift + + # process the %patch arguments + local arg + EPATCH_OPTS= + for arg in "$@" ; do + case ${arg} in + -b) EPATCH_OPTS+=" --suffix" ;; + *) EPATCH_OPTS+=" ${arg}" ;; + esac + done + + # extract the patch name from the Patch# line + set -- $(grep "^P${p#%p}: " "${spec}") + shift + epatch "${dir:+${dir}/}$*" + done + + eend +} + +EXPORT_FUNCTIONS src_unpack diff --git a/eclass/ruby-fakegem.eclass b/eclass/ruby-fakegem.eclass new file mode 100644 index 0000000..8ab4487 --- /dev/null +++ b/eclass/ruby-fakegem.eclass @@ -0,0 +1,556 @@ +# Copyright 1999-2020 Gentoo Authors +# Distributed under the terms of the GNU General Public License v2 + +# @ECLASS: ruby-fakegem.eclass +# @MAINTAINER: +# Ruby herd <ruby@gentoo.org> +# @AUTHOR: +# Author: Diego E. Pettenò <flameeyes@gentoo.org> +# Author: Alex Legler <a3li@gentoo.org> +# Author: Hans de Graaff <graaff@gentoo.org> +# @SUPPORTED_EAPIS: 4 5 6 7 +# @BLURB: An eclass for installing Ruby packages to behave like RubyGems. +# @DESCRIPTION: +# This eclass allows to install arbitrary Ruby libraries (including Gems), +# providing integration into the RubyGems system even for "regular" packages. + +inherit ruby-ng + +# @ECLASS-VARIABLE: RUBY_FAKEGEM_NAME +# @DESCRIPTION: +# Sets the Gem name for the generated fake gemspec. +# This variable MUST be set before inheriting the eclass. +RUBY_FAKEGEM_NAME="${RUBY_FAKEGEM_NAME:-${PN}}" + +# @ECLASS-VARIABLE: RUBY_FAKEGEM_VERSION +# @DESCRIPTION: +# Sets the Gem version for the generated fake gemspec. +# This variable MUST be set before inheriting the eclass. +RUBY_FAKEGEM_VERSION="${RUBY_FAKEGEM_VERSION:-${PV/_pre/.pre}}" + +# @ECLASS-VARIABLE: RUBY_FAKEGEM_TASK_DOC +# @DESCRIPTION: +# Specify the rake(1) task to run to generate documentation. +RUBY_FAKEGEM_TASK_DOC="${RUBY_FAKEGEM_TASK_DOC-rdoc}" + +# @ECLASS-VARIABLE: RUBY_FAKEGEM_RECIPE_TEST +# @DESCRIPTION: +# Specify one of the default testing function for ruby-fakegem: +# - rake (default; see also RUBY_FAKEGEM_TASK_TEST) +# - rspec (calls ruby-ng_rspec, adds dev-ruby/rspec:2 to the dependencies) +# - rspec3 (calls ruby-ng_rspec, adds dev-ruby/rspec:3 to the dependencies) +# - cucumber (calls ruby-ng_cucumber, adds dev-util/cucumber to the +# dependencies) +# - none +RUBY_FAKEGEM_RECIPE_TEST="${RUBY_FAKEGEM_RECIPE_TEST-rake}" + +# @ECLASS-VARIABLE: RUBY_FAKEGEM_TASK_TEST +# @DESCRIPTION: +# Specify the rake(1) task used for executing tests. Only valid +# if RUBY_FAKEGEM_RECIPE_TEST is set to "rake" (the default). +RUBY_FAKEGEM_TASK_TEST="${RUBY_FAKEGEM_TASK_TEST-test}" + +# @ECLASS-VARIABLE: RUBY_FAKEGEM_RECIPE_DOC +# @DESCRIPTION: +# Specify one of the default API doc building function for ruby-fakegem: +# - rake (default; see also RUBY_FAKEGEM_TASK_DOC) +# - rdoc (calls `rdoc-2`, adds dev-ruby/rdoc to the dependencies); +# - yard (calls `yard`, adds dev-ruby/yard to the dependencies); +# - none +case ${EAPI} in + 4|5|6) + RUBY_FAKEGEM_RECIPE_DOC="${RUBY_FAKEGEM_RECIPE_DOC-rake}" + ;; + *) + RUBY_FAKEGEM_RECIPE_DOC="${RUBY_FAKEGEM_RECIPE_DOC-rdoc}" + ;; +esac + +# @ECLASS-VARIABLE: RUBY_FAKEGEM_DOCDIR +# @DEFAULT_UNSET +# @DESCRIPTION: +# Specify the directory under which the documentation is built; +# if empty no documentation will be installed automatically. +# Note: if RUBY_FAKEGEM_RECIPE_DOC is set to `rdoc`, this variable is +# hardwired to `doc`. + +# @ECLASS-VARIABLE: RUBY_FAKEGEM_EXTRADOC +# @DEFAULT_UNSET +# @DESCRIPTION: +# Extra documentation to install (readme, changelogs, …). + +# @ECLASS-VARIABLE: RUBY_FAKEGEM_DOC_SOURCES +# @DESCRIPTION: +# Allow settings defined sources to scan for documentation. +# This only applies if RUBY_FAKEGEM_DOC_TASK is set to `rdoc`. +RUBY_FAKEGEM_DOC_SOURCES="${RUBY_FAKEGEM_DOC_SOURCES-lib}" + +# @ECLASS-VARIABLE: RUBY_FAKEGEM_BINWRAP +# @DESCRIPTION: +# Binaries to wrap around (relative to the RUBY_FAKEGEM_BINDIR directory) +RUBY_FAKEGEM_BINWRAP="${RUBY_FAKEGEM_BINWRAP-*}" + +# @ECLASS-VARIABLE: RUBY_FAKEGEM_BINDIR +# @DESCRIPTION: +# Path that contains binaries to be binwrapped. Equivalent to the +# gemspec bindir option. +RUBY_FAKEGEM_BINDIR="${RUBY_FAKEGEM_BINDIR-bin}" + +# @ECLASS-VARIABLE: RUBY_FAKEGEM_REQUIRE_PATHS +# @DEFAULT_UNSET +# @DESCRIPTION: +# Extra require paths (beside lib) to add to the specification + +# @ECLASS-VARIABLE: RUBY_FAKEGEM_GEMSPEC +# @DEFAULT_UNSET +# @DESCRIPTION: +# Filename of .gemspec file to install instead of generating a generic one. + +# @ECLASS-VARIABLE: RUBY_FAKEGEM_EXTRAINSTALL +# @DEFAULT_UNSET +# @DESCRIPTION: +# List of files and directories relative to the top directory that also +# get installed. Some gems provide extra files such as version information, +# Rails generators, or data that needs to be installed as well. + +case "${EAPI:-0}" in + 0|1|2|3) + die "Unsupported EAPI=${EAPI} (too old) for ruby-fakegem.eclass" ;; + 4|5|6|7) + ;; + *) + die "Unsupported EAPI=${EAPI} (unknown) for ${ECLASS}" + ;; +esac + + +RUBY_FAKEGEM_SUFFIX="${RUBY_FAKEGEM_SUFFIX:-}" + + +[[ ${RUBY_FAKEGEM_TASK_DOC} == "" ]] && RUBY_FAKEGEM_RECIPE_DOC="none" + +case ${RUBY_FAKEGEM_RECIPE_DOC} in + rake) + IUSE+=" doc" + ruby_add_bdepend "doc? ( dev-ruby/rake )" + RUBY_FAKEGEM_DOCDIR="doc" + ;; + rdoc) + IUSE+=" doc" + ruby_add_bdepend "doc? ( dev-ruby/rdoc )" + RUBY_FAKEGEM_DOCDIR="doc" + ;; + yard) + IUSE+="doc" + ruby_add_bdepend "doc? ( dev-ruby/yard )" + RUBY_FAKEGEM_DOCDIR="doc" + ;; + none) + [[ -n ${RUBY_FAKEGEM_DOCDIR} ]] && IUSE+=" doc" + ;; +esac + +[[ ${RUBY_FAKEGEM_TASK_TEST} == "" ]] && RUBY_FAKEGEM_RECIPE_TEST="none" + +case ${RUBY_FAKEGEM_RECIPE_TEST} in + rake) + IUSE+=" test" + RESTRICT+=" !test? ( test )" + ruby_add_bdepend "test? ( dev-ruby/rake )" + ;; + rspec) + IUSE+=" test" + RESTRICT+=" !test? ( test )" + # Also require a new enough rspec-core version that installs the + # rspec-2 wrapper. + ruby_add_bdepend "test? ( dev-ruby/rspec:2 >=dev-ruby/rspec-core-2.14.8-r2 )" + ;; + rspec3) + IUSE+=" test" + RESTRICT+=" !test? ( test )" + ruby_add_bdepend "test? ( dev-ruby/rspec:3 )" + ;; + cucumber) + IUSE+=" test" + RESTRICT+=" !test? ( test )" + ruby_add_bdepend "test? ( dev-util/cucumber )" + ;; + *) + RUBY_FAKEGEM_RECIPE_TEST="none" + ;; +esac + +SRC_URI="https://rubygems.org/gems/${RUBY_FAKEGEM_NAME}-${RUBY_FAKEGEM_VERSION}${RUBY_FAKEGEM_SUFFIX:+-${RUBY_FAKEGEM_SUFFIX}}.gem" + +# dev-ruby/psych is no longer installed and is incompatible with modern +# ruby versions. +ruby_add_bdepend "virtual/rubygems !!dev-ruby/psych" +ruby_add_rdepend virtual/rubygems +case ${EAPI} in + 4|5|6) + ;; + *) + ruby_add_depend virtual/rubygems + ;; +esac + +# @FUNCTION: ruby_fakegem_gemsdir +# @RETURN: Returns the gem data directory +# @DESCRIPTION: +# This function returns the gems data directory for the ruby +# implementation in question. +ruby_fakegem_gemsdir() { + local _gemsitedir=$(ruby_rbconfig_value 'sitelibdir') + _gemsitedir=${_gemsitedir//site_ruby/gems} + _gemsitedir=${_gemsitedir#${EPREFIX}} + + [[ -z ${_gemsitedir} ]] && { + eerror "Unable to find the gems dir" + die "Unable to find the gems dir" + } + + echo "${_gemsitedir}" +} + +# @FUNCTION: ruby_fakegem_doins +# @USAGE: <file> [file...] +# @DESCRIPTION: +# Installs the specified file(s) into the gems directory. +ruby_fakegem_doins() { + ( + insinto $(ruby_fakegem_gemsdir)/gems/${RUBY_FAKEGEM_NAME}-${RUBY_FAKEGEM_VERSION} + doins "$@" + ) || die "failed $0 $@" +} + +# @FUNCTION: ruby_fakegem_newins +# @USAGE: <file> <newname> +# @DESCRIPTION: +# Installs the specified file into the gems directory using the provided filename. +ruby_fakegem_newins() { + ( + # Since newins does not accept full paths but just basenames + # for the target file, we want to extend it here. + local newdirname=/$(dirname "$2") + [[ ${newdirname} == "/." ]] && newdirname= + + local newbasename=$(basename "$2") + + insinto $(ruby_fakegem_gemsdir)/gems/${RUBY_FAKEGEM_NAME}-${RUBY_FAKEGEM_VERSION}${newdirname} + newins "$1" ${newbasename} + ) || die "failed $0 $@" +} + +# @FUNCTION: ruby_fakegem_install_gemspec +# @DESCRIPTION: +# Install a .gemspec file for this package. Either use the file indicated +# by the RUBY_FAKEGEM_GEMSPEC variable, or generate one using +# ruby_fakegem_genspec. +ruby_fakegem_install_gemspec() { + local gemspec="${T}"/${RUBY_FAKEGEM_NAME}-${_ruby_implementation} + + ( + if [[ ${RUBY_FAKEGEM_GEMSPEC} != "" ]]; then + ruby_fakegem_gemspec_gemspec ${RUBY_FAKEGEM_GEMSPEC} ${gemspec} + else + local metadata="${WORKDIR}"/${_ruby_implementation}/metadata + + if [[ -e ${metadata} ]]; then + ruby_fakegem_metadata_gemspec ${metadata} ${gemspec} + else + ruby_fakegem_genspec ${gemspec} + fi + fi + ) || die "Unable to generate gemspec file." + + insinto $(ruby_fakegem_gemsdir)/specifications + newins ${gemspec} ${RUBY_FAKEGEM_NAME}-${RUBY_FAKEGEM_VERSION}.gemspec || die "Unable to install gemspec file." +} + +# @FUNCTION: ruby_fakegem_gemspec_gemspec +# @USAGE: <gemspec-input> <gemspec-output> +# @DESCRIPTION: +# Generates an installable version of the specification indicated by +# RUBY_FAKEGEM_GEMSPEC. This file is eval'ed to produce a final specification +# in a way similar to packaging the gemspec file. +ruby_fakegem_gemspec_gemspec() { + ${RUBY} -e "puts eval(File::open('$1').read).to_ruby" > $2 +} + +# @FUNCTION: ruby_fakegem_metadata_gemspec +# @USAGE: <gemspec-metadata> <gemspec-output> +# @DESCRIPTION: +# Generates an installable version of the specification indicated by +# the metadata distributed by the gem itself. This is similar to how +# rubygems creates an installation from a .gem file. +ruby_fakegem_metadata_gemspec() { + ${RUBY} -r yaml -e "puts Gem::Specification.from_yaml(File::open('$1', :encoding => 'UTF-8').read).to_ruby" > $2 +} + +# @FUNCTION: ruby_fakegem_genspec +# @USAGE: <output-gemspec> +# @DESCRIPTION: +# Generates a gemspec for the package and places it into the "specifications" +# directory of RubyGems. +# If the metadata normally distributed with a gem is present then that is +# used to generate the gemspec file. +# +# As a fallback we can generate our own version. +# In the gemspec, the following values are set: name, version, summary, +# homepage, and require_paths=["lib"]. +# See RUBY_FAKEGEM_NAME and RUBY_FAKEGEM_VERSION for setting name and version. +# See RUBY_FAKEGEM_REQUIRE_PATHS for setting extra require paths. +ruby_fakegem_genspec() { + case ${EAPI} in + 4|5|6) ;; + *) + eqawarn "Generating generic fallback gemspec *without* dependencies" + eqawarn "This will only work when there are no runtime dependencies" + eqawarn "Set RUBY_FAKEGEM_GEMSPEC to generate a proper specifications file" + ;; + esac + + local required_paths="'lib'" + for path in ${RUBY_FAKEGEM_REQUIRE_PATHS}; do + required_paths="${required_paths}, '${path}'" + done + + # We use the _ruby_implementation variable to avoid having stray + # copies with different implementations; while for now we're using + # the same exact content, we might have differences in the future, + # so better taking this into consideration. + local quoted_description=${DESCRIPTION//\"/\\\"} + cat - > $1 <<EOF +# generated by ruby-fakegem.eclass +Gem::Specification.new do |s| + s.name = "${RUBY_FAKEGEM_NAME}" + s.version = "${RUBY_FAKEGEM_VERSION}" + s.summary = "${quoted_description}" + s.homepage = "${HOMEPAGE}" + s.require_paths = [${required_paths}] +end +EOF +} + +# @FUNCTION: ruby_fakegem_binwrapper +# @USAGE: <command> [path] [content] +# @DESCRIPTION: +# Creates a new binary wrapper for a command installed by the RubyGem. +# path defaults to /usr/bin/$command content is optional and can be used +# to inject additional ruby code into the wrapper. This may be useful to +# e.g. force a specific version using the gem command. +ruby_fakegem_binwrapper() { + ( + local gembinary=$1 + local newbinary=${2:-/usr/bin/$gembinary} + local content=$3 + local relativegembinary=${RUBY_FAKEGEM_NAME}-${RUBY_FAKEGEM_VERSION}/${RUBY_FAKEGEM_BINDIR}/${gembinary} + local binpath=$(dirname $newbinary) + [[ ${binpath} = . ]] && binpath=/usr/bin + + # Try to find out whether the package is going to install for + # one or multiple implementations; if we're installing for a + # *single* implementation, no need to use “/usr/bin/env ruby” + # in the shebang, and we can actually avoid errors when + # calling the script by default. + local rubycmd= + for implementation in $(_ruby_get_all_impls); do + # ignore non-enabled implementations + use ruby_targets_${implementation} || continue + if [ -z $rubycmd ]; then + # if no other implementation was set before, set it. + rubycmd="$(ruby_implementation_command ${implementation})" + else + # if another implementation already arrived, then make + # it generic and break out of the loop. This ensures + # that we do at most two iterations. + rubycmd="/usr/bin/env ruby" + break + fi + done + + cat - > "${T}"/gembin-wrapper-${gembinary} <<EOF +#!${rubycmd} +# This is a simplified version of the RubyGems wrapper +# +# Generated by ruby-fakegem.eclass + +require 'rubygems' + +${content} +load Gem::default_path[-1] + "/gems/${relativegembinary}" + +EOF + + exeinto ${binpath:-/usr/bin} + newexe "${T}"/gembin-wrapper-${gembinary} $(basename $newbinary) + ) || die "Unable to create fakegem wrapper" +} + +# @FUNCTION: all_fakegem_compile +# @DESCRIPTION: +# Build documentation for the package if indicated by the doc USE flag +# and if there is a documetation task defined. +all_fakegem_compile() { + if [[ -n ${RUBY_FAKEGEM_DOCDIR} ]] && use doc; then + case ${RUBY_FAKEGEM_RECIPE_DOC} in + rake) + rake ${RUBY_FAKEGEM_TASK_DOC} || die "failed to (re)build documentation" + ;; + rdoc) + rdoc ${RUBY_FAKEGEM_DOC_SOURCES} || die "failed to (re)build documentation" + rm -f doc/js/*.gz || die "failed to remove duplicated compressed javascript files" + ;; + yard) + yard doc ${RUBY_FAKEGEM_DOC_SOURCES} || die "failed to (re)build documentation" + ;; + esac + fi +} + +# @FUNCTION: all_ruby_unpack +# @DESCRIPTION: +# Unpack the source archive, including support for unpacking gems. +all_ruby_unpack() { + # Special support for extracting .gem files; the file need to be + # extracted twice and the mtime from the archive _has_ to be + # ignored (it's always set to epoch 0). + for archive in ${A}; do + case "${archive}" in + *.gem) + # Make sure that we're not running unpack for more than + # one .gem file, since we won't support that at all. + [[ -d "${S}" ]] && die "Unable to unpack ${archive}, ${S} exists" + + ebegin "Unpacking .gem file..." + tar -mxf "${DISTDIR}"/${archive} || die + eend $? + + ebegin "Uncompressing metadata" + gunzip metadata.gz || die + eend $? + + mkdir "${S}" + pushd "${S}" &>/dev/null || die + + ebegin "Unpacking data.tar.gz" + tar -mxf "${my_WORKDIR}"/data.tar.gz || die + eend $? + + popd &>/dev/null || die + ;; + *.patch.bz2) + # We apply the patches with RUBY_PATCHES directly from DISTDIR, + # as the WORKDIR variable changes value between the global-scope + # and the time all_ruby_unpack/_prepare are called. Since we can + # simply decompress them when applying, this is much easier to + # deal with for us. + einfo "Keeping ${archive} as-is" + ;; + *) + unpack ${archive} + ;; + esac + done +} + +# @FUNCTION: all_ruby_compile +# @DESCRIPTION: +# Compile the package. +all_ruby_compile() { + all_fakegem_compile +} + +# @FUNCTION: each_fakegem_test +# @DESCRIPTION: +# Run tests for the package for each ruby target if the test task is defined. +each_fakegem_test() { + case ${RUBY_FAKEGEM_RECIPE_TEST} in + rake) + ${RUBY} -S rake ${RUBY_FAKEGEM_TASK_TEST} || die "tests failed" + ;; + rspec) + RSPEC_VERSION=2 ruby-ng_rspec + ;; + rspec3) + RSPEC_VERSION=3 ruby-ng_rspec + ;; + cucumber) + ruby-ng_cucumber + ;; + none) + ewarn "each_fakegem_test called, but \${RUBY_FAKEGEM_RECIPE_TEST} is 'none'" + ;; + esac +} + +if [[ ${RUBY_FAKEGEM_RECIPE_TEST} != none ]]; then + # @FUNCTION: each_ruby_test + # @DESCRIPTION: + # Run the tests for this package. + each_ruby_test() { + each_fakegem_test + } +fi + +# @FUNCTION: each_fakegem_install +# @DESCRIPTION: +# Install the package for each ruby target. +each_fakegem_install() { + ruby_fakegem_install_gemspec + + local _gemlibdirs="${RUBY_FAKEGEM_EXTRAINSTALL}" + for directory in "${RUBY_FAKEGEM_BINDIR}" lib; do + [[ -d ${directory} ]] && _gemlibdirs="${_gemlibdirs} ${directory}" + done + + [[ -n ${_gemlibdirs} ]] && \ + ruby_fakegem_doins -r ${_gemlibdirs} +} + +# @FUNCTION: each_ruby_install +# @DESCRIPTION: +# Install the package for each target. +each_ruby_install() { + each_fakegem_install +} + +# @FUNCTION: all_fakegem_install +# @DESCRIPTION: +# Install files common to all ruby targets. +all_fakegem_install() { + if [[ -n ${RUBY_FAKEGEM_DOCDIR} ]] && use doc; then + for dir in ${RUBY_FAKEGEM_DOCDIR}; do + [[ -d ${dir} ]] || continue + + pushd ${dir} &>/dev/null || die + dodoc -r * || die "failed to install documentation" + popd &>/dev/null || die + done + fi + + if [[ -n ${RUBY_FAKEGEM_EXTRADOC} ]]; then + dodoc ${RUBY_FAKEGEM_EXTRADOC} || die "failed to install further documentation" + fi + + # binary wrappers; we assume that all the implementations get the + # same binaries, or something is wrong anyway, so... + if [[ -n ${RUBY_FAKEGEM_BINWRAP} ]]; then + local bindir=$(find "${D}" -type d -path "*/gems/${RUBY_FAKEGEM_NAME}-${RUBY_FAKEGEM_VERSION}/${RUBY_FAKEGEM_BINDIR}" -print -quit) + + if [[ -d "${bindir}" ]]; then + pushd "${bindir}" &>/dev/null || die + for binary in ${RUBY_FAKEGEM_BINWRAP}; do + ruby_fakegem_binwrapper "${binary}" + done + popd &>/dev/null || die + fi + fi +} + +# @FUNCTION: all_ruby_install +# @DESCRIPTION: +# Install files common to all ruby targets. +all_ruby_install() { + all_fakegem_install +} diff --git a/eclass/ruby-ng-gnome2.eclass b/eclass/ruby-ng-gnome2.eclass new file mode 100644 index 0000000..3b18faf --- /dev/null +++ b/eclass/ruby-ng-gnome2.eclass @@ -0,0 +1,148 @@ +# Copyright 1999-2020 Gentoo Authors +# Distributed under the terms of the GNU General Public License v2 + +# @ECLASS: ruby-ng-gnome2.eclass +# @MAINTAINER: +# Ruby herd <ruby@gentoo.org> +# @AUTHOR: +# Author: Hans de Graaff <graaff@gentoo.org> +# @SUPPORTED_EAPIS: 6 7 +# @BLURB: An eclass to simplify handling of various ruby-gnome2 parts. +# @DESCRIPTION: +# This eclass simplifies installation of the various pieces of +# ruby-gnome2 since they share a very common installation procedure. + +case "${EAPI:-0}" in + 6) inherit eapi7-ver ;; + 7) ;; + *) + die "Unsupported EAPI=${EAPI} (unknown) for ${ECLASS}" + ;; +esac + +RUBY_FAKEGEM_NAME="${RUBY_FAKEGEM_NAME:-${PN#ruby-}}" +RUBY_FAKEGEM_TASK_TEST="" +RUBY_FAKEGEM_TASK_DOC="" + +# @ECLASS-VARIABLE: RUBY_GNOME2_NEED_VIRTX +# @PRE_INHERIT +# @DESCRIPTION: +# If set to 'yes', the test is run with virtx. Set before inheriting this +# eclass. +: ${RUBY_GNOME2_NEED_VIRTX:="no"} + +inherit ruby-fakegem +if [[ ${RUBY_GNOME2_NEED_VIRTX} == yes ]]; then + inherit virtualx +fi + +IUSE="test" +RESTRICT+=" !test? ( test )" + +DEPEND="virtual/pkgconfig" +ruby_add_bdepend " + dev-ruby/pkg-config + test? ( >=dev-ruby/test-unit-2 )" +SRC_URI="mirror://sourceforge/ruby-gnome2/ruby-gnome2-all-${PV}.tar.gz" +HOMEPAGE="https://ruby-gnome2.osdn.jp/" +LICENSE="LGPL-2.1+" +SLOT="0" +if ver_test -ge "3.4.0"; then + SRC_URI="https://github.com/ruby-gnome/ruby-gnome/archive/${PV}.tar.gz -> ruby-gnome2-${PV}.tar.gz" + RUBY_S=ruby-gnome-${PV}/${RUBY_FAKEGEM_NAME} +else + SRC_URI="mirror://sourceforge/ruby-gnome2/ruby-gnome2-all-${PV}.tar.gz" + RUBY_S=ruby-gnome2-all-${PV}/${RUBY_FAKEGEM_NAME} +fi + +ruby-ng-gnome2_all_ruby_prepare() { + # Avoid compilation of dependencies during test. + if [[ -e test/run-test.rb ]]; then + sed -i -e '/system(/s/which make/true/' test/run-test.rb || die + fi + + # work on top directory + pushd .. >/dev/null + + # Avoid native installer + if [[ -e glib2/lib/mkmf-gnome.rb ]]; then + sed -i -e '/native-package-installer/ s:^:#:' \ + -e '/^setup_homebrew/ s:^:#:' glib2/lib/mkmf-gnome.rb || die + fi + + popd >/dev/null +} + +all_ruby_prepare() { + ruby-ng-gnome2_all_ruby_prepare +} + +# @FUNCTION: each_ruby_configure +# @DESCRIPTION: +# Run the configure script in the subbinding for each specific ruby target. +each_ruby_configure() { + [[ -e extconf.rb ]] || return + + ${RUBY} extconf.rb || die "extconf.rb failed" +} + +# @FUNCTION: each_ruby_compile +# @DESCRIPTION: +# Compile the C bindings in the subbinding for each specific ruby target. +each_ruby_compile() { + [[ -e Makefile ]] || return + + # We have injected --no-undefined in Ruby as a safety precaution + # against broken ebuilds, but the Ruby-Gnome bindings + # unfortunately rely on the lazy load of other extensions; see bug + # #320545. + find . -name Makefile -print0 | xargs -0 \ + sed -i -e 's:-Wl,--no-undefined ::' \ + -e "s/^ldflags = /ldflags = $\(LDFLAGS\) /" \ + || die "--no-undefined removal failed" + + emake V=1 +} + +# @FUNCTION: each_ruby_install +# @DESCRIPTION: +# Install the files in the subbinding for each specific ruby target. +each_ruby_install() { + if [[ -e Makefile ]]; then + # Create the directories, or the package will create them as files. + local archdir=$(ruby_rbconfig_value "sitearchdir") + dodir ${archdir#${EPREFIX}} /usr/$(get_libdir)/pkgconfig + + emake DESTDIR="${D}" install + fi + + each_fakegem_install +} + +# @FUNCTION: all_ruby_install +# @DESCRIPTION: +# Install the files common to all ruby targets. +all_ruby_install() { + for doc in ../AUTHORS ../NEWS ChangeLog README; do + [[ -s ${doc} ]] && dodoc $doc + done + if [[ -d sample ]]; then + insinto /usr/share/doc/${PF} + doins -r sample + fi + + all_fakegem_install +} + +# @FUNCTION: each_ruby_test +# @DESCRIPTION: +# Run the tests for this package. +each_ruby_test() { + [[ -e test/run-test.rb ]] || return + + if [[ ${RUBY_GNOME2_NEED_VIRTX} == yes ]]; then + virtx ${RUBY} test/run-test.rb + else + ${RUBY} test/run-test.rb || die + fi +} diff --git a/eclass/ruby-ng.eclass b/eclass/ruby-ng.eclass new file mode 100644 index 0000000..e52c507 --- /dev/null +++ b/eclass/ruby-ng.eclass @@ -0,0 +1,774 @@ +# Copyright 1999-2020 Gentoo Authors +# Distributed under the terms of the GNU General Public License v2 + +# @ECLASS: ruby-ng.eclass +# @MAINTAINER: +# Ruby herd <ruby@gentoo.org> +# @AUTHOR: +# Author: Diego E. Pettenò <flameeyes@gentoo.org> +# Author: Alex Legler <a3li@gentoo.org> +# Author: Hans de Graaff <graaff@gentoo.org> +# @SUPPORTED_EAPIS: 4 5 6 7 +# @BLURB: An eclass for installing Ruby packages with proper support for multiple Ruby slots. +# @DESCRIPTION: +# The Ruby eclass is designed to allow an easier installation of Ruby packages +# and their incorporation into the Gentoo Linux system. +# +# Currently available targets are listed in ruby-utils.eclass +# +# This eclass does not define the implementation of the configure, +# compile, test, or install phases. Instead, the default phases are +# used. Specific implementations of these phases can be provided in +# the ebuild either to be run for each Ruby implementation, or for all +# Ruby implementations, as follows: +# +# * each_ruby_configure +# * all_ruby_configure + +# @ECLASS-VARIABLE: USE_RUBY +# @DEFAULT_UNSET +# @REQUIRED +# @DESCRIPTION: +# This variable contains a space separated list of targets (see above) a package +# is compatible to. It must be set before the `inherit' call. There is no +# default. All ebuilds are expected to set this variable. + +# @ECLASS-VARIABLE: RUBY_PATCHES +# @DEFAULT_UNSET +# @DESCRIPTION: +# A String or Array of filenames of patches to apply to all implementations. + +# @ECLASS-VARIABLE: RUBY_OPTIONAL +# @DEFAULT_UNSET +# @DESCRIPTION: +# Set the value to "yes" to make the dependency on a Ruby interpreter +# optional and then ruby_implementations_depend() to help populate +# BDEPEND, DEPEND and RDEPEND. + +# @ECLASS-VARIABLE: RUBY_S +# @DEFAULT_UNSET +# @DESCRIPTION: +# If defined this variable determines the source directory name after +# unpacking. This defaults to the name of the package. Note that this +# variable supports a wildcard mechanism to help with github tarballs +# that contain the commit hash as part of the directory name. + +# @ECLASS-VARIABLE: RUBY_QA_ALLOWED_LIBS +# @DEFAULT_UNSET +# @DESCRIPTION: +# If defined this variable contains a whitelist of shared objects that +# are allowed to exist even if they don't link to libruby. This avoids +# the QA check that makes this mandatory. This is most likely not what +# you are looking for if you get the related "Missing links" QA warning, +# since the proper fix is almost always to make sure the shared object +# is linked against libruby. There are cases were this is not the case +# and the shared object is generic code to be used in some other way +# (e.g. selenium's firefox driver extension). When set this argument is +# passed to "grep -E" to remove reporting of these shared objects. + +local inherits="" +case ${EAPI} in + 4|5) + inherits="eutils toolchain-funcs" + ;; + 6) + inherits="estack toolchain-funcs" + ;; + *) + inherits="estack" + ;; +esac + +inherit ${inherits} multilib ruby-utils + +EXPORT_FUNCTIONS src_unpack src_prepare src_configure src_compile src_test src_install pkg_setup + +case ${EAPI} in + 0|1|2|3) + die "Unsupported EAPI=${EAPI} (too old) for ruby-ng.eclass" ;; + 4|5|6|7) + # S is no longer automatically assigned when it doesn't exist. + S="${WORKDIR}" + ;; + *) + die "Unknown EAPI=${EAPI} for ruby-ng.eclass" +esac + +# @FUNCTION: ruby_implementation_depend +# @USAGE: target [comparator [version]] +# @RETURN: Package atom of a Ruby implementation to be used in dependencies. +# @DESCRIPTION: +# This function returns the formal package atom for a Ruby implementation. +# +# `target' has to be one of the valid values for USE_RUBY (see above) +# +# Set `comparator' and `version' to include a comparator (=, >=, etc.) and a +# version string to the returned string +ruby_implementation_depend() { + _ruby_implementation_depend $1 +} + +# @FUNCTION: _ruby_get_all_impls +# @INTERNAL +# @RETURN: list of valid values in USE_RUBY +# Return a list of valid implementations in USE_RUBY, skipping the old +# implementations that are no longer supported. +_ruby_get_all_impls() { + local i + for i in ${USE_RUBY}; do + case ${i} in + # removed implementations + ruby19|ruby20|ruby21|ruby22|ruby23|ruby24|jruby) + ;; + *) + echo ${i};; + esac + done +} + +# @FUNCTION: ruby_samelib +# @RETURN: use flag string with current ruby implementations +# @DESCRIPTION: +# Convenience function to output the use dependency part of a +# dependency. Used as a building block for ruby_add_rdepend() and +# ruby_add_bdepend(), but may also be useful in an ebuild to specify +# more complex dependencies. +ruby_samelib() { + local res= + for _ruby_implementation in $(_ruby_get_all_impls); do + has -${_ruby_implementation} $@ || \ + res="${res}ruby_targets_${_ruby_implementation}(-)?," + done + + echo "[${res%,}]" +} + +_ruby_atoms_samelib_generic() { + eshopts_push -o noglob + echo "RUBYTARGET? (" + for token in $*; do + case "$token" in + "||" | "(" | ")" | *"?") + echo "${token}" ;; + *]) + echo "${token%[*}[RUBYTARGET(-),${token/*[}" ;; + *) + echo "${token}[RUBYTARGET(-)]" ;; + esac + done + echo ")" + eshopts_pop +} + +# @FUNCTION: ruby_implementation_command +# @RETURN: the path to the given ruby implementation +# @DESCRIPTION: +# Not all implementations have the same command basename as the +# target; This function translate between the two +ruby_implementation_command() { + local _ruby_name=$1 + + # Add all USE_RUBY values where the flag name diverts from the binary here + + echo $(type -p ${_ruby_name} 2>/dev/null) +} + +_ruby_atoms_samelib() { + local atoms=$(_ruby_atoms_samelib_generic "$*") + + for _ruby_implementation in $(_ruby_get_all_impls); do + echo "${atoms//RUBYTARGET/ruby_targets_${_ruby_implementation}}" + done +} + +_ruby_wrap_conditions() { + local conditions="$1" + local atoms="$2" + + for condition in $conditions; do + atoms="${condition}? ( ${atoms} )" + done + + echo "$atoms" +} + +# @FUNCTION: ruby_add_rdepend +# @USAGE: dependencies +# @DESCRIPTION: +# Adds the specified dependencies, with use condition(s) to RDEPEND, +# taking the current set of ruby targets into account. This makes sure +# that all ruby dependencies of the package are installed for the same +# ruby targets. Use this function for all ruby dependencies instead of +# setting RDEPEND yourself. The list of atoms uses the same syntax as +# normal dependencies. +# +# Note: runtime dependencies are also added as build-time test +# dependencies. +ruby_add_rdepend() { + case $# in + 1) ;; + 2) + case ${EAPI} in + 4|5|6) + [[ "${GENTOO_DEV}" == "yes" ]] && eqawarn "You can now use the usual syntax in ruby_add_rdepend for $CATEGORY/$PF" + ruby_add_rdepend "$(_ruby_wrap_conditions "$1" "$2")" + return + ;; + *) + die "Use the usual depend syntax with a single argument in ruby_add_rdepend" + ;; + esac + ;; + *) + die "bad number of arguments to $0" + ;; + esac + + local dependency=$(_ruby_atoms_samelib "$1") + + RDEPEND="${RDEPEND} $dependency" + + # Add the dependency as a test-dependency since we're going to + # execute the code during test phase. + case ${EAPI} in + 4|5|6) DEPEND="${DEPEND} test? ( ${dependency} )" ;; + *) BDEPEND="${BDEPEND} test? ( ${dependency} )" ;; + esac + if ! has test "$IUSE"; then + IUSE+=" test" + RESTRICT+=" !test? ( test )" + fi +} + +# @FUNCTION: ruby_add_bdepend +# @USAGE: dependencies +# @DESCRIPTION: +# Adds the specified dependencies, with use condition(s) to DEPEND (or +# BDEPEND in EAPI7), taking the current set of ruby targets into +# account. This makes sure that all ruby dependencies of the package are +# installed for the same ruby targets. Use this function for all ruby +# dependencies instead of setting DEPEND or BDEPEND yourself. The list +# of atoms uses the same syntax as normal dependencies. +ruby_add_bdepend() { + case $# in + 1) ;; + 2) + case ${EAPI} in + 4|5|6) + [[ "${GENTOO_DEV}" == "yes" ]] && eqawarn "You can now use the usual syntax in ruby_add_bdepend for $CATEGORY/$PF" + ruby_add_bdepend "$(_ruby_wrap_conditions "$1" "$2")" + return + ;; + *) + die "Use the usual depend syntax with a single argument in ruby_add_bdepend" + ;; + esac + ;; + *) + die "bad number of arguments to $0" + ;; + esac + + local dependency=$(_ruby_atoms_samelib "$1") + + case ${EAPI} in + 4|5|6) DEPEND="${DEPEND} $dependency" ;; + *) BDEPEND="${BDEPEND} $dependency" ;; + esac + RDEPEND="${RDEPEND}" +} + +# @FUNCTION: ruby_add_depend +# @USAGE: dependencies +# @DESCRIPTION: +# Adds the specified dependencies to DEPEND in EAPI7, similar to +# ruby_add_bdepend. +ruby_add_depend() { + case ${EAPI} in + 4|5|6) die "only available in EAPI 7 and newer" ;; + *) ;; + esac + + case $# in + 1) ;; + *) die "bad number of arguments to $0" ;; + esac + + local dependency=$(_ruby_atoms_samelib "$1") + + DEPEND="${DEPEND} $dependency" +} + +# @FUNCTION: ruby_get_use_implementations +# @DESCRIPTION: +# Gets an array of ruby use targets enabled by the user +ruby_get_use_implementations() { + local i implementation + for implementation in $(_ruby_get_all_impls); do + use ruby_targets_${implementation} && i+=" ${implementation}" + done + echo $i +} + +# @FUNCTION: ruby_get_use_targets +# @DESCRIPTION: +# Gets an array of ruby use targets that the ebuild sets +ruby_get_use_targets() { + local t implementation + for implementation in $(_ruby_get_all_impls); do + t+=" ruby_targets_${implementation}" + done + echo $t +} + +# @FUNCTION: ruby_implementations_depend +# @RETURN: Dependencies suitable for injection into DEPEND and RDEPEND. +# @DESCRIPTION: +# Produces the dependency string for the various implementations of ruby +# which the package is being built against. This should not be used when +# RUBY_OPTIONAL is unset but must be used if RUBY_OPTIONAL=yes. Do not +# confuse this function with ruby_implementation_depend(). +# +# @EXAMPLE: +# EAPI=7 +# RUBY_OPTIONAL=yes +# +# inherit ruby-ng +# ... +# DEPEND="ruby? ( $(ruby_implementations_depend) )" +# RDEPEND="${DEPEND}" +ruby_implementations_depend() { + local depend + for _ruby_implementation in $(_ruby_get_all_impls); do + depend="${depend}${depend+ }ruby_targets_${_ruby_implementation}? ( $(ruby_implementation_depend $_ruby_implementation) )" + done + echo "${depend}" +} + +IUSE+=" $(ruby_get_use_targets)" +# If you specify RUBY_OPTIONAL you also need to take care of +# ruby useflag and dependency. +if [[ ${RUBY_OPTIONAL} != yes ]]; then + DEPEND="${DEPEND} $(ruby_implementations_depend)" + RDEPEND="${RDEPEND} $(ruby_implementations_depend)" + REQUIRED_USE+=" || ( $(ruby_get_use_targets) )" + case ${EAPI} in + 4|5|6) ;; + *) BDEPEND="${BDEPEND} $(ruby_implementations_depend)" ;; + esac +fi + +_ruby_invoke_environment() { + old_S=${S} + if [ -z "${RUBY_S}" ]; then + sub_S=${P} + else + sub_S=${RUBY_S} + fi + + # Special case, for the always-lovely GitHub fetches. With this, + # we allow the star glob to just expand to whatever directory it's + # called. + if [[ "${sub_S}" = *"*"* ]]; then + pushd "${WORKDIR}"/all &>/dev/null || die + # use an array to trigger filename expansion + # fun fact: this expansion fails in src_unpack() but the original + # code did not have any checks for failed expansion, so we can't + # really add one now without redesigning stuff hard. + sub_S=( ${sub_S} ) + if [[ ${#sub_S[@]} -gt 1 ]]; then + die "sub_S did expand to multiple paths: ${sub_S[*]}" + fi + popd &>/dev/null || die + fi + + environment=$1; shift + + my_WORKDIR="${WORKDIR}"/${environment} + S="${my_WORKDIR}"/"${sub_S}" + + if [[ -d "${S}" ]]; then + pushd "$S" &>/dev/null || die + elif [[ -d "${my_WORKDIR}" ]]; then + pushd "${my_WORKDIR}" &>/dev/null || die + else + pushd "${WORKDIR}" &>/dev/null || die + fi + + ebegin "Running ${_PHASE:-${EBUILD_PHASE}} phase for $environment" + "$@" + popd &>/dev/null || die + + S=${old_S} +} + +_ruby_each_implementation() { + local invoked=no + for _ruby_implementation in $(_ruby_get_all_impls); do + # only proceed if it's requested + use ruby_targets_${_ruby_implementation} || continue + + RUBY=$(ruby_implementation_command ${_ruby_implementation}) + invoked=yes + + if [[ -n "$1" ]]; then + _ruby_invoke_environment ${_ruby_implementation} "$@" + fi + + unset RUBY + done + + if [[ ${invoked} == "no" ]]; then + eerror "You need to select at least one compatible Ruby installation target via RUBY_TARGETS in make.conf." + eerror "Compatible targets for this package are: $(_ruby_get_all_impls)" + eerror + eerror "See https://www.gentoo.org/proj/en/prog_lang/ruby/index.xml#doc_chap3 for more information." + eerror + die "No compatible Ruby target selected." + fi +} + +# @FUNCTION: ruby-ng_pkg_setup +# @DESCRIPTION: +# Check whether at least one ruby target implementation is present. +ruby-ng_pkg_setup() { + # This only checks that at least one implementation is present + # before doing anything; by leaving the parameters empty we know + # it's a special case. + _ruby_each_implementation +} + +# @FUNCTION: ruby-ng_src_unpack +# @DESCRIPTION: +# Unpack the source archive. +ruby-ng_src_unpack() { + mkdir "${WORKDIR}"/all + pushd "${WORKDIR}"/all &>/dev/null || die + + # We don't support an each-unpack, it's either all or nothing! + if type all_ruby_unpack &>/dev/null; then + _ruby_invoke_environment all all_ruby_unpack + else + [[ -n ${A} ]] && unpack ${A} + fi + + popd &>/dev/null || die +} + +_ruby_apply_patches() { + case ${EAPI} in + 4|5) + for patch in "${RUBY_PATCHES[@]}"; do + if [ -f "${patch}" ]; then + epatch "${patch}" + elif [ -f "${FILESDIR}/${patch}" ]; then + epatch "${FILESDIR}/${patch}" + else + die "Cannot find patch ${patch}" + fi + done + ;; + 6) + if [[ -n ${RUBY_PATCHES[@]} ]]; then + eqawarn "RUBY_PATCHES is no longer supported, use PATCHES instead" + fi + ;; + *) + if [[ -n ${RUBY_PATCHES[@]} ]]; then + die "RUBY_PATCHES is no longer supported, use PATCHES instead" + fi + ;; + esac + + # This is a special case: instead of executing just in the special + # "all" environment, this will actually copy the effects on _all_ + # the other environments, and is thus executed before the copy + type all_ruby_prepare &>/dev/null && all_ruby_prepare +} + +_ruby_source_copy() { + # Until we actually find a reason not to, we use hardlinks, this + # should reduce the amount of disk space that is wasted by this. + cp -prlP all ${_ruby_implementation} \ + || die "Unable to copy ${_ruby_implementation} environment" +} + +# @FUNCTION: ruby-ng_src_prepare +# @DESCRIPTION: +# Apply patches and prepare versions for each ruby target +# implementation. Also carry out common clean up tasks. +ruby-ng_src_prepare() { + # Way too many Ruby packages are prepared on OSX without removing + # the extra data forks, we do it here to avoid repeating it for + # almost every other ebuild. + find . -name '._*' -delete + + # Handle PATCHES and user supplied patches via the default phase + case ${EAPI} in + 4|5) + ;; + *) + _ruby_invoke_environment all default + ;; + esac + + _ruby_invoke_environment all _ruby_apply_patches + + _PHASE="source copy" \ + _ruby_each_implementation _ruby_source_copy + + if type each_ruby_prepare &>/dev/null; then + _ruby_each_implementation each_ruby_prepare + fi +} + +# @FUNCTION: ruby-ng_src_configure +# @DESCRIPTION: +# Configure the package. +ruby-ng_src_configure() { + if type each_ruby_configure &>/dev/null; then + _ruby_each_implementation each_ruby_configure + fi + + type all_ruby_configure &>/dev/null && \ + _ruby_invoke_environment all all_ruby_configure +} + +# @FUNCTION: ruby-ng_src_compile +# @DESCRIPTION: +# Compile the package. +ruby-ng_src_compile() { + if type each_ruby_compile &>/dev/null; then + _ruby_each_implementation each_ruby_compile + fi + + type all_ruby_compile &>/dev/null && \ + _ruby_invoke_environment all all_ruby_compile +} + +# @FUNCTION: ruby-ng_src_test +# @DESCRIPTION: +# Run tests for the package. +ruby-ng_src_test() { + if type each_ruby_test &>/dev/null; then + _ruby_each_implementation each_ruby_test + fi + + type all_ruby_test &>/dev/null && \ + _ruby_invoke_environment all all_ruby_test +} + +_each_ruby_check_install() { + local scancmd=scanelf + # we have a Mach-O object here + [[ ${CHOST} == *-darwin ]] && scancmd=scanmacho + + local libruby_basename=$(ruby_rbconfig_value 'LIBRUBY_SO') + local libruby_soname=$(basename $(${scancmd} -F "%S#F" -qS "${EPREFIX}/usr/$(get_libdir)/${libruby_basename}") 2>/dev/null) + local sitedir=$(ruby_rbconfig_value 'sitedir') + local sitelibdir=$(ruby_rbconfig_value 'sitelibdir') + + # The current implementation lacks libruby (i.e.: jruby) + [[ -z ${libruby_soname} ]] && return 0 + + # Check also the gems directory, since we could be installing compiled + # extensions via ruby-fakegem; make sure to check only in sitelibdir, since + # that's what changes between two implementations (otherwise you'd get false + # positives now that Ruby 1.9.2 installs with the same sitedir as 1.8) + ${scancmd} -qnR "${D}${sitelibdir}" "${D}${sitelibdir/site_ruby/gems}" \ + | fgrep -v "${libruby_soname}" \ + | grep -E -v "${RUBY_QA_ALLOWED_LIBS}" \ + > "${T}"/ruby-ng-${_ruby_implementation}-mislink.log + + if [[ -s "${T}"/ruby-ng-${_ruby_implementation}-mislink.log ]]; then + ewarn "Extensions installed for ${_ruby_implementation} with missing links to ${libruby_soname}" + ewarn $(< "${T}"/ruby-ng-${_ruby_implementation}-mislink.log ) + die "Missing links to ${libruby_soname}" + fi +} + +# @FUNCTION: ruby-ng_src_install +# @DESCRIPTION: +# Install the package for each ruby target implementation. +ruby-ng_src_install() { + if type each_ruby_install &>/dev/null; then + _ruby_each_implementation each_ruby_install + fi + + type all_ruby_install &>/dev/null && \ + _ruby_invoke_environment all all_ruby_install + + _PHASE="check install" \ + _ruby_each_implementation _each_ruby_check_install +} + +# @FUNCTION: ruby_rbconfig_value +# @USAGE: rbconfig item +# @RETURN: Returns the value of the given rbconfig item of the Ruby interpreter in ${RUBY}. +ruby_rbconfig_value() { + echo $(${RUBY} -rrbconfig -e "puts RbConfig::CONFIG['$1']") +} + +# @FUNCTION: doruby +# @USAGE: file [file...] +# @DESCRIPTION: +# Installs the specified file(s) into the sitelibdir of the Ruby interpreter in ${RUBY}. +doruby() { + [[ -z ${RUBY} ]] && die "\$RUBY is not set" + ( # don't want to pollute calling env + sitelibdir=$(ruby_rbconfig_value 'sitelibdir') + insinto ${sitelibdir#${EPREFIX}} + insopts -m 0644 + doins "$@" + ) || die "failed to install $@" +} + +# @FUNCTION: ruby_get_libruby +# @RETURN: The location of libruby*.so belonging to the Ruby interpreter in ${RUBY}. +ruby_get_libruby() { + ${RUBY} -rrbconfig -e 'puts File.join(RbConfig::CONFIG["libdir"], RbConfig::CONFIG["LIBRUBY"])' +} + +# @FUNCTION: ruby_get_hdrdir +# @RETURN: The location of the header files belonging to the Ruby interpreter in ${RUBY}. +ruby_get_hdrdir() { + local rubyhdrdir=$(ruby_rbconfig_value 'rubyhdrdir') + + if [[ "${rubyhdrdir}" = "nil" ]] ; then + rubyhdrdir=$(ruby_rbconfig_value 'archdir') + fi + + echo "${rubyhdrdir}" +} + +# @FUNCTION: ruby_get_version +# @RETURN: The version of the Ruby interpreter in ${RUBY}, or what 'ruby' points to. +ruby_get_version() { + local ruby=${RUBY:-$(type -p ruby 2>/dev/null)} + + echo $(${ruby} -e 'puts RUBY_VERSION') +} + +# @FUNCTION: ruby_get_implementation +# @RETURN: The implementation of the Ruby interpreter in ${RUBY}, or what 'ruby' points to. +ruby_get_implementation() { + local ruby=${RUBY:-$(type -p ruby 2>/dev/null)} + + case $(${ruby} --version) in + *rubinius*) + echo "rbx" + ;; + *) + echo "mri" + ;; + esac +} + +# @FUNCTION: ruby-ng_rspec <arguments> +# @DESCRIPTION: +# This is simply a wrapper around the rspec command (executed by $RUBY}) +# which also respects TEST_VERBOSE and NOCOLOR environment variables. +# Optionally takes arguments to pass on to the rspec invocation. The +# environment variable RSPEC_VERSION can be used to control the specific +# rspec version that must be executed. It defaults to 2 for historical +# compatibility. +ruby-ng_rspec() { + local version=${RSPEC_VERSION-2} + local files="$@" + + # Explicitly pass the expected spec directory since the versioned + # rspec wrappers don't handle this automatically. + if [ ${#@} -eq 0 ]; then + files="spec" + fi + + if [[ "${DEPEND}${BDEPEND}" != *"dev-ruby/rspec"* ]]; then + ewarn "Missing test dependency dev-ruby/rspec" + fi + + local rspec_params= + case ${NOCOLOR} in + 1|yes|true) + rspec_params+=" --no-color" + ;; + *) + rspec_params+=" --color" + ;; + esac + + case ${TEST_VERBOSE} in + 1|yes|true) + rspec_params+=" --format documentation" + ;; + *) + rspec_params+=" --format progress" + ;; + esac + + ${RUBY} -S rspec-${version} ${rspec_params} ${files} || die "rspec failed" +} + +# @FUNCTION: ruby-ng_cucumber +# @DESCRIPTION: +# This is simply a wrapper around the cucumber command (executed by $RUBY}) +# which also respects TEST_VERBOSE and NOCOLOR environment variables. +ruby-ng_cucumber() { + if [[ "${DEPEND}${BDEPEND}" != *"dev-util/cucumber"* ]]; then + ewarn "Missing test dependency dev-util/cucumber" + fi + + local cucumber_params= + case ${NOCOLOR} in + 1|yes|true) + cucumber_params+=" --no-color" + ;; + *) + cucumber_params+=" --color" + ;; + esac + + case ${TEST_VERBOSE} in + 1|yes|true) + cucumber_params+=" --format pretty" + ;; + *) + cucumber_params+=" --format progress" + ;; + esac + + ${RUBY} -S cucumber ${cucumber_params} "$@" || die "cucumber failed" +} + +# @FUNCTION: ruby-ng_testrb-2 +# @DESCRIPTION: +# This is simply a replacement for the testrb command that load the test +# files and execute them, with test-unit 2.x. This actually requires +# either an old test-unit-2 version or 2.5.1-r1 or later, as they remove +# their script and we installed a broken wrapper for a while. +# This also respects TEST_VERBOSE and NOCOLOR environment variables. +ruby-ng_testrb-2() { + if [[ "${DEPEND}${BDEPEND}" != *"dev-ruby/test-unit"* ]]; then + ewarn "Missing test dependency dev-ruby/test-unit" + fi + + local testrb_params= + case ${NOCOLOR} in + 1|yes|true) + testrb_params+=" --no-use-color" + ;; + *) + testrb_params+=" --use-color=auto" + ;; + esac + + case ${TEST_VERBOSE} in + 1|yes|true) + testrb_params+=" --verbose=verbose" + ;; + *) + testrb_params+=" --verbose=normal" + ;; + esac + + ${RUBY} -S testrb-2 ${testrb_params} "$@" || die "testrb-2 failed" +} diff --git a/eclass/ruby-single.eclass b/eclass/ruby-single.eclass new file mode 100644 index 0000000..4ca5f5e --- /dev/null +++ b/eclass/ruby-single.eclass @@ -0,0 +1,91 @@ +# Copyright 1999-2018 Gentoo Foundation +# Distributed under the terms of the GNU General Public License v2 + +# @ECLASS: ruby-single.eclass +# @MAINTAINER: +# Ruby team <ruby@gentoo.org> +# @AUTHOR: +# Author: Hans de Graaff <graaff@gentoo.org> +# Based on python-single-r1 by: Michał Górny <mgorny@gentoo.org> +# @SUPPORTED_EAPIS: 4 5 6 7 +# @BLURB: An eclass for Ruby packages not installed for multiple implementations. +# @DESCRIPTION: +# An eclass for packages which don't support being installed for +# multiple Ruby implementations. This mostly includes ruby-based +# scripts. Set USE_RUBY to include all the ruby targets that have been +# verified to work and include the eclass. RUBY_DEPS is now available to +# pull in the dependency on the requested ruby targets. +# +# @CODE +# USE_RUBY="ruby20 ruby21" +# inherit ruby-single +# RDEPEND="${RUBY_DEPS}" +# @CODE + +case "${EAPI:-0}" in + 0|1|2|3) + die "Unsupported EAPI=${EAPI:-0} (too old) for ${ECLASS}" + ;; + 4|5|6|7) + ;; + *) + die "Unsupported EAPI=${EAPI} (unknown) for ${ECLASS}" + ;; +esac + +if [[ ! ${_RUBY_SINGLE} ]]; then + +inherit ruby-utils + +# @ECLASS-VARIABLE: USE_RUBY +# @DEFAULT_UNSET +# @REQUIRED +# @DESCRIPTION: +# This variable contains a space separated list of targets (see above) a package +# is compatible to. It must be set before the `inherit' call. There is no +# default. All ebuilds are expected to set this variable. + + +# @ECLASS-VARIABLE: RUBY_DEPS +# @DEFAULT_UNSET +# @DESCRIPTION: +# +# This is an eclass-generated Ruby dependency string for all +# implementations listed in USE_RUBY. Any one of the supported ruby +# targets will satisfy this dependency. A dependency on +# virtual/rubygems is also added to ensure that this is installed +# in time for the package to use it. +# +# Example use: +# @CODE +# RDEPEND="${RUBY_DEPS} +# dev-foo/mydep" +# BDEPEND="${RDEPEND}" +# @CODE +# +# Example value: +# @CODE +# || ( dev-lang/ruby:2.0 dev-lang/ruby:1.9 ) virtual/rubygems +# @CODE +# +# The order of dependencies will change over time to best match the +# current state of ruby targets, e.g. stable version first. + +_ruby_single_implementations_depend() { + local depend + for _ruby_implementation in ${RUBY_TARGETS_PREFERENCE}; do + if [[ ${USE_RUBY} =~ ${_ruby_implementation} ]]; then + depend="${depend} $(_ruby_implementation_depend $_ruby_implementation)" + fi + done + echo "|| ( ${depend} ) virtual/rubygems" +} + +_ruby_single_set_globals() { + RUBY_DEPS=$(_ruby_single_implementations_depend) +} +_ruby_single_set_globals + + +_RUBY_SINGLE=1 +fi diff --git a/eclass/ruby-utils.eclass b/eclass/ruby-utils.eclass new file mode 100644 index 0000000..e5752dc --- /dev/null +++ b/eclass/ruby-utils.eclass @@ -0,0 +1,107 @@ +# Copyright 1999-2020 Gentoo Authors +# Distributed under the terms of the GNU General Public License v2 + +# @ECLASS: ruby-utils.eclass +# @MAINTAINER: +# Ruby team <ruby@gentoo.org> +# @AUTHOR: +# Author: Hans de Graaff <graaff@gentoo.org> +# @BLURB: An eclass for supporting ruby scripts and bindings in non-ruby packages +# @DESCRIPTION: +# The ruby-utils eclass is designed to allow an easier installation of +# Ruby scripts and bindings for non-ruby packages. +# +# This eclass does not set any metadata variables nor export any phase +# functions. It can be inherited safely. + + +if [[ ! ${_RUBY_UTILS} ]]; then + + +# @ECLASS-VARIABLE: RUBY_TARGETS_PREFERENCE +# @INTERNAL +# @DESCRIPTION: +# This variable lists all the known ruby targets in preference of use as +# determined by the ruby team. By using this ordering rather than the +# USE_RUBY mandated ordering we have more control over which ruby +# implementation will be installed first (and thus eselected). This will +# provide for a better first installation experience. + +# All stable RUBY_TARGETS +RUBY_TARGETS_PREFERENCE="ruby26 ruby25 " + +# All other active ruby targets +RUBY_TARGETS_PREFERENCE+="ruby27 ruby30" + + +_ruby_implementation_depend() { + local rubypn= + local rubyslot= + + case $1 in + ruby18) + rubypn="dev-lang/ruby" + rubyslot=":1.8" + ;; + ruby19) + rubypn="dev-lang/ruby" + rubyslot=":1.9" + ;; + ruby20) + rubypn="dev-lang/ruby" + rubyslot=":2.0" + ;; + ruby21) + rubypn="dev-lang/ruby" + rubyslot=":2.1" + ;; + ruby22) + rubypn="dev-lang/ruby" + rubyslot=":2.2" + ;; + ruby23) + rubypn="dev-lang/ruby" + rubyslot=":2.3" + ;; + ruby24) + rubypn="dev-lang/ruby" + rubyslot=":2.4" + ;; + ruby25) + rubypn="dev-lang/ruby" + rubyslot=":2.5" + ;; + ruby26) + rubypn="dev-lang/ruby" + rubyslot=":2.6" + ;; + ruby27) + rubypn="dev-lang/ruby" + rubyslot=":2.7" + ;; + ruby30) + rubypn="dev-lang/ruby" + rubyslot=":3.0" + ;; + ree18) + rubypn="dev-lang/ruby-enterprise" + rubyslot=":1.8" + ;; + jruby) + rubypn="dev-java/jruby" + rubyslot="" + ;; + rbx) + rubypn="dev-lang/rubinius" + rubyslot="" + ;; + *) die "$1: unknown Ruby implementation" + esac + + echo "$2${rubypn}$3${rubyslot}" +} + + + +_RUBY_UTILS=1 +fi diff --git a/eclass/rust-toolchain.eclass b/eclass/rust-toolchain.eclass new file mode 100644 index 0000000..9d7360e --- /dev/null +++ b/eclass/rust-toolchain.eclass @@ -0,0 +1,122 @@ +# Copyright 1999-2020 Gentoo Authors +# Distributed under the terms of the GNU General Public License v2 + +# @ECLASS: rust-toolchain.eclass +# @MAINTAINER: +# Rust Project <rust@gentoo.org> +# @SUPPORTED_EAPIS: 6 7 +# @BLURB: helps map gentoo arches to rust ABIs +# @DESCRIPTION: +# This eclass contains a src_unpack default phase function, and +# helper functions, to aid in proper rust-ABI handling for various +# gentoo arches. + +case ${EAPI} in + 6) : ;; + 7) : ;; + *) die "EAPI=${EAPI:-0} is not supported" ;; +esac + +inherit multilib-build + +# @ECLASS-VARIABLE: RUST_TOOLCHAIN_BASEURL +# @DESCRIPTION: +# This variable specifies the base URL used by the +# rust_arch_uri and rust_all_arch_uris functions when +# generating the URI output list. +: ${RUST_TOOLCHAIN_BASEURL:=https://static.rust-lang.org/dist/} + +# @FUNCTION: rust_abi +# @USAGE: [CHOST-value] +# @DESCRIPTION: +# Outputs the Rust ABI name from a CHOST value, uses CHOST in the +# environment if none is specified. + +rust_abi() { + local CTARGET=${1:-${CHOST}} + case ${CTARGET%%*-} in + aarch64*) echo aarch64-unknown-linux-gnu;; + mips64*) echo mips64-unknown-linux-gnuabi64;; + powerpc64le*) echo powerpc64le-unknown-linux-gnu;; + powerpc64*) echo powerpc64-unknown-linux-gnu;; + x86_64*gnu) echo x86_64-unknown-linux-gnu;; + x86_64*musl) echo x86_64-unknown-linux-musl;; + armv6j*s*) echo arm-unknown-linux-gnueabi;; + armv6j*h*) echo arm-unknown-linux-gnueabihf;; + armv7a*h*) echo armv7-unknown-linux-gnueabihf;; + i?86*) echo i686-unknown-linux-gnu;; + mipsel*) echo mipsel-unknown-linux-gnu;; + mips*) echo mips-unknown-linux-gnu;; + powerpc*) echo powerpc-unknown-linux-gnu;; + s390x*) echo s390x-unknown-linux-gnu;; + *) echo ${CTARGET};; + esac +} + +# @FUNCTION: rust_all_abis +# @DESCRIPTION: +# Outputs a list of all the enabled Rust ABIs +rust_all_abis() { + if use multilib; then + local abi + local ALL_ABIS=() + for abi in $(multilib_get_enabled_abis); do + ALL_ABIS+=( $(rust_abi $(get_abi_CHOST ${abi})) ) + done + local abi_list + IFS=, eval 'abi_list=${ALL_ABIS[*]}' + echo ${abi_list} + else + rust_abi + fi +} + +# @FUNCTION: rust_arch_uri +# @USAGE: <rust-ABI> <base-uri> [alt-distfile-basename] +# @DESCRIPTION: +# Output the URI for use in SRC_URI, combining $RUST_TOOLCHAIN_BASEURL +# and the URI suffix provided in ARG2 with the rust ABI in ARG1, and +# optionally renaming to the distfile basename specified in ARG3. +# +# @EXAMPLE: +# SRC_URI="amd64? ( +# $(rust_arch_uri x86_64-unknown-linux-gnu rustc-${STAGE0_VERSION}) +# )" +# +rust_arch_uri() { + if [ -n "$3" ]; then + echo "${RUST_TOOLCHAIN_BASEURL}${2}-${1}.tar.xz -> ${3}-${1}.tar.xz" + else + echo "${RUST_TOOLCHAIN_BASEURL}${2}-${1}.tar.xz" + fi +} + +# @FUNCTION: rust_all_arch_uris +# @USAGE: <base-uri> [alt-distfile-basename] +# @DESCRIPTION: +# Outputs the URIs for SRC_URI to help fetch dependencies, using a base URI +# provided as an argument. Optionally allows for distfile renaming via a specified +# basename. +# +# @EXAMPLE: +# SRC_URI="$(rust_all_arch_uris rustc-${STAGE0_VERSION})" +# +rust_all_arch_uris() +{ + local uris="" + uris+="abi_x86_64? ( elibc_glibc? ( $(rust_arch_uri x86_64-unknown-linux-gnu "$@") ) + elibc_musl? ( $(rust_arch_uri x86_64-unknown-linux-musl "$@") ) ) " + uris+="arm? ( $(rust_arch_uri arm-unknown-linux-gnueabi "$@") + $(rust_arch_uri arm-unknown-linux-gnueabihf "$@") + $(rust_arch_uri armv7-unknown-linux-gnueabihf "$@") ) " + uris+="arm64? ( $(rust_arch_uri aarch64-unknown-linux-gnu "$@") ) " + uris+="mips? ( $(rust_arch_uri mips-unknown-linux-gnu "$@") + $(rust_arch_uri mipsel-unknown-linux-gnu "$@") + $(rust_arch_uri mips64-unknown-linux-gnuabi64 "$@") ) " + uris+="ppc? ( $(rust_arch_uri powerpc-unknown-linux-gnu "$@") ) " + uris+="ppc64? ( $(rust_arch_uri powerpc64-unknown-linux-gnu "$@") + $(rust_arch_uri powerpc64le-unknown-linux-gnu "$@") ) " + uris+="s390? ( $(rust_arch_uri s390x-unknown-linux-gnu "$@") ) " + uris+="abi_x86_32? ( $(rust_arch_uri i686-unknown-linux-gnu "$@") ) " + echo "${uris}" +} diff --git a/eclass/s6.eclass b/eclass/s6.eclass new file mode 100644 index 0000000..b84d5a1 --- /dev/null +++ b/eclass/s6.eclass @@ -0,0 +1,119 @@ +# Copyright 1999-2019 Gentoo Authors +# Distributed under the terms of the GNU General Public License v2 + +# @ECLASS: s6.eclass +# @MAINTAINER: +# William Hubbs <williamh@gentoo.org> +# @SUPPORTED_EAPIS: 5 6 7 +# @BLURB: helper functions to install s6 services +# @DESCRIPTION: +# This eclass provides helpers to install s6 services. +# @EXAMPLE: +# +# @CODE +# inherit s6 +# +# src_install() { +# ... +# s6_install_service myservice "${FILESDIR}"/run-s6 "${FILESDIR}"/finish-s6 +# ... +# If you want a service to be logged, install the log service as +# shown here. +# s6_install_service myservice/log "${FILESDIR}"/log-run-s6 \ +# "${FILESDIR}"/log-finish-s6 +# ... +# } +# @CODE + +case ${EAPI:-0} in + 5|6|7) ;; + *) die "${ECLASS}.eclass: API in EAPI ${EAPI} not yet established" ;; +esac + +# @FUNCTION: _s6_get_servicedir +# @INTERNAL +# @DESCRIPTION: +# Get unprefixed servicedir. +_s6_get_servicedir() { + echo /var/svc.d +} + +# @FUNCTION: s6_get_servicedir +# @DESCRIPTION: +# Output the path for the s6 service directory (not including ${D}). +s6_get_servicedir() { + debug-print-function ${FUNCNAME} "${@}" + + echo "${EPREFIX}$(_s6_get_servicedir)" +} + +# @FUNCTION: s6_install_service +# @USAGE: <servicename> <run> [finish] +# @DESCRIPTION: +# Install an s6 service. +# servicename is the name of the service. +# run is the run script for the service. +# finish is the optional finish script for the service. +s6_install_service() { + debug-print-function ${FUNCNAME} "${@}" + + local name="$1" + local run="$2" + local finish="$3" + + [[ $name ]] || + die "${ECLASS}.eclass: you must specify the s6 service name" + [[ $run ]] || + die "${ECLASS}.eclass: you must specify the s6 service run script" + + ( + local servicepath="$(_s6_get_servicedir)/$name" + exeinto "$servicepath" + newexe "$run" run + [[ $finish ]] && newexe "$finish" finish + ) +} + +# @FUNCTION: s6_service_down +# @USAGE: <servicename> +# @DESCRIPTION: +# Install the "down" flag so this service will not be started by +# default. +# servicename is the name of the service. +s6_service_down() { + debug-print-function ${FUNCNAME} "${@}" + + local name="$1" + + [[ $name ]] || + die "${ECLASS}.eclass: you must specify the s6 service name" + + ( + touch "$T"/down || die + local servicepath="$(_s6_get_servicedir)/$name" + insinto "$servicepath" + doins "$T"/down + ) +} + +# @FUNCTION: s6_service_nosetsid +# @USAGE: <servicename> +# @DESCRIPTION: +# Install the "nosetsid" flag so this service will not be made a session +# leader. +# servicename is the name of the service. +s6_service_nosetsid() { + debug-print-function ${FUNCNAME} "${@}" + + local name="$1" + + [[ $name ]] || + die "${ECLASS}.eclass: you must specify the s6 service name" + + ( + touch "$T"/nosetsid || die + local servicepath="$(_s6_get_servicedir)/$name" + insinto "$servicepath" + doins "$T"/nosetsid + ) +} diff --git a/eclass/savedconfig.eclass b/eclass/savedconfig.eclass new file mode 100644 index 0000000..e90a9b6 --- /dev/null +++ b/eclass/savedconfig.eclass @@ -0,0 +1,172 @@ +# Copyright 1999-2020 Gentoo Authors +# Distributed under the terms of the GNU General Public License v2 + +# @ECLASS: savedconfig.eclass +# @MAINTAINER: +# base-system@gentoo.org +# @SUPPORTED_EAPIS: 5 6 7 +# @BLURB: common API for saving/restoring complex configuration files +# @DESCRIPTION: +# It is not uncommon to come across a package which has a very fine +# grained level of configuration options that go way beyond what +# USE flags can properly describe. For this purpose, a common API +# of saving and restoring the configuration files was developed +# so users can modify these config files and the ebuild will take it +# into account as needed. +# +# Typically you can create your own configuration files quickly by +# doing: +# +# 1. Build the package with FEATURES=noclean USE=savedconfig. +# +# 2. Go into the build dir and edit the relevant configuration system +# (e.g. `make menuconfig` or `nano config-header.h`). You can look +# at the files in /etc/portage/savedconfig/ to see what files get +# loaded/restored. +# +# 3. Copy the modified configuration files out of the workdir and to +# the paths in /etc/portage/savedconfig/. +# +# 4. Emerge the package with just USE=savedconfig to get the custom +# build. + +inherit portability + +IUSE="savedconfig" + +case ${EAPI} in + [5-7]) ;; + *) die "EAPI=${EAPI:-0} is not supported" ;; +esac + +# @ECLASS-VARIABLE: _SAVEDCONFIG_CONFIGURATION_FILE +# @DEFAULT_UNSET +# @INTERNAL +# @DESCRIPTION: +# Path of configuration file, relative to /etc/portage/savedconfig, +# restored by restore_config() and saved by save_config(). + +# @FUNCTION: save_config +# @USAGE: <config files to save> +# @DESCRIPTION: +# Use this function to save the package's configuration file into the +# right location. You may specify any number of configuration files, +# but just make sure you call save_config with all of them at the same +# time in order for things to work properly. +save_config() { + if [[ ${EBUILD_PHASE} != "install" ]]; then + die "Bad package! save_config only for use in src_install functions!" + fi + [[ $# -eq 0 ]] && die "Usage: save_config <files>" + + local configfile + if [[ -n ${_SAVEDCONFIG_CONFIGURATION_FILE} ]] ; then + configfile="/etc/portage/savedconfig/${_SAVEDCONFIG_CONFIGURATION_FILE}" + else + configfile="/etc/portage/savedconfig/${CATEGORY}/${PF}" + fi + + if [[ $# -eq 1 && -f $1 ]] ; then + # Just one file, so have the ${configfile} be that config file + dodir "${configfile%/*}" + cp "$@" "${ED%/}/${configfile}" || die "failed to save $*" + else + # A dir, or multiple files, so have the ${configfile} be a dir + # with all the saved stuff below it + dodir "${configfile}" + treecopy "$@" "${ED%/}/${configfile}" || die "failed to save $*" + fi + + elog "Your configuration for ${CATEGORY}/${PF} has been saved in " + elog "\"${configfile}\" for your editing pleasure." + elog "You can edit these files by hand and remerge this package with" + elog "USE=savedconfig to customise the configuration." + elog "You can rename this file/directory to one of the following for" + elog "its configuration to apply to multiple versions:" + elog '${PORTAGE_CONFIGROOT}/etc/portage/savedconfig/' + elog '[${CTARGET}|${CHOST}|""]/${CATEGORY}/[${PF}|${P}|${PN}]' +} + +# @FUNCTION: restore_config +# @USAGE: <config files to restore> +# @DESCRIPTION: +# Restores the package's configuration file probably with user edits. +# You can restore a single file or a whole bunch, just make sure you call +# restore_config with all of the files to restore at the same time. +# +# Config files can be laid out as: +# @CODE +# ${PORTAGE_CONFIGROOT}/etc/portage/savedconfig/${CTARGET}/${CATEGORY}/${PF} +# ${PORTAGE_CONFIGROOT}/etc/portage/savedconfig/${CHOST}/${CATEGORY}/${PF} +# ${PORTAGE_CONFIGROOT}/etc/portage/savedconfig/${CATEGORY}/${PF} +# ${PORTAGE_CONFIGROOT}/etc/portage/savedconfig/${CTARGET}/${CATEGORY}/${P} +# ${PORTAGE_CONFIGROOT}/etc/portage/savedconfig/${CHOST}/${CATEGORY}/${P} +# ${PORTAGE_CONFIGROOT}/etc/portage/savedconfig/${CATEGORY}/${P} +# ${PORTAGE_CONFIGROOT}/etc/portage/savedconfig/${CTARGET}/${CATEGORY}/${PN} +# ${PORTAGE_CONFIGROOT}/etc/portage/savedconfig/${CHOST}/${CATEGORY}/${PN} +# ${PORTAGE_CONFIGROOT}/etc/portage/savedconfig/${CATEGORY}/${PN} +# @CODE +restore_config() { + case ${EBUILD_PHASE} in + unpack|compile|configure|prepare) ;; + *) die "Bad package! restore_config only for use in src_{unpack,compile,configure,prepare} functions!" ;; + esac + + use savedconfig || return + + local found check checked configfile + local base=${PORTAGE_CONFIGROOT%/}/etc/portage/savedconfig + for check in {${CATEGORY}/${PF},${CATEGORY}/${P},${CATEGORY}/${PN}}; do + configfile=${base}/${CTARGET:+"${CTARGET}/"}${check} + [[ -r ${configfile} ]] || configfile=${base}/${CHOST:+"${CHOST}/"}${check} + [[ -r ${configfile} ]] || configfile=${base}/${check} + [[ "${checked}" == *"${configfile} "* ]] && continue + einfo "Checking existence of \"${configfile}\" ..." + if [[ -r "${configfile}" ]] ; then + einfo "Found \"${configfile}\"" + found=${configfile} + _SAVEDCONFIG_CONFIGURATION_FILE=${configfile#${base}/} + break + fi + + checked+="${configfile} " + done + + if [[ -f ${found} ]]; then + elog "Building using saved configfile \"${found}\"" + if [ $# -gt 0 ]; then + cp -pPR "${found}" "$1" || die "Failed to restore ${found} to $1" + else + die "need to know the restoration filename" + fi + elif [[ -d ${found} ]]; then + elog "Building using saved config directory \"${found}\"" + local dest=${PWD} + pushd "${found}" > /dev/null + treecopy . "${dest}" || die "Failed to restore ${found} to $1" + popd > /dev/null + else + # maybe the user is screwing around with perms they shouldnt #289168 + if [[ ! -r ${base} ]] ; then + eerror "Unable to read ${base} -- please check its permissions." + die "Reading config files failed" + fi + ewarn "No saved config to restore - please remove USE=savedconfig or" + ewarn "provide a configuration file in ${PORTAGE_CONFIGROOT%/}/etc/portage/savedconfig/${CATEGORY}/${PN}" + ewarn "Your config file(s) will not be used this time" + fi +} + +savedconfig_pkg_postinst() { + # If the user has USE=savedconfig, then chances are they + # are modifying these files, so keep them around. #396169 + # This might lead to cruft build up, but the alternatives + # are worse :/. + + if use savedconfig ; then + find "${EROOT%/}/etc/portage/savedconfig/${CATEGORY}/${PF}" \ + -exec touch {} + 2>/dev/null + fi +} + +EXPORT_FUNCTIONS pkg_postinst diff --git a/eclass/scons-utils.eclass b/eclass/scons-utils.eclass new file mode 100644 index 0000000..c616e4a --- /dev/null +++ b/eclass/scons-utils.eclass @@ -0,0 +1,346 @@ +# Copyright 1999-2020 Gentoo Authors +# Distributed under the terms of the GNU General Public License v2 + +# @ECLASS: scons-utils.eclass +# @MAINTAINER: +# mgorny@gentoo.org +# @SUPPORTED_EAPIS: 0 1 2 3 4 5 6 7 +# @BLURB: helper functions to deal with SCons buildsystem +# @DESCRIPTION: +# This eclass provides a set of function to help developers sanely call +# dev-util/scons and pass parameters to it. +# +# As of dev-util/scons-3.0.1-r100, SCons supports Python 3. Since +# SCons* files in build systems are written as Python, all packages +# need to explicitly verify which versions of Python are supported +# and use appropriate Python suite eclass to select the implementation. +# The eclass needs to be inherited before scons-utils, and scons-utils +# will automatically take advantage of it. For more details, please see: +# https://wiki.gentoo.org/wiki/Project:Python/scons-utils_integration +# +# Please note that SCons is more like a 'build system creation kit', +# and requires a lot of upstream customization to be used sanely. +# You will often need to request fixes upstream and/or patch the build +# system. In particular: +# +# 1. There are no 'standard' variables. To respect CC, CXX, CFLAGS, +# CXXFLAGS, CPPFLAGS, LDFLAGS, upstream needs to define appropriate +# variables explicitly. In some cases, upstreams respect envvars, +# in others you need to pass them as options. +# +# 2. SCons scrubs out environment by default and replaces it with some +# pre-defined values. To respect environment variables such as PATH, +# Upstreams need to explicitly get them from os.environ and copy them +# to the build environment. +# +# @EXAMPLE: +# @CODE +# PYTHON_COMPAT=( python2_7 ) +# inherit python-any-r1 scons-utils toolchain-funcs +# +# EAPI=5 +# +# src_configure() { +# MYSCONS=( +# CC="$(tc-getCC)" +# ENABLE_NLS=$(usex nls) +# ) +# } +# +# src_compile() { +# escons "${MYSCONS[@]}" +# } +# +# src_install() { +# # note: this can be DESTDIR, INSTALL_ROOT, ... depending on package +# escons "${MYSCONS[@]}" DESTDIR="${D}" install +# } +# @CODE + +# -- public variables -- + +# @ECLASS-VARIABLE: SCONS_MIN_VERSION +# @DEFAULT_UNSET +# @DESCRIPTION: +# The minimal version of SCons required for the build to work. + +# @VARIABLE: myesconsargs +# @DEFAULT_UNSET +# @DESCRIPTION: +# DEPRECATED, EAPI 0..5 ONLY: pass options to escons instead +# +# List of package-specific options to pass to all SCons calls. Supposed to be +# set in src_configure(). + +# @ECLASS-VARIABLE: SCONSOPTS +# @DEFAULT_UNSET +# @DESCRIPTION: +# The default set of options to pass to scons. Similar to MAKEOPTS, +# supposed to be set in make.conf. If unset, escons() will use cleaned +# up MAKEOPTS instead. + +# @ECLASS-VARIABLE: EXTRA_ESCONS +# @DEFAULT_UNSET +# @DESCRIPTION: +# The additional parameters to pass to SCons whenever escons() is used. +# Much like EXTRA_EMAKE, this is not supposed to be used in make.conf +# and not in ebuilds! + +# @ECLASS-VARIABLE: USE_SCONS_TRUE +# @DESCRIPTION: +# DEPRECATED: use usex instead +# +# The default value for truth in scons-use() (1 by default). +: ${USE_SCONS_TRUE:=1} + +# @ECLASS-VARIABLE: USE_SCONS_FALSE +# @DESCRIPTION: +# DEPRECATED: use usex instead +# +# The default value for false in scons-use() (0 by default). +: ${USE_SCONS_FALSE:=0} + +# -- EAPI support check -- + +case ${EAPI:-0} in + 0|1|2|3|4|5|6|7) ;; + *) die "EAPI ${EAPI} unsupported." +esac + +inherit multiprocessing + +# -- ebuild variables setup -- + +if [[ -n ${SCONS_MIN_VERSION} ]]; then + SCONS_DEPEND=">=dev-util/scons-${SCONS_MIN_VERSION}" +else + SCONS_DEPEND="dev-util/scons" +fi + +if [[ ${_PYTHON_ANY_R1} ]]; then + # when using python-any-r1, use any-of dep API + BDEPEND="$(python_gen_any_dep "${SCONS_DEPEND}[\${PYTHON_USEDEP}]")" + + scons-utils_python_check_deps() { + has_version "${SCONS_DEPEND}[${PYTHON_USEDEP}]" + } + python_check_deps() { scons-utils_python_check_deps; } +elif [[ ${_PYTHON_SINGLE_R1} ]]; then + # when using python-single-r1, use PYTHON_MULTI_USEDEP API + BDEPEND=" + $(python_gen_cond_dep "${SCONS_DEPEND}[\${PYTHON_MULTI_USEDEP}]") + ${PYTHON_DEPS}" +elif [[ ${EAPI:-0} == [0123456] ]]; then + # in older EAPIs, just force Python 2.7 + BDEPEND="${SCONS_DEPEND}[python_targets_python2_7]" +elif [[ ${_PYTHON_R1} ]]; then + # when using python-r1, you need to depend on scons yourself + # (depending on whether you need any-r1 or full -r1 API) + # -- since this is a breaking API change, it applies to EAPI 7+ only + BDEPEND="" +elif [[ ${EAPI:-0} != [0123456] ]]; then + # in EAPI 7+, require appropriate eclass use + eerror "Using scons-utils.eclass without any python-r1 suite eclass is not supported." + eerror "Please make sure to configure and inherit appropriate -r1 eclass." + eerror "For more information and examples, please see:" + eerror " https://wiki.gentoo.org/wiki/Project:Python/scons-utils_integration" + die "Invalid use of scons-utils.eclass" +fi + +if [[ ${EAPI:-0} == [0123456] ]]; then + DEPEND=${BDEPEND} + unset BDEPEND +fi + +# -- public functions -- + +# @FUNCTION: escons +# @USAGE: [<args>...] +# @DESCRIPTION: +# Call scons, passing the supplied arguments. Like emake, this function +# does die on failure in EAPI 4. Respects nonfatal in EAPI 6 and newer. +escons() { + local ret + + debug-print-function ${FUNCNAME} "${@}" + + if [[ ! ${EPYTHON} ]]; then + if [[ ${EAPI:-0} != [0123456] ]]; then + eerror "EPYTHON is unset while calling escons. This most likely means that" + eerror "the ebuild did not call the appropriate eclass function before calling scons." + if [[ ${_PYTHON_ANY_R1} ]]; then + eerror "Please ensure that python-any-r1_pkg_setup is called in pkg_setup()." + elif [[ ${_PYTHON_SINGLE_R1} ]]; then + eerror "Please ensure that python-single-r1_pkg_setup is called in pkg_setup()." + else # python-r1 + eerror "Please ensure that python_setup is called before escons, or that escons" + eerror "is used within python_foreach_impl as appropriate." + fi + die "EPYTHON unset in escons" + else + local -x EPYTHON=python2.7 + fi + fi + + # Use myesconsargs in EAPI 5 and older + if [[ ${EAPI} == [012345] ]]; then + set -- "${myesconsargs[@]}" "${@}" + fi + + # if SCONSOPTS are _unset_, use cleaned MAKEOPTS + if [[ ! ${SCONSOPTS+set} ]]; then + local SCONSOPTS + _scons_clean_makeopts + fi + + # pass ebuild environment variables through! + local -x GENTOO_SCONS_ENV_PASSTHROUGH=1 + + set -- scons ${SCONSOPTS} ${EXTRA_ESCONS} "${@}" + echo "${@}" >&2 + "${@}" + ret=${?} + + if [[ ${ret} -ne 0 ]]; then + case "${EAPI:-0}" in + 0|1|2|3) # nonfatal in EAPIs 0 through 3 + ;; + 4|5) # 100% fatal in 4 & 5 + die "escons failed." + ;; + *) # respect nonfatal in 6 onwards + die -n "escons failed." + ;; + esac + fi + return ${ret} +} + +# @FUNCTION: _scons_clean_makeopts +# @USAGE: [makeflags] [...] +# @INTERNAL +# @DESCRIPTION: +# Strip the supplied makeflags (or ${MAKEOPTS} if called without +# an argument) of options not supported by SCons and make sure --jobs +# gets an argument. Output the resulting flag list (suitable +# for an assignment to SCONSOPTS). +_scons_clean_makeopts() { + local new_makeopts=() + + debug-print-function ${FUNCNAME} "${@}" + + if [[ ${#} -eq 0 ]]; then + debug-print "Using MAKEOPTS: [${MAKEOPTS}]" + set -- ${MAKEOPTS} + else + # unquote if necessary + set -- ${*} + fi + + # empty MAKEOPTS give out empty SCONSOPTS + # thus, we do need to worry about the initial setup + if [[ ${*} = ${_SCONS_CACHE_MAKEOPTS} ]]; then + SCONSOPTS=${_SCONS_CACHE_SCONSOPTS} + debug-print "Cache hit: [${SCONSOPTS}]" + return + fi + _SCONS_CACHE_MAKEOPTS=${*} + + while [[ ${#} -gt 0 ]]; do + case ${1} in + # clean, simple to check -- we like that + --jobs=*|--keep-going) + new_makeopts+=( ${1} ) + ;; + # need to take a look at the next arg and guess + --jobs) + if [[ ${#} -gt 1 && ${2} =~ ^[0-9]+$ ]]; then + new_makeopts+=( ${1} ${2} ) + shift + else + # no value means no limit, let's pass a default instead + new_makeopts+=( ${1}=$(( $(get_nproc) + 1 )) ) + fi + ;; + # strip other long options + --*) + ;; + # short option hell + -*) + local str new_optstr + new_optstr= + str=${1#-} + + while [[ -n ${str} ]]; do + case ${str} in + k*) + new_optstr+=k + ;; + # -j needs to come last + j) + if [[ ${#} -gt 1 && ${2} =~ ^[0-9]+$ ]]; then + new_optstr+="j ${2}" + shift + else + new_optstr+="j $(( $(get_nproc) + 1 ))" + fi + ;; + # otherwise, everything after -j is treated as an arg + j*) + new_optstr+=${str} + break + ;; + esac + str=${str#?} + done + + if [[ -n ${new_optstr} ]]; then + new_makeopts+=( -${new_optstr} ) + fi + ;; + esac + shift + done + + SCONSOPTS=${new_makeopts[*]} + _SCONS_CACHE_SCONSOPTS=${SCONSOPTS} + debug-print "New SCONSOPTS: [${SCONSOPTS}]" +} + +# @FUNCTION: use_scons +# @USAGE: <use-flag> [var-name] [var-opt-true] [var-opt-false] +# @DESCRIPTION: +# DEPRECATED, EAPI 0..5 ONLY: use usex instead +# +# Output a SCons parameter with value depending on the USE flag state. +# If the USE flag is set, output <var-name>=<var-opt-true>; otherwise +# <var-name>=<var-opt-false>. +# +# If <var-name> is omitted, <use-flag> will be used instead. However, +# if <use-flag> starts with an exclamation mark (!flag), 'no' will be +# prepended to the name (e.g. noflag). +# +# If <var-opt-true> and/or <var-opt-false> are omitted, +# ${USE_SCONS_TRUE} and/or ${USE_SCONS_FALSE} will be used instead. +use_scons() { + [[ ${EAPI} == [012345] ]] \ + || die "${FUNCNAME} is banned in EAPI ${EAPI}, use usex instead" + + local flag=${1} + local varname=${2:-${flag/\!/no}} + local vartrue=${3:-${USE_SCONS_TRUE}} + local varfalse=${4:-${USE_SCONS_FALSE}} + + debug-print-function ${FUNCNAME} "${@}" + + if [[ ${#} -eq 0 ]]; then + eerror "Usage: scons-use <use-flag> [var-name] [var-opt-true] [var-opt-false]" + die 'scons-use(): not enough arguments' + fi + + if use "${flag}"; then + echo "${varname}=${vartrue}" + else + echo "${varname}=${varfalse}" + fi +} diff --git a/eclass/selinux-policy-2.eclass b/eclass/selinux-policy-2.eclass new file mode 100644 index 0000000..5def86f --- /dev/null +++ b/eclass/selinux-policy-2.eclass @@ -0,0 +1,366 @@ +# Copyright 1999-2020 Gentoo Authors +# Distributed under the terms of the GNU General Public License v2 + +# Eclass for installing SELinux policy, and optionally +# reloading the reference-policy based modules. + +# @ECLASS: selinux-policy-2.eclass +# @MAINTAINER: +# selinux@gentoo.org +# @SUPPORTED_EAPIS: 6 7 +# @BLURB: This eclass supports the deployment of the various SELinux modules in sec-policy +# @DESCRIPTION: +# The selinux-policy-2.eclass supports deployment of the various SELinux modules +# defined in the sec-policy category. It is responsible for extracting the +# specific bits necessary for single-module deployment (instead of full-blown +# policy rebuilds) and applying the necessary patches. +# +# Also, it supports for bundling patches to make the whole thing just a bit more +# manageable. + +# @ECLASS-VARIABLE: MODS +# @DESCRIPTION: +# This variable contains the (upstream) module name for the SELinux module. +# This name is only the module name, not the category! +: ${MODS:="_illegal"} + +# @ECLASS-VARIABLE: BASEPOL +# @DESCRIPTION: +# This variable contains the version string of the selinux-base-policy package +# that this module build depends on. It is used to patch with the appropriate +# patch bundle(s) that are part of selinux-base-policy. +: ${BASEPOL:=${PVR}} + +# @ECLASS-VARIABLE: POLICY_PATCH +# @DESCRIPTION: +# This variable contains the additional patch(es) that need to be applied on top +# of the patchset already contained within the BASEPOL variable. The variable +# can be both a simple string (space-separated) or a bash array. +: ${POLICY_PATCH:=""} + +# @ECLASS-VARIABLE: POLICY_FILES +# @DESCRIPTION: +# When defined, this contains the files (located in the ebuilds' files/ +# directory) which should be copied as policy module files into the store. +# Generally, users would want to include at least a .te and .fc file, but .if +# files are supported as well. The variable can be both a simple string +# (space-separated) or a bash array. +: ${POLICY_FILES:=""} + +# @ECLASS-VARIABLE: POLICY_TYPES +# @DESCRIPTION: +# This variable informs the eclass for which SELinux policies the module should +# be built. Currently, Gentoo supports targeted, strict, mcs and mls. +# This variable is the same POLICY_TYPES variable that we tell SELinux +# users to set in make.conf. Therefore, it is not the module that should +# override it, but the user. +: ${POLICY_TYPES:="targeted strict mcs mls"} + +# @ECLASS-VARIABLE: SELINUX_GIT_REPO +# @DESCRIPTION: +# When defined, this variable overrides the default repository URL as used by +# this eclass. It allows end users to point to a different policy repository +# using a single variable, rather than having to set the packagename_LIVE_REPO +# variable for each and every SELinux policy module package they want to install. +# The default value is Gentoo's hardened-refpolicy repository. +: ${SELINUX_GIT_REPO:="https://anongit.gentoo.org/git/proj/hardened-refpolicy.git"}; + +# @ECLASS-VARIABLE: SELINUX_GIT_BRANCH +# @DESCRIPTION: +# When defined, this variable sets the Git branch to use of the repository. This +# allows for users and developers to use a different branch for the entire set of +# SELinux policy packages, rather than having to override them one by one with the +# packagename_LIVE_BRANCH variable. +# The default value is the 'master' branch. +: ${SELINUX_GIT_BRANCH:="master"}; + +case "${EAPI:-0}" in + 0|1|2|3|4|5) die "EAPI<6 is not supported";; + 6|7) : ;; + *) die "unknown EAPI" ;; +esac + +case ${BASEPOL} in + 9999) inherit git-r3 + EGIT_REPO_URI="${SELINUX_GIT_REPO}"; + EGIT_BRANCH="${SELINUX_GIT_BRANCH}"; + EGIT_CHECKOUT_DIR="${WORKDIR}/refpolicy";; +esac + +IUSE="" + +HOMEPAGE="https://wiki.gentoo.org/wiki/Project:SELinux" +if [[ -n ${BASEPOL} ]] && [[ "${BASEPOL}" != "9999" ]]; then + SRC_URI="https://github.com/SELinuxProject/refpolicy/releases/download/RELEASE_${PV/./_}/refpolicy-${PV}.tar.bz2 + https://dev.gentoo.org/~perfinion/patches/selinux-base-policy/patchbundle-selinux-base-policy-${BASEPOL}.tar.bz2" +elif [[ "${BASEPOL}" != "9999" ]]; then + SRC_URI="https://github.com/SELinuxProject/refpolicy/releases/download/RELEASE_${PV/./_}/refpolicy-${PV}.tar.bz2" +else + SRC_URI="" +fi + +LICENSE="GPL-2" +SLOT="0" +S="${WORKDIR}/" +PATCHBUNDLE="${DISTDIR}/patchbundle-selinux-base-policy-${BASEPOL}.tar.bz2" + +# Modules should always depend on at least the first release of the +# selinux-base-policy for which they are generated. +if [[ -n ${BASEPOL} ]]; then + RDEPEND=">=sys-apps/policycoreutils-2.0.82 + >=sec-policy/selinux-base-policy-${BASEPOL}" +else + RDEPEND=">=sys-apps/policycoreutils-2.0.82 + >=sec-policy/selinux-base-policy-${PV}" +fi +if [[ ${EAPI} == 6 ]]; then + DEPEND="${RDEPEND} + sys-devel/m4 + >=sys-apps/checkpolicy-2.0.21" +else + DEPEND="${RDEPEND}" + BDEPEND="sys-devel/m4 + >=sys-apps/checkpolicy-2.0.21" +fi + +EXPORT_FUNCTIONS src_unpack src_prepare src_compile src_install pkg_postinst pkg_postrm + +# @FUNCTION: selinux-policy-2_src_unpack +# @DESCRIPTION: +# Unpack the policy sources as offered by upstream (refpolicy). +selinux-policy-2_src_unpack() { + if [[ "${BASEPOL}" != "9999" ]]; then + unpack ${A} + else + git-r3_src_unpack + fi +} + +# @FUNCTION: selinux-policy-2_src_prepare +# @DESCRIPTION: +# Patch the reference policy sources with our set of enhancements. Start with +# the base patchbundle referred to by the ebuilds through the BASEPOL variable, +# then apply the additional patches as offered by the ebuild. +# +# Next, extract only those files needed for this particular module (i.e. the .te +# and .fc files for the given module in the MODS variable). +# +# Finally, prepare the build environments for each of the supported SELinux +# types (such as targeted or strict), depending on the POLICY_TYPES variable +# content. +selinux-policy-2_src_prepare() { + local modfiles + local add_interfaces=0; + + # Create 3rd_party location for user-contributed policies + cd "${S}/refpolicy/policy/modules" && mkdir 3rd_party; + + # Patch the sources with the base patchbundle + if [[ -n ${BASEPOL} ]] && [[ "${BASEPOL}" != "9999" ]]; then + cd "${S}" + einfo "Applying SELinux policy updates ... " + eapply -p0 "${WORKDIR}/0001-full-patch-against-stable-release.patch" + fi + + # Call in eapply_user. We do this early on as we start moving + # files left and right hereafter. + eapply_user + + # Copy additional files to the 3rd_party/ location + if [[ "$(declare -p POLICY_FILES 2>/dev/null 2>&1)" == "declare -a"* ]] || + [[ -n ${POLICY_FILES} ]]; then + add_interfaces=1; + cd "${S}/refpolicy/policy/modules" + for POLFILE in ${POLICY_FILES[@]}; + do + cp "${FILESDIR}/${POLFILE}" 3rd_party/ || die "Could not copy ${POLFILE} to 3rd_party/ location"; + done + fi + + # Apply the additional patches refered to by the module ebuild. + # But first some magic to differentiate between bash arrays and strings + if [[ "$(declare -p POLICY_PATCH 2>/dev/null 2>&1)" == "declare -a"* ]]; then + [[ -n ${POLICY_PATCH[*]} ]] && eapply -d "${S}/refpolicy/policy/modules" "${POLICY_PATCH[@]}" + else + [[ -n ${POLICY_PATCH} ]] && eapply -d "${S}/refpolicy/policy/modules" ${POLICY_PATCH} + fi + + # Collect only those files needed for this particular module + for i in ${MODS}; do + modfiles="$(find ${S}/refpolicy/policy/modules -iname $i.te) $modfiles" + modfiles="$(find ${S}/refpolicy/policy/modules -iname $i.fc) $modfiles" + modfiles="$(find ${S}/refpolicy/policy/modules -iname $i.cil) $modfiles" + if [[ ${add_interfaces} -eq 1 ]]; then + modfiles="$(find ${S}/refpolicy/policy/modules -iname $i.if) $modfiles" + fi + done + + for i in ${POLICY_TYPES}; do + mkdir "${S}"/${i} || die "Failed to create directory ${S}/${i}" + cp "${S}"/refpolicy/doc/Makefile.example "${S}"/${i}/Makefile \ + || die "Failed to copy Makefile.example to ${S}/${i}/Makefile" + + cp ${modfiles} "${S}"/${i} \ + || die "Failed to copy the module files to ${S}/${i}" + done +} + +# @FUNCTION: selinux-policy-2_src_compile +# @DESCRIPTION: +# Build the SELinux policy module (.pp file) for just the selected module, and +# this for each SELinux policy mentioned in POLICY_TYPES +selinux-policy-2_src_compile() { + local makeuse="" + for useflag in ${IUSE}; + do + use ${useflag} && makeuse="${makeuse} -D use_${useflag}" + done + + for i in ${POLICY_TYPES}; do + # Support USE flags in builds + export M4PARAM="${makeuse}" + emake NAME=$i SHAREDIR="${ROOT%/}"/usr/share/selinux -C "${S}"/${i} || die "${i} compile failed" + done +} + +# @FUNCTION: selinux-policy-2_src_install +# @DESCRIPTION: +# Install the built .pp (or copied .cil) files in the correct subdirectory within +# /usr/share/selinux. +selinux-policy-2_src_install() { + local BASEDIR="/usr/share/selinux" + + for i in ${POLICY_TYPES}; do + for j in ${MODS}; do + einfo "Installing ${i} ${j} policy package" + insinto ${BASEDIR}/${i} + if [[ -f "${S}/${i}/${j}.pp" ]] ; then + doins "${S}"/${i}/${j}.pp || die "Failed to add ${j}.pp to ${i}" + elif [[ -f "${S}/${i}/${j}.cil" ]] ; then + doins "${S}"/${i}/${j}.cil || die "Failed to add ${j}.cil to ${i}" + fi + + if [[ "${POLICY_FILES[@]}" == *"${j}.if"* ]]; then + insinto ${BASEDIR}/${i}/include/3rd_party + doins "${S}"/${i}/${j}.if || die "Failed to add ${j}.if to ${i}" + fi + done + done +} + +# @FUNCTION: selinux-policy-2_pkg_postinst +# @DESCRIPTION: +# Install the built .pp (or copied .cil) files in the SELinux policy stores, effectively +# activating the policy on the system. +selinux-policy-2_pkg_postinst() { + # Set root path and don't load policy into the kernel when cross compiling + local root_opts="" + if [[ "${ROOT%/}" != "" ]]; then + root_opts="-p ${ROOT%/} -n" + fi + + # build up the command in the case of multiple modules + local COMMAND + + for i in ${POLICY_TYPES}; do + if [[ "${i}" == "strict" ]] && [[ "${MODS}" = "unconfined" ]]; then + einfo "Ignoring loading of unconfined module in strict module store."; + continue; + fi + einfo "Inserting the following modules into the $i module store: ${MODS}" + + cd "${ROOT%/}/usr/share/selinux/${i}" || die "Could not enter /usr/share/selinux/${i}" + for j in ${MODS} ; do + if [[ -f "${j}.pp" ]] ; then + COMMAND="${j}.pp ${COMMAND}" + elif [[ -f "${j}.cil" ]] ; then + COMMAND="${j}.cil ${COMMAND}" + fi + done + + semodule ${root_opts} -s ${i} -i ${COMMAND} + if [[ $? -ne 0 ]]; then + ewarn "SELinux module load failed. Trying full reload..."; + local COMMAND_base="-i base.pp" + if has_version "<sys-apps/policycoreutils-2.5"; then + COMMAND_base="-b base.pp" + fi + + if [[ "${i}" == "targeted" ]]; then + semodule ${root_opts} -s ${i} ${COMMAND_base} -i $(ls *.pp | grep -v base.pp); + else + semodule ${root_opts} -s ${i} ${COMMAND_base} -i $(ls *.pp | grep -v base.pp | grep -v unconfined.pp); + fi + if [[ $? -ne 0 ]]; then + ewarn "Failed to reload SELinux policies." + ewarn "" + ewarn "If this is *not* the last SELinux module package being installed," + ewarn "then you can safely ignore this as the reloads will be retried" + ewarn "with other, recent modules." + ewarn "" + ewarn "If it is the last SELinux module package being installed however," + ewarn "then it is advised to look at the error above and take appropriate" + ewarn "action since the new SELinux policies are not loaded until the" + ewarn "command finished succesfully." + ewarn "" + ewarn "To reload, run the following command from within /usr/share/selinux/${i}:" + ewarn " semodule ${COMMAND_base} -i \$(ls *.pp | grep -v base.pp)" + ewarn "or" + ewarn " semodule ${COMMAND_base} -i \$(ls *.pp | grep -v base.pp | grep -v unconfined.pp)" + ewarn "depending on if you need the unconfined domain loaded as well or not." + else + einfo "SELinux modules reloaded succesfully." + fi + else + einfo "SELinux modules loaded succesfully." + fi + COMMAND=""; + done + + # Don't relabel when cross compiling + if [[ "${ROOT%/}" == "" ]]; then + # Relabel depending packages + local PKGSET=""; + if [[ -x /usr/bin/qdepends ]] ; then + PKGSET=$(/usr/bin/qdepends -Cq -r -Q ${CATEGORY}/${PN} | grep -v "sec-policy/selinux-"); + elif [[ -x /usr/bin/equery ]] ; then + PKGSET=$(/usr/bin/equery -Cq depends ${CATEGORY}/${PN} | grep -v "sec-policy/selinux-"); + fi + if [[ -n "${PKGSET}" ]] ; then + rlpkg ${PKGSET}; + fi + fi +} + +# @FUNCTION: selinux-policy-2_pkg_postrm +# @DESCRIPTION: +# Uninstall the module(s) from the SELinux policy stores, effectively +# deactivating the policy on the system. +selinux-policy-2_pkg_postrm() { + # Only if we are not upgrading + if [[ -z "${REPLACED_BY_VERSION}" ]]; then + # Set root path and don't load policy into the kernel when cross compiling + local root_opts="" + if [[ "${ROOT%/}" != "" ]]; then + root_opts="-p ${ROOT%/} -n" + fi + + # build up the command in the case of multiple modules + local COMMAND + for i in ${MODS}; do + COMMAND="-r ${i} ${COMMAND}" + done + + for i in ${POLICY_TYPES}; do + einfo "Removing the following modules from the $i module store: ${MODS}" + + semodule ${root_opts} -s ${i} ${COMMAND} + if [[ $? -ne 0 ]]; then + ewarn "SELinux module unload failed."; + else + einfo "SELinux modules unloaded succesfully." + fi + done + fi +} + diff --git a/eclass/sgml-catalog-r1.eclass b/eclass/sgml-catalog-r1.eclass new file mode 100644 index 0000000..1e1f178 --- /dev/null +++ b/eclass/sgml-catalog-r1.eclass @@ -0,0 +1,76 @@ +# Copyright 2019 Gentoo Authors +# Distributed under the terms of the GNU General Public License v2 + +# @ECLASS: sgml-catalog-r1.eclass +# @MAINTAINER: +# Michał Górny <mgorny@gentoo.org> +# @AUTHOR: +# Michał Górny <mgorny@gentoo.org> +# @SUPPORTED_EAPIS: 7 +# @BLURB: Functions for installing SGML catalogs +# @DESCRIPTION: +# This eclass regenerates /etc/sgml/catalog, /etc/sgml.{,c}env +# and /etc/env.d/93sgmltools-lite as necessary for the DocBook tooling. +# This is done via exported pkg_postinst and pkg_postrm phases. + +case ${EAPI:-0} in + 7) ;; + *) die "Unsupported EAPI=${EAPI} for ${ECLASS}";; +esac + +EXPORT_FUNCTIONS pkg_postinst pkg_postrm + +if [[ ! ${_SGML_CATALOG_R1} ]]; then + +if [[ ${CATEGORY}/${PN} != app-text/sgml-common ]]; then + RDEPEND=">=app-text/sgml-common-0.6.3-r7" +fi + +# @FUNCTION: sgml-catalog-r1_update_catalog +# @DESCRIPTION: +# Regenerate /etc/sgml/catalog to include all installed catalogs. +sgml-catalog-r1_update_catalog() { + local shopt_save=$(shopt -p nullglob) + shopt -s nullglob + local cats=( "${EROOT}"/etc/sgml/*.cat ) + ${shopt_save} + + if [[ ${#cats[@]} -gt 0 ]]; then + ebegin "Updating ${EROOT}/etc/sgml/catalog" + printf 'CATALOG "%s"\n' "${cats[@]}" > "${T}"/catalog && + mv "${T}"/catalog "${EROOT}"/etc/sgml/catalog + eend "${?}" + else + ebegin "Removing ${EROOT}/etc/sgml/catalog" + rm "${EROOT}"/etc/sgml/catalog && + { rmdir "${EROOT}"/etc/sgml &>/dev/null || :; } + eend "${?}" + fi +} + +# @FUNCTION: sgml-catalog-r1_update_env +# @DESCRIPTION: +# Regenerate environment variables and copy them to env.d. +sgml-catalog-r1_update_env() { + # gensgmlenv doesn't support overriding root + if [[ -z ${ROOT} && -x "${EPREFIX}/usr/bin/gensgmlenv" ]]; then + ebegin "Regenerating SGML environment variables" + gensgmlenv && + grep -v export "${EPREFIX}/etc/sgml/sgml.env" > "${T}"/93sgmltools-lite && + mv "${T}"/93sgmltools-lite "${EPREFIX}/etc/env.d/93sgmltools-lite" + eend "${?}" + fi +} + +sgml-catalog-r1_pkg_postinst() { + sgml-catalog-r1_update_catalog + sgml-catalog-r1_update_env +} + +sgml-catalog-r1_pkg_postrm() { + sgml-catalog-r1_update_catalog + sgml-catalog-r1_update_env +} + +_SGML_CATALOG_R1=1 +fi diff --git a/eclass/ssl-cert.eclass b/eclass/ssl-cert.eclass new file mode 100644 index 0000000..fdd6775 --- /dev/null +++ b/eclass/ssl-cert.eclass @@ -0,0 +1,286 @@ +# Copyright 1999-2020 Gentoo Authors +# Distributed under the terms of the GNU General Public License v2 + +# @ECLASS: ssl-cert.eclass +# @MAINTAINER: +# @AUTHOR: +# Max Kalika <max@gentoo.org> +# @SUPPORTED_EAPIS: 1 2 3 4 5 6 7 +# @BLURB: Eclass for SSL certificates +# @DESCRIPTION: +# This eclass implements a standard installation procedure for installing +# self-signed SSL certificates. +# @EXAMPLE: +# "install_cert /foo/bar" installs ${ROOT}/foo/bar.{key,csr,crt,pem} + +# Guard against unsupported EAPIs. We need EAPI >= 1 for slot dependencies. +case "${EAPI:-0}" in + 0) + die "${ECLASS}.eclass: EAPI=0 is not supported. Please upgrade to EAPI >= 1." + ;; + 1|2|3|4|5|6|7) + ;; + *) + die "${ECLASS}.eclass: EAPI=${EAPI} is not supported yet." + ;; +esac + +# @ECLASS-VARIABLE: SSL_CERT_MANDATORY +# @DESCRIPTION: +# Set to non zero if ssl-cert is mandatory for ebuild. +: ${SSL_CERT_MANDATORY:=0} + +# @ECLASS-VARIABLE: SSL_CERT_USE +# @DESCRIPTION: +# Use flag to append dependency to. +: ${SSL_CERT_USE:=ssl} + +# @ECLASS-VARIABLE: SSL_DEPS_SKIP +# @DESCRIPTION: +# Set to non zero to skip adding to DEPEND and IUSE. +: ${SSL_DEPS_SKIP:=0} + +if [[ "${SSL_DEPS_SKIP}" == "0" ]]; then + if [[ "${SSL_CERT_MANDATORY}" == "0" ]]; then + SSL_DEPEND="${SSL_CERT_USE}? ( || ( dev-libs/openssl:0 dev-libs/libressl:0 ) )" + IUSE="${SSL_CERT_USE}" + else + SSL_DEPEND="|| ( dev-libs/openssl:0 dev-libs/libressl:0 )" + fi + + case "${EAPI}" in + 1|2|3|4|5|6) + DEPEND="${SSL_DEPEND}" + ;; + *) + BDEPEND="${SSL_DEPEND}" + ;; + esac + + unset SSL_DEPEND +fi + +# @FUNCTION: gen_cnf +# @USAGE: +# @DESCRIPTION: +# Initializes variables and generates the needed +# OpenSSL configuration file and a CA serial file +# +# Access: private +gen_cnf() { + # Location of the config file + SSL_CONF="${T}/${$}ssl.cnf" + # Location of the CA serial file + SSL_SERIAL="${T}/${$}ca.ser" + # Location of some random files OpenSSL can use: don't use + # /dev/u?random here -- doesn't work properly on all platforms + SSL_RANDOM="${T}/environment:${T}/eclass-debug.log:/etc/resolv.conf" + + # These can be overridden in the ebuild + SSL_DAYS="${SSL_DAYS:-730}" + SSL_BITS="${SSL_BITS:-4096}" + SSL_MD="${SSL_MD:-sha256}" + SSL_COUNTRY="${SSL_COUNTRY:-US}" + SSL_STATE="${SSL_STATE:-California}" + SSL_LOCALITY="${SSL_LOCALITY:-Santa Barbara}" + SSL_ORGANIZATION="${SSL_ORGANIZATION:-SSL Server}" + SSL_UNIT="${SSL_UNIT:-For Testing Purposes Only}" + SSL_COMMONNAME="${SSL_COMMONNAME:-localhost}" + SSL_EMAIL="${SSL_EMAIL:-root@localhost}" + + # Create the CA serial file + echo "01" > "${SSL_SERIAL}" + + # Create the config file + ebegin "Generating OpenSSL configuration${1:+ for CA}" + cat <<-EOF > "${SSL_CONF}" + [ req ] + prompt = no + default_bits = ${SSL_BITS} + distinguished_name = req_dn + [ req_dn ] + C = ${SSL_COUNTRY} + ST = ${SSL_STATE} + L = ${SSL_LOCALITY} + O = ${SSL_ORGANIZATION} + OU = ${SSL_UNIT} + CN = ${SSL_COMMONNAME}${1:+ CA} + emailAddress = ${SSL_EMAIL} + EOF + eend $? + + return $? +} + +# @FUNCTION: get_base +# @USAGE: [if_ca] +# @RETURN: <base path> +# @DESCRIPTION: +# Simple function to determine whether we're creating +# a CA (which should only be done once) or final part +# +# Access: private +get_base() { + if [ "${1}" ] ; then + echo "${T}/${$}ca" + else + echo "${T}/${$}server" + fi +} + +# @FUNCTION: gen_key +# @USAGE: <base path> +# @DESCRIPTION: +# Generates an RSA key +# +# Access: private +gen_key() { + local base=$(get_base "$1") + ebegin "Generating ${SSL_BITS} bit RSA key${1:+ for CA}" + if openssl version | grep -i libressl > /dev/null; then + openssl genrsa -out "${base}.key" "${SSL_BITS}" &> /dev/null + else + openssl genrsa -rand "${SSL_RANDOM}" \ + -out "${base}.key" "${SSL_BITS}" &> /dev/null + fi + eend $? + + return $? +} + +# @FUNCTION: gen_csr +# @USAGE: <base path> +# @DESCRIPTION: +# Generates a certificate signing request using +# the key made by gen_key() +# +# Access: private +gen_csr() { + local base=$(get_base "$1") + ebegin "Generating Certificate Signing Request${1:+ for CA}" + openssl req -config "${SSL_CONF}" -new \ + -key "${base}.key" -out "${base}.csr" &>/dev/null + eend $? + + return $? +} + +# @FUNCTION: gen_crt +# @USAGE: <base path> +# @DESCRIPTION: +# Generates either a self-signed CA certificate using +# the csr and key made by gen_csr() and gen_key() or +# a signed server certificate using the CA cert previously +# created by gen_crt() +# +# Access: private +gen_crt() { + local base=$(get_base "$1") + if [ "${1}" ] ; then + ebegin "Generating self-signed X.509 Certificate for CA" + openssl x509 -extfile "${SSL_CONF}" \ + -${SSL_MD} \ + -days ${SSL_DAYS} -req -signkey "${base}.key" \ + -in "${base}.csr" -out "${base}.crt" &>/dev/null + else + local ca=$(get_base 1) + ebegin "Generating authority-signed X.509 Certificate" + openssl x509 -extfile "${SSL_CONF}" \ + -days ${SSL_DAYS} -req -CAserial "${SSL_SERIAL}" \ + -CAkey "${ca}.key" -CA "${ca}.crt" -${SSL_MD} \ + -in "${base}.csr" -out "${base}.crt" &>/dev/null + fi + eend $? + + return $? +} + +# @FUNCTION: gen_pem +# @USAGE: <base path> +# @DESCRIPTION: +# Generates a PEM file by concatinating the key +# and cert file created by gen_key() and gen_cert() +# +# Access: private +gen_pem() { + local base=$(get_base "$1") + ebegin "Generating PEM Certificate" + (cat "${base}.key"; echo; cat "${base}.crt") > "${base}.pem" + eend $? + + return $? +} + +# @FUNCTION: install_cert +# @USAGE: <certificates> +# @DESCRIPTION: +# Uses all the private functions above to generate and install the +# requested certificates. +# <certificates> are full pathnames relative to ROOT, without extension. +# +# Example: "install_cert /foo/bar" installs ${ROOT}/foo/bar.{key,csr,crt,pem} +# +# Access: public +install_cert() { + if [ $# -lt 1 ] ; then + eerror "At least one argument needed" + return 1; + fi + + case ${EBUILD_PHASE} in + unpack|prepare|configure|compile|test|install) + die "install_cert cannot be called in ${EBUILD_PHASE}" + ;; + esac + + # Generate a CA environment #164601 + gen_cnf 1 || return 1 + gen_key 1 || return 1 + gen_csr 1 || return 1 + gen_crt 1 || return 1 + echo + + gen_cnf || return 1 + echo + + local count=0 + for cert in "$@" ; do + # Check the requested certificate + if [ -z "${cert##*/}" ] ; then + ewarn "Invalid certification requested, skipping" + continue + fi + + # Check for previous existence of generated files + for type in key csr crt pem ; do + if [ -e "${ROOT}${cert}.${type}" ] ; then + ewarn "${ROOT}${cert}.${type}: exists, skipping" + continue 2 + fi + done + + # Generate the requested files + gen_key || continue + gen_csr || continue + gen_crt || continue + gen_pem || continue + echo + + # Install the generated files and set sane permissions + local base=$(get_base) + install -d "${ROOT}${cert%/*}" + install -m0400 "${base}.key" "${ROOT}${cert}.key" + install -m0444 "${base}.csr" "${ROOT}${cert}.csr" + install -m0444 "${base}.crt" "${ROOT}${cert}.crt" + install -m0400 "${base}.pem" "${ROOT}${cert}.pem" + : $(( ++count )) + done + + # Resulting status + if [ ${count} = 0 ] ; then + eerror "No certificates were generated" + return 1 + elif [ ${count} != ${#} ] ; then + ewarn "Some requested certificates were not generated" + fi +} diff --git a/eclass/stardict.eclass b/eclass/stardict.eclass new file mode 100644 index 0000000..5e96b01 --- /dev/null +++ b/eclass/stardict.eclass @@ -0,0 +1,59 @@ +# Copyright 1999-2020 Gentoo Authors +# Distributed under the terms of the GNU General Public License v2 + +# Author : Alastair Tse <liquidx@gentoo.org> +# +# Convienence class to do stardict dictionary installations. +# +# Usage: +# - Variables to set : +# * FROM_LANG - From this language +# * TO_LANG - To this language +# * DICT_PREFIX - SRC_URI prefix, like "dictd_www.mova.org_" +# * DICT_SUFFIX - SRC_URI after the prefix. + +RESTRICT="strip" + +[ -z "${DICT_SUFFIX}" ] && DICT_SUFFIX=${PN#stardict-[[:lower:]]*-} +[ -z "${DICT_P}" ] && DICT_P=stardict-${DICT_PREFIX}${DICT_SUFFIX}-${PV} + +if [ -n "${FROM_LANG}" -a -n "${TO_LANG}" ]; then + DESCRIPTION="Stardict Dictionary ${FROM_LANG} to ${TO_LANG}" +elif [ -z "${DESCRIPTION}" ]; then + DESCRIPTION="Another Stardict Dictionary" +fi + +HOMEPAGE="http://stardict.sourceforge.net/" +SRC_URI="mirror://sourceforge/stardict/${DICT_P}.tar.bz2" + +IUSE="gzip" +SLOT="0" +LICENSE="GPL-2" + +DEPEND="|| ( >=app-text/stardict-2.4.2 + app-text/sdcv + app-text/goldendict ) + gzip? ( app-arch/gzip + app-text/dictd )" + +S=${WORKDIR}/${DICT_P} + +stardict_src_compile() { + if use gzip; then + for file in *.idx; do + [[ -f $file ]] && gzip ${file} + done + for file in *.dict; do + [[ -f $file ]] && dictzip ${file} + done + fi +} + +stardict_src_install() { + insinto /usr/share/stardict/dic + doins *.dict.dz* + doins *.idx* + doins *.ifo +} + +EXPORT_FUNCTIONS src_compile src_install diff --git a/eclass/subversion.eclass b/eclass/subversion.eclass new file mode 100644 index 0000000..36b1fbb --- /dev/null +++ b/eclass/subversion.eclass @@ -0,0 +1,539 @@ +# Copyright 1999-2020 Gentoo Authors +# Distributed under the terms of the GNU General Public License v2 + +# @ECLASS: subversion.eclass +# @MAINTAINER: +# Akinori Hattori <hattya@gentoo.org> +# @AUTHOR: +# Original Author: Akinori Hattori <hattya@gentoo.org> +# @SUPPORTED_EAPIS: 4 5 6 7 +# @BLURB: Fetch software sources from subversion repositories +# @DESCRIPTION: +# The subversion eclass provides functions to fetch, patch and bootstrap +# software sources from subversion repositories. + +ESVN="${ECLASS}" + +case ${EAPI:-0} in + 4|5) + inherit eutils + EXPORT_FUNCTIONS src_unpack src_prepare pkg_preinst + ;; + 6|7) + inherit estack + EXPORT_FUNCTIONS src_unpack pkg_preinst + ;; + *) + die "${ESVN}: EAPI ${EAPI:-0} is not supported" + ;; +esac + +PROPERTIES+=" live" + +DEPEND=" + dev-vcs/subversion[http(+)] + net-misc/rsync" + +case ${EAPI} in + 4|5|6) ;; + *) BDEPEND="${DEPEND}"; DEPEND="" ;; +esac + +# @ECLASS-VARIABLE: ESVN_STORE_DIR +# @DESCRIPTION: +# subversion sources store directory. Users may override this in /etc/portage/make.conf +[[ -z ${ESVN_STORE_DIR} ]] && ESVN_STORE_DIR="${PORTAGE_ACTUAL_DISTDIR:-${DISTDIR}}/svn-src" + +# @ECLASS-VARIABLE: ESVN_FETCH_CMD +# @DESCRIPTION: +# subversion checkout command +ESVN_FETCH_CMD="svn checkout" + +# @ECLASS-VARIABLE: ESVN_UPDATE_CMD +# @DESCRIPTION: +# subversion update command +ESVN_UPDATE_CMD="svn update" + +# @ECLASS-VARIABLE: ESVN_SWITCH_CMD +# @DESCRIPTION: +# subversion switch command +ESVN_SWITCH_CMD="svn switch" + +# @ECLASS-VARIABLE: ESVN_OPTIONS +# @DESCRIPTION: +# the options passed to checkout or update. If you want a specific revision see +# ESVN_REPO_URI instead of using -rREV. +ESVN_OPTIONS="${ESVN_OPTIONS:-}" + +# @ECLASS-VARIABLE: ESVN_REPO_URI +# @DESCRIPTION: +# repository uri +# +# e.g. http://example.org/trunk, svn://example.org/branch/foo@1234 +# +# supported URI schemes: +# http:// +# https:// +# svn:// +# svn+ssh:// +# file:// +# +# to peg to a specific revision, append @REV to the repo's uri +ESVN_REPO_URI="${ESVN_REPO_URI:-}" + +# @ECLASS-VARIABLE: ESVN_REVISION +# @DESCRIPTION: +# User configurable revision checkout or update to from the repository +# +# Useful for live svn or trunk svn ebuilds allowing the user to peg +# to a specific revision +# +# Note: This should never be set in an ebuild! +ESVN_REVISION="${ESVN_REVISION:-}" + +# @ECLASS-VARIABLE: ESVN_USER +# @DESCRIPTION: +# User name +ESVN_USER="${ESVN_USER:-}" + +# @ECLASS-VARIABLE: ESVN_PASSWORD +# @DESCRIPTION: +# Password +ESVN_PASSWORD="${ESVN_PASSWORD:-}" + +# @ECLASS-VARIABLE: ESVN_PROJECT +# @DESCRIPTION: +# project name of your ebuild (= name space) +# +# subversion eclass will check out the subversion repository like: +# +# ${ESVN_STORE_DIR}/${ESVN_PROJECT}/${ESVN_REPO_URI##*/} +# +# so if you define ESVN_REPO_URI as http://svn.collab.net/repo/svn/trunk or +# http://svn.collab.net/repo/svn/trunk/. and PN is subversion-svn. +# it will check out like: +# +# ${ESVN_STORE_DIR}/subversion/trunk +# +# this is not used in order to declare the name of the upstream project. +# so that you can declare this like: +# +# # jakarta commons-loggin +# ESVN_PROJECT=commons/logging +# +# default: ${PN/-svn}. +ESVN_PROJECT="${ESVN_PROJECT:-${PN/-svn}}" + +# @ECLASS-VARIABLE: ESVN_BOOTSTRAP +# @DESCRIPTION: +# Bootstrap script or command like autogen.sh or etc.. +# Removed in EAPI 6 and later. +ESVN_BOOTSTRAP="${ESVN_BOOTSTRAP:-}" + +# @ECLASS-VARIABLE: ESVN_PATCHES +# @DESCRIPTION: +# subversion eclass can apply patches in subversion_bootstrap(). +# you can use regexp in this variable like *.diff or *.patch or etc. +# NOTE: patches will be applied before ESVN_BOOTSTRAP is processed. +# +# Patches are searched both in ${PWD} and ${FILESDIR}, if not found in either +# location, the installation dies. +# +# Removed in EAPI 6 and later, use PATCHES instead. +ESVN_PATCHES="${ESVN_PATCHES:-}" + +# @ECLASS-VARIABLE: ESVN_RESTRICT +# @DESCRIPTION: +# this should be a space delimited list of subversion eclass features to +# restrict. +# export) +# don't export the working copy to S. +ESVN_RESTRICT="${ESVN_RESTRICT:-}" + +# @ECLASS-VARIABLE: ESVN_OFFLINE +# @DESCRIPTION: +# Set this variable to a non-empty value to disable the automatic updating of +# an svn source tree. This is intended to be set outside the subversion source +# tree by users. +ESVN_OFFLINE="${ESVN_OFFLINE:-${EVCS_OFFLINE}}" + +# @ECLASS-VARIABLE: ESVN_UMASK +# @DESCRIPTION: +# Set this variable to a custom umask. This is intended to be set by users. +# By setting this to something like 002, it can make life easier for people +# who do development as non-root (but are in the portage group), and then +# switch over to building with FEATURES=userpriv. Or vice-versa. Shouldn't +# be a security issue here as anyone who has portage group write access +# already can screw the system over in more creative ways. +ESVN_UMASK="${ESVN_UMASK:-${EVCS_UMASK}}" + +# @ECLASS-VARIABLE: ESVN_UP_FREQ +# @DESCRIPTION: +# Set the minimum number of hours between svn up'ing in any given svn module. This is particularly +# useful for split KDE ebuilds where we want to ensure that all submodules are compiled for the same +# revision. It should also be kept user overrideable. +ESVN_UP_FREQ="${ESVN_UP_FREQ:=}" + +# @ECLASS-VARIABLE: ESCM_LOGDIR +# @DESCRIPTION: +# User configuration variable. If set to a path such as e.g. /var/log/scm any +# package inheriting from subversion.eclass will record svn revision to +# ${CATEGORY}/${PN}.log in that path in pkg_preinst. This is not supposed to be +# set by ebuilds/eclasses. It defaults to empty so users need to opt in. +ESCM_LOGDIR="${ESCM_LOGDIR:=}" + +# @FUNCTION: subversion_fetch +# @USAGE: [repo_uri] [destination] +# @DESCRIPTION: +# Wrapper function to fetch sources from subversion via svn checkout or svn update, +# depending on whether there is an existing working copy in ${ESVN_STORE_DIR}. +# +# Can take two optional parameters: +# repo_uri - a repository URI. default is ESVN_REPO_URI. +# destination - a check out path in S. +subversion_fetch() { + local repo_uri="$(subversion__get_repository_uri "${1:-${ESVN_REPO_URI}}")" + local revision="$(subversion__get_peg_revision "${1:-${ESVN_REPO_URI}}")" + local S_dest="${2}" + + if [[ -z ${repo_uri} ]]; then + die "${ESVN}: ESVN_REPO_URI (or specified URI) is empty." + fi + + [[ -n "${ESVN_REVISION}" ]] && revision="${ESVN_REVISION}" + + # check for the scheme + local scheme="${repo_uri%%:*}" + case "${scheme}" in + http|https) + ;; + svn|svn+ssh) + ;; + file) + ;; + *) + die "${ESVN}: fetch from '${scheme}' is not yet implemented." + ;; + esac + + addread "/etc/subversion" + addwrite "${ESVN_STORE_DIR}" + + if [[ -n "${ESVN_UMASK}" ]]; then + eumask_push "${ESVN_UMASK}" + fi + + if [[ ! -d ${ESVN_STORE_DIR} ]]; then + debug-print "${FUNCNAME}: initial checkout. creating subversion directory" + mkdir -m 775 -p "${ESVN_STORE_DIR}" || die "${ESVN}: can't mkdir ${ESVN_STORE_DIR}." + fi + + pushd "${ESVN_STORE_DIR}" >/dev/null || die "${ESVN}: can't chdir to ${ESVN_STORE_DIR}" + + local wc_path="$(subversion__get_wc_path "${repo_uri}")" + local options="${ESVN_OPTIONS} --config-dir ${ESVN_STORE_DIR}/.subversion" + + [[ -n "${revision}" ]] && options="${options} -r ${revision}" + + if [[ "${ESVN_OPTIONS}" = *-r* ]]; then + ewarn "\${ESVN_OPTIONS} contains -r, this usage is unsupported. Please" + ewarn "see \${ESVN_REPO_URI}" + fi + + if has_version ">=dev-vcs/subversion-1.6.0"; then + options="${options} --config-option=config:auth:password-stores=" + fi + + debug-print "${FUNCNAME}: wc_path = \"${wc_path}\"" + debug-print "${FUNCNAME}: ESVN_OPTIONS = \"${ESVN_OPTIONS}\"" + debug-print "${FUNCNAME}: options = \"${options}\"" + + if [[ ! -d ${wc_path}/.svn ]]; then + if [[ -n ${ESVN_OFFLINE} ]]; then + ewarn "ESVN_OFFLINE cannot be used when there is no existing checkout." + fi + # first check out + einfo "subversion check out start -->" + einfo " repository: ${repo_uri}${revision:+@}${revision}" + + debug-print "${FUNCNAME}: ${ESVN_FETCH_CMD} ${options} ${repo_uri}" + + mkdir -m 775 -p "${ESVN_PROJECT}" || die "${ESVN}: can't mkdir ${ESVN_PROJECT}." + cd "${ESVN_PROJECT}" || die "${ESVN}: can't chdir to ${ESVN_PROJECT}" + if [[ -n "${ESVN_USER}" ]]; then + ${ESVN_FETCH_CMD} ${options} --username "${ESVN_USER}" --password "${ESVN_PASSWORD}" "${repo_uri}" || die "${ESVN}: can't fetch to ${wc_path} from ${repo_uri}." + else + ${ESVN_FETCH_CMD} ${options} "${repo_uri}" || die "${ESVN}: can't fetch to ${wc_path} from ${repo_uri}." + fi + + elif [[ -n ${ESVN_OFFLINE} ]]; then + svn upgrade "${wc_path}" &>/dev/null + svn cleanup "${wc_path}" &>/dev/null + subversion_wc_info "${repo_uri}" || die "${ESVN}: unknown problem occurred while accessing working copy." + + if [[ -n ${ESVN_REVISION} && ${ESVN_REVISION} != ${ESVN_WC_REVISION} ]]; then + die "${ESVN}: You requested off-line updating and revision ${ESVN_REVISION} but only revision ${ESVN_WC_REVISION} is available locally." + fi + einfo "Fetching disabled: Using existing repository copy at revision ${ESVN_WC_REVISION}." + else + svn upgrade "${wc_path}" &>/dev/null + svn cleanup "${wc_path}" &>/dev/null + subversion_wc_info "${repo_uri}" || die "${ESVN}: unknown problem occurred while accessing working copy." + + local esvn_up_freq= + if [[ -n ${ESVN_UP_FREQ} ]]; then + if [[ -n ${ESVN_UP_FREQ//[[:digit:]]} ]]; then + die "${ESVN}: ESVN_UP_FREQ must be an integer value corresponding to the minimum number of hours between svn up." + elif [[ -z $(find "${wc_path}/.svn/entries" -mmin "+$((ESVN_UP_FREQ*60))") ]]; then + einfo "Fetching disabled since ${ESVN_UP_FREQ} hours has not passed since last update." + einfo "Using existing repository copy at revision ${ESVN_WC_REVISION}." + esvn_up_freq=no_update + fi + fi + + if [[ -z ${esvn_up_freq} ]]; then + if [[ ${ESVN_WC_UUID} != $(subversion__svn_info "${repo_uri}" "Repository UUID") ]]; then + # UUID mismatch. Delete working copy and check out it again. + einfo "subversion recheck out start -->" + einfo " old UUID: ${ESVN_WC_UUID}" + einfo " new UUID: $(subversion__svn_info "${repo_uri}" "Repository UUID")" + einfo " repository: ${repo_uri}${revision:+@}${revision}" + + rm -fr "${ESVN_PROJECT}" || die + + debug-print "${FUNCNAME}: ${ESVN_FETCH_CMD} ${options} ${repo_uri}" + + mkdir -m 775 -p "${ESVN_PROJECT}" || die "${ESVN}: can't mkdir ${ESVN_PROJECT}." + cd "${ESVN_PROJECT}" || die "${ESVN}: can't chdir to ${ESVN_PROJECT}" + if [[ -n "${ESVN_USER}" ]]; then + ${ESVN_FETCH_CMD} ${options} --username "${ESVN_USER}" --password "${ESVN_PASSWORD}" "${repo_uri}" || die "${ESVN}: can't fetch to ${wc_path} from ${repo_uri}." + else + ${ESVN_FETCH_CMD} ${options} "${repo_uri}" || die "${ESVN}: can't fetch to ${wc_path} from ${repo_uri}." + fi + elif [[ ${ESVN_WC_URL} != $(subversion__get_repository_uri "${repo_uri}") ]]; then + einfo "subversion switch start -->" + einfo " old repository: ${ESVN_WC_URL}@${ESVN_WC_REVISION}" + einfo " new repository: ${repo_uri}${revision:+@}${revision}" + + debug-print "${FUNCNAME}: ${ESVN_SWITCH_CMD} ${options} ${repo_uri}" + + cd "${wc_path}" || die "${ESVN}: can't chdir to ${wc_path}" + if [[ -n "${ESVN_USER}" ]]; then + ${ESVN_SWITCH_CMD} ${options} --username "${ESVN_USER}" --password "${ESVN_PASSWORD}" ${repo_uri} || die "${ESVN}: can't update ${wc_path} from ${repo_uri}." + else + ${ESVN_SWITCH_CMD} ${options} ${repo_uri} || die "${ESVN}: can't update ${wc_path} from ${repo_uri}." + fi + else + # update working copy + einfo "subversion update start -->" + einfo " repository: ${repo_uri}${revision:+@}${revision}" + + debug-print "${FUNCNAME}: ${ESVN_UPDATE_CMD} ${options}" + + cd "${wc_path}" || die "${ESVN}: can't chdir to ${wc_path}" + if [[ -n "${ESVN_USER}" ]]; then + ${ESVN_UPDATE_CMD} ${options} --username "${ESVN_USER}" --password "${ESVN_PASSWORD}" || die "${ESVN}: can't update ${wc_path} from ${repo_uri}." + else + ${ESVN_UPDATE_CMD} ${options} || die "${ESVN}: can't update ${wc_path} from ${repo_uri}." + fi + fi + + # export updated information for the working copy + subversion_wc_info "${repo_uri}" || die "${ESVN}: unknown problem occurred while accessing working copy." + fi + fi + + if [[ -n "${ESVN_UMASK}" ]]; then + eumask_pop + fi + + einfo " working copy: ${wc_path}" + + if ! has "export" ${ESVN_RESTRICT}; then + cd "${wc_path}" || die "${ESVN}: can't chdir to ${wc_path}" + + local S="${S}/${S_dest}" + mkdir -p "${S}" + + # export to the ${WORKDIR} + #* "svn export" has a bug. see https://bugs.gentoo.org/119236 + #* svn export . "${S}" || die "${ESVN}: can't export to ${S}." + rsync -rlpgo --exclude=".svn/" . "${S}" || die "${ESVN}: can't export to ${S}." + fi + + popd >/dev/null + echo +} + +# @FUNCTION: subversion_bootstrap +# @DESCRIPTION: +# Apply patches in ${ESVN_PATCHES} and run ${ESVN_BOOTSTRAP} if specified. +# Removed in EAPI 6 and later. +subversion_bootstrap() { + [[ ${EAPI} == [012345] ]] || die "${FUNCNAME} is removed from subversion.eclass in EAPI 6 and later" + + if has "export" ${ESVN_RESTRICT}; then + return + fi + + cd "${S}" + + if [[ -n ${ESVN_PATCHES} ]]; then + local patch fpatch + einfo "apply patches -->" + for patch in ${ESVN_PATCHES}; do + if [[ -f ${patch} ]]; then + epatch "${patch}" + else + for fpatch in ${FILESDIR}/${patch}; do + if [[ -f ${fpatch} ]]; then + epatch "${fpatch}" + else + die "${ESVN}: ${patch} not found" + fi + done + fi + done + echo + fi + + if [[ -n ${ESVN_BOOTSTRAP} ]]; then + einfo "begin bootstrap -->" + if [[ -f ${ESVN_BOOTSTRAP} && -x ${ESVN_BOOTSTRAP} ]]; then + einfo " bootstrap with a file: ${ESVN_BOOTSTRAP}" + eval "./${ESVN_BOOTSTRAP}" || die "${ESVN}: can't execute ESVN_BOOTSTRAP." + else + einfo " bootstrap with command: ${ESVN_BOOTSTRAP}" + eval "${ESVN_BOOTSTRAP}" || die "${ESVN}: can't eval ESVN_BOOTSTRAP." + fi + fi +} + +# @FUNCTION: subversion_wc_info +# @USAGE: [repo_uri] +# @RETURN: ESVN_WC_URL, ESVN_WC_ROOT, ESVN_WC_UUID, ESVN_WC_REVISION and ESVN_WC_PATH +# @DESCRIPTION: +# Get svn info for the specified repo_uri. The default repo_uri is ESVN_REPO_URI. +# +# The working copy information on the specified repository URI are set to +# ESVN_WC_* variables. +subversion_wc_info() { + local repo_uri="$(subversion__get_repository_uri "${1:-${ESVN_REPO_URI}}")" + local wc_path="$(subversion__get_wc_path "${repo_uri}")" + + debug-print "${FUNCNAME}: repo_uri = ${repo_uri}" + debug-print "${FUNCNAME}: wc_path = ${wc_path}" + + if [[ ! -d ${wc_path} ]]; then + return 1 + fi + + export ESVN_WC_URL="$(subversion__svn_info "${wc_path}" "URL")" + export ESVN_WC_ROOT="$(subversion__svn_info "${wc_path}" "Repository Root")" + export ESVN_WC_UUID="$(subversion__svn_info "${wc_path}" "Repository UUID")" + export ESVN_WC_REVISION="$(subversion__svn_info "${wc_path}" "Revision")" + export ESVN_WC_PATH="${wc_path}" +} + +# @FUNCTION: subversion_src_unpack +# @DESCRIPTION: +# Default src_unpack. Fetch. +subversion_src_unpack() { + subversion_fetch || die "${ESVN}: unknown problem occurred in subversion_fetch." +} + +# @FUNCTION: subversion_src_prepare +# @DESCRIPTION: +# Default src_prepare. Bootstrap. +# Removed in EAPI 6 and later. +subversion_src_prepare() { + [[ ${EAPI} == [012345] ]] || die "${FUNCNAME} is removed from subversion.eclass in EAPI 6 and later" + subversion_bootstrap || die "${ESVN}: unknown problem occurred in subversion_bootstrap." +} + +# @FUNCTION: subversion_pkg_preinst +# @USAGE: [repo_uri] +# @DESCRIPTION: +# Log the svn revision of source code. Doing this in pkg_preinst because we +# want the logs to stick around if packages are uninstalled without messing with +# config protection. +subversion_pkg_preinst() { + local pkgdate=$(date "+%Y%m%d %H:%M:%S") + if [[ -n ${ESCM_LOGDIR} ]]; then + local dir="${EROOT%/}${ESCM_LOGDIR}/${CATEGORY}" + if [[ ! -d ${dir} ]]; then + mkdir -p "${dir}" || eerror "Failed to create '${dir}' for logging svn revision" + fi + local logmessage="svn: ${pkgdate} - ${PF}:${SLOT} was merged at revision ${ESVN_WC_REVISION}" + if [[ -d ${dir} ]]; then + echo "${logmessage}" >>"${dir}/${PN}.log" + else + eerror "Could not log the message '${logmessage}' to '${dir}/${PN}.log'" + fi + fi +} + +## -- Private Functions + +## -- subversion__svn_info() ------------------------------------------------- # +# +# param $1 - a target. +# param $2 - a key name. +# +subversion__svn_info() { + local target="${1}" + local key="${2}" + + env LC_ALL=C svn info ${options} --username "${ESVN_USER}" --password "${ESVN_PASSWORD}" "${target}" \ + | grep -i "^${key}" \ + | cut -d" " -f2- +} + +## -- subversion__get_repository_uri() --------------------------------------- # +# +# param $1 - a repository URI. +subversion__get_repository_uri() { + local repo_uri="${1}" + + debug-print "${FUNCNAME}: repo_uri = ${repo_uri}" + if [[ -z ${repo_uri} ]]; then + die "${ESVN}: ESVN_REPO_URI (or specified URI) is empty." + fi + # delete trailing slash + if [[ -z ${repo_uri##*/} ]]; then + repo_uri="${repo_uri%/}" + fi + repo_uri="${repo_uri%@*}" + + echo "${repo_uri}" +} + +## -- subversion__get_wc_path() ---------------------------------------------- # +# +# param $1 - a repository URI. +subversion__get_wc_path() { + local repo_uri="$(subversion__get_repository_uri "${1}")" + + debug-print "${FUNCNAME}: repo_uri = ${repo_uri}" + + echo "${ESVN_STORE_DIR}/${ESVN_PROJECT}/${repo_uri##*/}" +} + +## -- subversion__get_peg_revision() ----------------------------------------- # +# +# param $1 - a repository URI. +subversion__get_peg_revision() { + local repo_uri="${1}" + local peg_rev= + + debug-print "${FUNCNAME}: repo_uri = ${repo_uri}" + # repo_uri has peg revision? + if [[ ${repo_uri} = *@* ]]; then + peg_rev="${repo_uri##*@}" + debug-print "${FUNCNAME}: peg_rev = ${peg_rev}" + else + debug-print "${FUNCNAME}: repo_uri does not have a peg revision." + fi + + echo "${peg_rev}" +} diff --git a/eclass/sword-module.eclass b/eclass/sword-module.eclass new file mode 100644 index 0000000..2ae58d1 --- /dev/null +++ b/eclass/sword-module.eclass @@ -0,0 +1,95 @@ +# Copyright 1999-2020 Gentoo Authors +# Distributed under the terms of the GNU General Public License v2 + +# @ECLASS: sword-module.eclass +# @MAINTAINER: +# Marek Szuba <marecki@gentoo.org> +# @SUPPORTED_EAPIS: 7 +# @BLURB: Simplify installation of SWORD modules +# @DESCRIPTION: +# This eclass provides dependencies, ebuild environment and the src_install +# function common to all app-text/sword modules published by the SWORD Project. +# +# Note that as of 2020-07-26 module archives published by SWORD are still +# not versioned and it is necessary to look at respective module pages in +# order to see what versions the currently available files are. Once +# a module file has been replicated to the Gentoo mirror network it will be +# versioned and remain available even after upstream has changed their +# version, however users not using mirrors will encounter hash conflicts +# on updated modules. Should that happen, please notify the relevant +# package maintainers that a new version is available. +# +# @EXAMPLE: +# sword-Personal-1.0.ebuild, a typical ebuild using sword-module.eclass: +# +# @CODE +# EAPI=7 +# +# SWORD_MINIMUM_VERSION="1.5.1a" +# +# inherit sword-module +# +# DESCRIPTION="SWORD module for storing one's own commentary" +# HOMEPAGE="https://crosswire.org/sword/modules/ModInfo.jsp?modName=Personal" +# LICENSE="public-domain" +# KEYWORDS="~amd64 ~ppc ~x86" +# +# @CODE + +case ${EAPI:-0} in + 0|1|2|3|4|5|6) + die "Unsupported EAPI=${EAPI} (too old) for ${ECLASS}" + ;; + 7) + ;; + *) + die "Unsupported EAPI=${EAPI} (unknown) for ${ECLASS}" + ;; +esac + +# @ECLASS-VARIABLE: SWORD_MINIMUM_VERSION +# @DEFAULT_UNSET +# @PRE_INHERIT +# @DESCRIPTION: +# If set to a non-null value, specifies the minimum version of app-text/sword +# the module requires. This will be included in RDEPEND. If null or unset, +# the dependency will be unversioned. +# Needs to be set before the inherit line. + +# @ECLASS-VARIABLE: SWORD_MODULE +# @PRE_INHERIT +# @DESCRIPTION: +# Case-sensitive name of the SWORD-Project module to install. If unset +# or null, use the name produced by removing the prefix 'sword-' from PN. +# Needs to be set before the inherit line. +: ${SWORD_MODULE:=${PN#sword-}} + +EXPORT_FUNCTIONS src_install + +# Unless overridden at ebuild level, append version to the name of the file +# fetched from upstream and let the Gentoo mirror network take care of +# persisting the versioned archive. +SRC_URI="https://crosswire.org/ftpmirror/pub/sword/packages/rawzip/${SWORD_MODULE}.zip -> ${SWORD_MODULE}-${PV}.zip" + +SLOT="0" + +# Module archives contain no top-level directory. +S="${WORKDIR}" + +if [[ ${SWORD_MINIMUM_VERSION} ]]; then + RDEPEND=">=app-text/sword-${SWORD_MINIMUM_VERSION}" +else + RDEPEND="app-text/sword" +fi + +BDEPEND="app-arch/unzip" + +# @FUNCTION: sword-module_src_install +# @DESCRIPTION: +# Install all the module files into directories used by app-text/sword. +sword-module_src_install() { + insinto /usr/share/sword/modules + doins -r modules/* + insinto /usr/share/sword/mods.d + doins mods.d/* +} diff --git a/eclass/systemd.eclass b/eclass/systemd.eclass new file mode 100644 index 0000000..81065a0 --- /dev/null +++ b/eclass/systemd.eclass @@ -0,0 +1,481 @@ +# Copyright 1999-2020 Gentoo Authors +# Distributed under the terms of the GNU General Public License v2 + +# @ECLASS: systemd.eclass +# @MAINTAINER: +# systemd@gentoo.org +# @SUPPORTED_EAPIS: 0 1 2 3 4 5 6 7 +# @BLURB: helper functions to install systemd units +# @DESCRIPTION: +# This eclass provides a set of functions to install unit files for +# sys-apps/systemd within ebuilds. +# @EXAMPLE: +# +# @CODE +# inherit systemd +# +# src_configure() { +# local myconf=( +# --enable-foo +# --with-systemdsystemunitdir="$(systemd_get_systemunitdir)" +# ) +# +# econf "${myconf[@]}" +# } +# @CODE + +inherit toolchain-funcs + +case ${EAPI:-0} in + 0|1|2|3|4|5|6|7) ;; + *) die "${ECLASS}.eclass API in EAPI ${EAPI} not yet established." +esac + +if [[ ${EAPI:-0} == [0123456] ]]; then + DEPEND="virtual/pkgconfig" +else + BDEPEND="virtual/pkgconfig" +fi + +# @FUNCTION: _systemd_get_dir +# @USAGE: <variable-name> <fallback-directory> +# @INTERNAL +# @DESCRIPTION: +# Try to obtain the <variable-name> variable from systemd.pc. +# If pkg-config or systemd is not installed, return <fallback-directory> +# instead. +_systemd_get_dir() { + [[ ${#} -eq 2 ]] || die "Usage: ${FUNCNAME} <variable-name> <fallback-directory>" + local variable=${1} fallback=${2} d + + if $(tc-getPKG_CONFIG) --exists systemd; then + d=$($(tc-getPKG_CONFIG) --variable="${variable}" systemd) || die + d=${d#${EPREFIX}} + else + d=${fallback} + fi + + echo "${d}" +} + +# @FUNCTION: _systemd_get_unitdir +# @INTERNAL +# @DESCRIPTION: +# Get unprefixed unitdir. +_systemd_get_systemunitdir() { + _systemd_get_dir systemdsystemunitdir /lib/systemd/system +} + +# @FUNCTION: systemd_get_systemunitdir +# @DESCRIPTION: +# Output the path for the systemd system unit directory (not including +# ${D}). This function always succeeds, even if systemd is not +# installed. +systemd_get_systemunitdir() { + has "${EAPI:-0}" 0 1 2 && ! use prefix && EPREFIX= + debug-print-function ${FUNCNAME} "${@}" + + echo "${EPREFIX}$(_systemd_get_systemunitdir)" +} + +# @FUNCTION: systemd_get_unitdir +# @DESCRIPTION: +# Deprecated alias for systemd_get_systemunitdir. +systemd_get_unitdir() { + [[ ${EAPI} == [012345] ]] || die "${FUNCNAME} is banned in EAPI 6, use systemd_get_systemunitdir instead" + + systemd_get_systemunitdir +} + +# @FUNCTION: _systemd_get_userunitdir +# @INTERNAL +# @DESCRIPTION: +# Get unprefixed userunitdir. +_systemd_get_userunitdir() { + _systemd_get_dir systemduserunitdir /usr/lib/systemd/user +} + +# @FUNCTION: systemd_get_userunitdir +# @DESCRIPTION: +# Output the path for the systemd user unit directory (not including +# ${D}). This function always succeeds, even if systemd is not +# installed. +systemd_get_userunitdir() { + has "${EAPI:-0}" 0 1 2 && ! use prefix && EPREFIX= + debug-print-function ${FUNCNAME} "${@}" + + echo "${EPREFIX}$(_systemd_get_userunitdir)" +} + +# @FUNCTION: _systemd_get_utildir +# @INTERNAL +# @DESCRIPTION: +# Get unprefixed utildir. +_systemd_get_utildir() { + _systemd_get_dir systemdutildir /lib/systemd +} + +# @FUNCTION: systemd_get_utildir +# @DESCRIPTION: +# Output the path for the systemd utility directory (not including +# ${D}). This function always succeeds, even if systemd is not +# installed. +systemd_get_utildir() { + has "${EAPI:-0}" 0 1 2 && ! use prefix && EPREFIX= + debug-print-function ${FUNCNAME} "${@}" + + echo "${EPREFIX}$(_systemd_get_utildir)" +} + +# @FUNCTION: _systemd_get_systemgeneratordir +# @INTERNAL +# @DESCRIPTION: +# Get unprefixed systemgeneratordir. +_systemd_get_systemgeneratordir() { + _systemd_get_dir systemdsystemgeneratordir /lib/systemd/system-generators +} + +# @FUNCTION: systemd_get_systemgeneratordir +# @DESCRIPTION: +# Output the path for the systemd system generator directory (not including +# ${D}). This function always succeeds, even if systemd is not +# installed. +systemd_get_systemgeneratordir() { + has "${EAPI:-0}" 0 1 2 && ! use prefix && EPREFIX= + debug-print-function ${FUNCNAME} "${@}" + + echo "${EPREFIX}$(_systemd_get_systemgeneratordir)" +} + +# @FUNCTION: systemd_dounit +# @USAGE: <unit>... +# @DESCRIPTION: +# Install systemd unit(s). Uses doins, thus it is fatal in EAPI 4 +# and non-fatal in earlier EAPIs. +systemd_dounit() { + debug-print-function ${FUNCNAME} "${@}" + + ( + insopts -m 0644 + insinto "$(_systemd_get_systemunitdir)" + doins "${@}" + ) +} + +# @FUNCTION: systemd_newunit +# @USAGE: <old-name> <new-name> +# @DESCRIPTION: +# Install systemd unit with a new name. Uses newins, thus it is fatal +# in EAPI 4 and non-fatal in earlier EAPIs. +systemd_newunit() { + debug-print-function ${FUNCNAME} "${@}" + + ( + insopts -m 0644 + insinto "$(_systemd_get_systemunitdir)" + newins "${@}" + ) +} + +# @FUNCTION: systemd_douserunit +# @USAGE: <unit>... +# @DESCRIPTION: +# Install systemd user unit(s). Uses doins, thus it is fatal in EAPI 4 +# and non-fatal in earlier EAPIs. +systemd_douserunit() { + debug-print-function ${FUNCNAME} "${@}" + + ( + insopts -m 0644 + insinto "$(_systemd_get_userunitdir)" + doins "${@}" + ) +} + +# @FUNCTION: systemd_newuserunit +# @USAGE: <old-name> <new-name> +# @DESCRIPTION: +# Install systemd user unit with a new name. Uses newins, thus it +# is fatal in EAPI 4 and non-fatal in earlier EAPIs. +systemd_newuserunit() { + debug-print-function ${FUNCNAME} "${@}" + + ( + insopts -m 0644 + insinto "$(_systemd_get_userunitdir)" + newins "${@}" + ) +} + +# @FUNCTION: systemd_install_serviced +# @USAGE: <conf-file> [<service>] +# @DESCRIPTION: +# Install <conf-file> as the template <service>.d/00gentoo.conf. +# If <service> is not specified +# <conf-file> with the .conf suffix stripped is used +# (e.g. foo.service.conf -> foo.service.d/00gentoo.conf). +systemd_install_serviced() { + debug-print-function ${FUNCNAME} "${@}" + + local src=${1} + local service=${2} + + [[ ${src} ]] || die "No file specified" + + if [[ ! ${service} ]]; then + [[ ${src} == *.conf ]] || die "Source file needs .conf suffix" + service=${src##*/} + service=${service%.conf} + fi + # avoid potentially common mistake + [[ ${service} == *.d ]] && die "Service must not have .d suffix" + + ( + insopts -m 0644 + insinto /etc/systemd/system/"${service}".d + newins "${src}" 00gentoo.conf + ) +} + +# @FUNCTION: systemd_dotmpfilesd +# @USAGE: <tmpfilesd>... +# @DESCRIPTION: +# Deprecated in favor of tmpfiles.eclass. +# +# Install systemd tmpfiles.d files. Uses doins, thus it is fatal +# in EAPI 4 and non-fatal in earlier EAPIs. +systemd_dotmpfilesd() { + debug-print-function ${FUNCNAME} "${@}" + + for f; do + [[ ${f} == *.conf ]] \ + || die 'tmpfiles.d files need to have .conf suffix.' + done + + ( + insopts -m 0644 + insinto /usr/lib/tmpfiles.d/ + doins "${@}" + ) +} + +# @FUNCTION: systemd_newtmpfilesd +# @USAGE: <old-name> <new-name>.conf +# @DESCRIPTION: +# Deprecated in favor of tmpfiles.eclass. +# +# Install systemd tmpfiles.d file under a new name. Uses newins, thus it +# is fatal in EAPI 4 and non-fatal in earlier EAPIs. +systemd_newtmpfilesd() { + debug-print-function ${FUNCNAME} "${@}" + + [[ ${2} == *.conf ]] \ + || die 'tmpfiles.d files need to have .conf suffix.' + + ( + insopts -m 0644 + insinto /usr/lib/tmpfiles.d/ + newins "${@}" + ) +} + +# @FUNCTION: systemd_enable_service +# @USAGE: <target> <service> +# @DESCRIPTION: +# Enable service in desired target, e.g. install a symlink for it. +# Uses dosym, thus it is fatal in EAPI 4 and non-fatal in earlier +# EAPIs. +systemd_enable_service() { + debug-print-function ${FUNCNAME} "${@}" + + [[ ${#} -eq 2 ]] || die "Synopsis: systemd_enable_service target service" + + local target=${1} + local service=${2} + local ud=$(_systemd_get_systemunitdir) + local destname=${service##*/} + + dodir "${ud}"/"${target}".wants && \ + dosym ../"${service}" "${ud}"/"${target}".wants/"${destname}" +} + +# @FUNCTION: systemd_enable_ntpunit +# @USAGE: <NN-name> <service>... +# @DESCRIPTION: +# Add an NTP service provider to the list of implementations +# in timedated. <NN-name> defines the newly-created ntp-units.d priority +# and name, while the remaining arguments list service units that will +# be added to that file. +# +# Uses doins, thus it is fatal in EAPI 4 and non-fatal in earlier +# EAPIs. +# +# Doc: https://www.freedesktop.org/wiki/Software/systemd/timedated/ +systemd_enable_ntpunit() { + debug-print-function ${FUNCNAME} "${@}" + if [[ ${#} -lt 2 ]]; then + die "Usage: systemd_enable_ntpunit <NN-name> <service>..." + fi + + local ntpunit_name=${1} + local services=( "${@:2}" ) + + if [[ ${ntpunit_name} != [0-9][0-9]-* ]]; then + die "ntpunit.d file must be named NN-name where NN are digits." + elif [[ ${ntpunit_name} == *.list ]]; then + die "The .list suffix is appended implicitly to ntpunit.d name." + fi + + local unitdir=$(systemd_get_systemunitdir) + local s + for s in "${services[@]}"; do + if [[ ! -f "${D}${unitdir}/${s}" ]]; then + die "ntp-units.d provider ${s} not installed (yet?) in \${D}." + fi + echo "${s}" >> "${T}"/${ntpunit_name}.list || die + done + + ( + insopts -m 0644 + insinto "$(_systemd_get_utildir)"/ntp-units.d + doins "${T}"/${ntpunit_name}.list + ) + local ret=${?} + + rm "${T}"/${ntpunit_name}.list || die + + return ${ret} +} + +# @FUNCTION: systemd_with_unitdir +# @USAGE: [<configure-option-name>] +# @DESCRIPTION: +# Note: deprecated and banned in EAPI 6. Please use full --with-...= +# parameter for improved ebuild readability. +# +# Output '--with-systemdsystemunitdir' as expected by systemd-aware configure +# scripts. This function always succeeds. Its output may be quoted in order +# to preserve whitespace in paths. systemd_to_myeconfargs() is preferred over +# this function. +# +# If upstream does use invalid configure option to handle installing systemd +# units (e.g. `--with-systemdunitdir'), you can pass the 'suffix' as an optional +# argument to this function (`$(systemd_with_unitdir systemdunitdir)'). Please +# remember to report a bug upstream as well. +systemd_with_unitdir() { + [[ ${EAPI:-0} != [012345] ]] && die "${FUNCNAME} is banned in EAPI ${EAPI}, use --with-${1:-systemdsystemunitdir}=\"\$(systemd_get_systemunitdir)\" instead" + + debug-print-function ${FUNCNAME} "${@}" + local optname=${1:-systemdsystemunitdir} + + echo --with-${optname}="$(systemd_get_systemunitdir)" +} + +# @FUNCTION: systemd_with_utildir +# @DESCRIPTION: +# Note: deprecated and banned in EAPI 6. Please use full --with-...= +# parameter for improved ebuild readability. +# +# Output '--with-systemdsystemutildir' as used by some packages to install +# systemd helpers. This function always succeeds. Its output may be quoted +# in order to preserve whitespace in paths. +systemd_with_utildir() { + [[ ${EAPI:-0} != [012345] ]] && die "${FUNCNAME} is banned in EAPI ${EAPI}, use --with-systemdutildir=\"\$(systemd_get_utildir)\" instead" + + debug-print-function ${FUNCNAME} "${@}" + + echo --with-systemdutildir="$(systemd_get_utildir)" +} + +# @FUNCTION: systemd_update_catalog +# @DESCRIPTION: +# Update the journald catalog. This needs to be called after installing +# or removing catalog files. This must be called in pkg_post* phases. +# +# If systemd is not installed, no operation will be done. The catalog +# will be (re)built once systemd is installed. +# +# See: https://www.freedesktop.org/wiki/Software/systemd/catalog +systemd_update_catalog() { + debug-print-function ${FUNCNAME} "${@}" + + [[ ${EBUILD_PHASE} == post* ]] \ + || die "${FUNCNAME} disallowed during ${EBUILD_PHASE_FUNC:-${EBUILD_PHASE}}" + + # Make sure to work on the correct system. + + local journalctl=${EPREFIX}/usr/bin/journalctl + if [[ -x ${journalctl} ]]; then + ebegin "Updating systemd journal catalogs" + journalctl --update-catalog + eend $? + else + debug-print "${FUNCNAME}: journalctl not found." + fi +} + +# @FUNCTION: systemd_is_booted +# @DESCRIPTION: +# Check whether the system was booted using systemd. +# +# This should be used purely for informational purposes, e.g. warning +# user that he needs to use systemd. Installed files or application +# behavior *must not* rely on this. Please remember to check MERGE_TYPE +# to not trigger the check on binary package build hosts! +# +# Returns 0 if systemd is used to boot the system, 1 otherwise. +# +# See: man sd_booted +systemd_is_booted() { + debug-print-function ${FUNCNAME} "${@}" + + [[ -d /run/systemd/system ]] + local ret=${?} + + debug-print "${FUNCNAME}: [[ -d /run/systemd/system ]] -> ${ret}" + return ${ret} +} + +# @FUNCTION: systemd_tmpfiles_create +# @USAGE: <tmpfilesd> ... +# @DESCRIPTION: +# Deprecated in favor of tmpfiles.eclass. +# +# Invokes systemd-tmpfiles --create with given arguments. +# Does nothing if ROOT != / or systemd-tmpfiles is not in PATH. +# This function should be called from pkg_postinst. +# +# Generally, this function should be called with the names of any tmpfiles +# fragments which have been installed, either by the build system or by a +# previous call to systemd_dotmpfilesd. This ensures that any tmpfiles are +# created without the need to reboot the system. +systemd_tmpfiles_create() { + debug-print-function ${FUNCNAME} "${@}" + + [[ ${EBUILD_PHASE} == postinst ]] || die "${FUNCNAME}: Only valid in pkg_postinst" + [[ ${#} -gt 0 ]] || die "${FUNCNAME}: Must specify at least one filename" + [[ ${ROOT:-/} == / ]] || return 0 + type systemd-tmpfiles &> /dev/null || return 0 + systemd-tmpfiles --create "${@}" +} + +# @FUNCTION: systemd_reenable +# @USAGE: <unit> ... +# @DESCRIPTION: +# Re-enables units if they are currently enabled. This resets symlinks to the +# defaults specified in the [Install] section. +# +# This function is intended to fix broken symlinks that result from moving +# the systemd system unit directory. It should be called from pkg_postinst +# for system units that define the 'Alias' option in their [Install] section. +# It is not necessary to call this function to fix dependency symlinks +# generated by the 'WantedBy' and 'RequiredBy' options. +systemd_reenable() { + type systemctl &>/dev/null || return 0 + local x + for x; do + if systemctl --quiet --root="${ROOT:-/}" is-enabled "${x}"; then + systemctl --root="${ROOT:-/}" reenable "${x}" + fi + done +} diff --git a/eclass/tests/autotools_eaclocal_amflags.sh b/eclass/tests/autotools_eaclocal_amflags.sh new file mode 100755 index 0000000..b39f542 --- /dev/null +++ b/eclass/tests/autotools_eaclocal_amflags.sh @@ -0,0 +1,31 @@ +#!/bin/bash +# Copyright 1999-2015 Gentoo Foundation +# Distributed under the terms of the GNU General Public License v2 + +source tests-common.sh + +inherit autotools + +test-it() { + tbegin "eaclocal_amflags $1: $2" + printf "ACLOCAL_AMFLAGS = %b\n" "$2" > Makefile.am + local flags=$(eaclocal_amflags) exp=${3:-$2} + [[ "${flags}" == "${exp}" ]] + if ! tend $? ; then + printf '### INPUT:\n%s\n' "$2" + printf '### FILE:\n%s\n' "$(<Makefile.am)" + printf '### EXPECTED:\n%s\n' "${exp}" + printf '### ACTUAL:\n%s\n' "${flags}" + fi + rm Makefile.am +} + +test-it simple "-Im4" +test-it simple "-I m4 -I lakdjfladsfj /////" + +test-it shell-exec '`echo hi`' "hi" +test-it shell-exec '`echo {0..3}`' "0 1 2 3" + +test-it multiline '-I oneline \\\n\t-I twoline' "-I oneline -I twoline" + +texit diff --git a/eclass/tests/distutils-r1.sh b/eclass/tests/distutils-r1.sh new file mode 100755 index 0000000..93496f9 --- /dev/null +++ b/eclass/tests/distutils-r1.sh @@ -0,0 +1,142 @@ +#!/bin/bash +# Copyright 1999-2020 Gentoo Authors +# Distributed under the terms of the GNU General Public License v2 + +EAPI=7 +PYTHON_COMPAT=( python3_8 ) +source tests-common.sh + +test-phase_name_free() { + local ph=${1} + + if declare -f "${ph}"; then + die "${ph} function declared while name reserved for phase!" + fi + if declare -f "${ph}_all"; then + die "${ph}_all function declared while name reserved for phase!" + fi +} + +test-distutils_enable_tests() { + local runner=${1} + local exp_IUSE=${2} + local exp_RESTRICT=${3} + local exp_BDEPEND=${4} + + local IUSE=${IUSE} + local RESTRICT=${RESTRICT} + local BDEPEND=${BDEPEND} + + tbegin "${runner}" + + distutils_enable_tests "${runner}" + + local ret var val + for var in IUSE RESTRICT BDEPEND; do + local exp_var=exp_${var} + # (this normalizes whitespace) + read -d $'\0' -r -a val <<<"${!var}" + val=${val[*]} + if [[ ${val} != "${!exp_var}" ]]; then + eindent + eerror "${var} expected: ${!exp_var}" + eerror "${var} actual: ${val}" + eoutdent + ret=1 + tret=1 + fi + done + + tend ${ret} +} + +test-DISTUTILS_USE_SETUPTOOLS() { + local DISTUTILS_USE_SETUPTOOLS=${1} + local exp_BDEPEND=${2} + local exp_RDEPEND=${3} + + tbegin "${1}" + + local BDEPEND= + local RDEPEND= + unset _DISTUTILS_R1 + inherit distutils-r1 + + local ret var val + for var in BDEPEND RDEPEND; do + local exp_var=exp_${var} + # (this normalizes whitespace) + read -d $'\0' -r -a val <<<"${!var}" + val=${val[*]} + if [[ ${val} != "${!exp_var}" ]]; then + eindent + eerror "${var} expected: ${!exp_var}" + eerror "${var} actual: ${val}" + eoutdent + ret=1 + tret=1 + fi + done + + tend ${ret} +} + +DISTUTILS_USE_SETUPTOOLS=no +inherit distutils-r1 + +tbegin "sane function names" + +test-phase_name_free python_prepare +test-phase_name_free python_configure +test-phase_name_free python_compile +test-phase_name_free python_test +test-phase_name_free python_install + +tend + +einfo distutils_enable_tests +eindent +BASE_IUSE="python_targets_python3_8" +BASE_DEPS="python_targets_python3_8? ( dev-lang/python:3.8 ) >=dev-lang/python-exec-2:=[python_targets_python3_8(-)?,-python_single_target_python3_8(-)]" +TEST_RESTRICT="!test? ( test )" + +einfo "empty RDEPEND" +eindent +RDEPEND="" +test-distutils_enable_tests pytest \ + "${BASE_IUSE} test" "${TEST_RESTRICT}" "${BASE_DEPS} test? ( >=dev-python/pytest-4.5.0[${PYTHON_USEDEP}] )" +test-distutils_enable_tests nose \ + "${BASE_IUSE} test" "${TEST_RESTRICT}" "${BASE_DEPS} test? ( >=dev-python/nose-1.3.7-r4[${PYTHON_USEDEP}] )" +test-distutils_enable_tests unittest \ + "${BASE_IUSE}" "" "${BASE_DEPS}" +test-distutils_enable_tests setup.py \ + "${BASE_IUSE}" "" "${BASE_DEPS}" +eoutdent + +einfo "non-empty RDEPEND" +eindent +BASE_RDEPEND="dev-python/foo[${PYTHON_USEDEP}]" +RDEPEND=${BASE_RDEPEND} +test-distutils_enable_tests pytest \ + "${BASE_IUSE} test" "${TEST_RESTRICT}" "${BASE_DEPS} test? ( ${BASE_RDEPEND} >=dev-python/pytest-4.5.0[${PYTHON_USEDEP}] )" +test-distutils_enable_tests nose \ + "${BASE_IUSE} test" "${TEST_RESTRICT}" "${BASE_DEPS} test? ( ${BASE_RDEPEND} >=dev-python/nose-1.3.7-r4[${PYTHON_USEDEP}] )" +test-distutils_enable_tests unittest \ + "${BASE_IUSE} test" "${TEST_RESTRICT}" "${BASE_DEPS} test? ( ${BASE_RDEPEND} )" +test-distutils_enable_tests setup.py \ + "${BASE_IUSE} test" "${TEST_RESTRICT}" "${BASE_DEPS} test? ( ${BASE_RDEPEND} )" +eoutdent + +eoutdent + +einfo DISTUTILS_USE_SETUPTOOLS +eindent +SETUPTOOLS_DEP=">=dev-python/setuptools-42.0.2[python_targets_python3_8(-)?,-python_single_target_python3_8(-)]" +test-DISTUTILS_USE_SETUPTOOLS no "${BASE_DEPS}" "${BASE_DEPS}" +test-DISTUTILS_USE_SETUPTOOLS bdepend "${BASE_DEPS} ${SETUPTOOLS_DEP}" "${BASE_DEPS}" +test-DISTUTILS_USE_SETUPTOOLS rdepend "${BASE_DEPS} ${SETUPTOOLS_DEP}" "${BASE_DEPS} ${SETUPTOOLS_DEP}" +test-DISTUTILS_USE_SETUPTOOLS pyproject.toml "${BASE_DEPS} dev-python/pyproject2setuppy[python_targets_python3_8(-)?,-python_single_target_python3_8(-)]" "${BASE_DEPS}" +test-DISTUTILS_USE_SETUPTOOLS manual "${BASE_DEPS}" "${BASE_DEPS}" +eoutdent + +texit diff --git a/eclass/tests/distutils-r1_single.sh b/eclass/tests/distutils-r1_single.sh new file mode 100755 index 0000000..80c152b --- /dev/null +++ b/eclass/tests/distutils-r1_single.sh @@ -0,0 +1,122 @@ +#!/bin/bash +# Copyright 1999-2020 Gentoo Authors +# Distributed under the terms of the GNU General Public License v2 + +EAPI=7 +PYTHON_COMPAT=( python3_8 ) +source tests-common.sh + +test-distutils_enable_tests() { + local runner=${1} + local exp_IUSE=${2} + local exp_RESTRICT=${3} + local exp_BDEPEND=${4} + + local IUSE=${IUSE} + local RESTRICT=${RESTRICT} + local BDEPEND=${BDEPEND} + + tbegin "${runner}" + + distutils_enable_tests "${runner}" + + local ret var + for var in IUSE RESTRICT BDEPEND; do + local exp_var=exp_${var} + # (this normalizes whitespace) + read -d $'\0' -r -a val <<<"${!var}" + val=${val[*]} + if [[ ${val} != "${!exp_var}" ]]; then + eindent + eerror "${var} expected: ${!exp_var}" + eerror "${var} actual: ${val}" + eoutdent + ret=1 + tret=1 + fi + done + + tend ${ret} +} + +test-DISTUTILS_USE_SETUPTOOLS() { + local DISTUTILS_USE_SETUPTOOLS=${1} + local exp_BDEPEND=${2} + local exp_RDEPEND=${3} + + tbegin "${1}" + + local BDEPEND= + local RDEPEND= + unset _DISTUTILS_R1 + inherit distutils-r1 + + local ret var val + for var in BDEPEND RDEPEND; do + local exp_var=exp_${var} + # (this normalizes whitespace) + read -d $'\0' -r -a val <<<"${!var}" + val=${val[*]} + if [[ ${val} != "${!exp_var}" ]]; then + eindent + eerror "${var} expected: ${!exp_var}" + eerror "${var} actual: ${val}" + eoutdent + ret=1 + tret=1 + fi + done + + tend ${ret} +} + +DISTUTILS_USE_SETUPTOOLS=no +DISTUTILS_SINGLE_IMPL=1 +inherit distutils-r1 + +einfo distutils_enable_tests +eindent +BASE_IUSE="+python_single_target_python3_8" +BASE_DEPS="python_single_target_python3_8? ( dev-lang/python:3.8 >=dev-lang/python-exec-2:=[python_targets_python3_8] )" +TEST_RESTRICT="!test? ( test )" + +einfo "empty RDEPEND" +eindent +RDEPEND="" +test-distutils_enable_tests pytest \ + "${BASE_IUSE} test" "${TEST_RESTRICT}" "${BASE_DEPS} test? ( python_single_target_python3_8? ( >=dev-python/pytest-4.5.0[python_targets_python3_8(-)] ) )" +test-distutils_enable_tests nose \ + "${BASE_IUSE} test" "${TEST_RESTRICT}" "${BASE_DEPS} test? ( python_single_target_python3_8? ( >=dev-python/nose-1.3.7-r4[python_targets_python3_8(-)] ) )" +test-distutils_enable_tests unittest \ + "${BASE_IUSE}" "" "${BASE_DEPS}" +test-distutils_enable_tests setup.py \ + "${BASE_IUSE}" "" "${BASE_DEPS}" +eoutdent + +einfo "non-empty RDEPEND" +eindent +BASE_RDEPEND="dev-python/foo[${PYTHON_SINGLE_USEDEP}]" +RDEPEND=${BASE_RDEPEND} +test-distutils_enable_tests pytest \ + "${BASE_IUSE} test" "${TEST_RESTRICT}" "${BASE_DEPS} test? ( ${BASE_RDEPEND} python_single_target_python3_8? ( >=dev-python/pytest-4.5.0[python_targets_python3_8(-)] ) )" +test-distutils_enable_tests nose \ + "${BASE_IUSE} test" "${TEST_RESTRICT}" "${BASE_DEPS} test? ( ${BASE_RDEPEND} python_single_target_python3_8? ( >=dev-python/nose-1.3.7-r4[python_targets_python3_8(-)] ) )" +test-distutils_enable_tests unittest \ + "${BASE_IUSE} test" "${TEST_RESTRICT}" "${BASE_DEPS} test? ( ${BASE_RDEPEND} )" +test-distutils_enable_tests setup.py \ + "${BASE_IUSE} test" "${TEST_RESTRICT}" "${BASE_DEPS} test? ( ${BASE_RDEPEND} )" +eoutdent + +eoutdent + +einfo DISTUTILS_USE_SETUPTOOLS +eindent +SETUPTOOLS_DEP="python_single_target_python3_8? ( >=dev-python/setuptools-42.0.2[python_targets_python3_8(-)] )" +test-DISTUTILS_USE_SETUPTOOLS no "${BASE_DEPS}" "${BASE_DEPS}" +test-DISTUTILS_USE_SETUPTOOLS bdepend "${BASE_DEPS} ${SETUPTOOLS_DEP}" "${BASE_DEPS}" +test-DISTUTILS_USE_SETUPTOOLS rdepend "${BASE_DEPS} ${SETUPTOOLS_DEP}" "${BASE_DEPS} ${SETUPTOOLS_DEP}" +test-DISTUTILS_USE_SETUPTOOLS pyproject.toml "${BASE_DEPS} python_single_target_python3_8? ( dev-python/pyproject2setuppy[python_targets_python3_8(-)] )" "${BASE_DEPS}" +test-DISTUTILS_USE_SETUPTOOLS manual "${BASE_DEPS}" "${BASE_DEPS}" +eoutdent + +texit diff --git a/eclass/tests/eapi7-ver.sh b/eclass/tests/eapi7-ver.sh new file mode 100755 index 0000000..d4aa4fd --- /dev/null +++ b/eclass/tests/eapi7-ver.sh @@ -0,0 +1,177 @@ +#!/bin/bash +# Copyright 1999-2017 Gentoo Foundation +# Distributed under the terms of the GNU General Public License v2 + +EAPI=6 + +source tests-common.sh + +inherit eapi7-ver + +teq() { + local expected=${1}; shift + + tbegin "${*} -> ${expected}" + local got=$("${@}") + [[ ${got} == ${expected} ]] + tend ${?} "returned: ${got}" +} + +teqr() { + local expected=$1; shift + tbegin "$* -> ${expected}" + "$@" + local ret=$? + [[ ${ret} -eq ${expected} ]] + tend $? "returned: ${ret}" +} + +txf() { + tbegin "XFAIL: ${*}" + local got=$("${@}" 2>&1) + [[ ${got} == die:* ]] + tend ${?} "function did not die" +} + +teq 1 ver_cut 1 1.2.3 +teq 1 ver_cut 1-1 1.2.3 +teq 1.2 ver_cut 1-2 1.2.3 +teq 2.3 ver_cut 2- 1.2.3 +teq 1.2.3 ver_cut 1- 1.2.3 +teq 3b ver_cut 3-4 1.2.3b_alpha4 +teq alpha ver_cut 5 1.2.3b_alpha4 +teq 1.2 ver_cut 1-2 .1.2.3 +teq .1.2 ver_cut 0-2 .1.2.3 +teq 2.3 ver_cut 2-3 1.2.3. +teq 2.3. ver_cut 2- 1.2.3. +teq 2.3. ver_cut 2-4 1.2.3. + +teq 1-2.3 ver_rs 1 - 1.2.3 +teq 1.2-3 ver_rs 2 - 1.2.3 +teq 1-2-3.4 ver_rs 1-2 - 1.2.3.4 +teq 1.2-3-4 ver_rs 2- - 1.2.3.4 +teq 1.2.3 ver_rs 2 . 1.2-3 +teq 1.2.3.a ver_rs 3 . 1.2.3a +teq 1.2-alpha-4 ver_rs 2-3 - 1.2_alpha4 +teq 1.23-b_alpha4 ver_rs 3 - 2 "" 1.2.3b_alpha4 +teq a1b_2-c-3-d4e5 ver_rs 3-5 _ 4-6 - a1b2c3d4e5 +teq .1-2.3 ver_rs 1 - .1.2.3 +teq -1.2.3 ver_rs 0 - .1.2.3 + +# truncating range +teq 1.2 ver_cut 0-2 1.2.3 +teq 2.3 ver_cut 2-5 1.2.3 +teq "" ver_cut 4 1.2.3 +teq "" ver_cut 0 1.2.3 +teq "" ver_cut 4- 1.2.3 +teq 1.2.3 ver_rs 0 - 1.2.3 +teq 1.2.3 ver_rs 3 . 1.2.3 +teq 1.2.3 ver_rs 3- . 1.2.3 +teq 1.2.3 ver_rs 3-5 . 1.2.3 + +txf ver_cut foo 1.2.3 +txf ver_rs -3 _ a1b2c3d4e5 +txf ver_rs 5-3 _ a1b2c3d4e5 + +# Tests from Portage's test_vercmp.py +teqr 0 ver_test 6.0 -gt 5.0 +teqr 0 ver_test 5.0 -gt 5 +teqr 0 ver_test 1.0-r1 -gt 1.0-r0 +teqr 0 ver_test 999999999999999999 -gt 999999999999999998 # 18 digits +teqr 0 ver_test 1.0.0 -gt 1.0 +teqr 0 ver_test 1.0.0 -gt 1.0b +teqr 0 ver_test 1b -gt 1 +teqr 0 ver_test 1b_p1 -gt 1_p1 +teqr 0 ver_test 1.1b -gt 1.1 +teqr 0 ver_test 12.2.5 -gt 12.2b +teqr 0 ver_test 4.0 -lt 5.0 +teqr 0 ver_test 5 -lt 5.0 +teqr 0 ver_test 1.0_pre2 -lt 1.0_p2 +teqr 0 ver_test 1.0_alpha2 -lt 1.0_p2 +teqr 0 ver_test 1.0_alpha1 -lt 1.0_beta1 +teqr 0 ver_test 1.0_beta3 -lt 1.0_rc3 +teqr 0 ver_test 1.001000000000000001 -lt 1.001000000000000002 +teqr 0 ver_test 1.00100000000 -lt 1.001000000000000001 +teqr 0 ver_test 999999999999999998 -lt 999999999999999999 +teqr 0 ver_test 1.01 -lt 1.1 +teqr 0 ver_test 1.0-r0 -lt 1.0-r1 +teqr 0 ver_test 1.0 -lt 1.0-r1 +teqr 0 ver_test 1.0 -lt 1.0.0 +teqr 0 ver_test 1.0b -lt 1.0.0 +teqr 0 ver_test 1_p1 -lt 1b_p1 +teqr 0 ver_test 1 -lt 1b +teqr 0 ver_test 1.1 -lt 1.1b +teqr 0 ver_test 12.2b -lt 12.2.5 +teqr 0 ver_test 4.0 -eq 4.0 +teqr 0 ver_test 1.0 -eq 1.0 +teqr 0 ver_test 1.0-r0 -eq 1.0 +teqr 0 ver_test 1.0 -eq 1.0-r0 +teqr 0 ver_test 1.0-r0 -eq 1.0-r0 +teqr 0 ver_test 1.0-r1 -eq 1.0-r1 +teqr 1 ver_test 1 -eq 2 +teqr 1 ver_test 1.0_alpha -eq 1.0_pre +teqr 1 ver_test 1.0_beta -eq 1.0_alpha +teqr 1 ver_test 1 -eq 0.0 +teqr 1 ver_test 1.0-r0 -eq 1.0-r1 +teqr 1 ver_test 1.0-r1 -eq 1.0-r0 +teqr 1 ver_test 1.0 -eq 1.0-r1 +teqr 1 ver_test 1.0-r1 -eq 1.0 +teqr 1 ver_test 1.0 -eq 1.0.0 +teqr 1 ver_test 1_p1 -eq 1b_p1 +teqr 1 ver_test 1b -eq 1 +teqr 1 ver_test 1.1b -eq 1.1 +teqr 1 ver_test 12.2b -eq 12.2 + +# A subset of tests from Paludis +teqr 0 ver_test 1.0_alpha -gt 1_alpha +teqr 0 ver_test 1.0_alpha -gt 1 +teqr 0 ver_test 1.0_alpha -lt 1.0 +teqr 0 ver_test 1.2.0.0_alpha7-r4 -gt 1.2_alpha7-r4 +teqr 0 ver_test 0001 -eq 1 +teqr 0 ver_test 01 -eq 001 +teqr 0 ver_test 0001.1 -eq 1.1 +teqr 0 ver_test 01.01 -eq 1.01 +teqr 0 ver_test 1.010 -eq 1.01 +teqr 0 ver_test 1.00 -eq 1.0 +teqr 0 ver_test 1.0100 -eq 1.010 +teqr 0 ver_test 1-r00 -eq 1-r0 + +# Additional tests +teqr 0 ver_test 0_rc99 -lt 0 +teqr 0 ver_test 011 -eq 11 +teqr 0 ver_test 019 -eq 19 +teqr 0 ver_test 1.2 -eq 001.2 +teqr 0 ver_test 1.2 -gt 1.02 +teqr 0 ver_test 1.2a -lt 1.2b +teqr 0 ver_test 1.2_pre1 -gt 1.2_pre1_beta2 +teqr 0 ver_test 1.2_pre1 -lt 1.2_pre1_p2 +teqr 0 ver_test 1.00 -lt 1.0.0 +teqr 0 ver_test 1.010 -eq 1.01 +teqr 0 ver_test 1.01 -lt 1.1 +teqr 0 ver_test 1.2_pre08-r09 -eq 1.2_pre8-r9 +teqr 0 ver_test 0 -lt 576460752303423488 # 2**59 +teqr 0 ver_test 0 -lt 9223372036854775808 # 2**63 + +# Bad number or ordering of arguments +txf ver_test 1 +txf ver_test 1 -lt 2 3 +txf ver_test -lt 1 2 + +# Bad operators +txf ver_test 1 "<" 2 +txf ver_test 1 lt 2 +txf ver_test 1 -foo 2 + +# Malformed versions +txf ver_test "" -ne 1 +txf ver_test 1. -ne 1 +txf ver_test 1ab -ne 1 +txf ver_test b -ne 1 +txf ver_test 1-r1_pre -ne 1 +txf ver_test 1-pre1 -ne 1 +txf ver_test 1_foo -ne 1 +txf ver_test 1_pre1.1 -ne 1 +txf ver_test 1-r1.0 -ne 1 +txf ver_test cvs.9999 -ne 9999 + +texit diff --git a/eclass/tests/eapi7-ver_benchmark.sh b/eclass/tests/eapi7-ver_benchmark.sh new file mode 100755 index 0000000..c467137 --- /dev/null +++ b/eclass/tests/eapi7-ver_benchmark.sh @@ -0,0 +1,147 @@ +#!/bin/bash +# Copyright 1999-2017 Gentoo Foundation +# Distributed under the terms of the GNU General Public License v2 + +EAPI=6 + +source tests-common.sh + +inherit eapi7-ver versionator + +cutting() { + local x + for x in {1..1000}; do + ver_cut 1 1.2.3 + ver_cut 1-2 1.2.3 + ver_cut 2- 1.2.3 + ver_cut 1- 1.2.3 + ver_cut 3-4 1.2.3b_alpha4 + ver_cut 5 1.2.3b_alpha4 + ver_cut 1-2 .1.2.3 + ver_cut 0-2 .1.2.3 + ver_cut 2-3 1.2.3. + ver_cut 2- 1.2.3. + ver_cut 2-4 1.2.3. + done >/dev/null +} + +cutting_versionator() { + local x + for x in {1..100}; do + get_version_component_range 1 1.2.3 + get_version_component_range 1-2 1.2.3 + get_version_component_range 2- 1.2.3 + get_version_component_range 1- 1.2.3 + get_version_component_range 3-4 1.2.3b_alpha4 + get_version_component_range 5 1.2.3b_alpha4 + get_version_component_range 1-2 .1.2.3 + get_version_component_range 0-2 .1.2.3 + get_version_component_range 2-3 1.2.3. + get_version_component_range 2- 1.2.3. + get_version_component_range 2-4 1.2.3. + done >/dev/null +} + +replacing() { + local x + for x in {1..1000}; do + ver_rs 1 - 1.2.3 + ver_rs 2 - 1.2.3 + ver_rs 1-2 - 1.2.3.4 + ver_rs 2- - 1.2.3.4 + ver_rs 2 . 1.2-3 + ver_rs 3 . 1.2.3a + ver_rs 2-3 - 1.2_alpha4 + #ver_rs 3 - 2 "" 1.2.3b_alpha4 + #ver_rs 3-5 _ 4-6 - a1b2c3d4e5 + ver_rs 1 - .1.2.3 + ver_rs 0 - .1.2.3 + done >/dev/null +} + +replacing_versionator() { + local x + for x in {1..100}; do + replace_version_separator 1 - 1.2.3 + replace_version_separator 2 - 1.2.3 + replace_version_separator 1-2 - 1.2.3.4 + replace_version_separator 2- - 1.2.3.4 + replace_version_separator 2 . 1.2-3 + replace_version_separator 3 . 1.2.3a + replace_version_separator 2-3 - 1.2_alpha4 + #replace_version_separator 3 - 2 "" 1.2.3b_alpha4 + #replace_version_separator 3-5 _ 4-6 - a1b2c3d4e5 + replace_version_separator 1 - .1.2.3 + replace_version_separator 0 - .1.2.3 + done >/dev/null +} + +comparing() { + local x + for x in {1..1000}; do + ver_test 1b_p1 -le 1_p1 + ver_test 1.1b -le 1.1 + ver_test 12.2.5 -le 12.2b + ver_test 4.0 -le 5.0 + ver_test 5 -le 5.0 + ver_test 1.0_pre2 -le 1.0_p2 + ver_test 1.0_alpha2 -le 1.0_p2 + ver_test 1.0_alpha1 -le 1.0_beta1 + ver_test 1.0_beta3 -le 1.0_rc3 + ver_test 1.001000000000000001 -le 1.001000000000000002 + done +} + +comparing_versionator() { + local x + for x in {1..100}; do + version_is_at_least 1b_p1 1_p1 + version_is_at_least 1.1b 1.1 + version_is_at_least 12.2.5 12.2b + version_is_at_least 4.0 5.0 + version_is_at_least 5 5.0 + version_is_at_least 1.0_pre2 1.0_p2 + version_is_at_least 1.0_alpha2 1.0_p2 + version_is_at_least 1.0_alpha1 1.0_beta1 + version_is_at_least 1.0_beta3 1.0_rc3 + version_is_at_least 1.001000000000000001 1.001000000000000002 + done +} + +get_times() { + local factor=${1}; shift + echo "${*}" + local real=() + local user=() + + for x in {1..5}; do + while read tt tv; do + case ${tt} in + real) real+=( $(dc -e "${tv} ${factor} * p") );; + user) user+=( $(dc -e "${tv} ${factor} * p") );; + esac + done < <( ( time -p "${@}" ) 2>&1 ) + done + + [[ ${#real[@]} == 5 ]] || die "Did not get 5 real times" + [[ ${#user[@]} == 5 ]] || die "Did not get 5 user times" + + local sum + for v in real user; do + vr="${v}[*]" + sum=$(dc -e "${!vr} + + + + 3 k 5 / p") + + vr="${v}[@]" + printf '%s %4.2f %4.2f %4.2f %4.2f %4.2f => %4.2f avg\n' \ + "${v}" "${!vr}" "${sum}" + done +} + +export LC_ALL=C + +get_times 1 cutting +get_times 10 cutting_versionator +get_times 1 replacing +get_times 10 replacing_versionator +get_times 1 comparing +get_times 10 comparing_versionator diff --git a/eclass/tests/eapi8-dosym.sh b/eclass/tests/eapi8-dosym.sh new file mode 100755 index 0000000..e1160c4 --- /dev/null +++ b/eclass/tests/eapi8-dosym.sh @@ -0,0 +1,78 @@ +#!/bin/bash +# Copyright 2020 Gentoo Authors +# Distributed under the terms of the GNU General Public License v2 + +EAPI=7 + +source tests-common.sh + +inherit eapi8-dosym + +dosym() { + echo "$1" +} + +# reference implementation using GNU realpath +ref_canonicalize() { + realpath -m -s "$1" +} + +ref_dosym_r() { + local link=$(realpath -m -s "/${2#/}") + realpath -m -s --relative-to="$(dirname "${link}")" "$1" +} + +randompath() { + dd if=/dev/urandom bs=128 count=1 2>/dev/null | LC_ALL=C sed \ + -e 's/[^a-zA-M]//g;s/[A-E]/\/.\//g;s/[F-J]/\/..\//g;s/[K-M]/\//g' \ + -e 's/^/\//;q' +} + +teq() { + local expected=$1; shift + tbegin "$* -> ${expected}" + local got=$("$@") + [[ ${got} == "${expected}" ]] + tend $? "returned: ${got}" +} + +for f in ref_canonicalize "_dosym8_canonicalize"; do + # canonicalize absolute paths + teq / ${f} / + teq /foo/baz/quux ${f} /foo/bar/../baz/quux + teq /foo ${f} /../../../foo + teq /bar ${f} /foo//./..///bar + teq /baz ${f} /foo/bar/../../../baz + teq /a/d/f/g ${f} /a/b/c/../../d/e/../f/g +done + +# canonicalize relative paths (not actually used) +teq . _dosym8_canonicalize . +teq foo _dosym8_canonicalize foo +teq foo _dosym8_canonicalize ./foo +teq ../foo _dosym8_canonicalize ../foo +teq ../baz _dosym8_canonicalize foo/bar/../../../baz + +for f in ref_dosym_r "dosym8 -r"; do + teq ../../bin/foo ${f} /bin/foo /usr/bin/foo + teq ../../../doc/foo-1 \ + ${f} /usr/share/doc/foo-1 /usr/share/texmf-site/doc/fonts/foo + teq ../../opt/bar/foo ${f} /opt/bar/foo /usr/bin/foo + teq ../c/d/e ${f} /a/b/c/d/e a/b/f/g + teq b/f ${f} /a/b///./c/d/../e/..//../f /a/././///g/../h + teq ../h ${f} /a/././///g/../h /a/b///./c/d/../e/..//../f + teq . ${f} /foo /foo/bar + teq .. ${f} /foo /foo/bar/baz + teq '../../fo . o/b ar' ${f} '/fo . o/b ar' '/baz / qu .. ux/qu x' + teq '../../f"o\o/b$a[]r' ${f} '/f"o\o/b$a[]r' '/ba\z/qu$u"x/qux' +done + +# set RANDOMTESTS to a positive number to enable random tests +for (( i = 0; i < RANDOMTESTS; i++ )); do + targ=$(randompath) + link=$(randompath) + out=$(ref_dosym_r "${targ}" "${link}") + teq "${out}" dosym8 -r "${targ}" "${link}" +done + +texit diff --git a/eclass/tests/estack_eshopts.sh b/eclass/tests/estack_eshopts.sh new file mode 100755 index 0000000..28346c6 --- /dev/null +++ b/eclass/tests/estack_eshopts.sh @@ -0,0 +1,69 @@ +#!/bin/bash +# Copyright 1999-2017 Gentoo Foundation +# Distributed under the terms of the GNU General Public License v2 + +source tests-common.sh + +inherit estack + +test-it() { + local s0 s1 s2 + + tbegin "push/pop '$*'" + s0=$(shopt -p) + t eshopts_push $* + s1=$(shopt -p) + t eshopts_pop + s2=$(shopt -p) + [[ ${s0} == "${s2}" ]] && \ + [[ ${s1} == *"shopt $*"* ]] + tend $? +} + +# should handle bug #395025 +for arg in nullglob dotglob extglob ; do + for flag in s u ; do + test-it -${flag} ${arg} + done +done + +# test 'set' options +set -f +tbegin "set +f" +s0=$- +t eshopts_push +f +s1=$- +t eshopts_pop +s2=$- +[[ ${s0} == "${s2}" ]] && +[[ ${s1} != *f* ]] +tend $? + +set +f +tbegin "set -f" +s0=$- +t eshopts_push -f +s1=$- +t eshopts_pop +s2=$- +[[ ${s0} == "${s2}" ]] && +[[ ${s1} == *f* ]] +tend $? + +tbegin "multi push/pop" +s0=$(shopt -p) +t eshopts_push -s dotglob +t eshopts_push -u dotglob +t eshopts_push -s extglob +t eshopts_push -u dotglob +t eshopts_push -s dotglob +t eshopts_pop +t eshopts_pop +t eshopts_pop +t eshopts_pop +t eshopts_pop +s1=$(shopt -p) +[[ ${s0} == "${s1}" ]] +tend $? + +texit diff --git a/eclass/tests/estack_estack.sh b/eclass/tests/estack_estack.sh new file mode 100755 index 0000000..4845243 --- /dev/null +++ b/eclass/tests/estack_estack.sh @@ -0,0 +1,52 @@ +#!/bin/bash +# Copyright 1999-2017 Gentoo Foundation +# Distributed under the terms of the GNU General Public License v2 + +source tests-common.sh + +inherit estack + +tbegin "initial stack state" +estack_pop teststack +# Should be empty and thus return 1 +[[ $? -eq 1 ]] +tend $? + +tbegin "simple push/pop" +estack_push ttt 1 +pu=$? +estack_pop ttt +po=$? +[[ ${pu}${po} == "00" ]] +tend $? + +tbegin "simple push/pop var" +estack_push xxx "boo ga boo" +pu=$? +estack_pop xxx i +po=$? +[[ ${pu}${po} == "00" ]] && [[ ${i} == "boo ga boo" ]] +tend $? + +tbegin "multi push/pop" +estack_push yyy {1..10} +pu=$? +i=0 +while estack_pop yyy ; do + : $(( i++ )) +done +[[ ${pu} -eq 0 && ${i} -eq 10 ]] +tend $? + +tbegin "umask push/pop" +u0=$(umask) +eumask_push 0000 +pu=$? +u1=$(umask) +eumask_pop +po=$? +u2=$(umask) +[[ ${pu}${po}:${u0}:${u1}:${u2} == "00:${u0}:0000:${u0}" ]] +tend $? + +texit diff --git a/eclass/tests/estack_evar.sh b/eclass/tests/estack_evar.sh new file mode 100755 index 0000000..29badba --- /dev/null +++ b/eclass/tests/estack_evar.sh @@ -0,0 +1,99 @@ +#!/bin/bash +# Copyright 1999-2017 Gentoo Foundation +# Distributed under the terms of the GNU General Public License v2 + +source tests-common.sh + +inherit estack + +tbegin "simple push/pop" +VAR=1 +evar_push VAR +pu=$? +VAR=2 +evar_pop +po=$? +[[ ${pu}${po}${VAR} == "001" ]] +tend $? + +tbegin "unset push/pop" +unset VAR +evar_push VAR +pu=$? +VAR=2 +evar_pop +po=$? +[[ ${pu}${po}${VAR+set} == "00" ]] +tend $? + +tbegin "empty push/pop" +VAR= +evar_push VAR +pu=$? +VAR=2 +evar_pop +po=$? +[[ ${pu}${po}${VAR+set}${VAR} == "00set" ]] +tend $? + +tbegin "export push/pop" +export VAR=exported +evar_push VAR +pu=$? +VAR=2 +evar_pop +po=$? +var=$(bash -c 'echo ${VAR}') +[[ ${pu}${po}${var} == "00exported" ]] +tend $? + +tbegin "unexport push/pop" +unset VAR +VAR=not-exported +evar_push VAR +pu=$? +VAR=2 +evar_pop +po=$? +var=$(bash -c 'echo ${VAR+set}') +[[ ${pu}${po}${VAR}${var} == "00not-exported" ]] +tend $? + +tbegin "multi push/pop" +A=a B=b C=c +evar_push A B C +pu=$? +A=A B=B C=C +evar_pop 1 +po1=$? +[[ ${A}${B}${C} == "ABc" ]] +po2=$? +evar_pop 2 +po3=$? +var=$(bash -c 'echo ${VAR+set}') +[[ ${pu}${po1}${po2}${po3}${A}${B}${C} == "0000abc" ]] +tend $? + +tbegin "simple push_set/pop" +VAR=1 +evar_push_set VAR 2 +pu=$? +[[ ${VAR} == "2" ]] +po1=$? +evar_pop +po2=$? +[[ ${pu}${po1}${po2}${VAR} == "0001" ]] +tend $? + +tbegin "unset push_set/pop" +VAR=1 +evar_push_set VAR +pu=$? +[[ ${VAR+set} != "set" ]] +po1=$? +evar_pop +po2=$? +[[ ${pu}${po1}${po2}${VAR} == "0001" ]] +tend $? + +texit diff --git a/eclass/tests/flag-o-matic.sh b/eclass/tests/flag-o-matic.sh new file mode 100755 index 0000000..676cc69 --- /dev/null +++ b/eclass/tests/flag-o-matic.sh @@ -0,0 +1,175 @@ +#!/bin/bash +# Copyright 1999-2019 Gentoo Authors +# Distributed under the terms of the GNU General Public License v2 + +source tests-common.sh + +inherit flag-o-matic + +CFLAGS="-a -b -c=1 --param l1-cache-size=32" +CXXFLAGS="-x -y -z=2" +LDFLAGS="-l -m -n=3 -Wl,--remove-me" +ftend() { + local ret=$? + local msg="Failed; flags are:" + local flag + for flag in $(all-flag-vars) ; do + msg+=$'\n\t'"${flag}=${!flag}" + done + tend ${ret} "${msg}" +} + +tbegin "is-flag" +! (is-flag 1 2 3) 2>/dev/null +ftend + +tbegin "is-ldflag" +! (is-ldflag 1 2 3) 2>/dev/null +ftend + +while read exp flag ; do + [[ -z ${exp}${flag} ]] && continue + + tbegin "is-flagq ${flag}" + is-flagq ${flag} + [[ ${exp} -eq $? ]] + ftend +done <<<" + 1 -L + 0 -a + 0 -x +" + +while read exp flag ; do + [[ -z ${exp}${flag} ]] && continue + + tbegin "is-ldflagq ${flag}" + is-ldflagq "${flag}" + [[ ${exp} -eq $? ]] + ftend +done <<<" + 1 -a + 0 -n=* + 1 -n +" + +tbegin "strip-unsupported-flags for -z=2" +strip-unsupported-flags +[[ ${CFLAGS} == "--param l1-cache-size=32" ]] && [[ ${CXXFLAGS} == "-z=2" ]] && [[ ${LDFLAGS} == "" ]] +ftend + +CFLAGS="-O2 -B/foo -O1" +CXXFLAGS="-O2 -B/foo -O1" +LDFLAGS="-O2 -B/foo -O1" +tbegin "strip-unsupported-flags for '-B/foo'" +strip-unsupported-flags +[[ ${CFLAGS} == "-O2 -B/foo -O1" ]] && [[ ${CXXFLAGS} == "-O2 -B/foo -O1" ]] && [[ ${LDFLAGS} == "-O2 -B/foo -O1" ]] +ftend + +CFLAGS="-O2 -B /foo -O1" +CXXFLAGS="-O2 -B /foo -O1" +LDFLAGS="-O2 -B /foo -O1" +tbegin "strip-unsupported-flags for '-B /foo'" +strip-unsupported-flags +[[ ${CFLAGS} == "-O2 -B /foo -O1" ]] && [[ ${CXXFLAGS} == "-O2 -B /foo -O1" ]] && [[ ${LDFLAGS} == "-O2 -B /foo -O1" ]] +ftend + +for var in $(all-flag-vars) ; do + eval ${var}=\"-filter -filter-glob -foo-${var%FLAGS}\" +done + +tbegin "filter-flags basic" +filter-flags -filter +( +for var in $(all-flag-vars) ; do + val=${!var} + [[ ${val} == "-filter-glob -foo-${var%FLAGS}" ]] || exit 1 +done +) +ftend + +tbegin "filter-flags glob" +filter-flags '-filter-*' +( +for var in $(all-flag-vars) ; do + val=${!var} + [[ ${val} == "-foo-${var%FLAGS}" ]] || exit 1 +done +) +ftend + +tbegin "strip-flags basic" +CXXFLAGS+=" -O999 " +strip-flags +[[ -z ${CFLAGS}${LDFLAGS}${CPPFLAGS} && ${CXXFLAGS} == "-O2" ]] +ftend + +tbegin "replace-flags basic" +CFLAGS="-O0 -foo" +replace-flags -O0 -O1 +[[ ${CFLAGS} == "-O1 -foo" ]] +ftend + +tbegin "replace-flags glob" +CXXFLAGS="-O0 -mcpu=bad -cow" +replace-flags '-mcpu=*' -mcpu=good +[[ ${CXXFLAGS} == "-O0 -mcpu=good -cow" ]] +ftend + +tbegin "append-cflags basic" +CFLAGS= +append-cflags -O0 +[[ ${CFLAGS} == " -O0" ]] +ftend + +tbegin "append-cflags -DFOO='a b c'" +CFLAGS= +append-cflags '-DFOO="a b c"' +[[ ${CFLAGS} == ' -DFOO="a b c"' ]] +ftend + +tbegin "raw-ldflags" +LDFLAGS='-Wl,-O1 -Wl,--as-needed -Wl,-z,now -flto' +LDFLAGS=$(raw-ldflags) +[[ ${LDFLAGS} == '-O1 --as-needed -z now' ]] +ftend + +tbegin "test-flags-CC (valid flags)" +out=$(test-flags-CC -O3) +[[ $? -eq 0 && ${out} == "-O3" ]] +ftend + +tbegin "test-flags-CC (valid flags, absolute path)" +absolute_CC=$(type -P $(tc-getCC)) +out=$(CC=${absolute_CC} test-flags-CC -O3) +[[ $? -eq 0 && ${out} == "-O3" ]] +ftend + +tbegin "test-flags-CC (invalid flags)" +out=$(test-flags-CC -finvalid-flag) +[[ $? -ne 0 && -z ${out} ]] +ftend + +if type -P clang >/dev/null ; then +tbegin "test-flags-CC (valid flags w/clang)" +out=$(CC=clang test-flags-CC -O3) +[[ $? -eq 0 && ${out} == "-O3" ]] +ftend + +tbegin "test-flags-CC (invalid flags w/clang)" +out=$(CC=clang test-flags-CC -finvalid-flag) +[[ $? -ne 0 && -z ${out} ]] +ftend + +tbegin "test-flags-CC (gcc-valid but clang-invalid flags)" +out=$(CC=clang test-flags-CC -finline-limit=1200) +[[ $? -ne 0 && -z ${out} ]] +ftend + +tbegin "test-flags-CC (unused flags w/clang)" +out=$(CC=clang test-flags-CC -Wl,-O1) +[[ $? -eq 0 && ${out} == "-Wl,-O1" ]] +ftend +fi + +texit diff --git a/eclass/tests/git-r3.sh b/eclass/tests/git-r3.sh new file mode 100755 index 0000000..2f452bf --- /dev/null +++ b/eclass/tests/git-r3.sh @@ -0,0 +1,208 @@ +#!/bin/bash +# Copyright 1999-2019 Gentoo Authors +# Distributed under the terms of the GNU General Public License v2 + +# git no longer allows ext: protocol, meh +exit 0 + +EAPI=7 + +source tests-common.sh + +inherit git-r3 + +testdir=${pkg_root}/git +mkdir "${testdir}" || die "unable to mkdir testdir" +cd "${testdir}" || die "unable to cd to testdir" + +EGIT3_STORE_DIR=store +mkdir "${EGIT3_STORE_DIR}" || die "unable to mkdir store" + +test_file() { + local fn=${1} + local expect=${2} + + if [[ ! -f ${fn} ]]; then + eerror "${fn} does not exist (not checked out?)" + else + local got=$(<"${fn}") + + if [[ ${got} != ${expect} ]]; then + eerror "${fn}, expected: ${expect}, got: ${got}" + else + return 0 + fi + fi + return 1 +} + +test_no_file() { + local fn=${1} + + if [[ -f ${fn} ]]; then + eerror "${fn} exists (wtf?!)" + else + return 0 + fi + return 1 +} + +test_repo_clean() { + local P=${P}_${FUNCNAME#test_} + + ( + mkdir repo + cd repo + git init -q + echo test > file + git add file + git commit -m 1 -q + echo other-text > file2 + git add file2 + git commit -m 2 -q + ) || die "unable to prepare repo" + + # we need to use an array to preserve whitespace + local EGIT_REPO_URI=( + "ext::git daemon --export-all --base-path=. --inetd %G/repo" + ) + + tbegin "fetching from a simple repo" + ( + git-r3_src_unpack + test_file "${WORKDIR}/${P}/file" test && \ + test_file "${WORKDIR}/${P}/file2" other-text + ) &>fetch.log + + eend ${?} || cat fetch.log +} + +test_repo_revert() { + local P=${P}_${FUNCNAME#test_} + + ( + cd repo + git revert -n HEAD^ + git commit -m r1 -q + ) || die "unable to prepare repo" + + # we need to use an array to preserve whitespace + local EGIT_REPO_URI=( + "ext::git daemon --export-all --base-path=. --inetd %G/repo" + ) + + tbegin "fetching revert" + ( + git-r3_src_unpack + test_no_file "${WORKDIR}/${P}/file" && \ + test_file "${WORKDIR}/${P}/file2" other-text + ) &>fetch.log + + eend ${?} || cat fetch.log +} + +test_repo_branch() { + local P=${P}_${FUNCNAME#test_} + + ( + cd repo + git branch -q other-branch HEAD^ + git checkout -q other-branch + echo one-more > file3 + git add file3 + git commit -m 3 -q + git checkout -q master + ) || die "unable to prepare repo" + + # we need to use an array to preserve whitespace + local EGIT_REPO_URI=( + "ext::git daemon --export-all --base-path=. --inetd %G/repo" + ) + local EGIT_BRANCH=other-branch + + tbegin "switching branches" + ( + git-r3_src_unpack + test_file "${WORKDIR}/${P}/file" test && \ + test_file "${WORKDIR}/${P}/file2" other-text && \ + test_file "${WORKDIR}/${P}/file3" one-more + ) &>fetch.log + + eend ${?} || cat fetch.log +} + +test_repo_merge() { + local P=${P}_${FUNCNAME#test_} + + ( + cd repo + git branch -q one-more-branch HEAD^ + git checkout -q one-more-branch + echo foobarbaz > file3 + git add file3 + git commit -m 3b -q + git checkout -q master + git merge -m 4 -q one-more-branch + ) || die "unable to prepare repo" + + # we need to use an array to preserve whitespace + local EGIT_REPO_URI=( + "ext::git daemon --export-all --base-path=. --inetd %G/repo" + ) + + tbegin "fetching a merge commit" + ( + git-r3_src_unpack + test_no_file "${WORKDIR}/${P}/file" && \ + test_file "${WORKDIR}/${P}/file2" other-text && \ + test_file "${WORKDIR}/${P}/file3" foobarbaz + ) &>fetch.log + + eend ${?} || cat fetch.log +} + +test_repo_revert_merge() { + local P=${P}_${FUNCNAME#test_} + + ( + cd repo + git branch -q to-be-reverted + git checkout -q to-be-reverted + echo trrm > file3 + git add file3 + git commit -m 5b -q + git checkout -q master + echo trrm > file2 + git add file2 + git commit -m 5 -q + git merge -m 6 -q to-be-reverted + echo trrm > file + git add file + git commit -m 7 -q + git revert -m 1 -n HEAD^ + git commit -m 7r -q + ) || die "unable to prepare repo" + + # we need to use an array to preserve whitespace + local EGIT_REPO_URI=( + "ext::git daemon --export-all --base-path=. --inetd %G/repo" + ) + + tbegin "fetching a revert of a merge commit" + ( + git-r3_src_unpack + test_file "${WORKDIR}/${P}/file" trrm && \ + test_file "${WORKDIR}/${P}/file2" trrm && \ + test_file "${WORKDIR}/${P}/file3" foobarbaz + ) &>fetch.log + + eend ${?} || cat fetch.log +} + +test_repo_clean +test_repo_revert +test_repo_branch +test_repo_merge +test_repo_revert_merge + +texit diff --git a/eclass/tests/git-r3_GIT_DIR.sh b/eclass/tests/git-r3_GIT_DIR.sh new file mode 100755 index 0000000..c17ae7b --- /dev/null +++ b/eclass/tests/git-r3_GIT_DIR.sh @@ -0,0 +1,64 @@ +#!/bin/bash +# Copyright 1999-2019 Gentoo Authors +# Distributed under the terms of the GNU General Public License v2 + +EAPI=7 + +source tests-common.sh + +inherit git-r3 + +testdir=${pkg_root}/git +mkdir "${testdir}" || die "unable to mkdir testdir" +cd "${testdir}" || die "unable to cd to testdir" + +EGIT3_STORE_DIR=store +mkdir "${EGIT3_STORE_DIR}" || die "unable to mkdir store" + +git() { :; } + +# Test cleaning up canonical repo URI +test_repouri() { + local uri=${1} + local expect=${2} + local -x GIT_DIR + + tbegin "GIT_DIR for ${uri}" + + _git-r3_set_gitdir "${uri}" &>/dev/null + local got=${GIT_DIR#${EGIT3_STORE_DIR}/} + + [[ ${expect} == ${got} ]] + tend ${?} || eerror "Expected: ${expect}, got: ${got}" +} + +test_repouri git://git.overlays.gentoo.org/proj/portage.git proj_portage.git +test_repouri https://git.overlays.gentoo.org/gitroot/proj/portage.git proj_portage.git +test_repouri git+ssh://git@git.overlays.gentoo.org/proj/portage.git proj_portage.git + +test_repouri git://anongit.freedesktop.org/mesa/mesa mesa_mesa.git +test_repouri ssh://git.freedesktop.org/git/mesa/mesa mesa_mesa.git +test_repouri http://anongit.freedesktop.org/git/mesa/mesa.git mesa_mesa.git +test_repouri http://cgit.freedesktop.org/mesa/mesa/ mesa_mesa.git + +test_repouri https://code.google.com/p/snakeoil/ snakeoil.git + +test_repouri git://git.code.sf.net/p/xournal/code xournal_code.git +test_repouri http://git.code.sf.net/p/xournal/code xournal_code.git + +test_repouri git://git.gnome.org/glibmm glibmm.git +test_repouri https://git.gnome.org/browse/glibmm glibmm.git +test_repouri ssh://USERNAME@git.gnome.org/git/glibmm glibmm.git + +test_repouri git://git.kernel.org/pub/scm/git/git.git git_git.git +test_repouri http://git.kernel.org/pub/scm/git/git.git git_git.git +test_repouri https://git.kernel.org/pub/scm/git/git.git git_git.git +test_repouri https://git.kernel.org/cgit/git/git.git/ git_git.git + +#test_repouri git@github.com:gentoo/identity.gentoo.org.git gentoo_identity.gentoo.org.git +test_repouri https://github.com/gentoo/identity.gentoo.org.git gentoo_identity.gentoo.org.git + +#test_repouri git@bitbucket.org:mgorny/python-exec.git mgorny_python-exec.git +test_repouri https://mgorny@bitbucket.org/mgorny/python-exec.git mgorny_python-exec.git + +texit diff --git a/eclass/tests/git-r3_subrepos.sh b/eclass/tests/git-r3_subrepos.sh new file mode 100755 index 0000000..0fcf1cd --- /dev/null +++ b/eclass/tests/git-r3_subrepos.sh @@ -0,0 +1,39 @@ +#!/bin/bash +# Copyright 1999-2019 Gentoo Authors +# Distributed under the terms of the GNU General Public License v2 + +EAPI=7 + +source tests-common.sh + +inherit git-r3 + +# Test getting submodule URIs +test_subrepos() { + local suburi=${1} + local expect=( "${@:2}" ) + + tbegin "subrepos for ${suburi} -> ${expect[0]}${expect[1]+...}" + + local subrepos + _git-r3_set_subrepos "${suburi}" "${repos[@]}" + + [[ ${expect[@]} == ${subrepos[@]} ]] + tend ${?} || eerror "Expected: ${expect[@]}, got: ${subrepos[@]}" +} + +# parent repos +repos=( http://foohub/fooman/foo.git git://foohub/fooman/foo.git ) + +# absolute URI +test_subrepos http://foo/bar http://foo/bar +test_subrepos /foo/bar /foo/bar + +# plain relative URI +test_subrepos ./baz http://foohub/fooman/foo.git/baz git://foohub/fooman/foo.git/baz + +# backward relative URIs +test_subrepos ../baz.git http://foohub/fooman/baz.git git://foohub/fooman/baz.git +test_subrepos ../../bazman/baz.git http://foohub/bazman/baz.git git://foohub/bazman/baz.git + +texit diff --git a/eclass/tests/linux-info_get_running_version.sh b/eclass/tests/linux-info_get_running_version.sh new file mode 100755 index 0000000..fbb5c82 --- /dev/null +++ b/eclass/tests/linux-info_get_running_version.sh @@ -0,0 +1,38 @@ +#!/bin/bash +# Copyright 1999-2015 Gentoo Foundation +# Distributed under the terms of the GNU General Public License v2 + +source tests-common.sh + +inherit linux-info + +test_get_running_version() { + local test_kv=$1 major=$2 minor=$3 patch=$4 extra=$5 + tbegin "get_running_version ${test_kv}" + uname() { echo "${test_kv}" ; } + ROOT=/:/:/:/: get_running_version + local r=$? + [[ ${r} -eq 0 && + ${major} == "${KV_MAJOR}" && + ${minor} == "${KV_MINOR}" && + ${patch} == "${KV_PATCH}" && + ${extra} == "${KV_EXTRA}" ]] + tend $? "FAIL: {ret: ${r}==0} {major: ${major}==${KV_MAJOR}} {minor: ${minor}==${KV_MINOR}} {patch: ${patch}==${KV_PATCH}} {extra: ${extra}==${KV_EXTRA}}" +} + +tests=( + # KV_FULL MAJOR MINOR PATCH EXTRA + 1.2.3 1 2 3 '' + 1.2.3.4 1 2 3 .4 + 1.2.3-ver+1.4 1 2 3 -ver+1.4 + 1.2-kern.3 1 2 0 -kern.3 + 1.2+kern.5 1 2 0 +kern.5 + 1.2.3_blah 1 2 3 _blah + 3.2.1-zen-vs2.3.2.5+ 3 2 1 -zen-vs2.3.2.5+ +) + +for (( i = 0; i < ${#tests[@]}; i += 5 )) ; do + test_get_running_version "${tests[@]:i:5}" +done + +texit diff --git a/eclass/tests/llvm.sh b/eclass/tests/llvm.sh new file mode 100755 index 0000000..8527d81 --- /dev/null +++ b/eclass/tests/llvm.sh @@ -0,0 +1,138 @@ +#!/bin/bash +# Copyright 1999-2020 Gentoo Authors +# Distributed under the terms of the GNU General Public License v2 + +EAPI=7 +source tests-common.sh + +inherit llvm + +# llvm_check_deps override to disable has_version use. +# in: ${LLVM_SLOT} +# returns 0 if installed (i.e. == LLVM_INSTALLED_SLOT), 1 otherwise +llvm_check_deps() { + [[ ${LLVM_SLOT} == ${LLVM_INSTALLED_SLOT} ]] +} + +# check_prefix <expected> [<args>...] +# Check output of `get_llvm_prefix <args>...`. +check_prefix() { + local expected=${1} + shift + + tbegin "get_llvm_prefix ${*}; inst=${LLVM_INSTALLED_SLOT} -> ${expected}" + prefix=$(get_llvm_prefix "${@}") + [[ ${prefix} == ${expected} ]] || + eerror "got: ${prefix} != exp: ${expected}" + tend ${?} +} + +# check_setup_path <expected> +# Check PATH after pkg_setup. +check_setup_path() { + local expected=${1} + shift + + tbegin "pkg_setup; max=${LLVM_MAX_SLOT}; inst=${LLVM_INSTALLED_SLOT} -> PATH=${expected}" + path=$(llvm_pkg_setup; echo "${PATH}") + [[ ${path} == ${expected} ]] || + eerror "got: ${path} != exp: ${expected}" + tend ${?} +} + + +EAPI=7 +BROOT=/broot +SYSROOT=/sysroot +ESYSROOT=/sysroot/eprefix +ROOT=/root +EROOT=/root/eprefix + +ebegin "Testing check_setup_path without max slot" +eindent + LLVM_INSTALLED_SLOT=11 \ + check_prefix /sysroot/eprefix/usr/lib/llvm/11 + LLVM_INSTALLED_SLOT=10 \ + check_prefix /sysroot/eprefix/usr/lib/llvm/10 +eoutdent + +ebegin "Testing check_setup_path with max slot" +eindent + LLVM_INSTALLED_SLOT=1* \ + check_prefix /sysroot/eprefix/usr/lib/llvm/11 11 + LLVM_INSTALLED_SLOT=1* \ + check_prefix /sysroot/eprefix/usr/lib/llvm/10 10 + LLVM_INSTALLED_SLOT=10 \ + check_prefix /sysroot/eprefix/usr/lib/llvm/10 11 +eoutdent + +ebegin "Testing check_setup_path option switches" +eindent + LLVM_INSTALLED_SLOT=11 \ + check_prefix /broot/usr/lib/llvm/11 -b + LLVM_INSTALLED_SLOT=11 \ + check_prefix /sysroot/eprefix/usr/lib/llvm/11 -d +eoutdent + +ebegin "Testing check_setup_path EAPI 6 API" +eindent + EAPI=6 \ + LLVM_INSTALLED_SLOT=11 \ + check_prefix /usr/lib/llvm/11 -d +eoutdent + +BASEPATH=/usr/lib/ccache/bin:/usr/bin:/usr/sbin:/bin:/sbin + +# TODO: cross support? +ESYSROOT= + +ebegin "Testing pkg_setup with all installed LLVM versions in PATH" +eindent + LLVM_MAX_SLOT=11 \ + LLVM_INSTALLED_SLOT=1* \ + PATH=${BASEPATH}:/usr/lib/llvm/11/bin \ + check_setup_path "${BASEPATH}:/usr/lib/llvm/11/bin" + + LLVM_MAX_SLOT=10 \ + LLVM_INSTALLED_SLOT=1* \ + PATH=${BASEPATH}:/usr/lib/llvm/11/bin:/usr/lib/llvm/10/bin \ + check_setup_path "${BASEPATH}:/usr/lib/llvm/10/bin:/usr/lib/llvm/11/bin" + + LLVM_MAX_SLOT=11 \ + LLVM_INSTALLED_SLOT=10 \ + PATH=${BASEPATH}:/usr/lib/llvm/10/bin \ + check_setup_path "${BASEPATH}:/usr/lib/llvm/10/bin" +eoutdent + +ebegin "Testing pkg_setup with the other LLVM version in PATH" +eindent + LLVM_MAX_SLOT=11 \ + LLVM_INSTALLED_SLOT=1* \ + PATH=${BASEPATH}:/usr/lib/llvm/10/bin \ + check_setup_path "${BASEPATH}:/usr/lib/llvm/11/bin:/usr/lib/llvm/10/bin" + + LLVM_MAX_SLOT=10 \ + LLVM_INSTALLED_SLOT=1* \ + PATH=${BASEPATH}:/usr/lib/llvm/11/bin \ + check_setup_path "${BASEPATH}:/usr/lib/llvm/10/bin:/usr/lib/llvm/11/bin" +eoutdent + +ebegin "Testing pkg_setup with LLVM missing from PATH" +eindent + LLVM_MAX_SLOT=11 \ + LLVM_INSTALLED_SLOT=1* \ + PATH=${BASEPATH} \ + check_setup_path "${BASEPATH}:/usr/lib/llvm/11/bin" + + LLVM_MAX_SLOT=10 \ + LLVM_INSTALLED_SLOT=1* \ + PATH=${BASEPATH} \ + check_setup_path "${BASEPATH}:/usr/lib/llvm/10/bin" + + LLVM_MAX_SLOT=11 \ + LLVM_INSTALLED_SLOT=10 \ + PATH=${BASEPATH} \ + check_setup_path "${BASEPATH}:/usr/lib/llvm/10/bin" +eoutdent + +texit diff --git a/eclass/tests/multilib.sh b/eclass/tests/multilib.sh new file mode 100755 index 0000000..a483d4b --- /dev/null +++ b/eclass/tests/multilib.sh @@ -0,0 +1,65 @@ +#!/bin/bash +# Copyright 2020 Gentoo Authors +# Distributed under the terms of the GNU General Public License v2 + +source tests-common.sh + +inherit multilib + +# Run 'multilib_env' and check what variables it expands to +test-multilib_env() { + local target=$1 exp_abi=$2 exp_vars=" $3" + tbegin "expand-target $1" + + # Reset default + unset MULTILIB_ABIS + unset DEFAULT_ABI + CFLAGS_default= + LDFLAGS_default= + LIBDIR_default=lib + CHOST_default=${target} + CTARGET_default=${CHOST_default} + LIBDIR_default=lib + + multilib_env ${target} + + local actual_abi="${DEFAULT_ABI}:${MULTILIB_ABIS}" + + local actual_vars="" + local abi var v + for abi in ${MULTILIB_ABIS}; do + actual_vars+=" ${abi}? (" + for var in CHOST LIBDIR CFLAGS LDFLAGS; do + v=${var}_${abi} + actual_vars+=" ${var}=${!v}" + done + actual_vars+=" )" + done + + [[ "${exp_abi}" == "${actual_abi}" && "${exp_vars}" == "${actual_vars}" ]] + + if ! tend $? ; then + printf '### EXPECTED ABI: %s\n' "${exp_abi}" + printf '### ACTUAL ABI: %s\n' "${actual_abi}" + printf '### EXPECTED VARS: %s\n' "${exp_vars}" + printf '### ACTUAL VARS: %s\n' "${actual_vars}" + fi +} + +# Pick a few interesting targets from: +# $ grep -h -o -R 'CHOST=.*' ../../profiles/ | sort -u + +test-multilib_env \ + "x86_64-pc-linux-gnu" \ + "amd64:amd64 x86" \ + "amd64? ( CHOST=x86_64-pc-linux-gnu LIBDIR=lib64 CFLAGS=-m64 LDFLAGS= ) x86? ( CHOST=i686-pc-linux-gnu LIBDIR=lib CFLAGS=-m32 LDFLAGS= )" +test-multilib_env \ + "x86_64-pc-linux-gnux32" \ + "x32:x32 amd64 x86" \ + "x32? ( CHOST=x86_64-pc-linux-gnux32 LIBDIR=libx32 CFLAGS=-mx32 LDFLAGS= ) amd64? ( CHOST=x86_64-pc-linux-gnu LIBDIR=lib64 CFLAGS=-m64 LDFLAGS= ) x86? ( CHOST=i686-pc-linux-gnu LIBDIR=lib CFLAGS=-m32 LDFLAGS= )" +test-multilib_env \ + "x86_64-gentoo-linux-musl" \ + "default:default" \ + "default? ( CHOST=x86_64-gentoo-linux-musl LIBDIR=lib CFLAGS= LDFLAGS= )" + +texit diff --git a/eclass/tests/multiprocessing_makeopts_jobs.sh b/eclass/tests/multiprocessing_makeopts_jobs.sh new file mode 100755 index 0000000..689313a --- /dev/null +++ b/eclass/tests/multiprocessing_makeopts_jobs.sh @@ -0,0 +1,50 @@ +#!/bin/bash +# Copyright 1999-2015 Gentoo Foundation +# Distributed under the terms of the GNU General Public License v2 + +source tests-common.sh + +inherit multiprocessing + +test-makeopts_jobs() { + local exp=$1; shift + tbegin "makeopts_jobs($1${2+; inf=${2}}) == ${exp}" + local indirect=$(MAKEOPTS="$*" makeopts_jobs) + local direct=$(makeopts_jobs "$@") + if [[ "${direct}" != "${indirect}" ]] ; then + tend 1 "Mismatch between MAKEOPTS/cli: '${indirect}' != '${direct}'" + else + [[ ${direct} == "${exp}" ]] + tend $? "Got back: ${act}" + fi +} + +tests=( + 999 "-j" + 999 "--jobs" + 999 "-j -l9" + 1 "" + 1 "-l9 -w" + 1 "-l9 -w-j4" + 1 "-l9--jobs=3" + 1 "-l9--jobs=8" + 2 "-j2" + 3 "-j 3" + 4 "-l3 -j 4 -w" + 5 "--jobs=5" + 6 "--jobs 6" + 7 "-l3 --jobs 7 -w" + 4 "-j1 -j 2 --jobs 3 --jobs=4" + 8 " -j 8 " + 999 "-kj" + 4 "-kj4" + 5 "-kj 5" +) +for (( i = 0; i < ${#tests[@]}; i += 2 )) ; do + test-makeopts_jobs "${tests[i]}" "${tests[i+1]}" +done + +# test custom inf value +test-makeopts_jobs 645 "-j" 645 + +texit diff --git a/eclass/tests/multiprocessing_makeopts_loadavg.sh b/eclass/tests/multiprocessing_makeopts_loadavg.sh new file mode 100755 index 0000000..d17d773 --- /dev/null +++ b/eclass/tests/multiprocessing_makeopts_loadavg.sh @@ -0,0 +1,48 @@ +#!/bin/bash +# Copyright 1999-2015 Gentoo Foundation +# Distributed under the terms of the GNU General Public License v2 + +source tests-common.sh + +inherit multiprocessing + +test-makeopts_loadavg() { + local exp=$1; shift + tbegin "makeopts_loadavg($1${2+; inf=${2}}) == ${exp}" + local indirect=$(MAKEOPTS="$*" makeopts_loadavg) + local direct=$(makeopts_loadavg "$@") + if [[ "${direct}" != "${indirect}" ]] ; then + tend 1 "Mismatch between MAKEOPTS/cli: '${indirect}' != '${direct}'" + else + [[ ${direct} == "${exp}" ]] + tend $? "Got back: ${direct}" + fi +} + +tests=( + 999 "-j" + 999 "-l" + 999 "" + 9 "-l9 -w" + 9 "-l 9 -w-j4" + 3 "-l3 -j 4 -w" + 5 "--load-average=5" + 6 "--load-average 6" + 7 "-l3 --load-average 7 -w" + 4 "-j1 -j 2 --load-average 3 --load-average=4" + 3 " --max-load=3 -x" + 8 " -l 8 " + 999 "-kl" + 4 "-kl4" + 5 "-kl 5" + 2.3 "-l 2.3" + 999 "-l 2.3.4" +) +for (( i = 0; i < ${#tests[@]}; i += 2 )) ; do + test-makeopts_loadavg "${tests[i]}" "${tests[i+1]}" +done + +# test custom inf value +test-makeopts_loadavg 645 "-l" 645 + +texit diff --git a/eclass/tests/python-utils-r1.sh b/eclass/tests/python-utils-r1.sh new file mode 100755 index 0000000..eb8223e --- /dev/null +++ b/eclass/tests/python-utils-r1.sh @@ -0,0 +1,216 @@ +#!/bin/bash +# Copyright 1999-2020 Gentoo Authors +# Distributed under the terms of the GNU General Public License v2 + +EAPI=7 +source tests-common.sh + +test_var() { + local var=${1} + local impl=${2} + local expect=${3} + + tbegin "${var} for ${impl}" + + local ${var} + _python_export ${impl} PYTHON ${var} + [[ ${!var} == ${expect} ]] || eerror "(${impl}: ${var}: ${!var} != ${expect}" + + tend ${?} +} + +test_is() { + local func=${1} + local expect=${2} + + tbegin "${func} (expecting: ${expect})" + + ${func} + [[ ${?} == ${expect} ]] + + tend ${?} +} + +test_fix_shebang() { + local from=${1} + local to=${2} + local expect=${3} + local args=( "${@:4}" ) + + tbegin "python_fix_shebang${args[@]+ ${args[*]}} from ${from} to ${to} (exp: ${expect})" + + echo "${from}" > "${tmpfile}" + output=$( EPYTHON=${to} python_fix_shebang "${args[@]}" -q "${tmpfile}" 2>&1 ) + + if [[ ${?} != 0 ]]; then + if [[ ${expect} != FAIL ]]; then + echo "${output}" + tend 1 + else + tend 0 + fi + else + [[ $(<"${tmpfile}") == ${expect} ]] \ + || eerror "${from} -> ${to}: $(<"${tmpfile}") != ${expect}" + tend ${?} + fi +} + +tmpfile=$(mktemp) + +inherit python-utils-r1 + +test_var EPYTHON python2_7 python2.7 +test_var PYTHON python2_7 /usr/bin/python2.7 +if [[ -x /usr/bin/python2.7 ]]; then + test_var PYTHON_SITEDIR python2_7 "/usr/lib*/python2.7/site-packages" + test_var PYTHON_INCLUDEDIR python2_7 /usr/include/python2.7 + test_var PYTHON_LIBPATH python2_7 "/usr/lib*/libpython2.7$(get_libname)" + test_var PYTHON_CONFIG python2_7 /usr/bin/python2.7-config + test_var PYTHON_CFLAGS python2_7 "*-I/usr/include/python2.7*" + test_var PYTHON_LIBS python2_7 "*-lpython2.7*" +fi +test_var PYTHON_PKG_DEP python2_7 '*dev-lang/python*:2.7' +test_var PYTHON_SCRIPTDIR python2_7 /usr/lib/python-exec/python2.7 + +test_var EPYTHON python3_6 python3.6 +test_var PYTHON python3_6 /usr/bin/python3.6 +if [[ -x /usr/bin/python3.6 ]]; then + abiflags=$(/usr/bin/python3.6 -c 'import sysconfig; print(sysconfig.get_config_var("ABIFLAGS"))') + test_var PYTHON_SITEDIR python3_6 "/usr/lib*/python3.6/site-packages" + test_var PYTHON_INCLUDEDIR python3_6 "/usr/include/python3.6${abiflags}" + test_var PYTHON_LIBPATH python3_6 "/usr/lib*/libpython3.6${abiflags}$(get_libname)" + test_var PYTHON_CONFIG python3_6 "/usr/bin/python3.6${abiflags}-config" + test_var PYTHON_CFLAGS python3_6 "*-I/usr/include/python3.6*" + test_var PYTHON_LIBS python3_6 "*-lpython3.6*" +fi +test_var PYTHON_PKG_DEP python3_6 '*dev-lang/python*:3.6' +test_var PYTHON_SCRIPTDIR python3_6 /usr/lib/python-exec/python3.6 + +test_var EPYTHON python3_7 python3.7 +test_var PYTHON python3_7 /usr/bin/python3.7 +if [[ -x /usr/bin/python3.7 ]]; then + abiflags=$(/usr/bin/python3.7 -c 'import sysconfig; print(sysconfig.get_config_var("ABIFLAGS"))') + test_var PYTHON_SITEDIR python3_7 "/usr/lib/python3.7/site-packages" + test_var PYTHON_INCLUDEDIR python3_7 "/usr/include/python3.7${abiflags}" + test_var PYTHON_LIBPATH python3_7 "/usr/lib*/libpython3.7${abiflags}$(get_libname)" + test_var PYTHON_CONFIG python3_7 "/usr/bin/python3.7${abiflags}-config" + test_var PYTHON_CFLAGS python3_7 "*-I/usr/include/python3.7*" + test_var PYTHON_LIBS python3_7 "*-lpython3.7*" +fi +test_var PYTHON_PKG_DEP python3_7 '*dev-lang/python*:3.7' +test_var PYTHON_SCRIPTDIR python3_7 /usr/lib/python-exec/python3.7 + +test_var EPYTHON python3_8 python3.8 +test_var PYTHON python3_8 /usr/bin/python3.8 +if [[ -x /usr/bin/python3.8 ]]; then + abiflags=$(/usr/bin/python3.8 -c 'import sysconfig; print(sysconfig.get_config_var("ABIFLAGS"))') + test_var PYTHON_SITEDIR python3_8 "/usr/lib/python3.8/site-packages" + test_var PYTHON_INCLUDEDIR python3_8 "/usr/include/python3.8${abiflags}" + test_var PYTHON_LIBPATH python3_8 "/usr/lib*/libpython3.8${abiflags}$(get_libname)" + test_var PYTHON_CONFIG python3_8 "/usr/bin/python3.8${abiflags}-config" + test_var PYTHON_CFLAGS python3_8 "*-I/usr/include/python3.8*" + test_var PYTHON_LIBS python3_8 "*-lpython3.8*" +fi +test_var PYTHON_PKG_DEP python3_8 '*dev-lang/python*:3.8' +test_var PYTHON_SCRIPTDIR python3_8 /usr/lib/python-exec/python3.8 + +test_var EPYTHON python3_9 python3.9 +test_var PYTHON python3_9 /usr/bin/python3.9 +if [[ -x /usr/bin/python3.9 ]]; then + abiflags=$(/usr/bin/python3.9 -c 'import sysconfig; print(sysconfig.get_config_var("ABIFLAGS"))') + test_var PYTHON_SITEDIR python3_9 "/usr/lib/python3.9/site-packages" + test_var PYTHON_INCLUDEDIR python3_9 "/usr/include/python3.9${abiflags}" + test_var PYTHON_LIBPATH python3_9 "/usr/lib*/libpython3.9${abiflags}$(get_libname)" + test_var PYTHON_CONFIG python3_9 "/usr/bin/python3.9${abiflags}-config" + test_var PYTHON_CFLAGS python3_9 "*-I/usr/include/python3.9*" + test_var PYTHON_LIBS python3_9 "*-lpython3.9*" +fi +test_var PYTHON_PKG_DEP python3_9 '*dev-lang/python*:3.9' +test_var PYTHON_SCRIPTDIR python3_9 /usr/lib/python-exec/python3.9 + +test_var EPYTHON pypy3 pypy3 +test_var PYTHON pypy3 /usr/bin/pypy3 +if [[ -x /usr/bin/pypy3 ]]; then + test_var PYTHON_SITEDIR pypy3 "/usr/lib*/pypy3.?/site-packages" + test_var PYTHON_INCLUDEDIR pypy3 "/usr/lib*/pypy3.?/include" +fi +test_var PYTHON_PKG_DEP pypy3 '*dev-python/pypy3*:0=' +test_var PYTHON_SCRIPTDIR pypy3 /usr/lib/python-exec/pypy3 + +test_is "python_is_python3 python2.7" 1 +test_is "python_is_python3 python3.2" 0 +test_is "python_is_python3 pypy" 1 +test_is "python_is_python3 pypy3" 0 + +# generic shebangs +test_fix_shebang '#!/usr/bin/python' python2.7 '#!/usr/bin/python2.7' +test_fix_shebang '#!/usr/bin/python' python3.6 '#!/usr/bin/python3.6' +test_fix_shebang '#!/usr/bin/python' pypy3 '#!/usr/bin/pypy3' + +# python2/python3 matching +test_fix_shebang '#!/usr/bin/python2' python2.7 '#!/usr/bin/python2.7' +test_fix_shebang '#!/usr/bin/python3' python2.7 FAIL +test_fix_shebang '#!/usr/bin/python3' python2.7 '#!/usr/bin/python2.7' --force +test_fix_shebang '#!/usr/bin/python3' python3.6 '#!/usr/bin/python3.6' +test_fix_shebang '#!/usr/bin/python2' python3.6 FAIL +test_fix_shebang '#!/usr/bin/python2' python3.6 '#!/usr/bin/python3.6' --force + +# pythonX.Y matching (those mostly test the patterns) +test_fix_shebang '#!/usr/bin/python2.7' python2.7 '#!/usr/bin/python2.7' +test_fix_shebang '#!/usr/bin/python2.7' python3.2 FAIL +test_fix_shebang '#!/usr/bin/python2.7' python3.2 '#!/usr/bin/python3.2' --force +test_fix_shebang '#!/usr/bin/python3.2' python3.2 '#!/usr/bin/python3.2' +test_fix_shebang '#!/usr/bin/python3.2' python2.7 FAIL +test_fix_shebang '#!/usr/bin/python3.2' python2.7 '#!/usr/bin/python2.7' --force +test_fix_shebang '#!/usr/bin/pypy' python2.7 FAIL +test_fix_shebang '#!/usr/bin/pypy' python2.7 '#!/usr/bin/python2.7' --force + +# fancy path handling +test_fix_shebang '#!/mnt/python2/usr/bin/python' python3.6 \ + '#!/mnt/python2/usr/bin/python3.6' +test_fix_shebang '#!/mnt/python2/usr/bin/python2' python2.7 \ + '#!/mnt/python2/usr/bin/python2.7' +test_fix_shebang '#!/mnt/python2/usr/bin/env python' python2.7 \ + '#!/mnt/python2/usr/bin/env python2.7' +test_fix_shebang '#!/mnt/python2/usr/bin/python2 python2' python2.7 \ + '#!/mnt/python2/usr/bin/python2.7 python2' +test_fix_shebang '#!/mnt/python2/usr/bin/python3 python2' python2.7 FAIL +test_fix_shebang '#!/mnt/python2/usr/bin/python3 python2' python2.7 \ + '#!/mnt/python2/usr/bin/python2.7 python2' --force +test_fix_shebang '#!/usr/bin/foo' python2.7 FAIL + +# regression test for bug #522080 +test_fix_shebang '#!/usr/bin/python ' python2.7 '#!/usr/bin/python2.7 ' + +# check _python_impl_matches behavior +test_is "_python_impl_matches python2_7 -2" 0 +test_is "_python_impl_matches python3_6 -2" 1 +test_is "_python_impl_matches python3_7 -2" 1 +test_is "_python_impl_matches pypy3 -2" 1 +test_is "_python_impl_matches python2_7 -3" 1 +test_is "_python_impl_matches python3_6 -3" 0 +test_is "_python_impl_matches python3_7 -3" 0 +test_is "_python_impl_matches pypy3 -3" 0 +test_is "_python_impl_matches python2_7 -2 python3_6" 0 +test_is "_python_impl_matches python3_6 -2 python3_6" 0 +test_is "_python_impl_matches python3_7 -2 python3_6" 1 +test_is "_python_impl_matches pypy3 -2 python3_6" 1 +test_is "_python_impl_matches python2_7 pypy3 -2 python3_6" 0 +test_is "_python_impl_matches python3_6 pypy3 -2 python3_6" 0 +test_is "_python_impl_matches python3_7 pypy3 -2 python3_6" 1 +test_is "_python_impl_matches pypy3 pypy3 -2 python3_6" 0 +set -f +test_is "_python_impl_matches python2_7 pypy*" 1 +test_is "_python_impl_matches python3_6 pypy*" 1 +test_is "_python_impl_matches python3_7 pypy*" 1 +test_is "_python_impl_matches pypy3 pypy*" 0 +test_is "_python_impl_matches python2_7 python*" 0 +test_is "_python_impl_matches python3_6 python*" 0 +test_is "_python_impl_matches python3_7 python*" 0 +test_is "_python_impl_matches pypy3 python*" 1 +set +f + +rm "${tmpfile}" + +texit diff --git a/eclass/tests/rebar_fix_include_path.sh b/eclass/tests/rebar_fix_include_path.sh new file mode 100755 index 0000000..8164e39 --- /dev/null +++ b/eclass/tests/rebar_fix_include_path.sh @@ -0,0 +1,181 @@ +#!/bin/bash +# Copyright 1999-2016 Gentoo Foundation +# Distributed under the terms of the GNU General Public License v2 + +source tests-common.sh + +EAPI=6 + +inherit rebar + +EPREFIX="${tmpdir}/fakeroot" +S="${WORKDIR}/${P}" + +setup() { + mkdir -p "${S}" || die + + for pkg in foo-0.1.0 bar-0.1.0; do + mkdir -p "${EPREFIX}$(get_erl_libs)/${pkg}/include" || die + done + + cat <<EOF >"${S}/typical.config" || die +%%% Comment + +{erl_opts, [debug_info, {src_dirs, ["src"]}, + {i, "include"}, + {i, "deps/foo/include"}, + {i, "../foo/include"}]}. + +{port_env, [{"CFLAGS", "\$CFLAGS"}, {"LDFLAGS", "\$LDFLAGS"}]}. +EOF + + cat <<EOF >"${S}/typical.config.expected" || die +%%% Comment + +{erl_opts, [debug_info, {src_dirs, ["src"]}, + {i, "include"}, + {i, "${EPREFIX}$(get_erl_libs)/foo-0.1.0/include"}, + {i, "../foo/include"}]}. + +{port_env, [{"CFLAGS", "\$CFLAGS"}, {"LDFLAGS", "\$LDFLAGS"}]}. +EOF + + cat <<EOF >"${S}/inc_one_line.config" || die +%%% Comment + +{erl_opts, [debug_info, {src_dirs, ["src"]}, {i, "include"}, {i, "deps/foo/include"}, {i, "../foo/include"}]}. + +{port_env, [{"CFLAGS", "\$CFLAGS"}, {"LDFLAGS", "\$LDFLAGS"}]}. +EOF + + cat <<EOF >"${S}/inc_one_line.config.expected" || die +%%% Comment + +{erl_opts, [debug_info, {src_dirs, ["src"]}, {i, "include"}, {i, "${EPREFIX}$(get_erl_libs)/foo-0.1.0/include"}, {i, "../foo/include"}]}. + +{port_env, [{"CFLAGS", "\$CFLAGS"}, {"LDFLAGS", "\$LDFLAGS"}]}. +EOF +} + +test_typical_config() { + local diff_rc + local unit_rc + + # Prepare + cd "${S}" || die + cp typical.config rebar.config || die + + # Run unit + (rebar_fix_include_path foo) + unit_rc=$? + + # Test result + diff rebar.config typical.config.expected + diff_rc=$? + + [[ ${unit_rc}${diff_rc} = 00 ]] +} + +test_typical_config_with_different_name() { + local diff_rc + local unit_rc + + # Prepare + cd "${S}" || die + cp typical.config other.config || die + + # Run unit + (rebar_fix_include_path foo other.config) + unit_rc=$? + + # Test result + diff other.config typical.config.expected + diff_rc=$? + + [[ ${unit_rc}${diff_rc} = 00 ]] +} + +test_multiple_versions() { + local diff_rc + local unit_rc + + # Prepare + cd "${S}" || die + cp typical.config rebar.config || die + mkdir -p "${EPREFIX}$(get_erl_libs)/foo-1.0.0/include" || die + + # Run unit + (rebar_fix_include_path foo 2>/dev/null) + unit_rc=$? + + # Test result + diff rebar.config typical.config + diff_rc=$? + + # Clean up + rm -r "${EPREFIX}$(get_erl_libs)/foo-1.0.0" || die + + [[ ${unit_rc}${diff_rc} = 10 ]] +} + +test_not_found() { + local diff_rc + local unit_rc + + # Prepare + cd "${S}" || die + cp typical.config rebar.config || die + + # Run unit + (rebar_fix_include_path fo 2>/dev/null) + unit_rc=$? + + # Test result + diff rebar.config typical.config + diff_rc=$? + + [[ ${unit_rc}${diff_rc} = 10 ]] +} + +test_includes_in_one_line() { + local diff_rc + local unit_rc + + # Prepare + cd "${S}" || die + cp inc_one_line.config rebar.config || die + + # Run unit + (rebar_fix_include_path foo) + unit_rc=$? + + # Test result + diff rebar.config inc_one_line.config.expected + diff_rc=$? + + [[ ${unit_rc}${diff_rc} = 00 ]] +} + +setup + +tbegin "rebar_fix_include_path deals with typical config" +test_typical_config +tend $? + +tbegin "rebar_fix_include_path deals with typical config with different name" +test_typical_config_with_different_name +tend $? + +tbegin "rebar_fix_include_path fails on multiple versions of dependency" +test_multiple_versions +tend $? + +tbegin "rebar_fix_include_path fails if dependency is not found" +test_not_found +tend $? + +tbegin "rebar_fix_include_path deals with all includes in one line" +test_includes_in_one_line +tend $? + +texit diff --git a/eclass/tests/rebar_remove_deps.sh b/eclass/tests/rebar_remove_deps.sh new file mode 100755 index 0000000..1b877b3 --- /dev/null +++ b/eclass/tests/rebar_remove_deps.sh @@ -0,0 +1,121 @@ +#!/bin/bash +# Copyright 1999-2016 Gentoo Foundation +# Distributed under the terms of the GNU General Public License v2 + +source tests-common.sh + +EAPI=6 + +inherit rebar + +EPREFIX="${tmpdir}/fakeroot" +S="${WORKDIR}/${P}" + +setup() { + mkdir -p "${S}" || die + + cat <<EOF >"${S}/rebar.config.expected" || die +%%% Comment + +{port_specs, [{"priv/lib/esip_drv.so", ["c_src/esip_codec.c"]}]}. + +{deps, []}. + +{clean_files, ["c_src/esip_codec.gcda", "c_src/esip_codec.gcno"]}. +EOF + + cat <<EOF >"${S}/typical.config" || die +%%% Comment + +{port_specs, [{"priv/lib/esip_drv.so", ["c_src/esip_codec.c"]}]}. + +{deps, [{stun, ".*", {git, "https://github.com/processone/stun", {tag, "1.0.3"}}}, + {fast_tls, ".*", {git, "https://github.com/processone/fast_tls", {tag, "1.0.3"}}}, + {p1_utils, ".*", {git, "https://github.com/processone/p1_utils", {tag, "1.0.3"}}}]}. + +{clean_files, ["c_src/esip_codec.gcda", "c_src/esip_codec.gcno"]}. +EOF + + cat <<EOF >"${S}/deps_one_line.config" || die +%%% Comment + +{port_specs, [{"priv/lib/esip_drv.so", ["c_src/esip_codec.c"]}]}. + +{deps, [{stun, ".*", {git, "https://github.com/processone/stun", {tag, "1.0.3"}}}, {fast_tls, ".*", {git, "https://github.com/processone/fast_tls", {tag, "1.0.3"}}}, {p1_utils, ".*", {git, "https://github.com/processone/p1_utils", {tag, "1.0.3"}}}]}. + +{clean_files, ["c_src/esip_codec.gcda", "c_src/esip_codec.gcno"]}. +EOF +} + +test_typical_config() { + local diff_rc + local unit_rc + + # Prepare + cd "${S}" || die + cp typical.config rebar.config || die + + # Run unit + (rebar_remove_deps) + unit_rc=$? + + # Test result + diff rebar.config rebar.config.expected + diff_rc=$? + + [[ ${unit_rc}${diff_rc} = 00 ]] +} + +test_typical_config_with_different_name() { + local diff_rc + local unit_rc + + # Prepare + cd "${S}" || die + cp typical.config other.config || die + + # Run unit + (rebar_remove_deps other.config) + unit_rc=$? + + # Test result + diff other.config rebar.config.expected + diff_rc=$? + + [[ ${unit_rc}${diff_rc} = 00 ]] +} + +test_deps_in_one_line() { + local diff_rc + local unit_rc + + # Prepare + cd "${S}" || die + cp deps_one_line.config rebar.config || die + + # Run unit + (rebar_remove_deps) + unit_rc=$? + + # Test result + diff rebar.config rebar.config.expected + diff_rc=$? + + [[ ${unit_rc}${diff_rc} = 00 ]] +} + +setup + +tbegin "rebar_remove_deps deals with typical config" +test_typical_config +tend $? + +tbegin "rebar_remove_deps deals with typical config with different name" +test_typical_config_with_different_name +tend $? + +tbegin "rebar_remove_deps deals with all deps in one line" +test_deps_in_one_line +tend $? + +texit diff --git a/eclass/tests/rebar_set_vsn.sh b/eclass/tests/rebar_set_vsn.sh new file mode 100755 index 0000000..315d8a7 --- /dev/null +++ b/eclass/tests/rebar_set_vsn.sh @@ -0,0 +1,114 @@ +#!/bin/bash +# Copyright 1999-2016 Gentoo Foundation +# Distributed under the terms of the GNU General Public License v2 + +source tests-common.sh + +EAPI=6 + +inherit rebar + +EPREFIX="${tmpdir}/fakeroot" +S="${WORKDIR}/${P}" + +setup() { + mkdir -p "${S}/src" || die + + cat <<EOF >"${S}/app.src.expected" || die +%%% Comment + +{application, esip, + [{description, "ProcessOne SIP server component in Erlang"}, + {vsn, "0"}, + {modules, []}, + {registered, []}, +EOF + + cat <<EOF >"${S}/app.src" || die +%%% Comment + +{application, esip, + [{description, "ProcessOne SIP server component in Erlang"}, + {vsn, git}, + {modules, []}, + {registered, []}, +EOF +} + +test_typical_app_src() { + local diff_rc + local unit_rc + + # Prepare + cd "${S}" || die + cp app.src "src/${PN}.app.src" || die + + # Run unit + (rebar_set_vsn) + unit_rc=$? + + # Test result + diff "src/${PN}.app.src" app.src.expected + diff_rc=$? + + [[ ${unit_rc}${diff_rc} = 00 ]] +} + +test_app_src_missing() { + local unit_rc + + # Prepare + cd "${S}" || die + rm -f "src/${PN}.app.src" || die + + # Run unit + (rebar_set_vsn 2>/dev/null) + unit_rc=$? + + [[ ${unit_rc} = 1 ]] +} + +test_set_custom_version() { + local diff_rc + local unit_rc + + # Prepare + cd "${S}" || die + cp app.src "src/${PN}.app.src" || die + cat <<EOF >"${S}/custom_app.src.expected" || die +%%% Comment + +{application, esip, + [{description, "ProcessOne SIP server component in Erlang"}, + {vsn, "1.2.3"}, + {modules, []}, + {registered, []}, +EOF + + # Run unit + (rebar_set_vsn 1.2.3) + unit_rc=$? + + # Test result + diff "src/${PN}.app.src" custom_app.src.expected + diff_rc=$? + + [[ ${unit_rc}${diff_rc} = 00 ]] +} + + +setup + +tbegin "rebar_set_vsn deals with typical app.src" +test_typical_app_src +tend $? + +tbegin "rebar_set_vsn fails when app.src is missing" +test_app_src_missing +tend $? + +tbegin "rebar_set_vsn sets custom version in app.src" +test_set_custom_version +tend $? + +texit diff --git a/eclass/tests/savedconfig.sh b/eclass/tests/savedconfig.sh new file mode 100755 index 0000000..7643cf4 --- /dev/null +++ b/eclass/tests/savedconfig.sh @@ -0,0 +1,80 @@ +#!/bin/bash +# Copyright 1999-2019 Gentoo Authors +# Distributed under the terms of the GNU General Public License v2 + +EAPI=7 + +source tests-common.sh + +inherit savedconfig + +quiet() { + local out ret + out=$("$@" 2>&1) + ret=$? + [[ ${ret} -eq 0 ]] || echo "${out}" + return ${ret} +} +sc() { EBUILD_PHASE=install quiet save_config "$@" ; } +rc() { EBUILD_PHASE=prepare quiet restore_config "$@" ; } + +cleanup() { rm -rf "${ED}"/* "${T}"/* "${WORKDIR}"/* ; } +test-it() { + local ret=0 + tbegin "$@" + mkdir -p "${ED}"/etc/portage/savedconfig + : $(( ret |= $? )) + pushd "${WORKDIR}" >/dev/null + : $(( ret |= $? )) + test + : $(( ret |= $? )) + popd >/dev/null + : $(( ret |= $? )) + tend ${ret} + cleanup +} + +test() { + touch f || return 1 + sc f || return 1 + [[ -f ${ED}/etc/portage/savedconfig/${CATEGORY}/${PF} ]] +} +test-it "simple save_config" + +test() { + touch a b c || return 1 + sc a b c || return 1 + [[ -d ${ED}/etc/portage/savedconfig/${CATEGORY}/${PF} ]] +} +test-it "multi save_config" + +test() { + mkdir dir || return 1 + touch dir/{a,b,c} || return 1 + sc dir || return 1 + [[ -d ${ED}/etc/portage/savedconfig/${CATEGORY}/${PF} ]] +} +test-it "dir save_config" + +PORTAGE_CONFIGROOT=${D} + +test() { + echo "ggg" > f || return 1 + rc f || return 1 + [[ $(<f) == "ggg" ]] +} +test-it "simple restore_config" + +test() { + echo "ggg" > f || return 1 + rc f || return 1 + [[ $(<f) == "ggg" ]] || return 1 + sc f || return 1 + + echo "hhh" > f || return 1 + rc f || return 1 + [[ $(<f) == "ggg" ]] +} +test-it "simple restore+save config" + +texit diff --git a/eclass/tests/scons-utils.sh b/eclass/tests/scons-utils.sh new file mode 100755 index 0000000..873312f --- /dev/null +++ b/eclass/tests/scons-utils.sh @@ -0,0 +1,62 @@ +#!/bin/bash +# Copyright 1999-2019 Gentoo Authors +# Distributed under the terms of the GNU General Public License v2 + +source tests-common.sh + +inherit scons-utils + +test-scons_clean_makeopts() { + tbegin "scons_clean_makeopts() for ${1}" + + local SCONSOPTS ret=0 + _scons_clean_makeopts ${1} + + if [[ ${SCONSOPTS} != ${2-${1}} ]]; then + eerror "Self-test failed:" + eindent + eerror "MAKEOPTS: ${1}" + eerror "Expected: ${2-${1}}" + eerror "Actual: ${SCONSOPTS}" + eoutdent + ret=1 + fi + + tend ${ret} + return ${ret} +} + +# jobcount expected for non-specified state +jc=$(( $(get_nproc) + 1 )) +# failed test counter +failed=0 + +# sane MAKEOPTS +test-scons_clean_makeopts '--jobs=14 -k' +test-scons_clean_makeopts '--jobs=14 -k' +test-scons_clean_makeopts '--jobs 15 -k' +test-scons_clean_makeopts '--jobs=16 --keep-going' +test-scons_clean_makeopts '-j17 --keep-going' +test-scons_clean_makeopts '-j 18 --keep-going' + +# needing cleaning +test-scons_clean_makeopts '--jobs -k' "--jobs=${jc} -k" +test-scons_clean_makeopts '--jobs --keep-going' "--jobs=${jc} --keep-going" +test-scons_clean_makeopts '-kj' "-kj ${jc}" + +# broken by definition (but passed as it breaks make as well) +test-scons_clean_makeopts '-jk' +test-scons_clean_makeopts '--jobs=randum' +test-scons_clean_makeopts '-kjrandum' + +# needing stripping +test-scons_clean_makeopts '--load-average=25 -kj16' '-kj16' +test-scons_clean_makeopts '--load-average 25 -k -j17' '-k -j17' +test-scons_clean_makeopts '-j2 HOME=/tmp' '-j2' +test-scons_clean_makeopts '--jobs funnystuff -k' "--jobs=${jc} -k" + +# bug #388961 +test-scons_clean_makeopts '--jobs -l3' "--jobs=${jc}" +test-scons_clean_makeopts '-j -l3' "-j ${jc}" + +texit diff --git a/eclass/tests/tests-common.sh b/eclass/tests/tests-common.sh new file mode 100644 index 0000000..2fc849c --- /dev/null +++ b/eclass/tests/tests-common.sh @@ -0,0 +1,107 @@ +#!/bin/bash +# Copyright 1999-2019 Gentoo Authors +# Distributed under the terms of the GNU General Public License v2 + +if ! source /lib/gentoo/functions.sh ; then + echo "Missing functions.sh. Please install sys-apps/gentoo-functions!" 1>&2 + exit 1 +fi + +# Let overlays override this so they can add their own testsuites. +TESTS_ECLASS_SEARCH_PATHS=( .. ) + +inherit() { + local e path + for e in "$@" ; do + for path in "${TESTS_ECLASS_SEARCH_PATHS[@]}" ; do + local eclass=${path}/${e}.eclass + if [[ -e "${eclass}" ]] ; then + source "${eclass}" + continue 2 + fi + done + die "could not find ${e}.eclass" + done +} +EXPORT_FUNCTIONS() { :; } + +debug-print() { + [[ ${#} -eq 0 ]] && return + + if [[ ${ECLASS_DEBUG_OUTPUT} == on ]]; then + printf 'debug: %s\n' "${@}" >&2 + elif [[ -n ${ECLASS_DEBUG_OUTPUT} ]]; then + printf 'debug: %s\n' "${@}" >> "${ECLASS_DEBUG_OUTPUT}" + fi +} + +debug-print-function() { + debug-print "${1}, parameters: ${*:2}" +} + +debug-print-section() { + debug-print "now in section ${*}" +} + +has() { + local needle=$1 + shift + + local x + for x in "$@"; do + [ "${x}" = "${needle}" ] && return 0 + done + return 1 +} +use() { has "$1" ${IUSE} ; } + +die() { + echo "die: $*" 1>&2 + exit 1 +} + +has_version() { + portageq has_version / "$@" +} + +tret=0 +tbegin() { + ebegin "Testing $*" +} +texit() { + rm -rf "${tmpdir}" + exit ${tret} +} +tend() { + t eend "$@" +} +t() { + "$@" + local ret=$? + : $(( tret |= ${ret} )) + return ${ret} +} + +tmpdir="${PWD}/tmp" +pkg_root="${tmpdir}/$0/${RANDOM}" +T="${pkg_root}/temp" +D="${pkg_root}/image" +WORKDIR="${pkg_root}/work" +ED=${D} +mkdir -p "${D}" "${T}" "${WORKDIR}" + +dodir() { + mkdir -p "${@/#/${ED}/}" +} + +elog() { einfo "$@" ; } + +IUSE="" +CATEGORY="dev-eclass" +PN="tests" +PV="0" +P="${PN}-${PV}" +PF=${P} +SLOT=0 + +addwrite() { :; } diff --git a/eclass/tests/toolchain-funcs.sh b/eclass/tests/toolchain-funcs.sh new file mode 100755 index 0000000..23ac568 --- /dev/null +++ b/eclass/tests/toolchain-funcs.sh @@ -0,0 +1,200 @@ +#!/bin/bash +# Copyright 1999-2019 Gentoo Authors +# Distributed under the terms of the GNU General Public License v2 + +source tests-common.sh + +inherit toolchain-funcs + +# +# TEST: tc-arch-kernel +# +test-tc-arch-kernel() { + local ret=0 + KV=$1 ; shift + for CHOST in "$@" ; do + exp=${CHOST##*:} + CHOST=${CHOST%%:*} + actual=$(tc-arch-kernel) + + if [[ ${actual} != ${exp:-${CHOST}} ]] ; then + eerror "Failure for CHOST: ${CHOST} Expected: ${exp} != Actual: ${actual}" + ((++ret)) + fi + done + return ${ret} +} +tbegin "tc-arch-kernel() (KV=2.6.30)" +test-tc-arch-kernel 2.6.30 \ + i{3..6}86:x86 x86_64:x86 \ + powerpc{,64}:powerpc i{3..6}86-gentoo-freebsd:i386 \ + or1k:openrisc or1k-linux-musl:openrisc +tend $? + +# +# TEST: tc-arch +# +tbegin "tc-arch" +ret=0 +for CHOST in \ + alpha arm{,eb}:arm avr32:avr bfin cris hppa i{3..6}86:x86 ia64 m68k \ + mips{,eb}:mips nios2 powerpc:ppc powerpc64:ppc64 s390{,x}:s390 \ + sh{1..4}{,eb}:sh sparc{,64}:sparc vax x86_64:amd64 +do + exp=${CHOST##*:} + CHOST=${CHOST%%:*} + actual=$(tc-arch) + + if [[ ${actual} != ${exp:-${CHOST}} ]] ; then + eerror "Failure for CHOST: ${CHOST} Expected: ${exp} != Actual: ${actual}" + : $((++ret)) + fi +done +tend ${ret} + +# +# TEST: tc-ld-is-gold +# +tbegin "tc-ld-is-gold (ld=bfd cc=bfd)" +LD=ld.bfd LDFLAGS=-fuse-ld=bfd tc-ld-is-gold && ret=1 || ret=0 +tend ${ret} + +tbegin "tc-ld-is-gold (ld=gold cc=default)" +LD=ld.gold tc-ld-is-gold +ret=$? +tend ${ret} + +tbegin "tc-ld-is-gold (ld=gold cc=bfd)" +LD=ld.gold LDFLAGS=-fuse-ld=bfd tc-ld-is-gold +ret=$? +tend ${ret} + +tbegin "tc-ld-is-gold (ld=bfd cc=gold)" +LD=ld.bfd LDFLAGS=-fuse-ld=gold tc-ld-is-gold +ret=$? +tend ${ret} + +# +# TEST: tc-ld-disable-gold +# +tbegin "tc-ld-disable-gold (bfd selected)" +( +export LD=ld.bfd LDFLAGS=-fuse-ld=bfd +ewarn() { :; } +tc-ld-disable-gold +[[ ${LD} == "ld.bfd" && ${LDFLAGS} == "-fuse-ld=bfd" ]] +) +tend $? + +tbegin "tc-ld-disable-gold (ld=gold)" +( +export LD=ld.gold LDFLAGS= +ewarn() { :; } +tc-ld-disable-gold +[[ ${LD} == "ld.bfd" || ${LDFLAGS} == *"-fuse-ld=bfd"* ]] +) +tend $? + +tbegin "tc-ld-disable-gold (cc=gold)" +( +export LD= LDFLAGS="-fuse-ld=gold" +ewarn() { :; } +tc-ld-disable-gold +[[ ${LD} == *"/ld.bfd" || ${LDFLAGS} == "-fuse-ld=gold -fuse-ld=bfd" ]] +) +tend $? + +unset CPP + +tbegin "tc-get-compiler-type (gcc)" +( +export CC=gcc +[[ $(tc-get-compiler-type) == gcc ]] +) +tend $? + +tbegin "tc-is-gcc (gcc)" +( +export CC=gcc +tc-is-gcc +) +tend $? + +tbegin "! tc-is-clang (gcc)" +( +export CC=gcc +! tc-is-clang +) +tend $? + +if type -P clang &>/dev/null; then + tbegin "tc-get-compiler-type (clang)" + ( + export CC=clang + [[ $(tc-get-compiler-type) == clang ]] + ) + tend $? + + tbegin "! tc-is-gcc (clang)" + ( + export CC=clang + ! tc-is-gcc + ) + tend $? + + tbegin "tc-is-clang (clang)" + ( + export CC=clang + tc-is-clang + ) + tend $? +fi + +if type -P pathcc &>/dev/null; then + tbegin "tc-get-compiler-type (pathcc)" + ( + export CC=pathcc + [[ $(tc-get-compiler-type) == pathcc ]] + ) + tend $? + + tbegin "! tc-is-gcc (pathcc)" + ( + export CC=pathcc + ! tc-is-gcc + ) + tend $? + + tbegin "! tc-is-clang (pathcc)" + ( + export CC=pathcc + ! tc-is-clang + ) + tend $? +fi + +for compiler in gcc clang not-really-a-compiler; do + if type -P ${compiler} &>/dev/null; then + tbegin "tc-cpp-is-true ($compiler, defined)" + ( + export CC=${compiler} + tc-cpp-is-true "defined(SOME_DEFINED_SYMBOL)" -DSOME_DEFINED_SYMBOL + ) + tend $? + tbegin "tc-cpp-is-true ($compiler, not defined)" + ( + export CC=${compiler} + ! tc-cpp-is-true "defined(SOME_UNDEFINED_SYMBOL)" + ) + tend $? + + tbegin "tc-cpp-is-true ($compiler, defined on -ggdb3)" + ( + export CC=${compiler} + tc-cpp-is-true "defined(SOME_DEFINED_SYMBOL)" -DSOME_DEFINED_SYMBOL -ggdb3 + ) + tend $? + fi +done + +texit diff --git a/eclass/tests/toolchain.sh b/eclass/tests/toolchain.sh new file mode 100755 index 0000000..118d68c --- /dev/null +++ b/eclass/tests/toolchain.sh @@ -0,0 +1,185 @@ +#!/bin/bash +# Copyright 1999-2019 Gentoo Authors +# Distributed under the terms of the GNU General Public License v2 + +EAPI=5 + +# apply exlass globals to test version parsing +TOOLCHAIN_GCC_PV=7.3.0 +PR=r0 + +source tests-common.sh + +inherit toolchain + +# Ignore actually running version of gcc and fake new version +# to force downgrade test on all conditions below. +gcc-version() { + echo "99.99" +} + +test_downgrade_arch_flags() { + local exp msg ret=0 ver + + ver=${1} + exp=${2} + shift 2 + CFLAGS=${@} + + tbegin "downgrade_arch_flags: ${ver} ${CFLAGS} => ${exp}" + + CHOST=x86_64 # needed for tc-arch + downgrade_arch_flags ${ver} + + if [[ ${CFLAGS} != ${exp} ]]; then + msg="Failure - Expected: \"${exp}\" Got: \"${CFLAGS}\" Ver: ${ver}" + ret=1 + fi + tend ${ret} ${msg} +} + +# ver expected given +test_downgrade_arch_flags 10 "-march=haswell" "-march=haswell" +test_downgrade_arch_flags 4.9 "-march=haswell" "-march=haswell" +test_downgrade_arch_flags 4.8 "-march=core-avx2" "-march=haswell" +test_downgrade_arch_flags 4.7 "-march=core-avx2" "-march=haswell" +test_downgrade_arch_flags 4.6 "-march=core-avx-i" "-march=haswell" +test_downgrade_arch_flags 4.5 "-march=core2" "-march=haswell" +test_downgrade_arch_flags 4.4 "-march=core2" "-march=haswell" +test_downgrade_arch_flags 4.3 "-march=core2" "-march=haswell" +test_downgrade_arch_flags 4.2 "-march=nocona" "-march=haswell" +test_downgrade_arch_flags 4.1 "-march=nocona" "-march=haswell" +test_downgrade_arch_flags 4.0 "-march=nocona" "-march=haswell" +test_downgrade_arch_flags 3.4 "-march=nocona" "-march=haswell" +test_downgrade_arch_flags 3.3 "-march=nocona" "-march=haswell" + +test_downgrade_arch_flags 4.9 "-march=bdver4" "-march=bdver4" +test_downgrade_arch_flags 4.8 "-march=bdver3" "-march=bdver4" +test_downgrade_arch_flags 4.7 "-march=bdver2" "-march=bdver4" +test_downgrade_arch_flags 4.6 "-march=bdver1" "-march=bdver4" +test_downgrade_arch_flags 4.5 "-march=amdfam10" "-march=bdver4" +test_downgrade_arch_flags 4.4 "-march=amdfam10" "-march=bdver4" +test_downgrade_arch_flags 4.3 "-march=amdfam10" "-march=bdver4" +test_downgrade_arch_flags 4.2 "-march=k8" "-march=bdver4" +test_downgrade_arch_flags 4.1 "-march=k8" "-march=bdver4" +test_downgrade_arch_flags 4.0 "-march=k8" "-march=bdver4" +test_downgrade_arch_flags 3.4 "-march=k8" "-march=bdver4" +test_downgrade_arch_flags 3.3 "-march=x86-64" "-march=bdver4" + +test_downgrade_arch_flags 3.4 "-march=c3-2" "-march=c3-2" +test_downgrade_arch_flags 3.3 "-march=c3" "-march=c3-2" + +test_downgrade_arch_flags 4.5 "-march=garbage" "-march=garbage" + +test_downgrade_arch_flags 10 "-mtune=intel" "-mtune=intel" +test_downgrade_arch_flags 4.9 "-mtune=intel" "-mtune=intel" +test_downgrade_arch_flags 4.8 "-mtune=generic" "-mtune=intel" +test_downgrade_arch_flags 3.4 "" "-mtune=generic" +test_downgrade_arch_flags 3.4 "" "-mtune=x86-64" +test_downgrade_arch_flags 3.3 "" "-mtune=anything" + +test_downgrade_arch_flags 4.5 "-march=amdfam10 -mtune=generic" "-march=btver2 -mtune=generic" +test_downgrade_arch_flags 3.3 "-march=k6-2" "-march=geode -mtune=barcelona" +test_downgrade_arch_flags 3.4 "-march=k8" "-march=btver2 -mtune=generic" + +test_downgrade_arch_flags 10 "-march=native" "-march=native" +test_downgrade_arch_flags 8 "-march=znver1" "-march=znver2" +test_downgrade_arch_flags 4.2 "-march=native" "-march=native" +test_downgrade_arch_flags 4.1 "-march=nocona" "-march=native" + +test_downgrade_arch_flags 10 "-march=foo -mno-sha -mno-rtm -mno-avx2 -mno-avx -mno-sse4.1" "-march=foo -mno-sha -mno-rtm -mno-avx2 -mno-avx -mno-sse4.1" +test_downgrade_arch_flags 4.9 "-march=foo -mno-sha -mno-rtm -mno-avx2 -mno-avx -mno-sse4.1" "-march=foo -mno-sha -mno-rtm -mno-avx2 -mno-avx -mno-sse4.1" +test_downgrade_arch_flags 4.8 "-march=foo -mno-rtm -mno-avx2 -mno-avx -mno-sse4.1" "-march=foo -mno-sha -mno-rtm -mno-avx2 -mno-avx -mno-sse4.1" +test_downgrade_arch_flags 4.7 "-march=foo -mno-avx2 -mno-avx -mno-sse4.1" "-march=foo -mno-sha -mno-rtm -mno-avx2 -mno-avx -mno-sse4.1" +test_downgrade_arch_flags 4.6 "-march=foo -mno-avx -mno-sse4.1" "-march=foo -mno-sha -mno-rtm -mno-avx2 -mno-avx -mno-sse4.1" +test_downgrade_arch_flags 4.3 "-march=foo -mno-sse4.1" "-march=foo -mno-sha -mno-rtm -mno-avx2 -mno-avx -mno-sse4.1" +test_downgrade_arch_flags 4.2 "-march=foo" "-march=foo -mno-sha -mno-rtm -mno-avx2 -mno-avx -mno-sse4.1" + +test_downgrade_arch_flags 4.4 "-O2 -march=core2 -ffoo -fblah" "-O2 -march=atom -mno-sha -ffoo -mno-rtm -fblah" + +# basic version parsing tests in preparation to eapi7-ver switch + +test_tc_version_is_at_least() { + local exp msg ret=0 want mine res + + want=${1} + mine=${2} + exp=${3} + + tbegin "tc_version_is_at_least: ${want} ${mine} => ${exp}" + + tc_version_is_at_least ${want} ${mine} + res=$? + + if [[ ${res} -ne ${exp} ]]; then + msg="Failure - Expected: \"${exp}\" Got: \"${res}\"" + ret=1 + fi + tend ${ret} ${msg} +} + +# want mine expect +test_tc_version_is_at_least 8 '' 1 +test_tc_version_is_at_least 8.0 '' 1 +test_tc_version_is_at_least 7 '' 0 +test_tc_version_is_at_least 7.0 '' 0 +test_tc_version_is_at_least ${TOOLCHAIN_GCC_PV} '' 0 +test_tc_version_is_at_least 5.0 6.0 0 + +test_tc_version_is_between() { + local exp msg ret=0 lo hi res + + lo=${1} + hi=${2} + exp=${3} + + tbegin "tc_version_is_between: ${lo} ${hi} => ${exp}" + + tc_version_is_between ${lo} ${hi} + res=$? + + if [[ ${res} -ne ${exp} ]]; then + msg="Failure - Expected: \"${exp}\" Got: \"${res}\"" + ret=1 + fi + tend ${ret} ${msg} +} + +# lo hi expect +test_tc_version_is_between 1 0 1 +test_tc_version_is_between 1 2 1 +test_tc_version_is_between 7 8 0 +test_tc_version_is_between ${TOOLCHAIN_GCC_PV} 8 0 +test_tc_version_is_between ${TOOLCHAIN_GCC_PV} ${TOOLCHAIN_GCC_PV} 1 +test_tc_version_is_between 7 ${TOOLCHAIN_GCC_PV} 1 +test_tc_version_is_between 8 9 1 + +# eclass has a few critical global variables worth not breaking +test_var_assert() { + local var_name exp + + var_name=${1} + exp=${2} + + tbegin "assert variable value: ${var_name} => ${exp}" + + if [[ ${!var_name} != ${exp} ]]; then + msg="Failure - Expected: \"${exp}\" Got: \"${!var_name}\"" + ret=1 + fi + tend ${ret} ${msg} +} + +# TODO: convert these globals to helpers to ease testing against multiple +# ${TOOLCHAIN_GCC_PV} vaues. +test_var_assert GCC_PV 7.3.0 +test_var_assert GCC_PVR 7.3.0 +test_var_assert GCC_RELEASE_VER 7.3.0 +test_var_assert GCC_BRANCH_VER 7.3 +test_var_assert GCCMAJOR 7 +test_var_assert GCCMINOR 3 +test_var_assert GCCMICRO 0 +test_var_assert GCC_CONFIG_VER 7.3.0 +test_var_assert PREFIX /usr + +texit diff --git a/eclass/tests/versionator_version_compare.sh b/eclass/tests/versionator_version_compare.sh new file mode 100755 index 0000000..c7a238c --- /dev/null +++ b/eclass/tests/versionator_version_compare.sh @@ -0,0 +1,199 @@ +#!/bin/bash +# Copyright 1999-2015 Gentoo Foundation +# Distributed under the terms of the GNU General Public License v2 + +source tests-common.sh + +inherit versionator + +eshopts_push -s extglob +ver=( "" "lt" "eq" "gt" ) +lt=1 eq=2 gt=3 + +test_version_compare() { + tbegin "version_compare ${1} -${ver[${2}]} ${3}" + version_compare "${1}" "${3}" + local r=$? + [[ ${r} -eq ${2} ]] + tend $? "FAIL: ${@} (got ${r} exp ${2})" +} + +echo " + 0 $lt 1 + 1 $lt 2 + 2 $gt 1 + 2 $eq 2 + 0 $eq 0 + 10 $lt 20 + 68 $eq 068 + 068 $gt 67 + 068 $lt 69 + + 1.0 $lt 2.0 + 2.0 $eq 2.0 + 2.0 $gt 1.0 + + 1.0 $gt 0.0 + 0.0 $eq 0.0 + 0.0 $lt 1.0 + + 0.1 $lt 0.2 + 0.2 $eq 0.2 + 0.3 $gt 0.2 + + 1.2 $lt 2.1 + 2.1 $gt 1.2 + + 1.2.3 $lt 1.2.4 + 1.2.4 $gt 1.2.3 + + 1.2.0 $gt 1.2 + 1.2.1 $gt 1.2 + 1.2 $lt 1.2.1 + + 1.2b $eq 1.2b + 1.2b $lt 1.2c + 1.2b $gt 1.2a + 1.2b $gt 1.2 + 1.2 $lt 1.2a + + 1.3 $gt 1.2a + 1.3 $lt 1.3a + + 1.0_alpha7 $lt 1.0_beta7 + 1.0_beta $lt 1.0_pre + 1.0_pre5 $lt 1.0_rc2 + 1.0_rc2 $lt 1.0 + + 1.0_p1 $gt 1.0 + 1.0_p1-r1 $gt 1.0_p1 + + 1.0_alpha6-r1 $gt 1.0_alpha6 + 1.0_beta6-r1 $gt 1.0_alpha6-r2 + + 1.0_pre1 $lt 1.0_p1 + + 1.0p $gt 1.0_p1 + 1.0r $gt 1.0-r1 + 1.6.15 $gt 1.6.10-r2 + 1.6.10-r2 $lt 1.6.15 + +" | while read a b c ; do + [[ -z "${a}${b}${c}" ]] && continue + test_version_compare "${a}" "${b}" "${c}" +done + + +for q in "alpha beta pre rc=${lt};${gt}" "p=${gt};${lt}" ; do + for p in ${q%%=*} ; do + c=${q##*=} + alt=${c%%;*} agt=${c##*;} + test_version_compare "1.0" $agt "1.0_${p}" + test_version_compare "1.0" $agt "1.0_${p}1" + test_version_compare "1.0" $agt "1.0_${p}068" + + test_version_compare "2.0_${p}" $alt "2.0" + test_version_compare "2.0_${p}1" $alt "2.0" + test_version_compare "2.0_${p}068" $alt "2.0" + + test_version_compare "1.0_${p}" $eq "1.0_${p}" + test_version_compare "0.0_${p}" $lt "0.0_${p}1" + test_version_compare "666_${p}3" $gt "666_${p}" + + test_version_compare "1_${p}7" $lt "1_${p}8" + test_version_compare "1_${p}7" $eq "1_${p}7" + test_version_compare "1_${p}7" $gt "1_${p}6" + test_version_compare "1_${p}09" $eq "1_${p}9" + + test_version_compare "1_${p}7-r0" $eq "1_${p}7" + test_version_compare "1_${p}7-r0" $lt "1_${p}7-r1" + test_version_compare "1_${p}7-r0" $lt "1_${p}7-r01" + test_version_compare "1_${p}7-r01" $eq "1_${p}7-r1" + test_version_compare "1_${p}8-r1" $gt "1_${p}7-r100" + + test_version_compare "1_${p}_alpha" $lt "1_${p}_beta" + done +done + +for p in "-r" "_p" ; do + test_version_compare "7.2${p}1" $lt "7.2${p}2" + test_version_compare "7.2${p}2" $gt "7.2${p}1" + test_version_compare "7.2${p}3" $gt "7.2${p}2" + test_version_compare "7.2${p}2" $lt "7.2${p}3" +done + +# The following tests all come from portage's test cases: +test_version_compare "6.0" $gt "5.0" +test_version_compare "5.0" $gt "5" +test_version_compare "1.0-r1" $gt "1.0-r0" +test_version_compare "1.0-r1" $gt "1.0" +test_version_compare "999999999999999999999999999999" $gt "999999999999999999999999999998" +test_version_compare "1.0.0" $gt "1.0" +test_version_compare "1.0.0" $gt "1.0b" +test_version_compare "1b" $gt "1" +test_version_compare "1b_p1" $gt "1_p1" +test_version_compare "1.1b" $gt "1.1" +test_version_compare "12.2.5" $gt "12.2b" + +test_version_compare "4.0" $lt "5.0" +test_version_compare "5" $lt "5.0" +test_version_compare "1.0_pre2" $lt "1.0_p2" +test_version_compare "1.0_alpha2" $lt "1.0_p2" +test_version_compare "1.0_alpha1" $lt "1.0_beta1" +test_version_compare "1.0_beta3" $lt "1.0_rc3" +test_version_compare "1.001000000000000000001" $lt "1.001000000000000000002" +test_version_compare "1.00100000000" $lt "1.0010000000000000001" +test_version_compare "999999999999999999999999999998" $lt "999999999999999999999999999999" +test_version_compare "1.01" $lt "1.1" +test_version_compare "1.0-r0" $lt "1.0-r1" +test_version_compare "1.0" $lt "1.0-r1" +test_version_compare "1.0" $lt "1.0.0" +test_version_compare "1.0b" $lt "1.0.0" +test_version_compare "1_p1" $lt "1b_p1" +test_version_compare "1" $lt "1b" +test_version_compare "1.1" $lt "1.1b" +test_version_compare "12.2b" $lt "12.2.5" + +test_version_compare "4.0" $eq "4.0" +test_version_compare "1.0" $eq "1.0" +test_version_compare "1.0-r0" $eq "1.0" +test_version_compare "1.0" $eq "1.0-r0" +test_version_compare "1.0-r0" $eq "1.0-r0" +test_version_compare "1.0-r1" $eq "1.0-r1" + +# The following were just tests for != in portage, we need something a bit +# more precise +test_version_compare "1" $lt "2" +test_version_compare "1.0_alpha" $lt "1.0_pre" +test_version_compare "1.0_beta" $gt "1.0_alpha" +test_version_compare "0" $lt "0.0" +test_version_compare "1.0-r0" $lt "1.0-r1" +test_version_compare "1.0-r1" $gt "1.0-r0" +test_version_compare "1.0" $lt "1.0-r1" +test_version_compare "1.0-r1" $gt "1.0" +test_version_compare "1_p1" $lt "1b_p1" +test_version_compare "1b" $gt "1" +test_version_compare "1.1b" $gt "1.1" +test_version_compare "12.2b" $gt "12.2" + +# The following tests all come from paludis's test cases: +test_version_compare "1.0" $gt "1" +test_version_compare "1" $lt "1.0" +test_version_compare "1.0_alpha" $gt "1_alpha" +test_version_compare "1.0_alpha" $gt "1" +test_version_compare "1.0_alpha" $lt "1.0" +test_version_compare "1.2.0.0_alpha7-r4" $gt "1.2_alpha7-r4" + +test_version_compare "0001" $eq "1" +test_version_compare "01" $eq "001" +test_version_compare "0001.1" $eq "1.1" +test_version_compare "01.01" $eq "1.01" +test_version_compare "1.010" $eq "1.01" +test_version_compare "1.00" $eq "1.0" +test_version_compare "1.0100" $eq "1.010" +test_version_compare "1" $eq "1-r0" +test_version_compare "1-r00" $eq "1-r0" + +eshopts_pop + +texit diff --git a/eclass/texlive-common.eclass b/eclass/texlive-common.eclass new file mode 100644 index 0000000..1fe3344 --- /dev/null +++ b/eclass/texlive-common.eclass @@ -0,0 +1,177 @@ +# Copyright 1999-2020 Gentoo Authors +# Distributed under the terms of the GNU General Public License v2 + +# @ECLASS: texlive-common.eclass +# @MAINTAINER: +# tex@gentoo.org +# @AUTHOR: +# Original Author: Alexis Ballier <aballier@gentoo.org> +# @SUPPORTED_EAPIS: 7 +# @BLURB: Provide various functions used by both texlive-core and texlive modules +# @DESCRIPTION: +# Purpose: Provide various functions used by both texlive-core and texlive +# modules. +# +# Note that this eclass *must* not assume the presence of any standard tex too + +if [[ -z ${_TEXLIVE_COMMON_ECLASS} ]]; then +_TEXLIVE_COMMON_ECLASS=1 + +case ${EAPI:-0} in + [0-6]) die "Unsupported EAPI=${EAPI:-0} (too old) for ${ECLASS}" ;; + 7) ;; + *) die "Unsupported EAPI=${EAPI} (unknown) for ${ECLASS}" ;; +esac + +TEXMF_PATH=/usr/share/texmf +TEXMF_DIST_PATH=/usr/share/texmf-dist +TEXMF_VAR_PATH=/var/lib/texmf + +# @FUNCTION: texlive-common_handle_config_files +# @DESCRIPTION: +# Has to be called in src_install after having installed the files in ${D} +# This function will move the relevant files to /etc/texmf and symling them +# from their original location. This is to allow easy update of texlive's +# configuration + +texlive-common_handle_config_files() { + # Handle config files properly + [[ -d ${ED}${TEXMF_PATH} ]] || return + cd "${ED}${TEXMF_PATH}" || die + + while read -r f; do + if [[ ${f#*config} != ${f} || ${f#doc} != ${f} || ${f#source} != ${f} || ${f#tex} != ${f} ]] ; then + continue + fi + dodir /etc/texmf/$(dirname ${f}).d + einfo "Moving (and symlinking) ${EPREFIX}${TEXMF_PATH}/${f} to ${EPREFIX}/etc/texmf/$(dirname ${f}).d" + mv "${ED}/${TEXMF_PATH}/${f}" "${ED}/etc/texmf/$(dirname ${f}).d" || die "mv ${f} failed." + dosym /etc/texmf/$(dirname ${f}).d/$(basename ${f}) ${TEXMF_PATH}/${f} + done < <(find -name '*.cnf' -type f -o -name '*.cfg' -type f | sed -e "s:\./::g") +} + +# @FUNCTION: texlive-common_is_file_present_in_texmf +# @DESCRIPTION: +# Return if a file is present in the texmf tree +# Call it from the directory containing texmf and texmf-dist + +texlive-common_is_file_present_in_texmf() { + local mark="${T}/${1}.found" + if [[ -d texmf ]]; then + find texmf -name ${1} -exec touch ${mark} {} + || die + fi + + if [[ -d texmf-dist ]]; then + find texmf-dist -name ${1} -exec touch ${mark} {} + || die + fi + [ -f "${mark}" ] +} + +# @FUNCTION: texlive-common_do_symlinks +# @USAGE: <src> <dest> +# @DESCRIPTION: +# Mimic the install_link function of texlinks +# +# Should have the same behavior as the one in /usr/bin/texlinks +# except that it is under the control of the package manager +# Note that $1 corresponds to $src and $2 to $dest in this function +# ( Arguments are switched because texlinks main function sends them switched ) +# This function should not be called from an ebuild, prefer etexlinks that will +# also do the fmtutil file parsing. + +texlive-common_do_symlinks() { + while [[ ${#} != 0 ]]; do + case ${1} in + cont-??|metafun|mptopdf) + einfo "Symlink ${1} skipped (special case)" + ;; + mf) + einfo "Symlink ${1} -> ${2} skipped (texlive-core takes care of it)" + ;; + *) + if [[ ${1} == ${2} ]]; then + einfo "Symlink ${1} -> ${2} skipped" + elif [[ -e ${ED}/usr/bin/${1} || -L ${ED}/usr/bin/${1} ]]; then + einfo "Symlink ${1} skipped (file exists)" + else + einfo "Making symlink from ${1} to ${2}" + dosym ${2} /usr/bin/${1} + fi + ;; + esac + shift; shift; + done +} + +# @FUNCTION: etexlinks +# @USAGE: <file> +# @DESCRIPTION: +# Mimic texlinks on a fmtutil format file +# +# $1 has to be a fmtutil format file like fmtutil.cnf +# etexlinks foo will install the symlinks that texlinks --cnffile foo would have +# created. We cannot use texlinks with portage as it is not DESTDIR aware. +# (It would not fail but will not create the symlinks if the target is not in +# the same dir as the source) +# Also, as this eclass must not depend on a tex distribution to be installed we +# cannot use texlinks from here. + +etexlinks() { + # Install symlinks from formats to engines + texlive-common_do_symlinks $(sed '/^[ ]*#/d; /^[ ]*$/d' "$1" | awk '{print $1, $2}') +} + +# @FUNCTION: dobin_texmf_scripts +# @USAGE: <file1> [file2] ... +# @DESCRIPTION: +# Symlinks a script from the texmf tree to /usr/bin. Requires permissions to be +# correctly set for the file that it will point to. + +dobin_texmf_scripts() { + while [[ ${#} -gt 0 ]] ; do + local trg=$(basename ${1} | sed 's,\.[^/]*$,,' | tr '[:upper:]' '[:lower:]') + einfo "Installing ${1} as ${trg} bin wrapper" + [[ -x ${ED}/usr/share/${1} ]] || die "Trying to install a non existing or non executable symlink to /usr/bin: ${1}" + dosym ../share/${1} /usr/bin/${trg} + shift + done +} + +# @FUNCTION: etexmf-update +# @DESCRIPTION: +# Runs texmf-update if it is available and prints a warning otherwise. This +# function helps in factorizing some code. Useful in ebuilds' pkg_postinst and +# pkg_postrm phases. + +etexmf-update() { + if has_version 'app-text/texlive-core' ; then + if [[ -z ${ROOT} && -x "${EPREFIX}"/usr/sbin/texmf-update ]] ; then + "${EPREFIX}"/usr/sbin/texmf-update + else + ewarn "Cannot run texmf-update for some reason." + ewarn "Your texmf tree might be inconsistent with your configuration" + ewarn "Please try to figure what has happened" + fi + fi +} + +# @FUNCTION: efmtutil-sys +# @DESCRIPTION: +# Runs fmtutil-sys if it is available and prints a warning otherwise. This +# function helps in factorizing some code. Used in ebuilds' pkg_postinst to +# force a rebuild of TeX formats. + +efmtutil-sys() { + if has_version 'app-text/texlive-core' ; then + if [[ -z ${ROOT} && -x "${EPREFIX}"/usr/bin/fmtutil-sys ]] ; then + einfo "Rebuilding formats" + "${EPREFIX}"/usr/bin/fmtutil-sys --all &> /dev/null || die + else + ewarn "Cannot run fmtutil-sys for some reason." + ewarn "Your formats might be inconsistent with your installed ${PN} version" + ewarn "Please try to figure what has happened" + fi + fi +} + +fi diff --git a/eclass/texlive-module.eclass b/eclass/texlive-module.eclass new file mode 100644 index 0000000..15988fb --- /dev/null +++ b/eclass/texlive-module.eclass @@ -0,0 +1,449 @@ +# Copyright 1999-2020 Gentoo Authors +# Distributed under the terms of the GNU General Public License v2 + +# @ECLASS: texlive-module.eclass +# @MAINTAINER: +# tex@gentoo.org +# @AUTHOR: +# Original Author: Alexis Ballier <aballier@gentoo.org> +# @SUPPORTED_EAPIS: 7 +# @BLURB: Provide generic install functions so that modular texlive's texmf ebuild will only have to inherit this eclass +# @DESCRIPTION: +# Purpose: Provide generic install functions so that modular texlive's texmf ebuilds will +# only have to inherit this eclass. +# Ebuilds have to provide TEXLIVE_MODULE_CONTENTS variable that contains the list +# of packages that it will install. (See below) +# +# For TeX Live versions prior to 2009, the ebuild was supposed to unpack the +# texmf and texmf-dist directories to ${WORKDIR} (which is what the default +# src_unpack does). +# Starting from TeX Live 2009, the eclass provides a src_unpack function taking +# care of unpacking and relocating the files that need it. +# +# It inherits texlive-common. Patching is supported via the PATCHES +# bash array. + +# @ECLASS-VARIABLE: TEXLIVE_MODULE_CONTENTS +# @REQUIRED +# @DESCRIPTION: +# The list of packages that will be installed. This variable will be expanded to +# SRC_URI: +# foo -> texlive-module-foo-${PV}.tar.xz + +# @ECLASS-VARIABLE: TEXLIVE_MODULE_DOC_CONTENTS +# @REQUIRED +# @DESCRIPTION: +# The list of packages that will be installed if the doc useflag is enabled. +# Expansion to SRC_URI is the same as for TEXLIVE_MODULE_CONTENTS. + +# @ECLASS-VARIABLE: TEXLIVE_MODULE_SRC_CONTENTS +# @REQUIRED +# @DESCRIPTION: +# The list of packages that will be installed if the source useflag is enabled. +# Expansion to SRC_URI is the same as for TEXLIVE_MODULE_CONTENTS. + +# @ECLASS-VARIABLE: TEXLIVE_MODULE_BINSCRIPTS +# @DEFAULT_UNSET +# @DESCRIPTION: +# A space separated list of files that are in fact scripts installed in the +# texmf tree and that we want to be available directly. They will be installed in +# /usr/bin. + +# @ECLASS-VARIABLE: TEXLIVE_MODULE_BINLINKS +# @DEFAULT_UNSET +# @DESCRIPTION: +# A space separated list of links to add for BINSCRIPTS. +# The systax is: foo:bar to create a symlink bar -> foo. + +# @ECLASS-VARIABLE: TL_PV +# @INTERNAL +# @DESCRIPTION: +# Normally the module's PV reflects the TeXLive release it belongs to. +# If this is not the case, TL_PV takes the version number for the +# needed app-text/texlive-core. + +# @ECLASS-VARIABLE: TL_MODULE_INFORMATION +# @DEFAULT_UNSET +# @DESCRIPTION: +# Information to display about the package. +# e.g. for enabling/disabling a feature + +if [[ -z ${_TEXLIVE_MODULE_ECLASS} ]]; then +_TEXLIVE_MODULE_ECLASS=1 + +case ${EAPI:-0} in + [0-6]) die "Unsupported EAPI=${EAPI:-0} (too old) for ${ECLASS}" ;; + 7) inherit texlive-common ;; + *) die "Unsupported EAPI=${EAPI} (unknown) for ${ECLASS}" ;; +esac + +HOMEPAGE="http://www.tug.org/texlive/" + +COMMON_DEPEND=">=app-text/texlive-core-${TL_PV:-${PV}}" + +IUSE="source" + +# Starting from TeX Live 2009, upstream provides .tar.xz modules. +PKGEXT=tar.xz + +# Now where should we get these files? +TEXLIVE_DEVS=${TEXLIVE_DEVS:- zlogene dilfridge } + +# We do not need anything from SYSROOT: +# Everything is built from the texlive install in / +# Generated files are noarch +BDEPEND="${COMMON_DEPEND} + app-arch/xz-utils" + +for i in ${TEXLIVE_MODULE_CONTENTS}; do + for tldev in ${TEXLIVE_DEVS}; do + SRC_URI="${SRC_URI} https://dev.gentoo.org/~${tldev}/distfiles/texlive/tl-${i}-${PV}.${PKGEXT}" + done +done + +# Forge doc SRC_URI +[[ -n ${TEXLIVE_MODULE_DOC_CONTENTS} ]] && SRC_URI="${SRC_URI} doc? (" +for i in ${TEXLIVE_MODULE_DOC_CONTENTS}; do + for tldev in ${TEXLIVE_DEVS}; do + SRC_URI="${SRC_URI} https://dev.gentoo.org/~${tldev}/distfiles/texlive/tl-${i}-${PV}.${PKGEXT}" + done +done +[[ -n ${TEXLIVE_MODULE_DOC_CONTENTS} ]] && SRC_URI="${SRC_URI} )" + +# Forge source SRC_URI +if [[ -n ${TEXLIVE_MODULE_SRC_CONTENTS} ]] ; then + SRC_URI="${SRC_URI} source? (" + for i in ${TEXLIVE_MODULE_SRC_CONTENTS}; do + for tldev in ${TEXLIVE_DEVS}; do + SRC_URI="${SRC_URI} https://dev.gentoo.org/~${tldev}/distfiles/texlive/tl-${i}-${PV}.${PKGEXT}" + done + done + SRC_URI="${SRC_URI} )" +fi + +RDEPEND="${COMMON_DEPEND}" + +IUSE="${IUSE} doc" + +# @ECLASS-VARIABLE: TEXLIVE_MODULE_OPTIONAL_ENGINE +# @DEFAULT_UNSET +# @DESCRIPTION: +# A space separated list of Tex engines that can be made optional. +# e.g. "luatex luajittex" + +if [[ -n ${TEXLIVE_MODULE_OPTIONAL_ENGINE} ]] ; then + for engine in ${TEXLIVE_MODULE_OPTIONAL_ENGINE} ; do + IUSE="${IUSE} +${engine}" + done +fi + +S="${WORKDIR}" + +# @FUNCTION: texlive-module_src_unpack +# @DESCRIPTION: +# Only for TeX Live 2009 and later. +# After unpacking, the files that need to be relocated are moved accordingly. + +RELOC_TARGET=texmf-dist + +texlive-module_src_unpack() { + unpack ${A} + + sed -n -e 's:\s*RELOC/::p' tlpkg/tlpobj/* > "${T}/reloclist" || die + sed -e 's/\/[^/]*$//' -e "s:^:${RELOC_TARGET}/:" "${T}/reloclist" | + sort -u | + xargs mkdir -p || die + local i + while read i; do + mv "${i}" "${RELOC_TARGET}/${i%/*}" || die + done < "${T}/reloclist" +} + +# @FUNCTION: texlive-module_add_format +# @DESCRIPTION: +# Creates/appends to a format.${PN}.cnf file for fmtutil. +# It parses the AddFormat directive of tlpobj files to create it. +# This will make fmtutil generate the formats when asked and allow the remaining +# src_compile phase to build the formats. + +texlive-module_add_format() { + local name engine mode patterns options + eval $@ + einfo "Appending to format.${PN}.cnf for $@" + + if [[ ! -d texmf-dist/fmtutil ]]; then + mkdir -p texmf-dist/fmtutil || die + fi + + [[ -f texmf-dist/fmtutil/format.${PN}.cnf ]] || { echo "# Generated for ${PN} by texlive-module.eclass" > texmf-dist/fmtutil/format.${PN}.cnf; } + [[ -n ${TEXLIVE_MODULE_OPTIONAL_ENGINE} ]] && has ${engine} ${TEXLIVE_MODULE_OPTIONAL_ENGINE} && use !${engine} && mode="disabled" + if [[ ${mode} = disabled ]]; then + printf "#! " >> texmf-dist/fmtutil/format.${PN}.cnf || die + fi + [[ -z ${patterns} ]] && patterns="-" + printf "${name}\t${engine}\t${patterns}\t${options}\n" >> texmf-dist/fmtutil/format.${PN}.cnf || die +} + +# @FUNCTION: texlive-module_make_language_def_lines +# @DESCRIPTION: +# Creates a language.${PN}.def entry to put in /etc/texmf/language.def.d. +# It parses the AddHyphen directive of tlpobj files to create it. + +texlive-module_make_language_def_lines() { + local lefthyphenmin righthyphenmin synonyms name file file_patterns file_exceptions luaspecial + eval $@ + einfo "Generating language.def entry for $@" + [[ -z ${lefthyphenmin} ]] && lefthyphenmin="2" + [[ -z ${righthyphenmin} ]] && righthyphenmin="3" + echo "\\addlanguage{$name}{$file}{}{$lefthyphenmin}{$righthyphenmin}" >> "${S}/language.${PN}.def" || die + if [[ -n ${synonyms} ]]; then + for i in $(echo $synonyms | tr ',' ' ') ; do + einfo "Generating language.def synonym $i for $@" + echo "\\addlanguage{$i}{$file}{}{$lefthyphenmin}{$righthyphenmin}" >> "${S}/language.${PN}.def" || die + done + fi +} + +# @FUNCTION: texlive-module_make_language_dat_lines +# @DESCRIPTION: +# Creates a language.${PN}.dat entry to put in /etc/texmf/language.dat.d. +# It parses the AddHyphen directive of tlpobj files to create it. + +texlive-module_make_language_dat_lines() { + local lefthyphenmin righthyphenmin synonyms name file file_patterns file_exceptions luaspecial + eval $@ + einfo "Generating language.dat entry for $@" + echo "$name $file" >> "${S}/language.${PN}.dat" || die + if [[ -n ${synonyms} ]]; then + for i in $(echo ${synonyms} | tr ',' ' ') ; do + einfo "Generating language.dat synonym ${i} for $@" + echo "=${i}" >> "${S}/language.${PN}.dat" || die + done + fi +} + +# @FUNCTION: texlive-module_synonyms_to_language_lua_line +# @DESCRIPTION: +# Helper function for texlive-module_make_language_lua_lines to generate a +# correctly formatted synonyms entry for language.dat.lua. + +texlive-module_synonyms_to_language_lua_line() { + local prev="" + for i in $(echo $@ | tr ',' ' ') ; do + printf "${prev} '%s'" ${i} + prev="," + done +} + +# @FUNCTION: texlive-module_make_language_lua_lines +# @DESCRIPTION: +# Only valid for TeXLive 2010 and later. +# Creates a language.${PN}.dat.lua entry to put in +# /etc/texmf/language.dat.lua.d. +# It parses the AddHyphen directive of tlpobj files to create it. + +texlive-module_make_language_lua_lines() { + local lefthyphenmin righthyphenmin synonyms name file file_patterns file_exceptions luaspecial + local dest="${S}/language.${PN}.dat.lua" + eval $@ + [[ -z ${lefthyphenmin} ]] && lefthyphenmin="2" + [[ -z ${righthyphenmin} ]] && righthyphenmin="3" + einfo "Generating language.dat.lua entry for $@" + printf "\t['%s'] = {\n" "${name}" >> "${dest}" || die + printf "\t\tloader = '%s',\n" "${file}" >> "${dest}" || die + printf "\t\tlefthyphenmin = %s,\n\t\trighthyphenmin = %s,\n" "${lefthyphenmin}" "${righthyphenmin}" >> "${dest}" || die + printf "\t\tsynonyms = {%s },\n" "$(texlive-module_synonyms_to_language_lua_line "${synonyms}")" >> "${dest}" || die + + if [[ -n ${file_patterns} ]]; then + printf "\t\tpatterns = '%s',\n" "${file_patterns}" >> "${dest}" || die + fi + + if [[ -n ${file_exceptions} ]]; then + printf "\t\thyphenation = '%s',\n" "${file_exceptions}" >> "${dest}" || die + fi + + if [[ -n ${luaspecial} ]]; then + printf "\t\tspecial = '%s',\n" "$luaspecial" >> "${dest}" || die + fi + + printf "\t},\n" >> "${dest}" || die +} + +# @FUNCTION: texlive-module_src_compile +# @DESCRIPTION: +# exported function: +# Generates the config files that are to be installed in /etc/texmf; +# texmf-update script will take care of merging the different config files for +# different packages in a single one used by the whole tex installation. +# +# Once the config files are generated, we build the format files using fmtutil +# (provided by texlive-core). The compiled format files will be sent to +# texmf-var/web2c, like fmtutil defaults to but with some trick to stay in the +# sandbox. + +texlive-module_src_compile() { + # Generate config files from the tlpobj files provided by TeX Live 2008 and + # later + for i in "${S}"/tlpkg/tlpobj/*; + do + grep '^execute ' "${i}" | sed -e 's/^execute //' | tr ' \t' '##' >> "${T}/jobs" || die + done + + for i in $(<"${T}/jobs"); + do + j="$(echo $i | tr '#' ' ')" + command=${j%% *} + parameter=${j#* } + case ${command} in + addMap) + echo "Map ${parameter}" >> "${S}/${PN}.cfg";; + addMixedMap) + echo "MixedMap ${parameter}" >> "${S}/${PN}.cfg";; + addKanjiMap) + echo "KanjiMap ${parameter}" >> "${S}/${PN}.cfg";; + addDvipsMap) + echo "p +${parameter}" >> "${S}/${PN}-config.ps";; + addDvipdfmMap) + echo "f ${parameter}" >> "${S}/${PN}-config";; + AddHyphen) + texlive-module_make_language_def_lines ${parameter} + texlive-module_make_language_dat_lines ${parameter} + texlive-module_make_language_lua_lines ${parameter} + ;; + AddFormat) + texlive-module_add_format ${parameter};; + BuildFormat) + einfo "Format ${parameter} already built.";; + BuildLanguageDat) + einfo "Language file $parameter already generated.";; + *) + die "No rule to proccess ${command}. Please file a bug." + esac + done + + # Determine texlive-core version for fmtutil call + fmt_call="$(has_version '>=app-text/texlive-core-2019' \ + && echo "fmtutil-user" || echo "fmtutil")" + + # Build format files + for i in texmf-dist/fmtutil/format*.cnf; do + if [[ -f ${i} ]]; then + einfo "Building format ${i}" + if [[ ! -d texmf-var ]]; then + mkdir texmf-var || die + fi + if [[ ! -d texmf-var/web2c ]]; then + mkdir texmf-var/web2c || die + fi + VARTEXFONTS="${T}/fonts" TEXMFHOME="${S}/texmf:${S}/texmf-dist:${S}/texmf-var"\ + env -u TEXINPUTS $fmt_call --cnffile "${i}" --fmtdir "${S}/texmf-var/web2c" --all\ + || die "failed to build format ${i}" + fi + done + + # Delete ls-R files, these should not be created but better be certain they + # do not end up being installed. + find . -name 'ls-R' -delete || die +} + +# @FUNCTION: texlive-module_src_install +# @DESCRIPTION: +# exported function: +# Installs texmf and config files to the system. + +texlive-module_src_install() { + for i in texmf-dist/fmtutil/format*.cnf; do + [[ -f ${i} ]] && etexlinks "${i}" + done + + dodir /usr/share + if use doc; then + if [[ -d texmf-doc ]]; then + cp -pR texmf-doc "${ED}/usr/share/" || die + fi + else + if [[ -d texmf-dist/doc ]]; then + rm -rf texmf-dist/doc || die + fi + + if [[ -d texmf/doc ]]; then + rm -rf texmf/doc || die + fi + fi + + if [[ -d texmf ]]; then + cp -pR texmf "${ED}/usr/share/" || die + fi + + if [[ -d texmf-dist ]]; then + cp -pR texmf-dist "${ED}/usr/share/" || die + fi + + if [[ -d tlpkg ]] && use source; then + cp -pR tlpkg "${ED}/usr/share/" || die + fi + + + if [[ -d texmf-var ]]; then + insinto /var/lib/texmf + doins -r texmf-var/. + fi + + insinto /etc/texmf/updmap.d + [[ -f ${S}/${PN}.cfg ]] && doins "${S}/${PN}.cfg" + insinto /etc/texmf/dvips.d + [[ -f ${S}/${PN}-config.ps ]] && doins "${S}/${PN}-config.ps" + insinto /etc/texmf/dvipdfm/config + [[ -f ${S}/${PN}-config ]] && doins "${S}/${PN}-config" + + if [[ -f ${S}/language.${PN}.def ]] ; then + insinto /etc/texmf/language.def.d + doins "${S}/language.${PN}.def" + fi + + if [[ -f ${S}/language.${PN}.dat ]] ; then + insinto /etc/texmf/language.dat.d + doins "${S}/language.${PN}.dat" + fi + + if [[ -f ${S}/language.${PN}.dat.lua ]] ; then + insinto /etc/texmf/language.dat.lua.d + doins "${S}/language.${PN}.dat.lua" + fi + + [[ -n ${TEXLIVE_MODULE_BINSCRIPTS} ]] && dobin_texmf_scripts ${TEXLIVE_MODULE_BINSCRIPTS} + if [[ -n ${TEXLIVE_MODULE_BINLINKS} ]] ; then + for i in ${TEXLIVE_MODULE_BINLINKS} ; do + [[ -f ${ED}/usr/bin/${i%:*} ]] || die "Trying to install an invalid BINLINK. This should not happen. Please file a bug." + dosym ${i%:*} /usr/bin/${i#*:} + done + fi + + texlive-common_handle_config_files + TEXMF_PATH=${TEXMF_DIST_PATH} texlive-common_handle_config_files +} + +# @FUNCTION: texlive-module_pkg_postinst +# @DESCRIPTION: +# exported function: +# Run texmf-update to ensure the tex installation is consistent with the +# installed texmf trees. + +texlive-module_pkg_postinst() { + etexmf-update + [[ -n ${TL_MODULE_INFORMATION} ]] && elog "${TL_MODULE_INFORMATION}" +} + +# @FUNCTION: texlive-module_pkg_postrm +# @DESCRIPTION: +# exported function: +# Run texmf-update to ensure the tex installation is consistent with the +# installed texmf trees. + +texlive-module_pkg_postrm() { + etexmf-update +} + +EXPORT_FUNCTIONS src_unpack src_compile src_install pkg_postinst pkg_postrm + +fi diff --git a/eclass/tmpfiles.eclass b/eclass/tmpfiles.eclass new file mode 100644 index 0000000..360c5e3 --- /dev/null +++ b/eclass/tmpfiles.eclass @@ -0,0 +1,139 @@ +# Copyright 2016-2019 Gentoo Authors +# Distributed under the terms of the GNU General Public License v2 + +# @ECLASS: tmpfiles.eclass +# @MAINTAINER: +# Gentoo systemd project <systemd@gentoo.org> +# William Hubbs <williamh@gentoo.org> +# @AUTHOR: +# Mike Gilbert <floppym@gentoo.org> +# William Hubbs <williamh@gentoo.org> +# @SUPPORTED_EAPIS: 5 6 7 +# @BLURB: Functions related to tmpfiles.d files +# @DESCRIPTION: +# This eclass provides functionality related to installing and +# creating volatile and temporary files based on configuration files$and +# locations defined at this URL: +# +# https://www.freedesktop.org/software/systemd/man/tmpfiles.d.html +# +# The dotmpfiles and newtmpfiles functions are used to install +# configuration files into /usr/lib/tmpfiles.d, then in pkg_postinst, +# the tmpfiles_process function must be called to process the newly +# installed tmpfiles.d entries. +# +# The tmpfiles.d files can be used by service managers to recreate/clean +# up temporary directories on boot or periodically. Additionally, +# the pkg_postinst() call ensures that the directories are created +# on systems that do not support tmpfiles.d natively, without a need +# for explicit fallback. +# +# @EXAMPLE: +# Typical usage of this eclass: +# +# @CODE +# EAPI=6 +# inherit tmpfiles +# +# ... +# +# src_install() { +# ... +# dotmpfiles "${FILESDIR}"/file1.conf "${FILESDIR}"/file2.conf +# newtmpfiles "${FILESDIR}"/file3.conf-${PV} file3.conf +# ... +# } +# +# pkg_postinst() { +# ... +# tmpfiles_process file1.conf file2.conf file3.conf +# ... +# } +# +# @CODE + +if [[ -z ${TMPFILES_ECLASS} ]]; then +TMPFILES_ECLASS=1 + +case "${EAPI}" in +5|6|7) ;; +*) die "API is undefined for EAPI ${EAPI}" ;; +esac + +RDEPEND="virtual/tmpfiles" + +# @FUNCTION: dotmpfiles +# @USAGE: <tmpfiles.d_file> ... +# @DESCRIPTION: +# Install one or more tmpfiles.d files into /usr/lib/tmpfiles.d. +dotmpfiles() { + debug-print-function "${FUNCNAME}" "$@" + + local f + for f; do + if [[ ${f} != *.conf ]]; then + die "tmpfiles.d files must end with .conf" + fi + done + + ( + insopts -m 0644 + insinto /usr/lib/tmpfiles.d + doins "$@" + ) +} + +# @FUNCTION: newtmpfiles +# @USAGE: <old-name> <new-name>.conf +# @DESCRIPTION: +# Install a tmpfiles.d file in /usr/lib/tmpfiles.d under a new name. +newtmpfiles() { + debug-print-function "${FUNCNAME}" "$@" + + if [[ $2 != *.conf ]]; then + die "tmpfiles.d files must end with .conf" + fi + + ( + insopts -m 0644 + insinto /usr/lib/tmpfiles.d + newins "$@" + ) +} + +# @FUNCTION: tmpfiles_process +# @USAGE: <filename> <filename> ... +# @DESCRIPTION: +# Call a tmpfiles.d implementation to create new volatile and temporary +# files and directories. +tmpfiles_process() { + debug-print-function "${FUNCNAME}" "$@" + + [[ ${EBUILD_PHASE} == postinst ]] || die "${FUNCNAME}: Only valid in pkg_postinst" + [[ ${#} -gt 0 ]] || die "${FUNCNAME}: Must specify at least one filename" + + # Only process tmpfiles for the currently running system + if [[ ${ROOT:-/} != / ]]; then + ewarn "Warning: tmpfiles.d not processed on ROOT != /. If you do not use" + ewarn "a service manager supporting tmpfiles.d, you need to run" + ewarn "the following command after booting (or chroot-ing with all" + ewarn "appropriate filesystems mounted) into the ROOT:" + ewarn + ewarn " tmpfiles --create" + ewarn + ewarn "Failure to do so may result in missing runtime directories" + ewarn "and failures to run programs or start services." + return + fi + + if type systemd-tmpfiles &> /dev/null; then + systemd-tmpfiles --create "$@" + elif type tmpfiles &> /dev/null; then + tmpfiles --create "$@" + fi + if [[ $? -ne 0 ]]; then + ewarn "The tmpfiles processor exited with a non-zero exit code" + fi +} + +fi diff --git a/eclass/toolchain-autoconf.eclass b/eclass/toolchain-autoconf.eclass new file mode 100644 index 0000000..2c8184f --- /dev/null +++ b/eclass/toolchain-autoconf.eclass @@ -0,0 +1,79 @@ +# Copyright 1999-2019 Gentoo Authors +# Distributed under the terms of the GNU General Public License v2 + +# @ECLASS: toolchain-autoconf.eclass +# @MAINTAINER: +# <base-system@gentoo.org> +# @SUPPORTED_EAPIS: 6 7 +# @BLURB: Common code for sys-devel/autoconf ebuilds +# @DESCRIPTION: +# This eclass contains the common phase functions migrated from +# sys-devel/autoconf eblits. + +case ${EAPI:-0} in + [0-5]) + die "${ECLASS} is banned in EAPI ${EAPI:-0}" + ;; + [6-7]) + ;; + *) + die "Unknown EAPI ${EAPI:-0}" + ;; +esac + +if [[ -z ${_TOOLCHAIN_AUTOCONF_ECLASS} ]]; then + +EXPORT_FUNCTIONS src_prepare src_configure src_install + +toolchain-autoconf_src_prepare() { + find -name Makefile.in -exec sed -i '/^pkgdatadir/s:$:-@VERSION@:' {} + || die + default +} + +toolchain-autoconf_src_configure() { + # Disable Emacs in the build system since it is in a separate package. + export EMACS=no + econf --program-suffix="-${PV}" || die + # econf updates config.{sub,guess} which forces the manpages + # to be regenerated which we dont want to do #146621 + touch man/*.1 +} + +# slot the info pages. do this w/out munging the source so we don't have +# to depend on texinfo to regen things. #464146 (among others) +slot_info_pages() { + [[ ${SLOT} == "0" ]] && return + + pushd "${ED}"/usr/share/info >/dev/null || die + rm -f dir || die + + # Rewrite all the references to other pages. + # before: * aclocal-invocation: (automake)aclocal Invocation. Generating aclocal.m4. + # after: * aclocal-invocation v1.13: (automake-1.13)aclocal Invocation. Generating aclocal.m4. + local p pages=( *.info ) args=() + for p in "${pages[@]/%.info}" ; do + args+=( + -e "/START-INFO-DIR-ENTRY/,/END-INFO-DIR-ENTRY/s|: (${p})| v${SLOT}&|" + -e "s:(${p}):(${p}-${SLOT}):g" + ) + done + sed -i "${args[@]}" * || die + + # Rewrite all the file references, and rename them in the process. + local f d + for f in * ; do + d=${f/.info/-${SLOT}.info} + mv "${f}" "${d}" || die + sed -i -e "s:${f}:${d}:g" * || die + done + + popd >/dev/null || die +} + +toolchain-autoconf_src_install() { + default + slot_info_pages +} + +_TOOLCHAIN_AUTOCONF_ECLASS=1 +fi diff --git a/eclass/toolchain-funcs.eclass b/eclass/toolchain-funcs.eclass new file mode 100644 index 0000000..267cf5c --- /dev/null +++ b/eclass/toolchain-funcs.eclass @@ -0,0 +1,1138 @@ +# Copyright 2002-2021 Gentoo Authors +# Distributed under the terms of the GNU General Public License v2 + +# @ECLASS: toolchain-funcs.eclass +# @MAINTAINER: +# Toolchain Ninjas <toolchain@gentoo.org> +# @BLURB: functions to query common info about the toolchain +# @DESCRIPTION: +# The toolchain-funcs aims to provide a complete suite of functions +# for gleaning useful information about the toolchain and to simplify +# ugly things like cross-compiling and multilib. All of this is done +# in such a way that you can rely on the function always returning +# something sane. + +if [[ -z ${_TOOLCHAIN_FUNCS_ECLASS} ]]; then +_TOOLCHAIN_FUNCS_ECLASS=1 + +inherit multilib + +# tc-getPROG <VAR [search vars]> <default> [tuple] +_tc-getPROG() { + local tuple=$1 + local v var vars=$2 + local prog=( $3 ) + + var=${vars%% *} + for v in ${vars} ; do + if [[ -n ${!v} ]] ; then + export ${var}="${!v}" + echo "${!v}" + return 0 + fi + done + + local search= + [[ -n $4 ]] && search=$(type -p $4-${prog[0]}) + [[ -z ${search} && -n ${!tuple} ]] && search=$(type -p ${!tuple}-${prog[0]}) + [[ -n ${search} ]] && prog[0]=${search##*/} + + export ${var}="${prog[*]}" + echo "${!var}" +} +tc-getBUILD_PROG() { + local vars="BUILD_$1 $1_FOR_BUILD HOST$1" + # respect host vars if not cross-compiling + # https://bugs.gentoo.org/630282 + tc-is-cross-compiler || vars+=" $1" + _tc-getPROG CBUILD "${vars}" "${@:2}" +} +tc-getPROG() { _tc-getPROG CHOST "$@"; } + +# @FUNCTION: tc-getAR +# @USAGE: [toolchain prefix] +# @RETURN: name of the archiver +tc-getAR() { tc-getPROG AR ar "$@"; } +# @FUNCTION: tc-getAS +# @USAGE: [toolchain prefix] +# @RETURN: name of the assembler +tc-getAS() { tc-getPROG AS as "$@"; } +# @FUNCTION: tc-getCC +# @USAGE: [toolchain prefix] +# @RETURN: name of the C compiler +tc-getCC() { tc-getPROG CC gcc "$@"; } +# @FUNCTION: tc-getCPP +# @USAGE: [toolchain prefix] +# @RETURN: name of the C preprocessor +tc-getCPP() { tc-getPROG CPP "${CC:-gcc} -E" "$@"; } +# @FUNCTION: tc-getCXX +# @USAGE: [toolchain prefix] +# @RETURN: name of the C++ compiler +tc-getCXX() { tc-getPROG CXX g++ "$@"; } +# @FUNCTION: tc-getLD +# @USAGE: [toolchain prefix] +# @RETURN: name of the linker +tc-getLD() { tc-getPROG LD ld "$@"; } +# @FUNCTION: tc-getSTRINGS +# @USAGE: [toolchain prefix] +# @RETURN: name of the strings program +tc-getSTRINGS() { tc-getPROG STRINGS strings "$@"; } +# @FUNCTION: tc-getSTRIP +# @USAGE: [toolchain prefix] +# @RETURN: name of the strip program +tc-getSTRIP() { tc-getPROG STRIP strip "$@"; } +# @FUNCTION: tc-getNM +# @USAGE: [toolchain prefix] +# @RETURN: name of the symbol/object thingy +tc-getNM() { tc-getPROG NM nm "$@"; } +# @FUNCTION: tc-getRANLIB +# @USAGE: [toolchain prefix] +# @RETURN: name of the archive indexer +tc-getRANLIB() { tc-getPROG RANLIB ranlib "$@"; } +# @FUNCTION: tc-getREADELF +# @USAGE: [toolchain prefix] +# @RETURN: name of the ELF reader +tc-getREADELF() { tc-getPROG READELF readelf "$@"; } +# @FUNCTION: tc-getOBJCOPY +# @USAGE: [toolchain prefix] +# @RETURN: name of the object copier +tc-getOBJCOPY() { tc-getPROG OBJCOPY objcopy "$@"; } +# @FUNCTION: tc-getOBJDUMP +# @USAGE: [toolchain prefix] +# @RETURN: name of the object dumper +tc-getOBJDUMP() { tc-getPROG OBJDUMP objdump "$@"; } +# @FUNCTION: tc-getF77 +# @USAGE: [toolchain prefix] +# @RETURN: name of the Fortran 77 compiler +tc-getF77() { tc-getPROG F77 gfortran "$@"; } +# @FUNCTION: tc-getFC +# @USAGE: [toolchain prefix] +# @RETURN: name of the Fortran 90 compiler +tc-getFC() { tc-getPROG FC gfortran "$@"; } +# @FUNCTION: tc-getGCJ +# @USAGE: [toolchain prefix] +# @RETURN: name of the java compiler +tc-getGCJ() { tc-getPROG GCJ gcj "$@"; } +# @FUNCTION: tc-getGO +# @USAGE: [toolchain prefix] +# @RETURN: name of the Go compiler +tc-getGO() { tc-getPROG GO gccgo "$@"; } +# @FUNCTION: tc-getPKG_CONFIG +# @USAGE: [toolchain prefix] +# @RETURN: name of the pkg-config tool +tc-getPKG_CONFIG() { tc-getPROG PKG_CONFIG pkg-config "$@"; } +# @FUNCTION: tc-getRC +# @USAGE: [toolchain prefix] +# @RETURN: name of the Windows resource compiler +tc-getRC() { tc-getPROG RC windres "$@"; } +# @FUNCTION: tc-getDLLWRAP +# @USAGE: [toolchain prefix] +# @RETURN: name of the Windows dllwrap utility +tc-getDLLWRAP() { tc-getPROG DLLWRAP dllwrap "$@"; } + +# @FUNCTION: tc-getBUILD_AR +# @USAGE: [toolchain prefix] +# @RETURN: name of the archiver for building binaries to run on the build machine +tc-getBUILD_AR() { tc-getBUILD_PROG AR ar "$@"; } +# @FUNCTION: tc-getBUILD_AS +# @USAGE: [toolchain prefix] +# @RETURN: name of the assembler for building binaries to run on the build machine +tc-getBUILD_AS() { tc-getBUILD_PROG AS as "$@"; } +# @FUNCTION: tc-getBUILD_CC +# @USAGE: [toolchain prefix] +# @RETURN: name of the C compiler for building binaries to run on the build machine +tc-getBUILD_CC() { tc-getBUILD_PROG CC gcc "$@"; } +# @FUNCTION: tc-getBUILD_CPP +# @USAGE: [toolchain prefix] +# @RETURN: name of the C preprocessor for building binaries to run on the build machine +tc-getBUILD_CPP() { tc-getBUILD_PROG CPP "$(tc-getBUILD_CC) -E" "$@"; } +# @FUNCTION: tc-getBUILD_CXX +# @USAGE: [toolchain prefix] +# @RETURN: name of the C++ compiler for building binaries to run on the build machine +tc-getBUILD_CXX() { tc-getBUILD_PROG CXX g++ "$@"; } +# @FUNCTION: tc-getBUILD_LD +# @USAGE: [toolchain prefix] +# @RETURN: name of the linker for building binaries to run on the build machine +tc-getBUILD_LD() { tc-getBUILD_PROG LD ld "$@"; } +# @FUNCTION: tc-getBUILD_STRINGS +# @USAGE: [toolchain prefix] +# @RETURN: name of the strings program for building binaries to run on the build machine +tc-getBUILD_STRINGS() { tc-getBUILD_PROG STRINGS strings "$@"; } +# @FUNCTION: tc-getBUILD_STRIP +# @USAGE: [toolchain prefix] +# @RETURN: name of the strip program for building binaries to run on the build machine +tc-getBUILD_STRIP() { tc-getBUILD_PROG STRIP strip "$@"; } +# @FUNCTION: tc-getBUILD_NM +# @USAGE: [toolchain prefix] +# @RETURN: name of the symbol/object thingy for building binaries to run on the build machine +tc-getBUILD_NM() { tc-getBUILD_PROG NM nm "$@"; } +# @FUNCTION: tc-getBUILD_RANLIB +# @USAGE: [toolchain prefix] +# @RETURN: name of the archive indexer for building binaries to run on the build machine +tc-getBUILD_RANLIB() { tc-getBUILD_PROG RANLIB ranlib "$@"; } +# @FUNCTION: tc-getBUILD_READELF +# @USAGE: [toolchain prefix] +# @RETURN: name of the ELF reader for building binaries to run on the build machine +tc-getBUILD_READELF() { tc-getBUILD_PROG READELF readelf "$@"; } +# @FUNCTION: tc-getBUILD_OBJCOPY +# @USAGE: [toolchain prefix] +# @RETURN: name of the object copier for building binaries to run on the build machine +tc-getBUILD_OBJCOPY() { tc-getBUILD_PROG OBJCOPY objcopy "$@"; } +# @FUNCTION: tc-getBUILD_PKG_CONFIG +# @USAGE: [toolchain prefix] +# @RETURN: name of the pkg-config tool for building binaries to run on the build machine +tc-getBUILD_PKG_CONFIG() { tc-getBUILD_PROG PKG_CONFIG pkg-config "$@"; } + +# @FUNCTION: tc-getTARGET_CPP +# @USAGE: [toolchain prefix] +# @RETURN: name of the C preprocessor for the toolchain being built (or used) +tc-getTARGET_CPP() { + if [[ -n ${CTARGET} ]]; then + _tc-getPROG CTARGET TARGET_CPP "gcc -E" "$@" + else + tc-getCPP "$@" + fi +} + +# @FUNCTION: tc-export +# @USAGE: <list of toolchain variables> +# @DESCRIPTION: +# Quick way to export a bunch of compiler vars at once. +tc-export() { + local var + for var in "$@" ; do + [[ $(type -t "tc-get${var}") != "function" ]] && die "tc-export: invalid export variable '${var}'" + "tc-get${var}" > /dev/null + done +} + +# @FUNCTION: tc-is-cross-compiler +# @RETURN: Shell true if we are using a cross-compiler, shell false otherwise +tc-is-cross-compiler() { + [[ ${CBUILD:-${CHOST}} != ${CHOST} ]] +} + +# @FUNCTION: tc-cpp-is-true +# @USAGE: <condition> [cpp flags] +# @RETURN: Shell true if the condition is true, shell false otherwise. +# @DESCRIPTION: +# Evaluate the given condition using the C preprocessor for CTARGET, if +# defined, or CHOST. Additional arguments are passed through to the cpp +# command. A typical condition would be in the form defined(__FOO__). +tc-cpp-is-true() { + local CONDITION=${1} + shift + + $(tc-getTARGET_CPP) "${@}" -P - <<-EOF >/dev/null 2>&1 + #if ${CONDITION} + true + #else + #error false + #endif + EOF +} + +# @FUNCTION: tc-detect-is-softfloat +# @RETURN: Shell true if detection was possible, shell false otherwise +# @DESCRIPTION: +# Detect whether the CTARGET (or CHOST) toolchain is a softfloat based +# one by examining the toolchain's output, if possible. Outputs a value +# alike tc-is-softfloat if detection was possible. +tc-detect-is-softfloat() { + # If fetching CPP falls back to the default (gcc -E) then fail + # detection as this may not be the correct toolchain. + [[ $(tc-getTARGET_CPP) == "gcc -E" ]] && return 1 + + case ${CTARGET:-${CHOST}} in + # Avoid autodetection for bare-metal targets. bug #666896 + *-newlib|*-elf|*-eabi) + return 1 ;; + + # arm-unknown-linux-gnueabi is ambiguous. We used to treat it as + # hardfloat but we now treat it as softfloat like most everyone + # else. Check existing toolchains to respect existing systems. + arm*) + if tc-cpp-is-true "defined(__ARM_PCS_VFP)"; then + echo "no" + else + # Confusingly __SOFTFP__ is defined only when + # -mfloat-abi is soft, not softfp. + if tc-cpp-is-true "defined(__SOFTFP__)"; then + echo "yes" + else + echo "softfp" + fi + fi + + return 0 ;; + *) + return 1 ;; + esac +} + +# @FUNCTION: tc-tuple-is-softfloat +# @RETURN: See tc-is-softfloat for the possible values. +# @DESCRIPTION: +# Determine whether the CTARGET (or CHOST) toolchain is a softfloat +# based one solely from the tuple. +tc-tuple-is-softfloat() { + local CTARGET=${CTARGET:-${CHOST}} + case ${CTARGET//_/-} in + bfin*|h8300*) + echo "only" ;; + *-softfloat-*) + echo "yes" ;; + *-softfp-*) + echo "softfp" ;; + arm*-hardfloat-*|arm*eabihf) + echo "no" ;; + # bare-metal targets have their defaults. bug #666896 + *-newlib|*-elf|*-eabi) + echo "no" ;; + arm*) + echo "yes" ;; + *) + echo "no" ;; + esac +} + +# @FUNCTION: tc-is-softfloat +# @DESCRIPTION: +# See if this toolchain is a softfloat based one. +# @CODE +# The possible return values: +# - only: the target is always softfloat (never had fpu) +# - yes: the target should support softfloat +# - softfp: (arm specific) the target should use hardfloat insns, but softfloat calling convention +# - no: the target doesn't support softfloat +# @CODE +# This allows us to react differently where packages accept +# softfloat flags in the case where support is optional, but +# rejects softfloat flags where the target always lacks an fpu. +tc-is-softfloat() { + tc-detect-is-softfloat || tc-tuple-is-softfloat +} + +# @FUNCTION: tc-is-static-only +# @DESCRIPTION: +# Return shell true if the target does not support shared libs, shell false +# otherwise. +tc-is-static-only() { + local host=${CTARGET:-${CHOST}} + + # *MiNT doesn't have shared libraries, only platform so far + [[ ${host} == *-mint* ]] +} + +# @FUNCTION: tc-stack-grows-down +# @DESCRIPTION: +# Return shell true if the stack grows down. This is the default behavior +# for the vast majority of systems out there and usually projects shouldn't +# care about such internal details. +tc-stack-grows-down() { + # List the few that grow up. + case ${ARCH} in + hppa|metag) return 1 ;; + esac + + # Assume all others grow down. + return 0 +} + +# @FUNCTION: tc-export_build_env +# @USAGE: [compiler variables] +# @DESCRIPTION: +# Export common build related compiler settings. +tc-export_build_env() { + tc-export "$@" + if tc-is-cross-compiler; then + # Some build envs will initialize vars like: + # : ${BUILD_LDFLAGS:-${LDFLAGS}} + # So make sure all variables are non-empty. #526734 + : ${BUILD_CFLAGS:=-O1 -pipe} + : ${BUILD_CXXFLAGS:=-O1 -pipe} + : ${BUILD_CPPFLAGS:= } + : ${BUILD_LDFLAGS:= } + else + # https://bugs.gentoo.org/654424 + : ${BUILD_CFLAGS:=${CFLAGS}} + : ${BUILD_CXXFLAGS:=${CXXFLAGS}} + : ${BUILD_CPPFLAGS:=${CPPFLAGS}} + : ${BUILD_LDFLAGS:=${LDFLAGS}} + fi + export BUILD_{C,CXX,CPP,LD}FLAGS + + # Some packages use XXX_FOR_BUILD. + local v + for v in BUILD_{C,CXX,CPP,LD}FLAGS ; do + export ${v#BUILD_}_FOR_BUILD="${!v}" + done +} + +# @FUNCTION: tc-env_build +# @USAGE: <command> [command args] +# @INTERNAL +# @DESCRIPTION: +# Setup the compile environment to the build tools and then execute the +# specified command. We use tc-getBUILD_XX here so that we work with +# all of the semi-[non-]standard env vars like $BUILD_CC which often +# the target build system does not check. +tc-env_build() { + tc-export_build_env + CFLAGS=${BUILD_CFLAGS} \ + CXXFLAGS=${BUILD_CXXFLAGS} \ + CPPFLAGS=${BUILD_CPPFLAGS} \ + LDFLAGS=${BUILD_LDFLAGS} \ + AR=$(tc-getBUILD_AR) \ + AS=$(tc-getBUILD_AS) \ + CC=$(tc-getBUILD_CC) \ + CPP=$(tc-getBUILD_CPP) \ + CXX=$(tc-getBUILD_CXX) \ + LD=$(tc-getBUILD_LD) \ + NM=$(tc-getBUILD_NM) \ + PKG_CONFIG=$(tc-getBUILD_PKG_CONFIG) \ + RANLIB=$(tc-getBUILD_RANLIB) \ + READELF=$(tc-getBUILD_READELF) \ + "$@" +} + +# @FUNCTION: econf_build +# @USAGE: [econf flags] +# @DESCRIPTION: +# Sometimes we need to locally build up some tools to run on CBUILD because +# the package has helper utils which are compiled+executed when compiling. +# This won't work when cross-compiling as the CHOST is set to a target which +# we cannot natively execute. +# +# For example, the python package will build up a local python binary using +# a portable build system (configure+make), but then use that binary to run +# local python scripts to build up other components of the overall python. +# We cannot rely on the python binary in $PATH as that often times will be +# a different version, or not even installed in the first place. Instead, +# we compile the code in a different directory to run on CBUILD, and then +# use that binary when compiling the main package to run on CHOST. +# +# For example, with newer EAPIs, you'd do something like: +# @CODE +# src_configure() { +# ECONF_SOURCE=${S} +# if tc-is-cross-compiler ; then +# mkdir "${WORKDIR}"/${CBUILD} +# pushd "${WORKDIR}"/${CBUILD} >/dev/null +# econf_build --disable-some-unused-stuff +# popd >/dev/null +# fi +# ... normal build paths ... +# } +# src_compile() { +# if tc-is-cross-compiler ; then +# pushd "${WORKDIR}"/${CBUILD} >/dev/null +# emake one-or-two-build-tools +# ln/mv build-tools to normal build paths in ${S}/ +# popd >/dev/null +# fi +# ... normal build paths ... +# } +# @CODE +econf_build() { + local CBUILD=${CBUILD:-${CHOST}} + tc-env_build econf --build=${CBUILD} --host=${CBUILD} "$@" +} + +# @FUNCTION: tc-ld-is-gold +# @USAGE: [toolchain prefix] +# @DESCRIPTION: +# Return true if the current linker is set to gold. +tc-ld-is-gold() { + local out + + # First check the linker directly. + out=$($(tc-getLD "$@") --version 2>&1) + if [[ ${out} == *"GNU gold"* ]] ; then + return 0 + fi + + # Then see if they're selecting gold via compiler flags. + # Note: We're assuming they're using LDFLAGS to hold the + # options and not CFLAGS/CXXFLAGS. + local base="${T}/test-tc-gold" + cat <<-EOF > "${base}.c" + int main() { return 0; } + EOF + out=$($(tc-getCC "$@") ${CFLAGS} ${CPPFLAGS} ${LDFLAGS} -Wl,--version "${base}.c" -o "${base}" 2>&1) + rm -f "${base}"* + if [[ ${out} == *"GNU gold"* ]] ; then + return 0 + fi + + # No gold here! + return 1 +} + +# @FUNCTION: tc-ld-is-lld +# @USAGE: [toolchain prefix] +# @DESCRIPTION: +# Return true if the current linker is set to lld. +tc-ld-is-lld() { + local out + + # First check the linker directly. + out=$($(tc-getLD "$@") --version 2>&1) + if [[ ${out} == *"LLD"* ]] ; then + return 0 + fi + + # Then see if they're selecting lld via compiler flags. + # Note: We're assuming they're using LDFLAGS to hold the + # options and not CFLAGS/CXXFLAGS. + local base="${T}/test-tc-lld" + cat <<-EOF > "${base}.c" + int main() { return 0; } + EOF + out=$($(tc-getCC "$@") ${CFLAGS} ${CPPFLAGS} ${LDFLAGS} -Wl,--version "${base}.c" -o "${base}" 2>&1) + rm -f "${base}"* + if [[ ${out} == *"LLD"* ]] ; then + return 0 + fi + + # No lld here! + return 1 +} + +# @FUNCTION: tc-ld-disable-gold +# @USAGE: [toolchain prefix] +# @DESCRIPTION: +# If the gold linker is currently selected, configure the compilation +# settings so that we use the older bfd linker instead. +tc-ld-disable-gold() { + tc-ld-is-gold "$@" && tc-ld-force-bfd "$@" +} + +# @FUNCTION: tc-ld-force-bfd +# @USAGE: [toolchain prefix] +# @DESCRIPTION: +# If the gold or lld linker is currently selected, configure the compilation +# settings so that we use the bfd linker instead. +tc-ld-force-bfd() { + if ! tc-ld-is-gold "$@" && ! tc-ld-is-lld "$@" ; then + # They aren't using gold or lld, so nothing to do! + return + fi + + ewarn "Forcing usage of the BFD linker" + + # Set up LD to point directly to bfd if it's available. + # We need to extract the first word in case there are flags appended + # to its value (like multilib). #545218 + local ld=$(tc-getLD "$@") + local bfd_ld="${ld%% *}.bfd" + local path_ld=$(which "${bfd_ld}" 2>/dev/null) + [[ -e ${path_ld} ]] && export LD=${bfd_ld} + + # Set up LDFLAGS to select bfd based on the gcc / clang version. + local fallback="true" + if tc-is-gcc; then + local major=$(gcc-major-version "$@") + local minor=$(gcc-minor-version "$@") + if [[ ${major} -gt 4 ]] || [[ ${major} -eq 4 && ${minor} -ge 8 ]]; then + # gcc-4.8+ supports -fuse-ld directly. + export LDFLAGS="${LDFLAGS} -fuse-ld=bfd" + fallback="false" + fi + elif tc-is-clang; then + local major=$(clang-major-version "$@") + local minor=$(clang-minor-version "$@") + if [[ ${major} -gt 3 ]] || [[ ${major} -eq 3 && ${minor} -ge 5 ]]; then + # clang-3.5+ supports -fuse-ld directly. + export LDFLAGS="${LDFLAGS} -fuse-ld=bfd" + fallback="false" + fi + fi + if [[ ${fallback} == "true" ]] ; then + # <=gcc-4.7 and <=clang-3.4 require some coercion. + # Only works if bfd exists. + if [[ -e ${path_ld} ]] ; then + local d="${T}/bfd-linker" + mkdir -p "${d}" + ln -sf "${path_ld}" "${d}"/ld + export LDFLAGS="${LDFLAGS} -B${d}" + else + die "unable to locate a BFD linker" + fi + fi +} + +# @FUNCTION: tc-has-openmp +# @USAGE: [toolchain prefix] +# @DESCRIPTION: +# See if the toolchain supports OpenMP. +tc-has-openmp() { + local base="${T}/test-tc-openmp" + cat <<-EOF > "${base}.c" + #include <omp.h> + int main() { + int nthreads, tid, ret = 0; + #pragma omp parallel private(nthreads, tid) + { + tid = omp_get_thread_num(); + nthreads = omp_get_num_threads(); ret += tid + nthreads; + } + return ret; + } + EOF + $(tc-getCC "$@") -fopenmp "${base}.c" -o "${base}" >&/dev/null + local ret=$? + rm -f "${base}"* + return ${ret} +} + +# @FUNCTION: tc-check-openmp +# @DESCRIPTION: +# Test for OpenMP support with the current compiler and error out with +# a clear error message, telling the user how to rectify the missing +# OpenMP support that has been requested by the ebuild. Using this function +# to test for OpenMP support should be preferred over tc-has-openmp and +# printing a custom message, as it presents a uniform interface to the user. +tc-check-openmp() { + if ! tc-has-openmp; then + eerror "Your current compiler does not support OpenMP!" + + if tc-is-gcc; then + eerror "Enable OpenMP support by building sys-devel/gcc with USE=\"openmp\"." + elif tc-is-clang; then + eerror "OpenMP support in sys-devel/clang is provided by sys-libs/libomp." + fi + + die "Active compiler does not have required support for OpenMP" + fi +} + +# @FUNCTION: tc-has-tls +# @USAGE: [-s|-c|-l] [toolchain prefix] +# @DESCRIPTION: +# See if the toolchain supports thread local storage (TLS). Use -s to test the +# compiler, -c to also test the assembler, and -l to also test the C library +# (the default). +tc-has-tls() { + local base="${T}/test-tc-tls" + cat <<-EOF > "${base}.c" + int foo(int *i) { + static __thread int j = 0; + return *i ? j : *i; + } + EOF + local flags + case $1 in + -s) flags="-S";; + -c) flags="-c";; + -l) ;; + -*) die "Usage: tc-has-tls [-c|-l] [toolchain prefix]";; + esac + : ${flags:=-fPIC -shared -Wl,-z,defs} + [[ $1 == -* ]] && shift + $(tc-getCC "$@") ${flags} "${base}.c" -o "${base}" >&/dev/null + local ret=$? + rm -f "${base}"* + return ${ret} +} + + +# Parse information from CBUILD/CHOST/CTARGET rather than +# use external variables from the profile. +tc-ninja_magic_to_arch() { +ninj() { [[ ${type} == "kern" ]] && echo $1 || echo $2 ; } + + local type=$1 + local host=$2 + [[ -z ${host} ]] && host=${CTARGET:-${CHOST}} + + case ${host} in + aarch64*) echo arm64;; + alpha*) echo alpha;; + arm*) echo arm;; + avr*) ninj avr32 avr;; + bfin*) ninj blackfin bfin;; + c6x*) echo c6x;; + cris*) echo cris;; + frv*) echo frv;; + hexagon*) echo hexagon;; + hppa*) ninj parisc hppa;; + i?86*) + # Starting with linux-2.6.24, the 'x86_64' and 'i386' + # trees have been unified into 'x86'. + # FreeBSD still uses i386 + if [[ ${type} == "kern" && ${host} == *freebsd* ]] ; then + echo i386 + else + echo x86 + fi + ;; + ia64*) echo ia64;; + m68*) echo m68k;; + metag*) echo metag;; + microblaze*) echo microblaze;; + mips*) echo mips;; + nios2*) echo nios2;; + nios*) echo nios;; + or1k*|or32*) echo openrisc;; + powerpc*) + # Starting with linux-2.6.15, the 'ppc' and 'ppc64' trees + # have been unified into simply 'powerpc', but until 2.6.16, + # ppc32 is still using ARCH="ppc" as default + if [[ ${type} == "kern" ]] ; then + echo powerpc + elif [[ ${host} == powerpc64* ]] ; then + echo ppc64 + else + echo ppc + fi + ;; + riscv*) echo riscv;; + s390*) echo s390;; + score*) echo score;; + sh64*) ninj sh64 sh;; + sh*) echo sh;; + sparc64*) ninj sparc64 sparc;; + sparc*) [[ ${PROFILE_ARCH} == "sparc64" ]] \ + && ninj sparc64 sparc \ + || echo sparc + ;; + tile*) echo tile;; + vax*) echo vax;; + x86_64*freebsd*) echo amd64;; + x86_64*) + # Starting with linux-2.6.24, the 'x86_64' and 'i386' + # trees have been unified into 'x86'. + if [[ ${type} == "kern" ]] ; then + echo x86 + else + echo amd64 + fi + ;; + xtensa*) echo xtensa;; + + # since our usage of tc-arch is largely concerned with + # normalizing inputs for testing ${CTARGET}, let's filter + # other cross targets (mingw and such) into the unknown. + *) echo unknown;; + esac +} +# @FUNCTION: tc-arch-kernel +# @USAGE: [toolchain prefix] +# @RETURN: name of the kernel arch according to the compiler target +tc-arch-kernel() { + tc-ninja_magic_to_arch kern "$@" +} +# @FUNCTION: tc-arch +# @USAGE: [toolchain prefix] +# @RETURN: name of the portage arch according to the compiler target +tc-arch() { + tc-ninja_magic_to_arch portage "$@" +} + +tc-endian() { + local host=$1 + [[ -z ${host} ]] && host=${CTARGET:-${CHOST}} + host=${host%%-*} + + case ${host} in + aarch64*be) echo big;; + aarch64) echo little;; + alpha*) echo little;; + arm*b*) echo big;; + arm*) echo little;; + cris*) echo little;; + hppa*) echo big;; + i?86*) echo little;; + ia64*) echo little;; + m68*) echo big;; + mips*l*) echo little;; + mips*) echo big;; + powerpc*le) echo little;; + powerpc*) echo big;; + riscv*) echo little;; + s390*) echo big;; + sh*b*) echo big;; + sh*) echo little;; + sparc*) echo big;; + x86_64*) echo little;; + *) echo wtf;; + esac +} + +# @FUNCTION: tc-get-compiler-type +# @RETURN: keyword identifying the compiler: gcc, clang, pathcc, unknown +tc-get-compiler-type() { + local code=' +#if defined(__PATHSCALE__) + HAVE_PATHCC +#elif defined(__clang__) + HAVE_CLANG +#elif defined(__GNUC__) + HAVE_GCC +#endif +' + local res=$($(tc-getCPP "$@") -E -P - <<<"${code}") + + case ${res} in + *HAVE_PATHCC*) echo pathcc;; + *HAVE_CLANG*) echo clang;; + *HAVE_GCC*) echo gcc;; + *) echo unknown;; + esac +} + +# @FUNCTION: tc-is-gcc +# @RETURN: Shell true if the current compiler is GCC, false otherwise. +tc-is-gcc() { + [[ $(tc-get-compiler-type) == gcc ]] +} + +# @FUNCTION: tc-is-clang +# @RETURN: Shell true if the current compiler is clang, false otherwise. +tc-is-clang() { + [[ $(tc-get-compiler-type) == clang ]] +} + +# Internal func. The first argument is the version info to expand. +# Query the preprocessor to improve compatibility across different +# compilers rather than maintaining a --version flag matrix. #335943 +_gcc_fullversion() { + local ver="$1"; shift + set -- $($(tc-getCPP "$@") -E -P - <<<"__GNUC__ __GNUC_MINOR__ __GNUC_PATCHLEVEL__") + eval echo "$ver" +} + +# @FUNCTION: gcc-fullversion +# @RETURN: compiler version (major.minor.micro: [3.4.6]) +gcc-fullversion() { + _gcc_fullversion '$1.$2.$3' "$@" +} +# @FUNCTION: gcc-version +# @RETURN: compiler version (major.minor: [3.4].6) +gcc-version() { + _gcc_fullversion '$1.$2' "$@" +} +# @FUNCTION: gcc-major-version +# @RETURN: major compiler version (major: [3].4.6) +gcc-major-version() { + _gcc_fullversion '$1' "$@" +} +# @FUNCTION: gcc-minor-version +# @RETURN: minor compiler version (minor: 3.[4].6) +gcc-minor-version() { + _gcc_fullversion '$2' "$@" +} +# @FUNCTION: gcc-micro-version +# @RETURN: micro compiler version (micro: 3.4.[6]) +gcc-micro-version() { + _gcc_fullversion '$3' "$@" +} + +# Internal func. Based on _gcc_fullversion() above. +_clang_fullversion() { + local ver="$1"; shift + set -- $($(tc-getCPP "$@") -E -P - <<<"__clang_major__ __clang_minor__ __clang_patchlevel__") + eval echo "$ver" +} + +# @FUNCTION: clang-fullversion +# @RETURN: compiler version (major.minor.micro: [3.4.6]) +clang-fullversion() { + _clang_fullversion '$1.$2.$3' "$@" +} +# @FUNCTION: clang-version +# @RETURN: compiler version (major.minor: [3.4].6) +clang-version() { + _clang_fullversion '$1.$2' "$@" +} +# @FUNCTION: clang-major-version +# @RETURN: major compiler version (major: [3].4.6) +clang-major-version() { + _clang_fullversion '$1' "$@" +} +# @FUNCTION: clang-minor-version +# @RETURN: minor compiler version (minor: 3.[4].6) +clang-minor-version() { + _clang_fullversion '$2' "$@" +} +# @FUNCTION: clang-micro-version +# @RETURN: micro compiler version (micro: 3.4.[6]) +clang-micro-version() { + _clang_fullversion '$3' "$@" +} + +# Returns the installation directory - internal toolchain +# function for use by _gcc-specs-exists (for flag-o-matic). +_gcc-install-dir() { + echo "$(LC_ALL=C $(tc-getCC) -print-search-dirs 2> /dev/null |\ + awk '$1=="install:" {print $2}')" +} +# Returns true if the indicated specs file exists - internal toolchain +# function for use by flag-o-matic. +_gcc-specs-exists() { + [[ -f $(_gcc-install-dir)/$1 ]] +} + +# Returns requested gcc specs directive unprocessed - for used by +# gcc-specs-directive() +# Note; later specs normally overwrite earlier ones; however if a later +# spec starts with '+' then it appends. +# gcc -dumpspecs is parsed first, followed by files listed by "gcc -v" +# as "Reading <file>", in order. Strictly speaking, if there's a +# $(gcc_install_dir)/specs, the built-in specs aren't read, however by +# the same token anything from 'gcc -dumpspecs' is overridden by +# the contents of $(gcc_install_dir)/specs so the result is the +# same either way. +_gcc-specs-directive_raw() { + local cc=$(tc-getCC) + local specfiles=$(LC_ALL=C ${cc} -v 2>&1 | awk '$1=="Reading" {print $NF}') + ${cc} -dumpspecs 2> /dev/null | cat - ${specfiles} | awk -v directive=$1 \ +'BEGIN { pspec=""; spec=""; outside=1 } +$1=="*"directive":" { pspec=spec; spec=""; outside=0; next } + outside || NF==0 || ( substr($1,1,1)=="*" && substr($1,length($1),1)==":" ) { outside=1; next } + spec=="" && substr($0,1,1)=="+" { spec=pspec " " substr($0,2); next } + { spec=spec $0 } +END { print spec }' + return 0 +} + +# Return the requested gcc specs directive, with all included +# specs expanded. +# Note, it does not check for inclusion loops, which cause it +# to never finish - but such loops are invalid for gcc and we're +# assuming gcc is operational. +gcc-specs-directive() { + local directive subdname subdirective + directive="$(_gcc-specs-directive_raw $1)" + while [[ ${directive} == *%\(*\)* ]]; do + subdname=${directive/*%\(} + subdname=${subdname/\)*} + subdirective="$(_gcc-specs-directive_raw ${subdname})" + directive="${directive//\%(${subdname})/${subdirective}}" + done + echo "${directive}" + return 0 +} + +# Returns true if gcc sets relro +gcc-specs-relro() { + local directive + directive=$(gcc-specs-directive link_command) + [[ "${directive/\{!norelro:}" != "${directive}" ]] +} +# Returns true if gcc sets now +gcc-specs-now() { + local directive + directive=$(gcc-specs-directive link_command) + [[ "${directive/\{!nonow:}" != "${directive}" ]] +} +# Returns true if gcc builds PIEs +gcc-specs-pie() { + local directive + directive=$(gcc-specs-directive cc1) + [[ "${directive/\{!nopie:}" != "${directive}" ]] +} +# Returns true if gcc builds with the stack protector +gcc-specs-ssp() { + local directive + directive=$(gcc-specs-directive cc1) + [[ "${directive/\{!fno-stack-protector:}" != "${directive}" ]] +} +# Returns true if gcc upgrades fstack-protector to fstack-protector-all +gcc-specs-ssp-to-all() { + local directive + directive=$(gcc-specs-directive cc1) + [[ "${directive/\{!fno-stack-protector-all:}" != "${directive}" ]] +} +# Returns true if gcc builds with fno-strict-overflow +gcc-specs-nostrict() { + local directive + directive=$(gcc-specs-directive cc1) + [[ "${directive/\{!fstrict-overflow:}" != "${directive}" ]] +} +# Returns true if gcc builds with fstack-check +gcc-specs-stack-check() { + local directive + directive=$(gcc-specs-directive cc1) + [[ "${directive/\{!fno-stack-check:}" != "${directive}" ]] +} + + +# @FUNCTION: tc-enables-pie +# @RETURN: Truth if the current compiler generates position-independent code (PIC) which can be linked into executables +# @DESCRIPTION: +# Return truth if the current compiler generates position-independent code (PIC) +# which can be linked into executables. +tc-enables-pie() { + tc-cpp-is-true "defined(__PIE__)" ${CPPFLAGS} ${CFLAGS} +} + +# @FUNCTION: tc-enables-ssp +# @RETURN: Truth if the current compiler enables stack smashing protection (SSP) on at least minimal level +# @DESCRIPTION: +# Return truth if the current compiler enables stack smashing protection (SSP) +# on level corresponding to any of the following options: +# -fstack-protector +# -fstack-protector-strong +# -fstack-protector-all +tc-enables-ssp() { + tc-cpp-is-true "defined(__SSP__) || defined(__SSP_STRONG__) || defined(__SSP_ALL__)" ${CPPFLAGS} ${CFLAGS} +} + +# @FUNCTION: tc-enables-ssp-strong +# @RETURN: Truth if the current compiler enables stack smashing protection (SSP) on at least middle level +# @DESCRIPTION: +# Return truth if the current compiler enables stack smashing protection (SSP) +# on level corresponding to any of the following options: +# -fstack-protector-strong +# -fstack-protector-all +tc-enables-ssp-strong() { + tc-cpp-is-true "defined(__SSP_STRONG__) || defined(__SSP_ALL__)" ${CPPFLAGS} ${CFLAGS} +} + +# @FUNCTION: tc-enables-ssp-all +# @RETURN: Truth if the current compiler enables stack smashing protection (SSP) on maximal level +# @DESCRIPTION: +# Return truth if the current compiler enables stack smashing protection (SSP) +# on level corresponding to any of the following options: +# -fstack-protector-all +tc-enables-ssp-all() { + tc-cpp-is-true "defined(__SSP_ALL__)" ${CPPFLAGS} ${CFLAGS} +} + + +# @FUNCTION: gen_usr_ldscript +# @USAGE: [-a] <list of libs to create linker scripts for> +# @DESCRIPTION: +# This function is deprecated. Use the version from +# usr-ldscript.eclass instead. +gen_usr_ldscript() { + ewarn "${FUNCNAME}: Please migrate to usr-ldscript.eclass" + + local lib libdir=$(get_libdir) output_format="" auto=false suffix=$(get_libname) + [[ -z ${ED+set} ]] && local ED=${D%/}${EPREFIX}/ + + tc-is-static-only && return + + # We only care about stuffing / for the native ABI. #479448 + if [[ $(type -t multilib_is_native_abi) == "function" ]] ; then + multilib_is_native_abi || return 0 + fi + + # Eventually we'd like to get rid of this func completely #417451 + case ${CTARGET:-${CHOST}} in + *-darwin*) ;; + *-android*) return 0 ;; + *linux*|*-freebsd*|*-openbsd*|*-netbsd*) + use prefix && return 0 ;; + *) return 0 ;; + esac + + # Just make sure it exists + dodir /usr/${libdir} + + if [[ $1 == "-a" ]] ; then + auto=true + shift + dodir /${libdir} + fi + + # OUTPUT_FORMAT gives hints to the linker as to what binary format + # is referenced ... makes multilib saner + local flags=( ${CFLAGS} ${LDFLAGS} -Wl,--verbose ) + if $(tc-getLD) --version | grep -q 'GNU gold' ; then + # If they're using gold, manually invoke the old bfd. #487696 + local d="${T}/bfd-linker" + mkdir -p "${d}" + ln -sf $(which ${CHOST}-ld.bfd) "${d}"/ld + flags+=( -B"${d}" ) + fi + output_format=$($(tc-getCC) "${flags[@]}" 2>&1 | sed -n 's/^OUTPUT_FORMAT("\([^"]*\)",.*/\1/p') + [[ -n ${output_format} ]] && output_format="OUTPUT_FORMAT ( ${output_format} )" + + for lib in "$@" ; do + local tlib + if ${auto} ; then + lib="lib${lib}${suffix}" + else + # Ensure /lib/${lib} exists to avoid dangling scripts/symlinks. + # This especially is for AIX where $(get_libname) can return ".a", + # so /lib/${lib} might be moved to /usr/lib/${lib} (by accident). + [[ -r ${ED}/${libdir}/${lib} ]] || continue + #TODO: better die here? + fi + + case ${CTARGET:-${CHOST}} in + *-darwin*) + if ${auto} ; then + tlib=$(scanmacho -qF'%S#F' "${ED}"/usr/${libdir}/${lib}) + else + tlib=$(scanmacho -qF'%S#F' "${ED}"/${libdir}/${lib}) + fi + [[ -z ${tlib} ]] && die "unable to read install_name from ${lib}" + tlib=${tlib##*/} + + if ${auto} ; then + mv "${ED}"/usr/${libdir}/${lib%${suffix}}.*${suffix#.} "${ED}"/${libdir}/ || die + # some install_names are funky: they encode a version + if [[ ${tlib} != ${lib%${suffix}}.*${suffix#.} ]] ; then + mv "${ED}"/usr/${libdir}/${tlib%${suffix}}.*${suffix#.} "${ED}"/${libdir}/ || die + fi + rm -f "${ED}"/${libdir}/${lib} + fi + + # Mach-O files have an id, which is like a soname, it tells how + # another object linking against this lib should reference it. + # Since we moved the lib from usr/lib into lib this reference is + # wrong. Hence, we update it here. We don't configure with + # libdir=/lib because that messes up libtool files. + # Make sure we don't lose the specific version, so just modify the + # existing install_name + if [[ ! -w "${ED}/${libdir}/${tlib}" ]] ; then + chmod u+w "${ED}${libdir}/${tlib}" # needed to write to it + local nowrite=yes + fi + install_name_tool \ + -id "${EPREFIX}"/${libdir}/${tlib} \ + "${ED}"/${libdir}/${tlib} || die "install_name_tool failed" + [[ -n ${nowrite} ]] && chmod u-w "${ED}${libdir}/${tlib}" + # Now as we don't use GNU binutils and our linker doesn't + # understand linker scripts, just create a symlink. + pushd "${ED}/usr/${libdir}" > /dev/null + ln -snf "../../${libdir}/${tlib}" "${lib}" + popd > /dev/null + ;; + *) + if ${auto} ; then + tlib=$(scanelf -qF'%S#F' "${ED}"/usr/${libdir}/${lib}) + [[ -z ${tlib} ]] && die "unable to read SONAME from ${lib}" + mv "${ED}"/usr/${libdir}/${lib}* "${ED}"/${libdir}/ || die + # some SONAMEs are funky: they encode a version before the .so + if [[ ${tlib} != ${lib}* ]] ; then + mv "${ED}"/usr/${libdir}/${tlib}* "${ED}"/${libdir}/ || die + fi + rm -f "${ED}"/${libdir}/${lib} + else + tlib=${lib} + fi + cat > "${ED}/usr/${libdir}/${lib}" <<-END_LDSCRIPT + /* GNU ld script + Since Gentoo has critical dynamic libraries in /lib, and the static versions + in /usr/lib, we need to have a "fake" dynamic lib in /usr/lib, otherwise we + run into linking problems. This "fake" dynamic lib is a linker script that + redirects the linker to the real lib. And yes, this works in the cross- + compiling scenario as the sysroot-ed linker will prepend the real path. + + See bug https://bugs.gentoo.org/4411 for more info. + */ + ${output_format} + GROUP ( ${EPREFIX}/${libdir}/${tlib} ) + END_LDSCRIPT + ;; + esac + fperms a+x "/usr/${libdir}/${lib}" || die "could not change perms on ${lib}" + done +} + +fi diff --git a/eclass/toolchain-glibc.eclass b/eclass/toolchain-glibc.eclass new file mode 100644 index 0000000..f48f705 --- /dev/null +++ b/eclass/toolchain-glibc.eclass @@ -0,0 +1,1481 @@ +# Copyright 1999-2019 Gentoo Authors +# Distributed under the terms of the GNU General Public License v2 + +# @ECLASS: toolchain-glibc.eclass +# @MAINTAINER: +# <toolchain@gentoo.org> +# @SUPPORTED_EAPIS: 0 1 2 3 4 5 6 +# @BLURB: Common code for sys-libs/glibc ebuilds +# @DESCRIPTION: +# This eclass contains the common phase functions migrated from +# sys-libs/glibc eblits. + +if [[ -z ${_TOOLCHAIN_GLIBC_ECLASS} ]]; then + +inherit eutils versionator toolchain-funcs flag-o-matic gnuconfig \ + multilib systemd unpacker multiprocessing prefix + +case ${EAPI:-0} in + 0|1|2|3) EXPORT_FUNCTIONS pkg_setup src_unpack src_compile src_test \ + src_install pkg_preinst pkg_postinst;; + 2|3) EXPORT_FUNCTIONS pkg_setup src_unpack src_prepare src_configure \ + src_compile src_test src_install pkg_preinst pkg_postinst;; + 4|5) EXPORT_FUNCTIONS pkg_pretend pkg_setup src_unpack src_prepare \ + src_configure src_compile src_test src_install \ + pkg_preinst pkg_postinst;; + 6) EXPORT_FUNCTIONS pkg_pretend;; + *) die "Unsupported EAPI=${EAPI}";; +esac + +# == common == + +alt_prefix() { + is_crosscompile && echo /usr/${CTARGET} +} + +if [[ ${EAPI:-0} == [012] ]] ; then + : ${ED:=${D}} + : ${EROOT:=${ROOT}} +fi +# This indirection is for binpkgs. #523332 +_nonfatal() { nonfatal "$@" ; } +if [[ ${EAPI:-0} == [0123] ]] ; then + nonfatal() { "$@" ; } + _nonfatal() { "$@" ; } +fi + +# We need to be able to set alternative headers for +# compiling for non-native platform +# Will also become useful for testing kernel-headers without screwing up +# the whole system. +# note: intentionally undocumented. +alt_headers() { + echo ${ALT_HEADERS:=$(alt_prefix)/usr/include} +} +alt_build_headers() { + if [[ -z ${ALT_BUILD_HEADERS} ]] ; then + ALT_BUILD_HEADERS="${EPREFIX}$(alt_headers)" + if tc-is-cross-compiler ; then + ALT_BUILD_HEADERS=${SYSROOT}$(alt_headers) + if [[ ! -e ${ALT_BUILD_HEADERS}/linux/version.h ]] ; then + local header_path=$(echo '#include <linux/version.h>' | $(tc-getCPP ${CTARGET}) ${CFLAGS} 2>&1 | grep -o '[^"]*linux/version.h') + ALT_BUILD_HEADERS=${header_path%/linux/version.h} + fi + fi + fi + echo "${ALT_BUILD_HEADERS}" +} + +alt_libdir() { + echo $(alt_prefix)/$(get_libdir) +} +alt_usrlibdir() { + echo $(alt_prefix)/usr/$(get_libdir) +} + +builddir() { + echo "${WORKDIR}/build-${ABI}-${CTARGET}-$1" +} + +setup_target_flags() { + # This largely mucks with compiler flags. None of which should matter + # when building up just the headers. + just_headers && return 0 + + case $(tc-arch) in + x86) + # -march needed for #185404 #199334 + # TODO: When creating the first glibc cross-compile, this test will + # always fail as it does a full link which in turn requires glibc. + # Probably also applies when changing multilib profile settings (e.g. + # enabling x86 when the profile was amd64-only previously). + # We could change main to _start and pass -nostdlib here so that we + # only test the gcc code compilation. Or we could do a compile and + # then look for the symbol via scanelf. + if ! glibc_compile_test "" 'void f(int i, void *p) {if (__sync_fetch_and_add(&i, 1)) f(i, p);}\nint main(){return 0;}\n' 2>/dev/null ; then + local t=${CTARGET_OPT:-${CTARGET}} + t=${t%%-*} + filter-flags '-march=*' + export CFLAGS="-march=${t} ${CFLAGS}" + einfo "Auto adding -march=${t} to CFLAGS #185404" + fi + ;; + amd64) + # -march needed for #185404 #199334 + # Note: This test only matters when the x86 ABI is enabled, so we could + # optimize a bit and elide it. + # TODO: See cross-compile issues listed above for x86. + if ! glibc_compile_test "${CFLAGS_x86}" 'void f(int i, void *p) {if (__sync_fetch_and_add(&i, 1)) f(i, p);}\nint main(){return 0;}\n' 2>/dev/null ; then + local t=${CTARGET_OPT:-${CTARGET}} + t=${t%%-*} + # Normally the target is x86_64-xxx, so turn that into the -march that + # gcc actually accepts. #528708 + [[ ${t} == "x86_64" ]] && t="x86-64" + filter-flags '-march=*' + # ugly, ugly, ugly. ugly. + CFLAGS_x86=$(CFLAGS=${CFLAGS_x86} filter-flags '-march=*'; echo "${CFLAGS}") + export CFLAGS_x86="${CFLAGS_x86} -march=${t}" + einfo "Auto adding -march=${t} to CFLAGS_x86 #185404" + fi + ;; + mips) + # The mips abi cannot support the GNU style hashes. #233233 + filter-ldflags -Wl,--hash-style=gnu -Wl,--hash-style=both + ;; + sparc) + # Both sparc and sparc64 can use -fcall-used-g6. -g7 is bad, though. + filter-flags "-fcall-used-g7" + append-flags "-fcall-used-g6" + + # If the CHOST is the basic one (e.g. not sparcv9-xxx already), + # try to pick a better one so glibc can use cpu-specific .S files. + # We key off the CFLAGS to get a good value. Also need to handle + # version skew. + # We can't force users to set their CHOST to their exact machine + # as many of these are not recognized by config.sub/gcc and such :(. + # Note: If the mcpu values don't scale, we might try probing CPP defines. + # Note: Should we factor in -Wa,-AvXXX flags too ? Or -mvis/etc... ? + + local cpu + case ${CTARGET} in + sparc64-*) + case $(get-flag mcpu) in + niagara[234]) + if version_is_at_least 2.8 ; then + cpu="sparc64v2" + elif version_is_at_least 2.4 ; then + cpu="sparc64v" + elif version_is_at_least 2.2.3 ; then + cpu="sparc64b" + fi + ;; + niagara) + if version_is_at_least 2.4 ; then + cpu="sparc64v" + elif version_is_at_least 2.2.3 ; then + cpu="sparc64b" + fi + ;; + ultrasparc3) + cpu="sparc64b" + ;; + *) + # We need to force at least v9a because the base build doesn't + # work with just v9. + # https://sourceware.org/bugzilla/show_bug.cgi?id=19477 + [[ -z ${cpu} ]] && append-flags "-Wa,-xarch=v9a" + ;; + esac + ;; + sparc-*) + case $(get-flag mcpu) in + niagara[234]) + if version_is_at_least 2.8 ; then + cpu="sparcv9v2" + elif version_is_at_least 2.4 ; then + cpu="sparcv9v" + elif version_is_at_least 2.2.3 ; then + cpu="sparcv9b" + else + cpu="sparcv9" + fi + ;; + niagara) + if version_is_at_least 2.4 ; then + cpu="sparcv9v" + elif version_is_at_least 2.2.3 ; then + cpu="sparcv9b" + else + cpu="sparcv9" + fi + ;; + ultrasparc3) + cpu="sparcv9b" + ;; + v9|ultrasparc) + cpu="sparcv9" + ;; + v8|supersparc|hypersparc|leon|leon3) + cpu="sparcv8" + ;; + esac + ;; + esac + [[ -n ${cpu} ]] && CTARGET_OPT="${cpu}-${CTARGET#*-}" + ;; + esac +} + +setup_flags() { + # Make sure host make.conf doesn't pollute us + if is_crosscompile || tc-is-cross-compiler ; then + CHOST=${CTARGET} strip-unsupported-flags + fi + + # Store our CFLAGS because it's changed depending on which CTARGET + # we are building when pulling glibc on a multilib profile + CFLAGS_BASE=${CFLAGS_BASE-${CFLAGS}} + CFLAGS=${CFLAGS_BASE} + CXXFLAGS_BASE=${CXXFLAGS_BASE-${CXXFLAGS}} + CXXFLAGS=${CXXFLAGS_BASE} + ASFLAGS_BASE=${ASFLAGS_BASE-${ASFLAGS}} + ASFLAGS=${ASFLAGS_BASE} + + # Over-zealous CFLAGS can often cause problems. What may work for one + # person may not work for another. To avoid a large influx of bugs + # relating to failed builds, we strip most CFLAGS out to ensure as few + # problems as possible. + strip-flags + strip-unsupported-flags + filter-flags -m32 -m64 -mabi=* + filter-ldflags -Wl,-rpath=* + + # Bug 492892. + filter-flags -frecord-gcc-switches + + unset CBUILD_OPT CTARGET_OPT + if use multilib ; then + CTARGET_OPT=$(get_abi_CTARGET) + [[ -z ${CTARGET_OPT} ]] && CTARGET_OPT=$(get_abi_CHOST) + fi + + setup_target_flags + + if [[ -n ${CTARGET_OPT} && ${CBUILD} == ${CHOST} ]] && ! is_crosscompile; then + CBUILD_OPT=${CTARGET_OPT} + fi + + # Lock glibc at -O2 -- linuxthreads needs it and we want to be + # conservative here. -fno-strict-aliasing is to work around #155906 + filter-flags -O? + append-flags -O2 -fno-strict-aliasing + + # Can't build glibc itself with fortify code. Newer versions add + # this flag for us, so no need to do it manually. + version_is_at_least 2.16 ${PV} || append-cppflags -U_FORTIFY_SOURCE + + # building glibc <2.25 with SSP is fraught with difficulty, especially + # due to __stack_chk_fail_local which would mean significant changes + # to the glibc build process. See bug #94325 #293721 + # Note we have to handle both user-given CFLAGS and gcc defaults via + # spec rules here. We can't simply add -fno-stack-protector as it gets + # added before user flags, and we can't just filter-flags because + # _filter_hardened doesn't support globs. + filter-flags -fstack-protector* + if ! version_is_at_least 2.25 ; then + tc-enables-ssp && append-flags $(test-flags -fno-stack-protector) + fi + + if [[ $(gcc-major-version) -lt 6 ]]; then + # Starting with gcc-6 (and fully upstreamed pie patches) we control + # default enabled/disabled pie via use flags. So nothing to do + # here. #618160 + + if use hardened && tc-enables-pie ; then + # Force PIC macro definition for all compilations since they're all + # either -fPIC or -fPIE with the default-PIE compiler. + append-cppflags -DPIC + else + # Don't build -fPIE without the default-PIE compiler and the + # hardened-pie patch + filter-flags -fPIE + fi + fi +} + +want_nptl() { + [[ -z ${LT_VER} ]] && return 0 + want_tls || return 1 + use nptl || return 1 + + # Older versions of glibc had incomplete arch support for nptl. + # But if you're building those now, you can handle USE=nptl yourself. + return 0 +} + +want_linuxthreads() { + [[ -z ${LT_VER} ]] && return 1 + use linuxthreads +} + +want_tls() { + # Archs that can use TLS (Thread Local Storage) + case $(tc-arch) in + x86) + # requires i486 or better #106556 + [[ ${CTARGET} == i[4567]86* ]] && return 0 + return 1 + ;; + esac + + return 0 +} + +want__thread() { + want_tls || return 1 + + # For some reason --with-tls --with__thread is causing segfaults on sparc32. + [[ ${PROFILE_ARCH} == "sparc" ]] && return 1 + + [[ -n ${WANT__THREAD} ]] && return ${WANT__THREAD} + + # only test gcc -- can't test linking yet + tc-has-tls -c ${CTARGET} + WANT__THREAD=$? + + return ${WANT__THREAD} +} + +use_multiarch() { + # Make sure binutils is new enough to support indirect functions #336792 + # This funky sed supports gold and bfd linkers. + local bver nver + bver=$($(tc-getLD ${CTARGET}) -v | sed -n -r '1{s:[^0-9]*::;s:^([0-9.]*).*:\1:;p}') + case $(tc-arch ${CTARGET}) in + amd64|x86) nver="2.20" ;; + arm) nver="2.22" ;; + hppa) nver="2.23" ;; + ppc|ppc64) nver="2.20" ;; + # ifunc was added in 2.23, but glibc also needs machinemode which is in 2.24. + s390) nver="2.24" ;; + sparc) nver="2.21" ;; + *) return 1 ;; + esac + version_is_at_least ${nver} ${bver} +} + +# Setup toolchain variables that had historically +# been defined in the profiles for these archs. +setup_env() { + # silly users + unset LD_RUN_PATH + unset LD_ASSUME_KERNEL + + if is_crosscompile || tc-is-cross-compiler ; then + multilib_env ${CTARGET_OPT:-${CTARGET}} + + if ! use multilib ; then + MULTILIB_ABIS=${DEFAULT_ABI} + else + MULTILIB_ABIS=${MULTILIB_ABIS:-${DEFAULT_ABI}} + fi + + # If the user has CFLAGS_<CTARGET> in their make.conf, use that, + # and fall back on CFLAGS. + local VAR=CFLAGS_${CTARGET//[-.]/_} + CFLAGS=${!VAR-${CFLAGS}} + einfo " $(printf '%15s' 'Manual CFLAGS:') ${CFLAGS}" + fi + + setup_flags + + export ABI=${ABI:-${DEFAULT_ABI:-default}} + + if just_headers ; then + # Avoid mixing host's CC and target's CFLAGS_${ABI}: + # At this bootstrap stage we have only binutils for + # target but not compiler yet. + einfo "Skip CC ABI injection. We can't use (cross-)compiler yet." + return 0 + fi + + local VAR=CFLAGS_${ABI} + # We need to export CFLAGS with abi information in them because glibc's + # configure script checks CFLAGS for some targets (like mips). Keep + # around the original clean value to avoid appending multiple ABIs on + # top of each other. + : ${__GLIBC_CC:=$(tc-getCC ${CTARGET_OPT:-${CTARGET}})} + export __GLIBC_CC CC="${__GLIBC_CC} ${!VAR}" + einfo " $(printf '%15s' 'Manual CC:') ${CC}" +} + +foreach_abi() { + setup_env + + local ret=0 + local abilist="" + if use multilib ; then + abilist=$(get_install_abis) + else + abilist=${DEFAULT_ABI} + fi + local -x ABI + for ABI in ${abilist:-default} ; do + setup_env + einfo "Running $1 for ABI ${ABI}" + $1 + : $(( ret |= $? )) + done + return ${ret} +} + +just_headers() { + is_crosscompile && use headers-only +} + +glibc_banner() { + local b="Gentoo ${PVR}" + [[ -n ${SNAP_VER} ]] && b+=" snapshot ${SNAP_VER}" + [[ -n ${PATCH_VER} ]] && ! use vanilla && b+=" p${PATCH_VER}" + echo "${b}" +} + +# == phases == + +glibc_compile_test() { + local ret save_cflags=${CFLAGS} + CFLAGS+=" $1" + shift + + pushd "${T}" >/dev/null + + rm -f glibc-test* + printf '%b' "$*" > glibc-test.c + + _nonfatal emake -s glibc-test + ret=$? + + popd >/dev/null + + CFLAGS=${save_cflags} + return ${ret} +} + +glibc_run_test() { + local ret + + if [[ ${EMERGE_FROM} == "binary" ]] ; then + # ignore build failures when installing a binary package #324685 + glibc_compile_test "" "$@" 2>/dev/null || return 0 + else + if ! glibc_compile_test "" "$@" ; then + ewarn "Simple build failed ... assuming this is desired #324685" + return 0 + fi + fi + + pushd "${T}" >/dev/null + + ./glibc-test + ret=$? + rm -f glibc-test* + + popd >/dev/null + + return ${ret} +} + +check_devpts() { + # Make sure devpts is mounted correctly for use w/out setuid pt_chown. + + # If merely building the binary package, then there's nothing to verify. + [[ ${MERGE_TYPE} == "buildonly" ]] && return + + # Only sanity check when installing the native glibc. + [[ ${ROOT} != "/" ]] && return + + # Older versions always installed setuid, so no need to check. + in_iuse suid || return + + # If they're opting in to the old suid code, then no need to check. + use suid && return + + if awk '$3 == "devpts" && $4 ~ /[, ]gid=5[, ]/ { exit 1 }' /proc/mounts ; then + eerror "In order to use glibc with USE=-suid, you must make sure that" + eerror "you have devpts mounted at /dev/pts with the gid=5 option." + eerror "Openrc should do this for you, so you should check /etc/fstab" + eerror "and make sure you do not have any invalid settings there." + # Do not die on older kernels as devpts did not export these settings #489520. + if version_is_at_least 2.6.25 $(uname -r) ; then + die "mount & fix your /dev/pts settings" + fi + fi +} + +toolchain-glibc_pkg_pretend() { + if [[ ${EAPI:-0} == 6 ]]; then + eerror "We're moving code back to the ebuilds to get away from the ancient EAPI cruft." + eerror "From EAPI=6 on you'll have to define the phases in the glibc ebuilds." + die "Silly overlay authors..." + fi + + # For older EAPIs, this is run in pkg_preinst. + if [[ ${EAPI:-0} != [0123] ]] ; then + check_devpts + fi + + # Prevent native builds from downgrading. + if [[ ${MERGE_TYPE} != "buildonly" ]] && \ + [[ ${ROOT} == "/" ]] && \ + [[ ${CBUILD} == ${CHOST} ]] && \ + [[ ${CHOST} == ${CTARGET} ]] ; then + # The high rev # is to allow people to downgrade between -r# versions. + # We want to block 2.20->2.19, but 2.20-r3->2.20-r2 should be fine. + # Hopefully we never actually use a r# this high. + if has_version ">${CATEGORY}/${P}-r10000" ; then + eerror "Sanity check to keep you from breaking your system:" + eerror " Downgrading glibc is not supported and a sure way to destruction" + [[ ${I_ALLOW_TO_BREAK_MY_SYSTEM} = yes ]] || die "Aborting to save your system." + fi + + if ! glibc_run_test '#include <pwd.h>\nint main(){return getpwuid(0)==0;}\n' + then + eerror "Your patched vendor kernel is broken. You need to get an" + eerror "update from whoever is providing the kernel to you." + eerror "https://sourceware.org/bugzilla/show_bug.cgi?id=5227" + eerror "http://bugs.gentoo.org/262698" + die "keeping your system alive, say thank you" + fi + + if ! glibc_run_test '#include <unistd.h>\n#include <sys/syscall.h>\nint main(){return syscall(1000)!=-1;}\n' + then + eerror "Your old kernel is broken. You need to update it to" + eerror "a newer version as syscall(<bignum>) will break." + eerror "http://bugs.gentoo.org/279260" + die "keeping your system alive, say thank you" + fi + fi + + # users have had a chance to phase themselves, time to give em the boot + if [[ -e ${EROOT}/etc/locale.gen ]] && [[ -e ${EROOT}/etc/locales.build ]] ; then + eerror "You still haven't deleted ${EROOT}/etc/locales.build." + eerror "Do so now after making sure ${EROOT}/etc/locale.gen is kosher." + die "lazy upgrader detected" + fi + + if [[ ${CTARGET} == i386-* ]] ; then + eerror "i386 CHOSTs are no longer supported." + eerror "Chances are you don't actually want/need i386." + eerror "Please read http://www.gentoo.org/doc/en/change-chost.xml" + die "please fix your CHOST" + fi + + if [[ -e /proc/xen ]] && [[ $(tc-arch) == "x86" ]] && ! is-flag -mno-tls-direct-seg-refs ; then + ewarn "You are using Xen but don't have -mno-tls-direct-seg-refs in your CFLAGS." + ewarn "This will result in a 50% performance penalty when running with a 32bit" + ewarn "hypervisor, which is probably not what you want." + fi + + # Make sure host system is up to date #394453 + if has_version '<sys-libs/glibc-2.13' && \ + [[ -n $(scanelf -qys__guard -F'#s%F' "${EROOT}"/lib*/l*-*.so) ]] + then + ebegin "Scanning system for __guard to see if you need to rebuild first ..." + local files=$( + scanelf -qys__guard -F'#s%F' \ + "${EROOT}"/*bin/ \ + "${EROOT}"/lib* \ + "${EROOT}"/usr/*bin/ \ + "${EROOT}"/usr/lib* | \ + egrep -v \ + -e "^${EROOT}/lib.*/(libc|ld)-2.*.so$" \ + -e "^${EROOT}/sbin/(ldconfig|sln)$" + ) + [[ -z ${files} ]] + if ! eend $? ; then + eerror "Your system still has old SSP __guard symbols. You need to" + eerror "rebuild all the packages that provide these files first:" + eerror "${files}" + die "old __guard detected" + fi + fi +} + +toolchain-glibc_pkg_setup() { + [[ ${EAPI:-0} == [0123] ]] && toolchain-glibc_pkg_pretend +} + +# The following Kernel version handling functions are mostly copied from portage +# source. It's better not to use linux-info.eclass here since a) it adds too +# much magic, see bug 326693 for some of the arguments, and b) some of the +# functions are just not provided. + +tc_glibc_get_KV() { + uname -r + return $? +} + +tc_glibc_KV_major() { + [[ -z $1 ]] && return 1 + local KV=$@ + echo "${KV%%.*}" +} + +tc_glibc_KV_minor() { + [[ -z $1 ]] && return 1 + local KV=$@ + KV=${KV#*.} + echo "${KV%%.*}" +} + +tc_glibc_KV_micro() { + [[ -z $1 ]] && return 1 + local KV=$@ + KV=${KV#*.*.} + echo "${KV%%[^[:digit:]]*}" +} + +tc_glibc_KV_to_int() { + [[ -z $1 ]] && return 1 + local KV_MAJOR=$(tc_glibc_KV_major "$1") + local KV_MINOR=$(tc_glibc_KV_minor "$1") + local KV_MICRO=$(tc_glibc_KV_micro "$1") + local KV_int=$(( KV_MAJOR * 65536 + KV_MINOR * 256 + KV_MICRO )) + + # We make version 2.2.0 the minimum version we will handle as + # a sanity check ... if its less, we fail ... + if [[ ${KV_int} -ge 131584 ]] ; then + echo "${KV_int}" + return 0 + fi + return 1 +} + +tc_glibc_int_to_KV() { + local version=$1 major minor micro + major=$((version / 65536)) + minor=$(((version % 65536) / 256)) + micro=$((version % 256)) + echo ${major}.${minor}.${micro} +} + +eend_KV() { + [[ $(tc_glibc_KV_to_int $1) -ge $(tc_glibc_KV_to_int $2) ]] + eend $? +} + +get_kheader_version() { + printf '#include <linux/version.h>\nLINUX_VERSION_CODE\n' | \ + $(tc-getCPP ${CTARGET}) -I "$(alt_build_headers)" - | \ + tail -n 1 +} + +check_nptl_support() { + # don't care about the compiler here as we aren't using it + just_headers && return + + local run_kv build_kv want_kv + run_kv=$(tc_glibc_get_KV) + build_kv=$(tc_glibc_int_to_KV $(get_kheader_version)) + want_kv=${NPTL_KERN_VER} + + ebegin "Checking gcc for __thread support" + if ! eend $(want__thread ; echo $?) ; then + echo + eerror "Could not find a gcc that supports the __thread directive!" + eerror "Please update your binutils/gcc and try again." + die "No __thread support in gcc!" + fi + + if ! is_crosscompile && ! tc-is-cross-compiler ; then + # Building fails on an non-supporting kernel + ebegin "Checking kernel version (${run_kv} >= ${want_kv})" + if ! eend_KV ${run_kv} ${want_kv} ; then + echo + eerror "You need a kernel of at least ${want_kv} for NPTL support!" + die "Kernel version too low!" + fi + fi + + ebegin "Checking linux-headers version (${build_kv} >= ${want_kv})" + if ! eend_KV ${build_kv} ${want_kv} ; then + echo + eerror "You need linux-headers of at least ${want_kv} for NPTL support!" + die "linux-headers version too low!" + fi +} + +unpack_pkg() { + local a=${PN} + [[ -n ${SNAP_VER} ]] && a="${a}-${RELEASE_VER}" + [[ -n $1 ]] && a="${a}-$1" + if [[ -n ${SNAP_VER} ]] ; then + a="${a}-${SNAP_VER}" + else + if [[ -n $2 ]] ; then + a="${a}-$2" + else + a="${a}-${RELEASE_VER}" + fi + fi + if has ${a}.tar.xz ${A} ; then + unpacker ${a}.tar.xz + else + unpack ${a}.tar.bz2 + fi + [[ -n $1 ]] && { mv ${a} $1 || die ; } +} + +toolchain-glibc_do_src_unpack() { + # Check NPTL support _before_ we unpack things to save some time + want_nptl && check_nptl_support + + unpack_pkg + + cd "${S}" + touch locale/C-translit.h #185476 #218003 + [[ -n ${LT_VER} ]] && unpack_pkg linuxthreads ${LT_VER} + [[ -n ${PORTS_VER} ]] && unpack_pkg ports ${PORTS_VER} + [[ -n ${LIBIDN_VER} ]] && unpack_pkg libidn + + if [[ -n ${PATCH_VER} ]] ; then + cd "${WORKDIR}" + unpack glibc-${RELEASE_VER}-patches-${PATCH_VER}.tar.bz2 + # pull out all the addons + local d + for d in extra/*/configure ; do + d=${d%/configure} + [[ -d ${S}/${d} ]] && die "${d} already exists in \${S}" + mv "${d}" "${S}" || die "moving ${d} failed" + done + fi +} + +toolchain-glibc_src_unpack() { + setup_env + + toolchain-glibc_do_src_unpack + [[ ${EAPI:-0} == [01] ]] && cd "${S}" && toolchain-glibc_src_prepare +} + +toolchain-glibc_src_prepare() { + # tag, glibc is it + if ! version_is_at_least 2.17 ; then + [[ -e csu/Banner ]] && die "need new banner location" + glibc_banner > csu/Banner + fi + if [[ -n ${PATCH_VER} ]] && ! use vanilla ; then + EPATCH_MULTI_MSG="Applying Gentoo Glibc Patchset ${RELEASE_VER}-${PATCH_VER} ..." \ + EPATCH_EXCLUDE=${GLIBC_PATCH_EXCLUDE} \ + EPATCH_SUFFIX="patch" \ + ARCH=$(tc-arch) \ + epatch "${WORKDIR}"/patches + fi + + if just_headers ; then + if [[ -e ports/sysdeps/mips/preconfigure ]] ; then + # mips peeps like to screw with us. if building headers, + # we don't have a real compiler, so we can't let them + # insert -mabi on us. + sed -i '/CPPFLAGS=.*-mabi/s|.*|:|' ports/sysdeps/mips/preconfigure || die + find ports/sysdeps/mips/ -name Makefile -exec sed -i '/^CC.*-mabi=/s:-mabi=.*:-D_MIPS_SZPTR=32:' {} + + fi + fi + + epatch_user + + gnuconfig_update + + # Glibc is stupid sometimes, and doesn't realize that with a + # static C-Only gcc, -lgcc_eh doesn't exist. + # https://sourceware.org/ml/libc-alpha/2003-09/msg00100.html + # https://sourceware.org/ml/libc-alpha/2005-02/msg00042.html + # But! Finally fixed in recent versions: + # https://sourceware.org/ml/libc-alpha/2012-05/msg01865.html + if ! version_is_at_least 2.16 ; then + echo 'int main(){}' > "${T}"/gcc_eh_test.c + if ! $(tc-getCC ${CTARGET}) ${CFLAGS} ${LDFLAGS} "${T}"/gcc_eh_test.c -lgcc_eh 2>/dev/null ; then + sed -i -e 's:-lgcc_eh::' Makeconfig || die "sed gcc_eh" + fi + fi + + cd "${WORKDIR}" + find . -type f '(' -size 0 -o -name "*.orig" ')' -delete + find . -name configure -exec touch {} + + + eprefixify extra/locale/locale-gen + + # Fix permissions on some of the scripts. + chmod u+x "${S}"/scripts/*.sh +} +dump_toolchain_settings() { + echo + + einfo "$*" + + local v + for v in ABI CBUILD CHOST CTARGET CBUILD_OPT CTARGET_OPT CC LD {AS,C,CPP,CXX,LD}FLAGS ; do + einfo " $(printf '%15s' ${v}:) ${!v}" + done + + # The glibc configure script doesn't properly use LDFLAGS all the time. + export CC="$(tc-getCC ${CTARGET}) ${LDFLAGS}" + einfo " $(printf '%15s' 'Manual CC:') ${CC}" + echo +} + +glibc_do_configure() { + # Glibc does not work with gold (for various reasons) #269274. + tc-ld-disable-gold + + dump_toolchain_settings "Configuring glibc for $1" + + local myconf=() + + # set addons + pushd "${S}" > /dev/null + local addons=$(echo */configure | sed \ + -e 's:/configure::g' \ + -e 's:\(linuxthreads\|nptl\|rtkaio\|glibc-compat\)\( \|$\)::g' \ + -e 's: \+$::' \ + -e 's! !,!g' \ + -e 's!^!,!' \ + -e '/^,\*$/d') + [[ -d ports ]] && addons+=",ports" + popd > /dev/null + + if has_version '<sys-libs/glibc-2.13' ; then + myconf+=( --enable-old-ssp-compat ) + fi + + if version_is_at_least 2.25 ; then + case ${CTARGET} in + m68k*) + # setjmp() is not compatible with stack protection: + # https://sourceware.org/PR24202 + myconf+=( --enable-stack-protector=no ) + ;; + mips*) + # dlopen() detects stack smash on mips n32 ABI. + # Cause is unknown: https://bugs.gentoo.org/640130 + myconf+=( --enable-stack-protector=no ) + ;; + powerpc-*) + # Currently gcc on powerpc32 generates invalid code for + # __builtin_return_address(0) calls. Normally programs + # don't do that but malloc hooks in glibc do: + # https://gcc.gnu.org/PR81996 + # https://bugs.gentoo.org/629054 + myconf+=( --enable-stack-protector=no ) + ;; + *) + myconf+=( --enable-stack-protector=all ) + ;; + esac + fi + + # Keep a whitelist of targets supporing IFUNC. glibc's ./configure + # is not robust enough to detect proper support: + # https://bugs.gentoo.org/641216 + # https://sourceware.org/PR22634#c0 + case $(tc-arch ${CTARGET}) in + # Keep whitelist of targets where autodetection mostly works. + amd64|x86|sparc|ppc|ppc64|arm|arm64|s390) ;; + # Blacklist everywhere else + *) myconf+=( libc_cv_ld_gnu_indirect_function=no ) ;; + esac + + if version_is_at_least 2.25 ; then + myconf+=( --enable-stackguard-randomization ) + else + myconf+=( $(use_enable hardened stackguard-randomization) ) + fi + + [[ $(tc-is-softfloat) == "yes" ]] && myconf+=( --without-fp ) + + if [[ $1 == "linuxthreads" ]] ; then + if want_tls ; then + myconf+=( --with-tls ) + + if ! want__thread || use glibc-compat20 || [[ ${LT_KER_VER} == 2.[02].* ]] ; then + myconf+=( --without-__thread ) + else + myconf+=( --with-__thread ) + fi + else + myconf+=( --without-tls --without-__thread ) + fi + + myconf+=( --disable-sanity-checks ) + addons="linuxthreads${addons}" + myconf+=( --enable-kernel=${LT_KER_VER} ) + elif [[ $1 == "nptl" ]] ; then + # Newer versions require nptl, so there is no addon for it. + version_is_at_least 2.20 || addons="nptl${addons}" + myconf+=( --enable-kernel=${NPTL_KERN_VER} ) + else + die "invalid pthread option" + fi + myconf+=( --enable-add-ons="${addons#,}" ) + + # Since SELinux support is only required for nscd, only enable it if: + # 1. USE selinux + # 2. only for the primary ABI on multilib systems + # 3. Not a crosscompile + if ! is_crosscompile && use selinux ; then + if use multilib ; then + if is_final_abi ; then + myconf+=( --with-selinux ) + else + myconf+=( --without-selinux ) + fi + else + myconf+=( --with-selinux ) + fi + else + myconf+=( --without-selinux ) + fi + + # Force a few tests where we always know the answer but + # configure is incapable of finding it. + if is_crosscompile ; then + export \ + libc_cv_c_cleanup=yes \ + libc_cv_forced_unwind=yes + fi + + myconf+=( + --without-cvs + --disable-werror + --enable-bind-now + --build=${CBUILD_OPT:-${CBUILD}} + --host=${CTARGET_OPT:-${CTARGET}} + $(use_enable profile) + $(use_with gd) + --with-headers=$(alt_build_headers) + --prefix="${EPREFIX}/usr" + --sysconfdir="${EPREFIX}/etc" + --localstatedir="${EPREFIX}/var" + --libdir='$(prefix)'/$(get_libdir) + --mandir='$(prefix)'/share/man + --infodir='$(prefix)'/share/info + --libexecdir='$(libdir)'/misc/glibc + --with-bugurl=http://bugs.gentoo.org/ + --with-pkgversion="$(glibc_banner)" + $(use_multiarch || echo --disable-multi-arch) + $(in_iuse rpc && use_enable rpc obsolete-rpc || echo --enable-obsolete-rpc) + $(in_iuse systemtap && use_enable systemtap) + $(in_iuse nscd && use_enable nscd) + ${EXTRA_ECONF} + ) + + # We rely on sys-libs/timezone-data for timezone tools normally. + if version_is_at_least 2.23 ; then + myconf+=( $(use_enable vanilla timezone-tools) ) + fi + + # These libs don't have configure flags. + ac_cv_lib_audit_audit_log_user_avc_message=$(in_iuse audit && usex audit || echo no) + ac_cv_lib_cap_cap_init=$(in_iuse caps && usex caps || echo no) + + # There is no configure option for this and we need to export it + # since the glibc build will re-run configure on itself + export libc_cv_rootsbindir="${EPREFIX}/sbin" + export libc_cv_slibdir="${EPREFIX}/$(get_libdir)" + + # We take care of patching our binutils to use both hash styles, + # and many people like to force gnu hash style only, so disable + # this overriding check. #347761 + export libc_cv_hashstyle=no + + # Overtime, generating info pages can be painful. So disable this for + # versions older than the latest stable to avoid the issue (this ver + # should be updated from time to time). #464394 #465816 + if ! version_is_at_least 2.17 ; then + export ac_cv_prog_MAKEINFO=: + fi + + local builddir=$(builddir "$1") + mkdir -p "${builddir}" + cd "${builddir}" + set -- "${S}"/configure "${myconf[@]}" + echo "$@" + "$@" || die "failed to configure glibc" + + # ia64 static cross-compilers are a pita in so much that they + # can't produce static ELFs (as the libgcc.a is broken). so + # disable building of the programs for those targets if it + # doesn't work. + # XXX: We could turn this into a compiler test, but ia64 is + # the only one that matters, so this should be fine for now. + if is_crosscompile && [[ ${CTARGET} == ia64* ]] ; then + sed -i '1i+link-static = touch $@' config.make + fi + + # If we're trying to migrate between ABI sets, we need + # to lie and use a local copy of gcc. Like if the system + # is built with MULTILIB_ABIS="amd64 x86" but we want to + # add x32 to it, gcc/glibc don't yet support x32. + if [[ -n ${GCC_BOOTSTRAP_VER} ]] && use multilib ; then + echo 'main(){}' > "${T}"/test.c + if ! $(tc-getCC ${CTARGET}) ${CFLAGS} ${LDFLAGS} "${T}"/test.c -Wl,-emain -lgcc 2>/dev/null ; then + sed -i -e '/^CC = /s:$: -B$(objdir)/../'"gcc-${GCC_BOOTSTRAP_VER}/${ABI}:" config.make || die + mkdir -p sunrpc + cp $(which rpcgen) sunrpc/cross-rpcgen || die + touch -t 202001010101 sunrpc/cross-rpcgen || die + fi + fi +} + +toolchain-glibc_headers_configure() { + export ABI=default + + local builddir=$(builddir "headers") + mkdir -p "${builddir}" + cd "${builddir}" + + # if we don't have a compiler yet, we can't really test it now ... + # hopefully they don't affect header generation, so let's hope for + # the best here ... + local v vars=( + ac_cv_header_cpuid_h=yes + libc_cv_{386,390,alpha,arm,hppa,ia64,mips,{powerpc,sparc}{,32,64},sh,x86_64}_tls=yes + libc_cv_asm_cfi_directives=yes + libc_cv_broken_visibility_attribute=no + libc_cv_c_cleanup=yes + libc_cv_forced_unwind=yes + libc_cv_gcc___thread=yes + libc_cv_mlong_double_128=yes + libc_cv_mlong_double_128ibm=yes + libc_cv_ppc_machine=yes + libc_cv_ppc_rel16=yes + libc_cv_predef_fortify_source=no + libc_cv_visibility_attribute=yes + libc_cv_z_combreloc=yes + libc_cv_z_execstack=yes + libc_cv_z_initfirst=yes + libc_cv_z_nodelete=yes + libc_cv_z_nodlopen=yes + libc_cv_z_relro=yes + libc_mips_abi=${ABI} + libc_mips_float=$([[ $(tc-is-softfloat) == "yes" ]] && echo soft || echo hard) + # These libs don't have configure flags. + ac_cv_lib_audit_audit_log_user_avc_message=no + ac_cv_lib_cap_cap_init=no + ) + if ! version_is_at_least 2.25 ; then + vars+=( + libc_cv_predef_stack_protector=no + ) + fi + einfo "Forcing cached settings:" + for v in "${vars[@]}" ; do + einfo " ${v}" + export ${v} + done + + # Blow away some random CC settings that screw things up. #550192 + if [[ -d ${S}/sysdeps/mips ]]; then + pushd "${S}"/sysdeps/mips >/dev/null + sed -i -e '/^CC +=/s:=.*:= -D_MIPS_SZPTR=32:' mips32/Makefile mips64/n32/Makefile || die + sed -i -e '/^CC +=/s:=.*:= -D_MIPS_SZPTR=64:' mips64/n64/Makefile || die + if version_is_at_least 2.21 ; then + # Force the mips ABI to the default. This is OK because the set of + # installed headers in this phase is the same between the 3 ABIs. + # If this ever changes, this hack will break, but that's unlikely + # as glibc discourages that behavior. + # https://crbug.com/647033 + sed -i -e 's:abiflag=.*:abiflag=_ABIO32:' preconfigure || die + fi + popd >/dev/null + fi + + local myconf=() + myconf+=( + --disable-sanity-checks + --enable-hacker-mode + --without-cvs + --disable-werror + --enable-bind-now + --build=${CBUILD_OPT:-${CBUILD}} + --host=${CTARGET_OPT:-${CTARGET}} + --with-headers=$(alt_build_headers) + --prefix="${EPREFIX}/usr" + ${EXTRA_ECONF} + ) + + local addons + [[ -d ${S}/ports ]] && addons+=",ports" + # Newer versions require nptl, so there is no addon for it. + version_is_at_least 2.20 || addons+=",nptl" + myconf+=( --enable-add-ons="${addons#,}" ) + + # Nothing is compiled here which would affect the headers for the target. + # So forcing CC/CFLAGS is sane. + set -- "${S}"/configure "${myconf[@]}" + echo "$@" + CC="$(tc-getBUILD_CC)" \ + CFLAGS="-O1 -pipe" \ + CPPFLAGS="-U_FORTIFY_SOURCE" \ + LDFLAGS="" \ + "$@" || die "failed to configure glibc" +} + +toolchain-glibc_do_src_configure() { + if just_headers ; then + toolchain-glibc_headers_configure + else + want_linuxthreads && glibc_do_configure linuxthreads + want_nptl && glibc_do_configure nptl + fi +} + +toolchain-glibc_src_configure() { + foreach_abi toolchain-glibc_do_src_configure +} + +toolchain-glibc_do_src_compile() { + local t + for t in linuxthreads nptl ; do + if want_${t} ; then + [[ ${EAPI:-0} == [01] ]] && glibc_do_configure ${t} + emake -C "$(builddir ${t})" || die "make ${t} for ${ABI} failed" + fi + done +} + +toolchain-glibc_src_compile() { + if just_headers ; then + [[ ${EAPI:-0} == [01] ]] && toolchain-glibc_headers_configure + return + fi + + foreach_abi toolchain-glibc_do_src_compile +} + +glibc_src_test() { + cd "$(builddir $1)" + nonfatal emake -j1 check && return 0 + einfo "make check failed - re-running with --keep-going to get the rest of the results" + nonfatal emake -j1 -k check + ewarn "make check failed for ${ABI}-${CTARGET}-$1" + return 1 +} + +toolchain-glibc_do_src_test() { + local ret=0 t + for t in linuxthreads nptl ; do + if want_${t} ; then + glibc_src_test ${t} + : $(( ret |= $? )) + fi + done + return ${ret} +} + +toolchain-glibc_src_test() { + # Give tests more time to complete. + export TIMEOUTFACTOR=5 + + foreach_abi toolchain-glibc_do_src_test || die "tests failed" +} + +toolchain-glibc_do_src_install() { + local builddir=$(builddir $(want_linuxthreads && echo linuxthreads || echo nptl)) + cd "${builddir}" + + emake install_root="${D}$(alt_prefix)" install || die + + if want_linuxthreads && want_nptl ; then + einfo "Installing NPTL to $(alt_libdir)/tls/..." + cd "$(builddir nptl)" + dodir $(alt_libdir)/tls $(alt_usrlibdir)/nptl + + local l src_lib + for l in libc libm librt libpthread libthread_db ; do + # take care of shared lib first ... + l=${l}.so + if [[ -e ${l} ]] ; then + src_lib=${l} + else + src_lib=$(eval echo */${l}) + fi + cp -a ${src_lib} "${ED}"$(alt_libdir)/tls/${l} || die "copying nptl ${l}" + fperms a+rx $(alt_libdir)/tls/${l} + dosym ${l} $(alt_libdir)/tls/$(scanelf -qSF'%S#F' ${src_lib}) + + # then grab the linker script or the symlink ... + if [[ -L ${ED}$(alt_usrlibdir)/${l} ]] ; then + dosym $(alt_libdir)/tls/${l} $(alt_usrlibdir)/nptl/${l} + else + sed \ + -e "s:/${l}:/tls/${l}:g" \ + -e "s:/${l/%.so/_nonshared.a}:/nptl/${l/%.so/_nonshared.a}:g" \ + "${ED}"$(alt_usrlibdir)/${l} > "${ED}"$(alt_usrlibdir)/nptl/${l} + fi + + # then grab the static lib ... + src_lib=${src_lib/%.so/.a} + [[ ! -e ${src_lib} ]] && src_lib=${src_lib/%.a/_pic.a} + cp -a ${src_lib} "${ED}"$(alt_usrlibdir)/nptl/ || die "copying nptl ${src_lib}" + src_lib=${src_lib/%.a/_nonshared.a} + if [[ -e ${src_lib} ]] ; then + cp -a ${src_lib} "${ED}"$(alt_usrlibdir)/nptl/ || die "copying nptl ${src_lib}" + fi + done + + # use the nptl linker instead of the linuxthreads one as the linuxthreads + # one may lack TLS support and that can be really bad for business + cp -a elf/ld.so "${ED}"$(alt_libdir)/$(scanelf -qSF'%S#F' elf/ld.so) || die "copying nptl interp" + fi + + # Normally real_pv is ${PV}. Live ebuilds are exception, there we need + # to infer upstream version: + # '#define VERSION "2.26.90"' -> '2.26.90' + local upstream_pv=$(sed -n -r 's/#define VERSION "(.*)"/\1/p' "${S}"/version.h) + # Newer versions get fancy with libm linkage to include vectorized support. + # While we don't really need a ldscript here, portage QA checks get upset. + if [[ -e ${ED}$(alt_usrlibdir)/libm-${upstream_pv}.a ]] ; then + dosym ../../$(get_libdir)/libm-${upstream_pv}.so $(alt_usrlibdir)/libm-${upstream_pv}.so + fi + + # We'll take care of the cache ourselves + rm -f "${ED}"/etc/ld.so.cache + + # Everything past this point just needs to be done once ... + is_final_abi || return 0 + + # Make sure the non-native interp can be found on multilib systems even + # if the main library set isn't installed into the right place. Maybe + # we should query the active gcc for info instead of hardcoding it ? + local i ldso_abi ldso_name + local ldso_abi_list=( + # x86 + amd64 /lib64/ld-linux-x86-64.so.2 + x32 /libx32/ld-linux-x32.so.2 + x86 /lib/ld-linux.so.2 + # mips + o32 /lib/ld.so.1 + n32 /lib32/ld.so.1 + n64 /lib64/ld.so.1 + # powerpc + ppc /lib/ld.so.1 + ppc64 /lib64/ld64.so.1 + # s390 + s390 /lib/ld.so.1 + s390x /lib/ld64.so.1 + # sparc + sparc32 /lib/ld-linux.so.2 + sparc64 /lib64/ld-linux.so.2 + ) + case $(tc-endian) in + little) + ldso_abi_list+=( + # arm + arm64 /lib/ld-linux-aarch64.so.1 + ) + ;; + big) + ldso_abi_list+=( + # arm + arm64 /lib/ld-linux-aarch64_be.so.1 + ) + ;; + esac + if [[ ${SYMLINK_LIB} == "yes" ]] && [[ ! -e ${ED}/$(alt_prefix)/lib ]] ; then + dosym $(get_abi_LIBDIR ${DEFAULT_ABI}) $(alt_prefix)/lib + fi + for (( i = 0; i < ${#ldso_abi_list[@]}; i += 2 )) ; do + ldso_abi=${ldso_abi_list[i]} + has ${ldso_abi} $(get_install_abis) || continue + + ldso_name="$(alt_prefix)${ldso_abi_list[i+1]}" + if [[ ! -L ${ED}/${ldso_name} && ! -e ${ED}/${ldso_name} ]] ; then + dosym ../$(get_abi_LIBDIR ${ldso_abi})/${ldso_name##*/} ${ldso_name} + fi + done + + # With devpts under Linux mounted properly, we do not need the pt_chown + # binary to be setuid. This is because the default owners/perms will be + # exactly what we want. + if in_iuse suid && ! use suid ; then + find "${ED}" -name pt_chown -exec chmod -s {} + + fi + + ################################################################# + # EVERYTHING AFTER THIS POINT IS FOR NATIVE GLIBC INSTALLS ONLY # + # Make sure we install some symlink hacks so that when we build + # a 2nd stage cross-compiler, gcc finds the target system + # headers correctly. See gcc/doc/gccinstall.info + if is_crosscompile ; then + # We need to make sure that /lib and /usr/lib always exists. + # gcc likes to use relative paths to get to its multilibs like + # /usr/lib/../lib64/. So while we don't install any files into + # /usr/lib/, we do need it to exist. + cd "${ED}"$(alt_libdir)/.. + [[ -e lib ]] || mkdir lib + cd "${ED}"$(alt_usrlibdir)/.. + [[ -e lib ]] || mkdir lib + + dosym usr/include $(alt_prefix)/sys-include + return 0 + fi + + # Files for Debian-style locale updating + dodir /usr/share/i18n + sed \ + -e "/^#/d" \ + -e "/SUPPORTED-LOCALES=/d" \ + -e "s: \\\\::g" -e "s:/: :g" \ + "${S}"/localedata/SUPPORTED > "${ED}"/usr/share/i18n/SUPPORTED \ + || die "generating /usr/share/i18n/SUPPORTED failed" + cd "${WORKDIR}"/extra/locale + dosbin locale-gen || die + doman *.[0-8] + insinto /etc + doins locale.gen || die + + # Make sure all the ABI's can find the locales and so we only + # have to generate one set + local a + keepdir /usr/$(get_libdir)/locale + for a in $(get_install_abis) ; do + if [[ ! -e ${ED}/usr/$(get_abi_LIBDIR ${a})/locale ]] ; then + dosym /usr/$(get_libdir)/locale /usr/$(get_abi_LIBDIR ${a})/locale + fi + done + + cd "${S}" + + # Install misc network config files + insinto /etc + doins nscd/nscd.conf posix/gai.conf nss/nsswitch.conf || die + doins "${WORKDIR}"/extra/etc/*.conf || die + + if ! in_iuse nscd || use nscd ; then + doinitd "$(prefixify_ro "${WORKDIR}"/extra/etc/nscd)" || die + + local nscd_args=( + -e "s:@PIDFILE@:$(strings "${ED}"/usr/sbin/nscd | grep nscd.pid):" + ) + version_is_at_least 2.16 || nscd_args+=( -e 's: --foreground : :' ) + sed -i "${nscd_args[@]}" "${ED}"/etc/init.d/nscd + + # Newer versions of glibc include the nscd.service themselves. + # TODO: Drop the $FILESDIR copy once 2.19 goes stable. + if version_is_at_least 2.19 ; then + systemd_dounit nscd/nscd.service || die + systemd_newtmpfilesd nscd/nscd.tmpfiles nscd.conf || die + else + systemd_dounit "${FILESDIR}"/nscd.service || die + systemd_newtmpfilesd "${FILESDIR}"/nscd.tmpfilesd nscd.conf || die + fi + else + # Do this since extra/etc/*.conf above might have nscd.conf. + rm -f "${ED}"/etc/nscd.conf + fi + + echo 'LDPATH="include ld.so.conf.d/*.conf"' > "${T}"/00glibc + doenvd "${T}"/00glibc || die + + for d in BUGS ChangeLog* CONFORMANCE FAQ NEWS NOTES PROJECTS README* ; do + [[ -s ${d} ]] && dodoc ${d} + done + + # Prevent overwriting of the /etc/localtime symlink. We'll handle the + # creation of the "factory" symlink in pkg_postinst(). + rm -f "${ED}"/etc/localtime +} + +toolchain-glibc_headers_install() { + local builddir=$(builddir "headers") + cd "${builddir}" + emake install_root="${D}$(alt_prefix)" install-headers || die + if ! version_is_at_least 2.16 ; then + insinto $(alt_headers)/bits + doins bits/stdio_lim.h || die + fi + insinto $(alt_headers)/gnu + doins "${S}"/include/gnu/stubs.h || die "doins include gnu" + # Make sure we install the sys-include symlink so that when + # we build a 2nd stage cross-compiler, gcc finds the target + # system headers correctly. See gcc/doc/gccinstall.info + dosym usr/include $(alt_prefix)/sys-include +} + +toolchain-glibc_src_install() { + if just_headers ; then + export ABI=default + toolchain-glibc_headers_install + return + fi + + foreach_abi toolchain-glibc_do_src_install +} + +# Simple test to make sure our new glibc isn't completely broken. +# Make sure we don't test with statically built binaries since +# they will fail. Also, skip if this glibc is a cross compiler. +# +# If coreutils is built with USE=multicall, some of these files +# will just be wrapper scripts, not actual ELFs we can test. +glibc_sanity_check() { + cd / #228809 + + # We enter ${ED} so to avoid trouble if the path contains + # special characters; for instance if the path contains the + # colon character (:), then the linker will try to split it + # and look for the libraries in an unexpected place. This can + # lead to unsafe code execution if the generated prefix is + # within a world-writable directory. + # (e.g. /var/tmp/portage:${HOSTNAME}) + pushd "${ED}"/$(get_libdir) >/dev/null + + local x striptest + for x in cal date env free ls true uname uptime ; do + x=$(type -p ${x}) + [[ -z ${x} || ${x} != ${EPREFIX}/* ]] && continue + striptest=$(LC_ALL="C" file -L ${x} 2>/dev/null) || continue + case ${striptest} in + *"statically linked"*) continue;; + *"ASCII text"*) continue;; + esac + # We need to clear the locale settings as the upgrade might want + # incompatible locale data. This test is not for verifying that. + LC_ALL=C \ + ./ld-*.so --library-path . ${x} > /dev/null \ + || die "simple run test (${x}) failed" + done + + popd >/dev/null +} + +toolchain-glibc_pkg_preinst() { + # nothing to do if just installing headers + just_headers && return + + # prepare /etc/ld.so.conf.d/ for files + mkdir -p "${EROOT}"/etc/ld.so.conf.d + + # Default /etc/hosts.conf:multi to on for systems with small dbs. + if [[ $(wc -l < "${EROOT}"/etc/hosts) -lt 1000 ]] ; then + sed -i '/^multi off/s:off:on:' "${ED}"/etc/host.conf + elog "Defaulting /etc/host.conf:multi to on" + fi + + [[ ${ROOT} != "/" ]] && return 0 + [[ -d ${ED}/$(get_libdir) ]] || return 0 + [[ -z ${BOOTSTRAP_RAP} ]] && glibc_sanity_check + + # For newer EAPIs, this was run in pkg_pretend. + if [[ ${EAPI:-0} == [0123] ]] ; then + check_devpts + fi +} + +toolchain-glibc_pkg_postinst() { + # nothing to do if just installing headers + just_headers && return + + if ! tc-is-cross-compiler && [[ -x ${EROOT}/usr/sbin/iconvconfig ]] ; then + # Generate fastloading iconv module configuration file. + "${EROOT}"/usr/sbin/iconvconfig --prefix="${ROOT}" + fi + + if ! is_crosscompile && [[ ${ROOT} == "/" ]] ; then + # Reload init ... if in a chroot or a diff init package, ignore + # errors from this step #253697 + /sbin/telinit U 2>/dev/null + + # if the host locales.gen contains no entries, we'll install everything + local locale_list="${EROOT}etc/locale.gen" + if [[ -z $(locale-gen --list --config "${locale_list}") ]] ; then + ewarn "Generating all locales; edit /etc/locale.gen to save time/space" + locale_list="${EROOT}usr/share/i18n/SUPPORTED" + fi + locale-gen -j $(makeopts_jobs) --config "${locale_list}" + fi +} + +_TOOLCHAIN_GLIBC_ECLASS=1 +fi diff --git a/eclass/toolchain.eclass b/eclass/toolchain.eclass new file mode 100644 index 0000000..59f8660 --- /dev/null +++ b/eclass/toolchain.eclass @@ -0,0 +1,2427 @@ +# Copyright 1999-2020 Gentoo Authors +# Distributed under the terms of the GNU General Public License v2 + +# Maintainer: Toolchain Ninjas <toolchain@gentoo.org> +# @SUPPORTED_EAPIS: 5 6 7 + +DESCRIPTION="The GNU Compiler Collection" +HOMEPAGE="https://gcc.gnu.org/" + +inherit eutils flag-o-matic gnuconfig libtool multilib pax-utils toolchain-funcs prefix + +tc_is_live() { + [[ ${PV} == *9999* ]] +} + +if tc_is_live ; then + EGIT_REPO_URI="https://gcc.gnu.org/git/gcc.git" + # naming style: + # gcc-10.1.0_pre9999 -> gcc-10-branch + # Note that the micro version is required or lots of stuff will break. + # To checkout master set gcc_LIVE_BRANCH="master" in the ebuild before + # inheriting this eclass. + EGIT_BRANCH="releases/${PN}-${PV%.?.?_pre9999}" + EGIT_BRANCH=${EGIT_BRANCH//./_} + inherit git-r3 +fi + +FEATURES=${FEATURES/multilib-strict/} + +case ${EAPI:-0} in + 0|1|2|3|4*) die "Need to upgrade to at least EAPI=5" ;; + 5*|6) inherit eapi7-ver ;; + 7) ;; + *) die "I don't speak EAPI ${EAPI}." ;; +esac + +EXPORT_FUNCTIONS pkg_pretend pkg_setup src_unpack src_prepare src_configure \ + src_compile src_test src_install pkg_postinst pkg_postrm + +#---->> globals <<---- + +export CTARGET=${CTARGET:-${CHOST}} +if [[ ${CTARGET} = ${CHOST} ]] ; then + if [[ ${CATEGORY} == cross-* ]] ; then + export CTARGET=${CATEGORY#cross-} + fi +fi +: ${TARGET_ABI:=${ABI}} +: ${TARGET_MULTILIB_ABIS:=${MULTILIB_ABIS}} +: ${TARGET_DEFAULT_ABI:=${DEFAULT_ABI}} + +is_crosscompile() { + [[ ${CHOST} != ${CTARGET} ]] +} + +# General purpose version check. Without a second arg matches up to minor version (x.x.x) +tc_version_is_at_least() { + ver_test "${2:-${GCC_RELEASE_VER}}" -ge "$1" +} + +# General purpose version range check +# Note that it matches up to but NOT including the second version +tc_version_is_between() { + tc_version_is_at_least "${1}" && ! tc_version_is_at_least "${2}" +} + +GCC_PV=${TOOLCHAIN_GCC_PV:-${PV}} +GCC_PVR=${GCC_PV} +[[ ${PR} != "r0" ]] && GCC_PVR=${GCC_PVR}-${PR} + +# GCC_RELEASE_VER must always match 'gcc/BASE-VER' value. +# It's an internal representation of gcc version used for: +# - versioned paths on disk +# - 'gcc -dumpversion' output. Must always match <digit>.<digit>.<digit>. +GCC_RELEASE_VER=$(ver_cut 1-3 ${GCC_PV}) + +GCC_BRANCH_VER=$(ver_cut 1-2 ${GCC_PV}) +GCCMAJOR=$(ver_cut 1 ${GCC_PV}) +GCCMINOR=$(ver_cut 2 ${GCC_PV}) +GCCMICRO=$(ver_cut 3 ${GCC_PV}) + +# Ideally this variable should allow for custom gentoo versioning +# of binary and gcc-config names not directly tied to upstream +# versioning. In practive it's hard to untangle from gcc/BASE-VER +# (GCC_RELEASE_VER) value. +GCC_CONFIG_VER=${GCC_RELEASE_VER} + +# Pre-release support. Versioning schema: +# 1.0.0_pre9999: live ebuild +# 1.2.3_alphaYYYYMMDD: weekly snapshots +# 1.2.3_rcYYYYMMDD: release candidates +if [[ ${GCC_PV} == *_alpha* ]] ; then + # weekly snapshots + SNAPSHOT=${GCCMAJOR}-${GCC_PV##*_alpha} +elif [[ ${GCC_PV} == *_rc* ]] ; then + # release candidates + SNAPSHOT=${GCC_PV%_rc*}-RC-${GCC_PV##*_rc} +fi + +PREFIX=${TOOLCHAIN_PREFIX:-${EPREFIX}/usr} + +LIBPATH=${TOOLCHAIN_LIBPATH:-${PREFIX}/lib/gcc/${CTARGET}/${GCC_CONFIG_VER}} +INCLUDEPATH=${TOOLCHAIN_INCLUDEPATH:-${LIBPATH}/include} + +if is_crosscompile ; then + BINPATH=${TOOLCHAIN_BINPATH:-${PREFIX}/${CHOST}/${CTARGET}/gcc-bin/${GCC_CONFIG_VER}} + HOSTLIBPATH=${PREFIX}/${CHOST}/${CTARGET}/lib/${GCC_CONFIG_VER} +else + BINPATH=${TOOLCHAIN_BINPATH:-${PREFIX}/${CTARGET}/gcc-bin/${GCC_CONFIG_VER}} +fi + +DATAPATH=${TOOLCHAIN_DATAPATH:-${PREFIX}/share/gcc-data/${CTARGET}/${GCC_CONFIG_VER}} + +# Dont install in /usr/include/g++-v3/, but in gcc internal directory. +# We will handle /usr/include/g++-v3/ with gcc-config ... +STDCXX_INCDIR=${TOOLCHAIN_STDCXX_INCDIR:-${LIBPATH}/include/g++-v${GCC_BRANCH_VER/\.*/}} + +#---->> LICENSE+SLOT+IUSE logic <<---- + +LICENSE="GPL-3+ LGPL-3+ || ( GPL-3+ libgcc libstdc++ gcc-runtime-library-exception-3.1 ) FDL-1.3+" +IUSE="test vanilla +nls" +RESTRICT="!test? ( test )" + +tc_supports_dostrip() { + case ${EAPI:-0} in + 5*|6) return 1 ;; + 7) return 0 ;; + *) die "Update apply_patches() for ${EAPI}." ;; + esac +} + +tc_supports_dostrip || RESTRICT+=" strip" # cross-compilers need controlled stripping + +TC_FEATURES=() + +tc_has_feature() { + has "$1" "${TC_FEATURES[@]}" +} + +if [[ ${PN} != "kgcc64" && ${PN} != gcc-* ]] ; then + # --enable-altivec was dropped before gcc-4. We don't set it. + # We drop USE=altivec for newer gccs only to avoid rebuilds + # for most stable users. Once gcc-10 is stable we can drop it. + if ! tc_version_is_at_least 10; then + IUSE+=" altivec" + fi + IUSE+=" debug +cxx +nptl" TC_FEATURES+=(nptl) + [[ -n ${PIE_VER} ]] && IUSE+=" nopie" + [[ -n ${SPECS_VER} ]] && IUSE+=" nossp" + # fortran support appeared in 4.1, but 4.1 needs outdated mpfr + tc_version_is_at_least 4.2 && IUSE+=" +fortran" TC_FEATURES+=(fortran) + tc_version_is_at_least 3 && IUSE+=" doc hardened multilib objc" + tc_version_is_between 3 7 && IUSE+=" awt gcj" TC_FEATURES+=(gcj) + tc_version_is_at_least 3.3 && IUSE+=" pgo" + tc_version_is_at_least 4.0 && + IUSE+=" objc-gc" TC_FEATURES+=(objc-gc) + tc_version_is_at_least 4.1 && IUSE+=" libssp objc++" + tc_version_is_at_least 4.2 && IUSE+=" +openmp" + tc_version_is_at_least 4.3 && IUSE+=" fixed-point" + tc_version_is_at_least 4.7 && IUSE+=" go" + # sanitizer support appeared in gcc-4.8, but <gcc-5 does not + # support modern glibc. + tc_version_is_at_least 5 && IUSE+=" +sanitize" + # Note: + # <gcc-4.8 supported graphite, it required forked ppl + # versions which we dropped. Since graphite was also experimental in + # the older versions, we don't want to bother supporting it. #448024 + # <gcc-5 supported graphite, it required cloog + # <gcc-6.5 supported graphite, it required old incompatible isl + tc_version_is_at_least 6.5 && + IUSE+=" graphite" TC_FEATURES+=(graphite) + tc_version_is_between 4.9 8 && IUSE+=" cilk" + tc_version_is_at_least 4.9 && IUSE+=" ada +vtv" + tc_version_is_at_least 5.0 && IUSE+=" jit" + tc_version_is_between 5.0 9 && IUSE+=" mpx" + tc_version_is_at_least 6.0 && IUSE+=" +pie +ssp +pch" + # systemtap is a gentoo-specific switch: bug #654748 + tc_version_is_at_least 8.0 && + IUSE+=" systemtap" TC_FEATURES+=(systemtap) + tc_version_is_at_least 9.0 && IUSE+=" d" + tc_version_is_at_least 9.1 && IUSE+=" lto" + tc_version_is_at_least 10 && IUSE+=" zstd" TC_FEATURES+=(zstd) + tc_version_is_at_least 11 && IUSE+=" valgrind" TC_FEATURES+=(valgrind) + tc_version_is_at_least 11 && IUSE+=" custom-cflags" +fi + +if tc_version_is_at_least 10; then + # Note: currently we pull in releases, snapshots and + # git versions into the same SLOT. + SLOT="${GCCMAJOR}" +else + SLOT="${GCC_CONFIG_VER}" +fi + +#---->> DEPEND <<---- + +RDEPEND="sys-libs/zlib + nls? ( virtual/libintl )" + +tc_version_is_at_least 3 && RDEPEND+=" virtual/libiconv" + +if tc_version_is_at_least 4 ; then + GMP_MPFR_DEPS=">=dev-libs/gmp-4.3.2:0= >=dev-libs/mpfr-2.4.2:0=" + if tc_version_is_at_least 4.3 ; then + RDEPEND+=" ${GMP_MPFR_DEPS}" + elif tc_has_feature fortran ; then + RDEPEND+=" fortran? ( ${GMP_MPFR_DEPS} )" + fi +fi + +tc_version_is_at_least 4.5 && RDEPEND+=" >=dev-libs/mpc-0.8.1:0=" + +if tc_has_feature objc-gc ; then + if tc_version_is_at_least 7 ; then + RDEPEND+=" objc-gc? ( >=dev-libs/boehm-gc-7.4.2 )" + fi +fi + +if tc_has_feature graphite ; then + RDEPEND+=" graphite? ( >=dev-libs/isl-0.14:0= )" +fi + +BDEPEND=" + >=sys-devel/bison-1.875 + >=sys-devel/flex-2.5.4 + nls? ( sys-devel/gettext ) + test? ( + >=dev-util/dejagnu-1.4.4 + >=sys-devel/autogen-5.5.4 + )" +DEPEND="${RDEPEND}" + +if tc_has_feature gcj ; then + GCJ_DEPS=">=media-libs/libart_lgpl-2.1" + GCJ_GTK_DEPS=" + x11-base/xorg-proto + x11-libs/libXt + x11-libs/libX11 + x11-libs/libXtst + =x11-libs/gtk+-2* + virtual/pkgconfig + " + tc_version_is_at_least 3.4 && GCJ_GTK_DEPS+=" x11-libs/pango" + tc_version_is_at_least 4.2 && GCJ_DEPS+=" app-arch/zip app-arch/unzip" + DEPEND+=" gcj? ( awt? ( ${GCJ_GTK_DEPS} ) ${GCJ_DEPS} )" +fi + +if tc_has_feature systemtap ; then + # gcc needs sys/sdt.h headers on target + DEPEND+=" systemtap? ( dev-util/systemtap )" +fi + +if tc_has_feature zstd ; then + DEPEND+=" zstd? ( app-arch/zstd )" +fi + +if tc_has_feature valgrind; then + BDEPEND+=" valgrind? ( dev-util/valgrind )" +fi + +case ${EAPI:-0} in + 5*|6) DEPEND+=" ${BDEPEND}" ;; +esac + +PDEPEND=">=sys-devel/gcc-config-2.3" + +#---->> S + SRC_URI essentials <<---- + +# Set the source directory depending on whether we're using +# a live git tree, snapshot, or release tarball. +S=$( + if tc_is_live ; then + echo ${EGIT_CHECKOUT_DIR} + elif [[ -n ${SNAPSHOT} ]] ; then + echo ${WORKDIR}/gcc-${SNAPSHOT} + else + echo ${WORKDIR}/gcc-${GCC_RELEASE_VER} + fi +) + +gentoo_urls() { + local devspace="HTTP~vapier/dist/URI HTTP~rhill/dist/URI + HTTP~zorry/patches/gcc/URI HTTP~blueness/dist/URI + HTTP~tamiko/distfiles/URI HTTP~slyfox/distfiles/URI" + devspace=${devspace//HTTP/https:\/\/dev.gentoo.org\/} + echo mirror://gentoo/$1 ${devspace//URI/$1} +} + +# This function handles the basics of setting the SRC_URI for a gcc ebuild. +# To use, set SRC_URI with: +# +# SRC_URI="$(get_gcc_src_uri)" +# +# Other than the variables normally set by portage, this function's behavior +# can be altered by setting the following: +# +# GCC_TARBALL_SRC_URI +# Override link to main tarball into SRC_URI. Used by dev-lang/gnat-gpl +# to provide gcc tarball snapshots. Patches are usually reused as-is. +# +# SNAPSHOT +# If set, this variable signals that we should be using a snapshot of +# gcc. It is expected to be in the format "YYYY-MM-DD". Note that if +# the ebuild has a _pre suffix, this variable is ignored and the +# prerelease tarball is used instead. +# +# PATCH_VER +# PATCH_GCC_VER +# This should be set to the version of the gentoo patch tarball. +# The resulting filename of this tarball will be: +# gcc-${PATCH_GCC_VER:-${GCC_RELEASE_VER}}-patches-${PATCH_VER}.tar.bz2 +# +# PIE_VER +# PIE_GCC_VER +# These variables control patching in various updates for the logic +# controlling Position Independant Executables. PIE_VER is expected +# to be the version of this patch, and PIE_GCC_VER the gcc version of +# the patch: +# An example: +# PIE_VER="8.7.6.5" +# PIE_GCC_VER="3.4.0" +# The resulting filename of this tarball will be: +# gcc-${PIE_GCC_VER:-${GCC_RELEASE_VER}}-piepatches-v${PIE_VER}.tar.bz2 +# +# SPECS_VER +# SPECS_GCC_VER +# This is for the minispecs files included in the hardened gcc-4.x +# The specs files for hardenedno*, vanilla and for building the "specs" file. +# SPECS_VER is expected to be the version of this patch, SPECS_GCC_VER +# the gcc version of the patch. +# An example: +# SPECS_VER="8.7.6.5" +# SPECS_GCC_VER="3.4.0" +# The resulting filename of this tarball will be: +# gcc-${SPECS_GCC_VER:-${GCC_RELEASE_VER}}-specs-${SPECS_VER}.tar.bz2 +# +# CYGWINPORTS_GITREV +# If set, this variable signals that we should apply additional patches +# maintained by upstream Cygwin developers at github/cygwinports/gcc, +# using the specified git commit id there. The list of patches to +# apply is extracted from gcc.cygport, maintained there as well. +# This is done for compilers running on Cygwin, not for cross compilers +# with a Cygwin target. +get_gcc_src_uri() { + export PATCH_GCC_VER=${PATCH_GCC_VER:-${GCC_RELEASE_VER}} + export UCLIBC_GCC_VER=${UCLIBC_GCC_VER:-${PATCH_GCC_VER}} + export PIE_GCC_VER=${PIE_GCC_VER:-${GCC_RELEASE_VER}} + export HTB_GCC_VER=${HTB_GCC_VER:-${GCC_RELEASE_VER}} + export SPECS_GCC_VER=${SPECS_GCC_VER:-${GCC_RELEASE_VER}} + + # Set where to download gcc itself depending on whether we're using a + # live git tree, snapshot, or release tarball. + if tc_is_live ; then + : # Nothing to do w/git snapshots. + elif [[ -n ${GCC_TARBALL_SRC_URI} ]] ; then + # pull gcc tarball from another location. Frequently used by gnat-gpl. + GCC_SRC_URI="${GCC_TARBALL_SRC_URI}" + elif [[ -n ${SNAPSHOT} ]] ; then + GCC_SRC_URI="ftp://gcc.gnu.org/pub/gcc/snapshots/${SNAPSHOT}/gcc-${SNAPSHOT}.tar.xz" + else + if tc_version_is_between 5.5 6 || tc_version_is_between 6.4 7 || tc_version_is_at_least 7.2 ; then + GCC_SRC_URI="mirror://gnu/gcc/gcc-${GCC_PV}/gcc-${GCC_RELEASE_VER}.tar.xz" + else + GCC_SRC_URI="mirror://gnu/gcc/gcc-${GCC_PV}/gcc-${GCC_RELEASE_VER}.tar.bz2" + fi + fi + + [[ -n ${UCLIBC_VER} ]] && \ + GCC_SRC_URI+=" $(gentoo_urls gcc-${UCLIBC_GCC_VER}-uclibc-patches-${UCLIBC_VER}.tar.bz2)" + [[ -n ${PATCH_VER} ]] && \ + GCC_SRC_URI+=" $(gentoo_urls gcc-${PATCH_GCC_VER}-patches-${PATCH_VER}.tar.bz2)" + + [[ -n ${PIE_VER} ]] && \ + PIE_CORE=${PIE_CORE:-gcc-${PIE_GCC_VER}-piepatches-v${PIE_VER}.tar.bz2} && \ + GCC_SRC_URI+=" $(gentoo_urls ${PIE_CORE})" + + # gcc minispec for the hardened gcc 4 compiler + [[ -n ${SPECS_VER} ]] && \ + GCC_SRC_URI+=" $(gentoo_urls gcc-${SPECS_GCC_VER}-specs-${SPECS_VER}.tar.bz2)" + + if tc_has_feature gcj ; then + if tc_version_is_at_least 4.5 ; then + GCC_SRC_URI+=" gcj? ( ftp://sourceware.org/pub/java/ecj-4.5.jar )" + elif tc_version_is_at_least 4.3 ; then + GCC_SRC_URI+=" gcj? ( ftp://sourceware.org/pub/java/ecj-4.3.jar )" + fi + fi + + # Cygwin patches from https://github.com/cygwinports/gcc + [[ -n ${CYGWINPORTS_GITREV} ]] && \ + GCC_SRC_URI+=" elibc_Cygwin? ( https://github.com/cygwinports/gcc/archive/${CYGWINPORTS_GITREV}.tar.gz + -> gcc-cygwinports-${CYGWINPORTS_GITREV}.tar.gz )" + + echo "${GCC_SRC_URI}" +} + +SRC_URI=$(get_gcc_src_uri) + +#---->> pkg_pretend <<---- + +toolchain_pkg_pretend() { + if ! _tc_use_if_iuse cxx ; then + _tc_use_if_iuse go && \ + ewarn 'Go requires a C++ compiler, disabled due to USE="-cxx"' + _tc_use_if_iuse objc++ && \ + ewarn 'Obj-C++ requires a C++ compiler, disabled due to USE="-cxx"' + _tc_use_if_iuse gcj && \ + ewarn 'GCJ requires a C++ compiler, disabled due to USE="-cxx"' + fi + + want_minispecs +} + +#---->> pkg_setup <<---- + +toolchain_pkg_setup() { + # we dont want to use the installed compiler's specs to build gcc + unset GCC_SPECS + unset LANGUAGES #265283 +} + +#---->> src_unpack <<---- + +toolchain_src_unpack() { + if tc_is_live ; then + git-r3_src_unpack + fi + + default_src_unpack +} + +#---->> src_prepare <<---- + +# 'epatch' is not available in EAPI=7. Abstract away patchset application +# until we eventually get all gcc ebuilds on EAPI=7 or later. +tc_apply_patches() { + [[ ${#@} -lt 2 ]] && die "usage: tc_apply_patches <message> <patches...>" + + einfo "$1"; shift + + case ${EAPI:-0} in + # Note: even for EAPI=6 we used 'epatch' semantics. To avoid + # breaking existing ebuilds use 'eapply' only in EAPI=7 or later. + 5*|6) epatch "$@" ;; + 7) eapply "$@" ;; + *) die "Update apply_patches() for ${EAPI}." ;; + esac +} + +toolchain_src_prepare() { + export BRANDING_GCC_PKGVERSION="Gentoo ${GCC_PVR}" + cd "${S}" + + do_gcc_gentoo_patches + do_gcc_PIE_patches + do_gcc_CYGWINPORTS_patches + + if tc_is_live ; then + BRANDING_GCC_PKGVERSION="${BRANDING_GCC_PKGVERSION}, commit ${EGIT_VERSION}" + fi + + case ${EAPI:-0} in + 5*) epatch_user;; + 6|7) eapply_user ;; + *) die "Update toolchain_src_prepare() for ${EAPI}." ;; + esac + + if ( tc_version_is_at_least 4.8.2 || _tc_use_if_iuse hardened ) \ + && ! use vanilla ; then + make_gcc_hard + fi + + # make sure the pkg config files install into multilib dirs. + # since we configure with just one --libdir, we can't use that + # (as gcc itself takes care of building multilibs). #435728 + find "${S}" -name Makefile.in \ + -exec sed -i '/^pkgconfigdir/s:=.*:=$(toolexeclibdir)/pkgconfig:' {} + + + setup_multilib_osdirnames + gcc_version_patch + + local actual_version=$(< "${S}"/gcc/BASE-VER) + if [[ "${GCC_RELEASE_VER}" != "${actual_version}" ]] ; then + eerror "'${S}/gcc/BASE-VER' contains '${actual_version}', expected '${GCC_RELEASE_VER}'" + die "Please set 'TOOLCHAIN_GCC_PV' to '${actual_version}'" + fi + + # >= gcc-4.3 doesn't bundle ecj.jar, so copy it + if tc_version_is_at_least 4.3 && _tc_use_if_iuse gcj ; then + if tc_version_is_at_least 4.5 ; then + einfo "Copying ecj-4.5.jar" + cp -pPR "${DISTDIR}/ecj-4.5.jar" "${S}/ecj.jar" || die + else + einfo "Copying ecj-4.3.jar" + cp -pPR "${DISTDIR}/ecj-4.3.jar" "${S}/ecj.jar" || die + fi + fi + + # Prevent libffi from being installed + if tc_version_is_between 3.0 4.8 ; then + sed -i -e 's/\(install.*:\) install-.*recursive/\1/' "${S}"/libffi/Makefile.in || die + sed -i -e 's/\(install-data-am:\).*/\1/' "${S}"/libffi/include/Makefile.in || die + fi + + # Fixup libtool to correctly generate .la files with portage + elibtoolize --portage --shallow --no-uclibc + + gnuconfig_update + + # update configure files + local f + einfo "Fixing misc issues in configure files" + for f in $(grep -l 'autoconf version 2.13' $(find "${S}" -name configure)) ; do + ebegin " Updating ${f/${S}\/} [LANG]" + patch "${f}" "${FILESDIR}"/gcc-configure-LANG.patch >& "${T}"/configure-patch.log \ + || eerror "Please file a bug about this" + eend $? + done + sed -i 's|A-Za-z0-9|[:alnum:]|g' "${S}"/gcc/*.awk #215828 + + # Prevent new texinfo from breaking old versions (see #198182, #464008) + if tc_version_is_at_least 4.1; then + tc_apply_patches "Remove texinfo (bug #198182, bug #464008)" "${FILESDIR}"/gcc-configure-texinfo.patch + fi + + # >=gcc-4 + if [[ -x contrib/gcc_update ]] ; then + einfo "Touching generated files" + ./contrib/gcc_update --touch | \ + while read f ; do + einfo " ${f%%...}" + done + fi +} + +do_gcc_gentoo_patches() { + if ! use vanilla ; then + if [[ -n ${PATCH_VER} ]] ; then + tc_apply_patches "Applying Gentoo patches ..." "${WORKDIR}"/patch/*.patch + BRANDING_GCC_PKGVERSION="${BRANDING_GCC_PKGVERSION} p${PATCH_VER}" + fi + if [[ -n ${UCLIBC_VER} ]] ; then + tc_apply_patches "Applying uClibc patches ..." "${WORKDIR}"/uclibc/*.patch + fi + fi +} + +do_gcc_PIE_patches() { + want_pie || return 0 + use vanilla && return 0 + + tc_apply_patches "Applying pie patches ..." "${WORKDIR}"/piepatch/*.patch + + BRANDING_GCC_PKGVERSION="${BRANDING_GCC_PKGVERSION}, pie-${PIE_VER}" +} + +do_gcc_CYGWINPORTS_patches() { + [[ -n ${CYGWINPORTS_GITREV} ]] || return 0 + use elibc_Cygwin || return 0 + + local p d="${WORKDIR}/gcc-${CYGWINPORTS_GITREV}" + # readarray -t is available since bash-4.4 only, #690686 + local patches=( $( + for p in $( + sed -e '1,/PATCH_URI="/d;/"/,$d' < "${d}"/gcc.cygport + ); do + echo "${d}/${p}" + done + ) ) + tc_apply_patches "Applying cygwin port patches ..." ${patches[*]} +} + +# configure to build with the hardened GCC specs as the default +make_gcc_hard() { + local gcc_hard_flags="" + + # If we use gcc-6 or newer with pie enable to compile older gcc we need to pass -no-pie + # to stage1; bug #618908 + if ! tc_version_is_at_least 6.0 && [[ $(gcc-major-version) -ge 6 ]] ; then + einfo "Disabling PIE in stage1 (only) ..." + sed -i -e "/^STAGE1_LDFLAGS/ s/$/ -no-pie/" "${S}"/Makefile.in || die + fi + + # Gcc >= 6.X we can use configurations options to turn pie/ssp on as default + if tc_version_is_at_least 6.0 ; then + if _tc_use_if_iuse pie ; then + einfo "Updating gcc to use automatic PIE building ..." + fi + if _tc_use_if_iuse ssp ; then + einfo "Updating gcc to use automatic SSP building ..." + fi + if _tc_use_if_iuse hardened ; then + # Will add some hardened options as default, like: + # -fstack-clash-protection + # -z now + # see *_all_extra-options.patch gcc patches. + gcc_hard_flags+=" -DEXTRA_OPTIONS" + # rebrand to make bug reports easier + BRANDING_GCC_PKGVERSION=${BRANDING_GCC_PKGVERSION/Gentoo/Gentoo Hardened} + fi + else + if _tc_use_if_iuse hardened ; then + # rebrand to make bug reports easier + BRANDING_GCC_PKGVERSION=${BRANDING_GCC_PKGVERSION/Gentoo/Gentoo Hardened} + if hardened_gcc_works ; then + einfo "Updating gcc to use automatic PIE + SSP building ..." + gcc_hard_flags+=" -DEFAULT_PIE_SSP" + elif hardened_gcc_works pie ; then + einfo "Updating gcc to use automatic PIE building ..." + ewarn "SSP has not been enabled by default" + gcc_hard_flags+=" -DEFAULT_PIE" + elif hardened_gcc_works ssp ; then + einfo "Updating gcc to use automatic SSP building ..." + ewarn "PIE has not been enabled by default" + gcc_hard_flags+=" -DEFAULT_SSP" + else + # do nothing if hardened isn't supported, but don't die either + ewarn "hardened is not supported for this arch in this gcc version" + return 0 + fi + else + if hardened_gcc_works ssp ; then + einfo "Updating gcc to use automatic SSP building ..." + gcc_hard_flags+=" -DEFAULT_SSP" + fi + fi + fi + + # we want to be able to control the pie patch logic via something other + # than ALL_CFLAGS... + sed -e '/^ALL_CFLAGS/iHARD_CFLAGS = ' \ + -e 's|^ALL_CFLAGS = |ALL_CFLAGS = $(HARD_CFLAGS) |' \ + -i "${S}"/gcc/Makefile.in + # Need to add HARD_CFLAGS to ALL_CXXFLAGS on >= 4.7 + if tc_version_is_at_least 4.7 ; then + sed -e '/^ALL_CXXFLAGS/iHARD_CFLAGS = ' \ + -e 's|^ALL_CXXFLAGS = |ALL_CXXFLAGS = $(HARD_CFLAGS) |' \ + -i "${S}"/gcc/Makefile.in + fi + + sed -i \ + -e "/^HARD_CFLAGS = /s|=|= ${gcc_hard_flags} |" \ + "${S}"/gcc/Makefile.in || die + +} + +# This is a historical wart. The original Gentoo/amd64 port used: +# lib32 - 32bit binaries (x86) +# lib64 - 64bit binaries (x86_64) +# lib - "native" binaries (a symlink to lib64) +# Most other distros use the logic (including mainline gcc): +# lib - 32bit binaries (x86) +# lib64 - 64bit binaries (x86_64) +# Over time, Gentoo is migrating to the latter form. +# +# Unfortunately, due to distros picking the lib32 behavior, newer gcc +# versions will dynamically detect whether to use lib or lib32 for its +# 32bit multilib. So, to keep the automagic from getting things wrong +# while people are transitioning from the old style to the new style, +# we always set the MULTILIB_OSDIRNAMES var for relevant targets. +setup_multilib_osdirnames() { + is_multilib || return 0 + + local config + local libdirs="../lib64 ../lib32" + + # this only makes sense for some Linux targets + case ${CTARGET} in + x86_64*-linux*) config="i386" ;; + powerpc64*-linux*) config="rs6000" ;; + sparc64*-linux*) config="sparc" ;; + s390x*-linux*) config="s390" ;; + *) return 0 ;; + esac + config+="/t-linux64" + + local sed_args=() + if tc_version_is_at_least 4.6 ; then + sed_args+=( -e 's:$[(]call if_multiarch[^)]*[)]::g' ) + fi + if [[ ${SYMLINK_LIB} == "yes" ]] ; then + einfo "updating multilib directories to be: ${libdirs}" + if tc_version_is_at_least 4.6.4 || tc_version_is_at_least 4.7 ; then + sed_args+=( -e '/^MULTILIB_OSDIRNAMES.*lib32/s:[$][(]if.*):../lib32:' ) + else + sed_args+=( -e "/^MULTILIB_OSDIRNAMES/s:=.*:= ${libdirs}:" ) + fi + else + einfo "using upstream multilib; disabling lib32 autodetection" + sed_args+=( -r -e 's:[$][(]if.*,(.*)[)]:\1:' ) + fi + sed -i "${sed_args[@]}" "${S}"/gcc/config/${config} || die +} + +gcc_version_patch() { + # gcc-4.3+ has configure flags (whoo!) + tc_version_is_at_least 4.3 && return 0 + + local version_string=${GCC_RELEASE_VER} + + einfo "patching gcc version: ${version_string} (${BRANDING_GCC_PKGVERSION})" + + local gcc_sed=( -e 's:gcc\.gnu\.org/bugs\.html:bugs\.gentoo\.org/:' ) + if grep -qs VERSUFFIX "${S}"/gcc/version.c ; then + gcc_sed+=( -e "/VERSUFFIX \"\"/s:\"\":\" (${BRANDING_GCC_PKGVERSION})\":" ) + else + version_string="${version_string} (${BRANDING_GCC_PKGVERSION})" + gcc_sed+=( -e "/const char version_string\[\] = /s:= \".*\":= \"${version_string}\":" ) + fi + sed -i "${gcc_sed[@]}" "${S}"/gcc/version.c || die +} + +#---->> src_configure <<---- + +toolchain_src_configure() { + downgrade_arch_flags + gcc_do_filter_flags + + einfo "CFLAGS=\"${CFLAGS}\"" + einfo "CXXFLAGS=\"${CXXFLAGS}\"" + einfo "LDFLAGS=\"${LDFLAGS}\"" + + # Force internal zip based jar script to avoid random + # issues with 3rd party jar implementations. #384291 + export JAR=no + + # For hardened gcc 4.3 piepatchset to build the hardened specs + # file (build.specs) to use when building gcc. + if ! tc_version_is_at_least 4.4 && want_minispecs ; then + setup_minispecs_gcc_build_specs + fi + + local confgcc=( --host=${CHOST} ) + + if is_crosscompile || tc-is-cross-compiler ; then + # Straight from the GCC install doc: + # "GCC has code to correctly determine the correct value for target + # for nearly all native systems. Therefore, we highly recommend you + # not provide a configure target when configuring a native compiler." + confgcc+=( --target=${CTARGET} ) + fi + [[ -n ${CBUILD} ]] && confgcc+=( --build=${CBUILD} ) + + confgcc+=( + --prefix="${PREFIX}" + --bindir="${BINPATH}" + --includedir="${INCLUDEPATH}" + --datadir="${DATAPATH}" + --mandir="${DATAPATH}/man" + --infodir="${DATAPATH}/info" + --with-gxx-include-dir="${STDCXX_INCDIR}" + ) + + # Stick the python scripts in their own slotted directory (bug #279252) + # + # --with-python-dir=DIR + # Specifies where to install the Python modules used for aot-compile. DIR + # should not include the prefix used in installation. For example, if the + # Python modules are to be installed in /usr/lib/python2.5/site-packages, + # then --with-python-dir=/lib/python2.5/site-packages should be passed. + # + # This should translate into "/share/gcc-data/${CTARGET}/${GCC_CONFIG_VER}/python" + if tc_version_is_at_least 4.4 ; then + confgcc+=( --with-python-dir=${DATAPATH/$PREFIX/}/python ) + fi + + ### language options + + local GCC_LANG="c" + is_cxx && GCC_LANG+=",c++" + is_d && GCC_LANG+=",d" + is_gcj && GCC_LANG+=",java" + is_go && GCC_LANG+=",go" + is_jit && GCC_LANG+=",jit" + if is_objc || is_objcxx ; then + GCC_LANG+=",objc" + if tc_version_is_at_least 4 ; then + use objc-gc && confgcc+=( --enable-objc-gc ) + fi + is_objcxx && GCC_LANG+=",obj-c++" + fi + + # fortran support just got sillier! the lang value can be f77 for + # fortran77, f95 for fortran95, or just plain old fortran for the + # currently supported standard depending on gcc version. + is_fortran && GCC_LANG+=",fortran" + is_f77 && GCC_LANG+=",f77" + is_f95 && GCC_LANG+=",f95" + + is_ada && GCC_LANG+=",ada" + + confgcc+=( --enable-languages=${GCC_LANG} ) + + ### general options + + confgcc+=( + --enable-obsolete + --enable-secureplt + --disable-werror + --with-system-zlib + ) + + if use nls ; then + confgcc+=( --enable-nls --without-included-gettext ) + else + confgcc+=( --disable-nls ) + fi + + tc_version_is_at_least 3.4 || confgcc+=( --disable-libunwind-exceptions ) + + # Use the default ("release") checking because upstream usually neglects + # to test "disabled" so it has a history of breaking. bug #317217 + if tc_version_is_at_least 3.4 && in_iuse debug ; then + # The "release" keyword is new to 4.0. bug #551636 + local off=$(tc_version_is_at_least 4.0 && echo release || echo no) + confgcc+=( --enable-checking="${GCC_CHECKS_LIST:-$(usex debug yes ${off})}" ) + fi + + # Branding + tc_version_is_at_least 4.3 && confgcc+=( + --with-bugurl=https://bugs.gentoo.org/ + --with-pkgversion="${BRANDING_GCC_PKGVERSION}" + ) + + # If we want hardened support with the newer piepatchset for >=gcc 4.4 + if tc_version_is_at_least 4.4 && want_minispecs && in_iuse hardened ; then + confgcc+=( $(use_enable hardened esp) ) + fi + + # allow gcc to search for clock funcs in the main C lib. + # if it can't find them, then tough cookies -- we aren't + # going to link in -lrt to all C++ apps. bug #411681 + if tc_version_is_at_least 4.4 && is_cxx ; then + confgcc+=( --enable-libstdcxx-time ) + fi + + # Build compiler itself using LTO + if tc_version_is_at_least 9.1 && _tc_use_if_iuse lto ; then + confgcc+=( --with-build-config=bootstrap-lto ) + fi + + # Support to disable pch when building libstdcxx + if tc_version_is_at_least 6.0 && ! _tc_use_if_iuse pch ; then + confgcc+=( --disable-libstdcxx-pch ) + fi + + # The jit language requires this. + is_jit && confgcc+=( --enable-host-shared ) + + # build-id was disabled for file collisions: bug #526144 + # + # # Turn on the -Wl,--build-id flag by default for ELF targets. bug #525942 + # # This helps with locating debug files. + # case ${CTARGET} in + # *-linux-*|*-elf|*-eabi) + # tc_version_is_at_least 4.5 && confgcc+=( + # --enable-linker-build-id + # ) + # ;; + # esac + + # newer gcc versions like to bootstrap themselves with C++, + # so we need to manually disable it ourselves + if tc_version_is_between 4.7 4.8 && ! is_cxx ; then + confgcc+=( --disable-build-with-cxx --disable-build-poststage1-with-cxx ) + fi + + ### Cross-compiler options + if is_crosscompile ; then + # Enable build warnings by default with cross-compilers when system + # paths are included (e.g. via -I flags). + confgcc+=( --enable-poison-system-directories ) + + # When building a stage1 cross-compiler (just C compiler), we have to + # disable a bunch of features or gcc goes boom + local needed_libc="" + case ${CTARGET} in + *-linux) needed_libc=error-unknown-libc;; + *-dietlibc) needed_libc=dietlibc;; + *-elf|*-eabi) + needed_libc=newlib + # Bare-metal targets don't have access to clock_gettime() + # arm-none-eabi example: bug #589672 + # But we explicitly do --enable-libstdcxx-time above. + # Undoing it here. + confgcc+=( --disable-libstdcxx-time ) + ;; + *-freebsd*) needed_libc=freebsd-lib;; + *-gnu*) needed_libc=glibc;; + *-klibc) needed_libc=klibc;; + *-musl*) needed_libc=musl;; + *-uclibc*) + # Enable shared library support only on targets + # that support it: bug #291870 + if ! echo '#include <features.h>' | \ + $(tc-getCPP ${CTARGET}) -E -dD - 2>/dev/null | \ + grep -q __HAVE_SHARED__ + then + confgcc+=( --disable-shared ) + fi + needed_libc=uclibc-ng + ;; + *-cygwin) needed_libc=cygwin;; + x86_64-*-mingw*|\ + *-w64-mingw*) needed_libc=mingw64-runtime;; + avr) confgcc+=( --enable-shared --disable-threads );; + esac + if [[ -n ${needed_libc} ]] ; then + local confgcc_no_libc=( --disable-shared ) + # requires libc: bug #734820 + tc_version_is_at_least 4.6 && confgcc_no_libc+=( --disable-libquadmath ) + # requires libc + tc_version_is_at_least 4.8 && confgcc_no_libc+=( --disable-libatomic ) + if ! has_version ${CATEGORY}/${needed_libc} ; then + confgcc+=( + "${confgcc_no_libc[@]}" + --disable-threads + --without-headers + ) + if [[ $needed_libc == glibc ]]; then + # By default gcc looks at glibc's headers + # to detect long double support. This does + # not work for --disable-headers mode. + # Any >=glibc-2.4 is good enough for float128. + # The option appeared in gcc-4.2. + confgcc+=( --with-long-double-128 ) + fi + elif has_version "${CATEGORY}/${needed_libc}[headers-only(-)]" ; then + confgcc+=( + "${confgcc_no_libc[@]}" + --with-sysroot="${PREFIX}"/${CTARGET} + ) + else + confgcc+=( --with-sysroot="${PREFIX}"/${CTARGET} ) + fi + fi + + tc_version_is_at_least 4.2 && confgcc+=( --disable-bootstrap ) + else + if tc-is-static-only ; then + confgcc+=( --disable-shared ) + else + confgcc+=( --enable-shared ) + fi + case ${CHOST} in + mingw*|*-mingw*) + confgcc+=( --enable-threads=win32 ) ;; + *) + confgcc+=( --enable-threads=posix ) ;; + esac + fi + + # __cxa_atexit is "essential for fully standards-compliant handling of + # destructors", but apparently requires glibc. + case ${CTARGET} in + *-uclibc*) + if tc_has_feature nptl ; then + confgcc+=( + --disable-__cxa_atexit + $(use_enable nptl tls) + ) + fi + tc_version_is_between 3.3 3.4 && confgcc+=( --enable-sjlj-exceptions ) + if tc_version_is_between 3.4 4.3 ; then + confgcc+=( --enable-clocale=uclibc ) + fi + ;; + *-elf|*-eabi) + confgcc+=( --with-newlib ) + ;; + *-musl*) + confgcc+=( --enable-__cxa_atexit ) + ;; + *-gnu*) + confgcc+=( + --enable-__cxa_atexit + --enable-clocale=gnu + ) + ;; + *-freebsd*) + confgcc+=( --enable-__cxa_atexit ) + ;; + *-solaris*) + confgcc+=( --enable-__cxa_atexit ) + ;; + esac + + ### arch options + + gcc-multilib-configure + + # gcc has fixed-point arithmetic support in 4.3 for mips targets that can + # significantly increase compile time by several hours. This will allow + # users to control this feature in the event they need the support. + tc_version_is_at_least 4.3 && in_iuse fixed-point && confgcc+=( $(use_enable fixed-point) ) + + case $(tc-is-softfloat) in + yes) confgcc+=( --with-float=soft ) ;; + softfp) confgcc+=( --with-float=softfp ) ;; + *) + # If they've explicitly opt-ed in, do hardfloat, + # otherwise let the gcc default kick in. + case ${CTARGET//_/-} in + *-hardfloat-*|*eabihf) confgcc+=( --with-float=hard ) ;; + esac + esac + + local with_abi_map=() + case $(tc-arch) in + arm) #264534 #414395 + local a arm_arch=${CTARGET%%-*} + # Remove trailing endian variations first: eb el be bl b l + for a in e{b,l} {b,l}e b l ; do + if [[ ${arm_arch} == *${a} ]] ; then + arm_arch=${arm_arch%${a}} + break + fi + done + # Convert armv7{a,r,m} to armv7-{a,r,m} + [[ ${arm_arch} == armv7? ]] && arm_arch=${arm_arch/7/7-} + # See if this is a valid --with-arch flag + if (srcdir=${S}/gcc target=${CTARGET} with_arch=${arm_arch}; + . "${srcdir}"/config.gcc) &>/dev/null + then + confgcc+=( --with-arch=${arm_arch} ) + fi + + # Make default mode thumb for microcontroller classes #418209 + [[ ${arm_arch} == *-m ]] && confgcc+=( --with-mode=thumb ) + + # Enable hardvfp + if [[ $(tc-is-softfloat) == "no" ]] && \ + [[ ${CTARGET} == armv[67]* ]] && \ + tc_version_is_at_least 4.5 + then + # Follow the new arm hardfp distro standard by default + confgcc+=( --with-float=hard ) + case ${CTARGET} in + armv6*) confgcc+=( --with-fpu=vfp ) ;; + armv7*) confgcc+=( --with-fpu=vfpv3-d16 ) ;; + esac + fi + ;; + mips) + # Add --with-abi flags to set default ABI + confgcc+=( --with-abi=$(gcc-abi-map ${TARGET_DEFAULT_ABI}) ) + ;; + amd64) + # drop the older/ABI checks once this get's merged into some + # version of gcc upstream + if tc_version_is_at_least 4.8 && has x32 $(get_all_abis TARGET) ; then + confgcc+=( --with-abi=$(gcc-abi-map ${TARGET_DEFAULT_ABI}) ) + fi + ;; + x86) + # Default arch for x86 is normally i386, lets give it a bump + # since glibc will do so based on CTARGET anyways + confgcc+=( --with-arch=${CTARGET%%-*} ) + ;; + hppa) + # Enable sjlj exceptions for backward compatibility on hppa + [[ ${GCCMAJOR} == "3" ]] && confgcc+=( --enable-sjlj-exceptions ) + ;; + ppc) + # Set up defaults based on current CFLAGS + is-flagq -mfloat-gprs=double && confgcc+=( --enable-e500-double ) + [[ ${CTARGET//_/-} == *-e500v2-* ]] && confgcc+=( --enable-e500-double ) + ;; + ppc64) + # On ppc64 big endian target gcc assumes elfv1 by default, + # and elfv2 on little endian + # but musl does not support elfv1 at all on any endian ppc64 + # see https://git.musl-libc.org/cgit/musl/tree/INSTALL + # https://bugs.gentoo.org/704784 + # https://gcc.gnu.org/PR93157 + [[ ${CTARGET} == powerpc64-*-musl ]] && confgcc+=( --with-abi=elfv2 ) + ;; + riscv) + # Add --with-abi flags to set default ABI + confgcc+=( --with-abi=$(gcc-abi-map ${TARGET_DEFAULT_ABI}) ) + ;; + esac + + # if the target can do biarch (-m32/-m64), enable it. overhead should + # be small, and should simplify building of 64bit kernels in a 32bit + # userland by not needing sys-devel/kgcc64. #349405 + case $(tc-arch) in + ppc|ppc64) tc_version_is_at_least 3.4 && confgcc+=( --enable-targets=all ) ;; + sparc) tc_version_is_at_least 4.4 && confgcc+=( --enable-targets=all ) ;; + amd64|x86) tc_version_is_at_least 4.3 && confgcc+=( --enable-targets=all ) ;; + esac + + # On Darwin we need libdir to be set in order to get correct install names + # for things like libobjc-gnu, libgcj and libfortran. If we enable it on + # non-Darwin we screw up the behaviour this eclass relies on. We in + # particular need this over --libdir for bug #255315. + [[ ${CTARGET} == *-darwin* ]] && \ + confgcc+=( --enable-version-specific-runtime-libs ) + + ### library options + + if tc_version_is_between 3.0 7.0 ; then + if is_gcj ; then + confgcc+=( --disable-gjdoc ) + use awt && confgcc+=( --enable-java-awt=gtk ) + else + confgcc+=( --disable-libgcj ) + fi + fi + + if tc_version_is_at_least 4.2 ; then + if in_iuse openmp ; then + # Make sure target has pthreads support. #326757 #335883 + # There shouldn't be a chicken & egg problem here as openmp won't + # build without a C library, and you can't build that w/out + # already having a compiler ... + if ! is_crosscompile || \ + $(tc-getCPP ${CTARGET}) -E - <<<"#include <pthread.h>" >& /dev/null + then + confgcc+=( $(use_enable openmp libgomp) ) + else + # Force disable as the configure script can be dumb #359855 + confgcc+=( --disable-libgomp ) + fi + else + # For gcc variants where we don't want openmp (e.g. kgcc) + confgcc+=( --disable-libgomp ) + fi + fi + + if tc_version_is_at_least 4.0 ; then + if _tc_use_if_iuse libssp ; then + confgcc+=( --enable-libssp ) + else + if hardened_gcc_is_stable ssp; then + export gcc_cv_libc_provides_ssp=yes + fi + if _tc_use_if_iuse ssp; then + # On some targets USE="ssp -libssp" is an invalid + # configuration as target libc does not provide + # stack_chk_* functions. Do not disable libssp there. + case ${CTARGET} in + mingw*|*-mingw*) ewarn "Not disabling libssp" ;; + *) confgcc+=( --disable-libssp ) ;; + esac + else + confgcc+=( --disable-libssp ) + fi + fi + fi + + if in_iuse ada ; then + confgcc+=( --disable-libada ) + fi + + if in_iuse cilk ; then + confgcc+=( $(use_enable cilk libcilkrts) ) + fi + + if in_iuse mpx ; then + confgcc+=( $(use_enable mpx libmpx) ) + fi + + if in_iuse systemtap ; then + confgcc+=( $(use_enable systemtap) ) + fi + + if in_iuse valgrind ; then + confgcc+=( $(use_enable valgrind valgrind-annotations) ) + fi + + if in_iuse vtv ; then + confgcc+=( + $(use_enable vtv vtable-verify) + # See Note [implicitly enabled flags] + $(usex vtv '' --disable-libvtv) + ) + fi + + if in_iuse zstd ; then + confgcc+=( $(use_with zstd) ) + fi + + if tc_version_is_at_least 4.6 ; then + confgcc+=( --enable-lto ) + elif tc_version_is_at_least 4.5 ; then + confgcc+=( --disable-lto ) + fi + + # graphite was added in 4.4 but we only support it in 6.5+ due to external + # library issues. #448024, #701270 + if tc_version_is_at_least 6.5 && in_iuse graphite ; then + confgcc+=( $(use_with graphite isl) ) + use graphite && confgcc+=( --disable-isl-version-check ) + elif tc_version_is_at_least 5.0 ; then + confgcc+=( --without-isl ) + elif tc_version_is_at_least 4.8 ; then + confgcc+=( --without-cloog ) + elif tc_version_is_at_least 4.4 ; then + confgcc+=( --without-{cloog,ppl} ) + fi + + if tc_version_is_at_least 4.8; then + if in_iuse sanitize ; then + # See Note [implicitly enabled flags] + confgcc+=( $(usex sanitize '' --disable-libsanitizer) ) + else + confgcc+=( --disable-libsanitizer ) + fi + fi + + if tc_version_is_at_least 6.0 && in_iuse pie ; then + confgcc+=( $(use_enable pie default-pie) ) + fi + + if tc_version_is_at_least 6.0 && in_iuse ssp ; then + confgcc+=( + # This defaults to -fstack-protector-strong. + $(use_enable ssp default-ssp) + ) + fi + + # Disable gcc info regeneration -- it ships with generated info pages + # already. Our custom version/urls/etc... trigger it. #464008 + export gcc_cv_prog_makeinfo_modern=no + + # Do not let the X detection get in our way. We know things can be found + # via system paths, so no need to hardcode things that'll break multilib. + # Older gcc versions will detect ac_x_libraries=/usr/lib64 which ends up + # killing the 32bit builds which want /usr/lib. + export ac_cv_have_x='have_x=yes ac_x_includes= ac_x_libraries=' + + confgcc+=( "$@" ${EXTRA_ECONF} ) + + # Nothing wrong with a good dose of verbosity + echo + einfo "PREFIX: ${PREFIX}" + einfo "BINPATH: ${BINPATH}" + einfo "LIBPATH: ${LIBPATH}" + einfo "DATAPATH: ${DATAPATH}" + einfo "STDCXX_INCDIR: ${STDCXX_INCDIR}" + echo + einfo "Languages: ${GCC_LANG}" + echo + einfo "Configuring GCC with: ${confgcc[@]//--/\n\t--}" + echo + + # Build in a separate build tree + mkdir -p "${WORKDIR}"/build + pushd "${WORKDIR}"/build > /dev/null + + # and now to do the actual configuration + addwrite /dev/zero + echo "${S}"/configure "${confgcc[@]}" + # Older gcc versions did not detect bash and re-exec itself, so force the + # use of bash. Newer ones will auto-detect, but this is not harmful. + CONFIG_SHELL="${EPREFIX}/bin/bash" \ + bash "${S}"/configure "${confgcc[@]}" || die "failed to run configure" + + # return to whatever directory we were in before + popd > /dev/null +} + +# Replace -m flags unsupported by the version being built with the best +# available equivalent +downgrade_arch_flags() { + local arch bver i isa myarch mytune rep ver + + bver=${1:-${GCC_BRANCH_VER}} + # Don't perform downgrade if running gcc is older than ebuild's. + tc_version_is_at_least ${bver} $(gcc-version) || return 0 + [[ $(tc-arch) != amd64 && $(tc-arch) != x86 ]] && return 0 + + myarch=$(get-flag march) + mytune=$(get-flag mtune) + + # If -march=native isn't supported we have to tease out the actual arch + if [[ ${myarch} == native || ${mytune} == native ]] ; then + if ! tc_version_is_at_least 4.2 ${bver}; then + arch=$($(tc-getCC) -march=native -v -E -P - </dev/null 2>&1 \ + | sed -rn "/cc1.*-march/s:.*-march=([^ ']*).*:\1:p") + replace-cpu-flags native ${arch} + fi + fi + + # Handle special -mtune flags + [[ ${mytune} == intel ]] && ! tc_version_is_at_least 4.9 ${bver} && replace-cpu-flags intel generic + [[ ${mytune} == generic ]] && ! tc_version_is_at_least 4.2 ${bver} && filter-flags '-mtune=*' + [[ ${mytune} == x86-64 ]] && filter-flags '-mtune=*' + tc_version_is_at_least 3.4 ${bver} || filter-flags '-mtune=*' + + # "added" "arch" "replacement" + local archlist=( + 9 znver2 znver1 + 4.9 bdver4 bdver3 + 4.9 bonnell atom + 4.9 broadwell core-avx2 + 4.9 haswell core-avx2 + 4.9 ivybridge core-avx-i + 4.9 nehalem corei7 + 4.9 sandybridge corei7-avx + 4.9 silvermont corei7 + 4.9 westmere corei7 + 4.8 bdver3 bdver2 + 4.8 btver2 btver1 + 4.7 bdver2 bdver1 + 4.7 core-avx2 core-avx-i + 4.6 bdver1 amdfam10 + 4.6 btver1 amdfam10 + 4.6 core-avx-i core2 + 4.6 corei7 core2 + 4.6 corei7-avx core2 + 4.5 atom core2 + 4.3 amdfam10 k8 + 4.3 athlon64-sse3 k8 + 4.3 barcelona k8 + 4.3 core2 nocona + 4.3 geode k6-2 # gcc.gnu.org/PR41989#c22 + 4.3 k8-sse3 k8 + 4.3 opteron-sse3 k8 + 3.4 athlon-fx x86-64 + 3.4 athlon64 x86-64 + 3.4 c3-2 c3 + 3.4 k8 x86-64 + 3.4 opteron x86-64 + 3.4 pentium-m pentium3 + 3.4 pentium3m pentium3 + 3.4 pentium4m pentium4 + ) + + for ((i = 0; i < ${#archlist[@]}; i += 3)) ; do + myarch=$(get-flag march) + mytune=$(get-flag mtune) + + ver=${archlist[i]} + arch=${archlist[i + 1]} + rep=${archlist[i + 2]} + + [[ ${myarch} != ${arch} && ${mytune} != ${arch} ]] && continue + + if ! tc_version_is_at_least ${ver} ${bver}; then + einfo "Downgrading '${myarch}' (added in gcc ${ver}) with '${rep}'..." + [[ ${myarch} == ${arch} ]] && replace-cpu-flags ${myarch} ${rep} + [[ ${mytune} == ${arch} ]] && replace-cpu-flags ${mytune} ${rep} + continue + else + break + fi + done + + # we only check -mno* here since -m* get removed by strip-flags later on + local isalist=( + 4.9 -mno-sha + 4.9 -mno-avx512pf + 4.9 -mno-avx512f + 4.9 -mno-avx512er + 4.9 -mno-avx512cd + 4.8 -mno-xsaveopt + 4.8 -mno-xsave + 4.8 -mno-rtm + 4.8 -mno-fxsr + 4.7 -mno-lzcnt + 4.7 -mno-bmi2 + 4.7 -mno-avx2 + 4.6 -mno-tbm + 4.6 -mno-rdrnd + 4.6 -mno-fsgsbase + 4.6 -mno-f16c + 4.6 -mno-bmi + 4.5 -mno-xop + 4.5 -mno-movbe + 4.5 -mno-lwp + 4.5 -mno-fma4 + 4.4 -mno-pclmul + 4.4 -mno-fma + 4.4 -mno-avx + 4.4 -mno-aes + 4.3 -mno-ssse3 + 4.3 -mno-sse4a + 4.3 -mno-sse4 + 4.3 -mno-sse4.2 + 4.3 -mno-sse4.1 + 4.3 -mno-popcnt + 4.3 -mno-abm + ) + + for ((i = 0; i < ${#isalist[@]}; i += 2)) ; do + ver=${isalist[i]} + isa=${isalist[i + 1]} + tc_version_is_at_least ${ver} ${bver} || filter-flags ${isa} ${isa/-m/-mno-} + done +} + +gcc_do_filter_flags() { + # Allow users to explicitly avoid flag sanitization via + # USE=custom-cflags. + if ! _tc_use_if_iuse custom-cflags; then + # Over-zealous CFLAGS can often cause problems. What may work for one + # person may not work for another. To avoid a large influx of bugs + # relating to failed builds, we strip most CFLAGS out to ensure as few + # problems as possible. + strip-flags + # Lock gcc at -O2; we want to be conservative here. + filter-flags '-O?' + append-flags -O2 + fi + + # dont want to funk ourselves + filter-flags '-mabi*' -m31 -m32 -m64 + + filter-flags -frecord-gcc-switches # 490738 + filter-flags -mno-rtm -mno-htm # 506202 + + if tc_version_is_between 3.2 3.4 ; then + # XXX: this is so outdated it's barely useful, but it don't hurt... + replace-cpu-flags G3 750 + replace-cpu-flags G4 7400 + replace-cpu-flags G5 7400 + + # XXX: should add a sed or something to query all supported flags + # from the gcc source and trim everything else ... + filter-flags -f{no-,}unit-at-a-time -f{no-,}web -mno-tls-direct-seg-refs + filter-flags -f{no-,}stack-protector{,-all} + filter-flags -fvisibility-inlines-hidden -fvisibility=hidden + # and warning options + filter-flags -Wextra -Wstack-protector + fi + if ! tc_version_is_at_least 4.1 ; then + filter-flags -fdiagnostics-show-option + filter-flags -Wstack-protector + fi + + if tc_version_is_between 6 8 ; then + # -mstackrealign triggers crashes in exception throwing + # at least on ada: bug #688580 + # The reason is unknown. Drop the flag for now. + filter-flags -mstackrealign + fi + + if tc_version_is_at_least 3.4 ; then + case $(tc-arch) in + amd64|x86) + filter-flags '-mcpu=*' + + tc_version_is_between 4.4 4.5 && append-flags -mno-avx # 357287 + + if tc_version_is_between 4.6 4.7 ; then + # https://bugs.gentoo.org/411333 + # https://bugs.gentoo.org/466454 + replace-cpu-flags c3-2 pentium2 pentium3 pentium3m pentium-m i686 + fi + ;; + alpha) + # https://bugs.gentoo.org/454426 + append-ldflags -Wl,--no-relax + ;; + sparc) + # temporary workaround for random ICEs reproduced by multiple users + # https://bugs.gentoo.org/457062 + tc_version_is_between 4.6 4.8 && MAKEOPTS+=" -j1" + ;; + *-macos) + # http://gcc.gnu.org/PR25127 + tc_version_is_between 4.0 4.2 && \ + filter-flags '-mcpu=*' '-march=*' '-mtune=*' + ;; + esac + fi + + strip-unsupported-flags + + # these are set here so we have something sane at configure time + if is_crosscompile ; then + # Set this to something sane for both native and target + CFLAGS="-O2 -pipe" + FFLAGS=${CFLAGS} + FCFLAGS=${CFLAGS} + + # "hppa2.0-unknown-linux-gnu" -> hppa2_0_unknown_linux_gnu + local VAR="CFLAGS_"${CTARGET//[-.]/_} + CXXFLAGS=${!VAR-${CFLAGS}} + fi + + export GCJFLAGS=${GCJFLAGS:-${CFLAGS}} +} + +setup_minispecs_gcc_build_specs() { + # Setup the "build.specs" file for gcc 4.3 to use when building. + if hardened_gcc_works pie ; then + cat "${WORKDIR}"/specs/pie.specs >> "${WORKDIR}"/build.specs + fi + if hardened_gcc_works ssp ; then + for s in ssp sspall ; do + cat "${WORKDIR}"/specs/${s}.specs >> "${WORKDIR}"/build.specs + done + fi + for s in nostrict znow ; do + cat "${WORKDIR}"/specs/${s}.specs >> "${WORKDIR}"/build.specs + done + export GCC_SPECS="${WORKDIR}"/build.specs +} + +gcc-multilib-configure() { + if ! is_multilib ; then + confgcc+=( --disable-multilib ) + # Fun times: if we are building for a target that has multiple + # possible ABI formats, and the user has told us to pick one + # that isn't the default, then not specifying it via the list + # below will break that on us. + else + confgcc+=( --enable-multilib ) + fi + + # translate our notion of multilibs into gcc's + local abi list + for abi in $(get_all_abis TARGET) ; do + local l=$(gcc-abi-map ${abi}) + [[ -n ${l} ]] && list+=",${l}" + done + if [[ -n ${list} ]] ; then + case ${CTARGET} in + x86_64*) + tc_version_is_at_least 4.8 && confgcc+=( --with-multilib-list=${list:1} ) + ;; + esac + fi +} + +gcc-abi-map() { + # Convert the ABI name we use in Gentoo to what gcc uses + local map=() + case ${CTARGET} in + mips*) map=("o32 32" "n32 n32" "n64 64") ;; + riscv*) map=("lp64d lp64d" "lp64 lp64" "ilp32d ilp32d" "ilp32 ilp32") ;; + x86_64*) map=("amd64 m64" "x86 m32" "x32 mx32") ;; + esac + + local m + for m in "${map[@]}" ; do + l=( ${m} ) + [[ $1 == ${l[0]} ]] && echo ${l[1]} && break + done +} + +#----> src_compile <---- + +toolchain_src_compile() { + touch "${S}"/gcc/c-gperf.h + + # Do not make manpages if we do not have perl ... + [[ ! -x /usr/bin/perl ]] \ + && find "${WORKDIR}"/build -name '*.[17]' -exec touch {} + + + # To compile ada library standard files special compiler options are passed + # via ADAFLAGS in the Makefile. + # Unset ADAFLAGS as setting this override the options + unset ADAFLAGS + + # Older gcc versions did not detect bash and re-exec itself, so force the + # use of bash. Newer ones will auto-detect, but this is not harmful. + # This needs to be set for compile as well, as it's used in libtool + # generation, which will break install otherwise (at least in 3.3.6): #664486 + CONFIG_SHELL="${EPREFIX}/bin/bash" \ + gcc_do_make ${GCC_MAKE_TARGET} +} + +gcc_do_make() { + # This function accepts one optional argument, the make target to be used. + # If omitted, gcc_do_make will try to guess whether it should use all, + # or bootstrap-lean depending on CTARGET and arch. + # An example of how to use this function: + # + # gcc_do_make all-target-libstdc++-v3 + + [[ -n ${1} ]] && GCC_MAKE_TARGET=${1} + + # default target + if is_crosscompile || tc-is-cross-compiler ; then + # 3 stage bootstrapping doesnt quite work when you cant run the + # resulting binaries natively ^^; + GCC_MAKE_TARGET=${GCC_MAKE_TARGET-all} + else + if tc_version_is_at_least 3.3 && _tc_use_if_iuse pgo; then + GCC_MAKE_TARGET=${GCC_MAKE_TARGET-profiledbootstrap} + else + GCC_MAKE_TARGET=${GCC_MAKE_TARGET-bootstrap-lean} + fi + fi + + # Older versions of GCC could not do profiledbootstrap in parallel due to + # collisions with profiling info. + if [[ ${GCC_MAKE_TARGET} == "profiledbootstrap" ]]; then + ! tc_version_is_at_least 4.6 && export MAKEOPTS="${MAKEOPTS} -j1" + fi + + if [[ ${GCC_MAKE_TARGET} == "all" ]] ; then + STAGE1_CFLAGS=${STAGE1_CFLAGS-"${CFLAGS}"} + elif [[ $(gcc-version) == "3.4" && ${GCC_BRANCH_VER} == "3.4" ]] && gcc-specs-ssp ; then + # See bug #79852 + STAGE1_CFLAGS=${STAGE1_CFLAGS-"-O2"} + fi + + if is_crosscompile; then + # In 3.4, BOOT_CFLAGS is never used on a crosscompile... + # but I'll leave this in anyways as someone might have had + # some reason for putting it in here... --eradicator + BOOT_CFLAGS=${BOOT_CFLAGS-"-O2"} + else + # we only want to use the system's CFLAGS if not building a + # cross-compiler. + BOOT_CFLAGS=${BOOT_CFLAGS-"$(get_abi_CFLAGS ${TARGET_DEFAULT_ABI}) ${CFLAGS}"} + fi + + einfo "Compiling ${PN} (${GCC_MAKE_TARGET})..." + + pushd "${WORKDIR}"/build >/dev/null + + emake \ + LDFLAGS="${LDFLAGS}" \ + STAGE1_CFLAGS="${STAGE1_CFLAGS}" \ + LIBPATH="${LIBPATH}" \ + BOOT_CFLAGS="${BOOT_CFLAGS}" \ + ${GCC_MAKE_TARGET} \ + || die "emake failed with ${GCC_MAKE_TARGET}" + + if is_ada; then + # Without these links it is not getting the good compiler + # Need to check why + ln -s gcc ../build/prev-gcc || die + ln -s ${CHOST} ../build/prev-${CHOST} || die + # Building standard ada library + emake -C gcc gnatlib-shared + # Building gnat toold + emake -C gcc gnattools + fi + + if ! is_crosscompile && _tc_use_if_iuse cxx && _tc_use_if_iuse doc ; then + if type -p doxygen > /dev/null ; then + if tc_version_is_at_least 4.3 ; then + cd "${CTARGET}"/libstdc++-v3/doc + emake doc-man-doxygen || ewarn "failed to make docs" + elif tc_version_is_at_least 3.0 ; then + cd "${CTARGET}"/libstdc++-v3 + emake doxygen-man || ewarn "failed to make docs" + fi + # Clean bogus manpages. #113902 + find -name '*_build_*' -delete + # Blow away generated directory references. Newer versions of gcc + # have gotten better at this, but not perfect. This is easier than + # backporting all of the various doxygen patches. #486754 + find -name '*_.3' -exec grep -l ' Directory Reference ' {} + | \ + xargs rm -f + else + ewarn "Skipping libstdc++ manpage generation since you don't have doxygen installed" + fi + fi + + popd >/dev/null +} + +#---->> src_test <<---- + +toolchain_src_test() { + cd "${WORKDIR}"/build + # 'asan' wants to be preloaded first, so does 'sandbox'. + # To make asan tests work disable sandbox for all of test suite. + # 'backtrace' tests also does not like 'libsandbox.so' presence. + SANDBOX_ON=0 LD_PRELOAD= emake -k check +} + +#---->> src_install <<---- + +toolchain_src_install() { + cd "${WORKDIR}"/build + + # Don't allow symlinks in private gcc include dir as this can break the build + find gcc/include*/ -type l -delete + + # Copy over the info pages. We disabled their generation earlier, but the + # build system only expects to install out of the build dir, not the source. #464008 + mkdir -p gcc/doc + local x= + for x in "${S}"/gcc/doc/*.info* ; do + if [[ -f ${x} ]] ; then + cp "${x}" gcc/doc/ || die + fi + done + + # We remove the generated fixincludes, as they can cause things to break + # (ncurses, openssl, etc). We do not prevent them from being built, as + # in the following commit which we revert: + # https://sources.gentoo.org/cgi-bin/viewvc.cgi/gentoo-x86/eclass/toolchain.eclass?r1=1.647&r2=1.648 + # This is because bsd userland needs fixedincludes to build gcc, while + # linux does not. Both can dispose of them afterwards. + while read x ; do + grep -q 'It has been auto-edited by fixincludes from' "${x}" \ + && rm -f "${x}" + done < <(find gcc/include*/ -name '*.h') + + # Do the 'make install' from the build directory + S="${WORKDIR}"/build emake -j1 DESTDIR="${D}" install || die + + # Punt some tools which are really only useful while building gcc + find "${ED}" -name install-tools -prune -type d -exec rm -rf "{}" \; + # This one comes with binutils + find "${ED}" -name libiberty.a -delete + + # Move the libraries to the proper location + gcc_movelibs + + # Basic sanity check + if ! is_crosscompile ; then + local EXEEXT + eval $(grep ^EXEEXT= "${WORKDIR}"/build/gcc/config.log) + [[ -r ${D}${BINPATH}/gcc${EXEEXT} ]] || die "gcc not found in ${ED}" + fi + + dodir /etc/env.d/gcc + create_gcc_env_entry + create_revdep_rebuild_entry + + # Setup the gcc_env_entry for hardened gcc 4 with minispecs + want_minispecs && copy_minispecs_gcc_specs + + # Make sure we dont have stuff lying around that + # can nuke multiple versions of gcc + gcc_slot_java + + dodir /usr/bin + cd "${D}"${BINPATH} + # Ugh: we really need to auto-detect this list. + # It's constantly out of date. + for x in cpp gcc g++ c++ gcov g77 gcj gcjh gfortran gccgo gnat* ; do + # For some reason, g77 gets made instead of ${CTARGET}-g77... + # this should take care of that + if [[ -f ${x} ]] ; then + # In case they're hardlinks, clear out the target first + # otherwise the mv below will complain. + rm -f ${CTARGET}-${x} + mv ${x} ${CTARGET}-${x} + fi + + if [[ -f ${CTARGET}-${x} ]] ; then + if ! is_crosscompile ; then + ln -sf ${CTARGET}-${x} ${x} + dosym ${BINPATH}/${CTARGET}-${x} \ + /usr/bin/${x}-${GCC_CONFIG_VER} + fi + # Create versioned symlinks + dosym ${BINPATH}/${CTARGET}-${x} \ + /usr/bin/${CTARGET}-${x}-${GCC_CONFIG_VER} + fi + + if [[ -f ${CTARGET}-${x}-${GCC_CONFIG_VER} ]] ; then + rm -f ${CTARGET}-${x}-${GCC_CONFIG_VER} + ln -sf ${CTARGET}-${x} ${CTARGET}-${x}-${GCC_CONFIG_VER} + fi + done + + # When gcc builds a crosscompiler it does not install unprefixed tools. + # When cross-building gcc does install native tools. + if ! is_crosscompile; then + # Rename the main go binaries as we don't want to clobber dev-lang/go + # when gcc-config runs. #567806 + if tc_version_is_at_least 5 && is_go ; then + for x in go gofmt; do + mv ${x} ${x}-${GCCMAJOR} || die + done + fi + fi + + # As gcc installs object files built against bost ${CHOST} and ${CTARGET} + # ideally we will need to strip them using different tools: + # Using ${CHOST} tools: + # - "${D}${BINPATH}" + # - (for is_crosscompile) "${D}${HOSTLIBPATH}" + # - "${D}${PREFIX}/libexec/gcc/${CTARGET}/${GCC_CONFIG_VER}" + # Using ${CTARGET} tools: + # - "${D}${LIBPATH}" + # As dostrip does not specify host to override ${CHOST} tools just skip + # non-native binary stripping. + is_crosscompile && tc_supports_dostrip && dostrip -x "${LIBPATH}" + + cd "${S}" + if is_crosscompile; then + rm -rf "${ED}"/usr/share/{man,info} + rm -rf "${D}"${DATAPATH}/{man,info} + else + if tc_version_is_at_least 3.0 ; then + local cxx_mandir=$(find "${WORKDIR}/build/${CTARGET}/libstdc++-v3" -name man) + if [[ -d ${cxx_mandir} ]] ; then + cp -r "${cxx_mandir}"/man? "${D}${DATAPATH}"/man/ + fi + fi + fi + + # portage regenerates 'dir' files on it's own: bug #672408 + # Drop 'dir' files to avoid collisions. + if [[ -f "${D}${DATAPATH}"/info/dir ]]; then + einfo "Deleting '${D}${DATAPATH}/info/dir'" + rm "${D}${DATAPATH}"/info/dir || die + fi + + # prune empty dirs left behind + find "${ED}" -depth -type d -delete 2>/dev/null + + # libstdc++.la: Delete as it doesn't add anything useful: g++ itself + # handles linkage correctly in the dynamic & static case. It also just + # causes us pain: any C++ progs/libs linking with libtool will gain a + # reference to the full libstdc++.la file which is gcc version specific. + # libstdc++fs.la: It doesn't link against anything useful. + # libsupc++.la: This has no dependencies. + # libcc1.la: There is no static library, only dynamic. + # libcc1plugin.la: Same as above, and it's loaded via dlopen. + # libcp1plugin.la: Same as above, and it's loaded via dlopen. + # libgomp.la: gcc itself handles linkage (libgomp.spec). + # libgomp-plugin-*.la: Same as above, and it's an internal plugin only + # loaded via dlopen. + # libgfortran.la: gfortran itself handles linkage correctly in the + # dynamic & static case (libgfortran.spec). #573302 + # libgfortranbegin.la: Same as above, and it's an internal lib. + # libmpx.la: gcc itself handles linkage correctly (libmpx.spec). + # libmpxwrappers.la: See above. + # libitm.la: gcc itself handles linkage correctly (libitm.spec). + # libvtv.la: gcc itself handles linkage correctly. + # lib*san.la: Sanitizer linkage is handled internally by gcc, and they + # do not support static linking. #487550 #546700 + find "${D}${LIBPATH}" \ + '(' \ + -name libstdc++.la -o \ + -name libstdc++fs.la -o \ + -name libsupc++.la -o \ + -name libcc1.la -o \ + -name libcc1plugin.la -o \ + -name libcp1plugin.la -o \ + -name 'libgomp.la' -o \ + -name 'libgomp-plugin-*.la' -o \ + -name libgfortran.la -o \ + -name libgfortranbegin.la -o \ + -name libmpx.la -o \ + -name libmpxwrappers.la -o \ + -name libitm.la -o \ + -name libvtv.la -o \ + -name 'lib*san.la' \ + ')' -type f -delete + + # Use gid of 0 because some stupid ports don't have + # the group 'root' set to gid 0. Send to /dev/null + # for people who are testing as non-root. + chown -R root:0 "${D}${LIBPATH}" 2>/dev/null + + # Installing gdb pretty-printers into gdb-specific location. + local py gdbdir=/usr/share/gdb/auto-load${LIBPATH} + pushd "${D}${LIBPATH}" >/dev/null + for py in $(find . -name '*-gdb.py') ; do + local multidir=${py%/*} + insinto "${gdbdir}/${multidir}" + sed -i "/^libdir =/s:=.*:= '${LIBPATH}/${multidir}':" "${py}" || die #348128 + doins "${py}" || die + rm "${py}" || die + done + popd >/dev/null + + # Don't scan .gox files for executable stacks - false positives + export QA_EXECSTACK="usr/lib*/go/*/*.gox" + export QA_WX_LOAD="usr/lib*/go/*/*.gox" + + # Disable RANDMMAP so PCH works. #301299 + if tc_version_is_at_least 4.3 ; then + pax-mark -r "${D}${PREFIX}/libexec/gcc/${CTARGET}/${GCC_CONFIG_VER}/cc1" + pax-mark -r "${D}${PREFIX}/libexec/gcc/${CTARGET}/${GCC_CONFIG_VER}/cc1plus" + fi + + # Disable MPROTECT so java works. #574808 + if is_gcj ; then + pax-mark -m "${D}${PREFIX}/libexec/gcc/${CTARGET}/${GCC_CONFIG_VER}/ecj1" + pax-mark -m "${D}${PREFIX}/${CTARGET}/gcc-bin/${GCC_CONFIG_VER}/gij" + fi +} + +# Move around the libs to the right location. For some reason, +# when installing gcc, it dumps internal libraries into /usr/lib +# instead of the private gcc lib path +gcc_movelibs() { + # older versions of gcc did not support --print-multi-os-directory + tc_version_is_at_least 3.2 || return 0 + + # For non-target libs which are for CHOST and not CTARGET, we want to + # move them to the compiler-specific CHOST internal dir. This is stuff + # that you want to link against when building tools rather than building + # code to run on the target. + if tc_version_is_at_least 5 && is_crosscompile ; then + dodir "${HOSTLIBPATH#${EPREFIX}}" + mv "${ED}"/usr/$(get_libdir)/libcc1* "${D}${HOSTLIBPATH}" || die + fi + # libgccjit gets installed to /usr/lib, not /usr/$(get_libdir). Probably + # due to a bug in gcc build system. + if is_jit ; then + dodir "${LIBPATH#${EPREFIX}}" + mv "${ED}"/usr/lib/libgccjit* "${D}${LIBPATH}" || die + fi + + # For all the libs that are built for CTARGET, move them into the + # compiler-specific CTARGET internal dir. + local x multiarg removedirs="" + for multiarg in $($(XGCC) -print-multi-lib) ; do + multiarg=${multiarg#*;} + multiarg=${multiarg//@/ -} + + local OS_MULTIDIR=$($(XGCC) ${multiarg} --print-multi-os-directory) + local MULTIDIR=$($(XGCC) ${multiarg} --print-multi-directory) + local TODIR="${D}${LIBPATH}"/${MULTIDIR} + local FROMDIR= + + [[ -d ${TODIR} ]] || mkdir -p ${TODIR} + + for FROMDIR in \ + "${LIBPATH}"/${OS_MULTIDIR} \ + "${LIBPATH}"/../${MULTIDIR} \ + "${PREFIX}"/lib/${OS_MULTIDIR} \ + "${PREFIX}"/${CTARGET}/lib/${OS_MULTIDIR} + do + removedirs="${removedirs} ${FROMDIR}" + FROMDIR=${D}${FROMDIR} + if [[ ${FROMDIR} != "${TODIR}" && -d ${FROMDIR} ]] ; then + local files=$(find "${FROMDIR}" -maxdepth 1 ! -type d 2>/dev/null) + if [[ -n ${files} ]] ; then + mv ${files} "${TODIR}" || die + fi + fi + done + fix_libtool_libdir_paths "${LIBPATH}/${MULTIDIR}" + + # SLOT up libgcj.pc if it's available (and let gcc-config worry about links) + FROMDIR="${PREFIX}/lib/${OS_MULTIDIR}" + for x in "${D}${FROMDIR}"/pkgconfig/libgcj*.pc ; do + [[ -f ${x} ]] || continue + sed -i "/^libdir=/s:=.*:=${LIBPATH}/${MULTIDIR}:" "${x}" || die + mv "${x}" "${D}${FROMDIR}"/pkgconfig/libgcj-${GCC_PV}.pc || die + done + done + + # We remove directories separately to avoid this case: + # mv SRC/lib/../lib/*.o DEST + # rmdir SRC/lib/../lib/ + # mv SRC/lib/../lib32/*.o DEST # Bork + for FROMDIR in ${removedirs} ; do + rmdir "${D}"${FROMDIR} >& /dev/null + done + find -depth "${ED}" -type d -exec rmdir {} + >& /dev/null +} + +# make sure the libtool archives have libdir set to where they actually +# -are-, and not where they -used- to be. also, any dependencies we have +# on our own .la files need to be updated. +fix_libtool_libdir_paths() { + local libpath="$1" + + pushd "${D}" >/dev/null + + pushd "./${libpath}" >/dev/null + local dir="${PWD#${D%/}}" + local allarchives=$(echo *.la) + allarchives="\(${allarchives// /\\|}\)" + popd >/dev/null + + # The libdir might not have any .la files. #548782 + find "./${dir}" -maxdepth 1 -name '*.la' \ + -exec sed -i -e "/^libdir=/s:=.*:='${dir}':" {} + || die + # Would be nice to combine these, but -maxdepth can not be specified + # on sub-expressions. + find "./${PREFIX}"/lib* -maxdepth 3 -name '*.la' \ + -exec sed -i -e "/^dependency_libs=/s:/[^ ]*/${allarchives}:${libpath}/\1:g" {} + || die + find "./${dir}/" -maxdepth 1 -name '*.la' \ + -exec sed -i -e "/^dependency_libs=/s:/[^ ]*/${allarchives}:${libpath}/\1:g" {} + || die + + popd >/dev/null +} + +create_gcc_env_entry() { + dodir /etc/env.d/gcc + local gcc_envd_base="/etc/env.d/gcc/${CTARGET}-${GCC_CONFIG_VER}" + + local gcc_specs_file + local gcc_envd_file="${ED}${gcc_envd_base}" + if [[ -z $1 ]] ; then + # I'm leaving the following commented out to remind me that it + # was an insanely -bad- idea. Stuff broke. GCC_SPECS isnt unset + # on chroot or in non-toolchain.eclass gcc ebuilds! + #gcc_specs_file="${LIBPATH}/specs" + gcc_specs_file="" + else + gcc_envd_file+="-$1" + gcc_specs_file="${LIBPATH}/$1.specs" + fi + + # We want to list the default ABI's LIBPATH first so libtool + # searches that directory first. This is a temporary + # workaround for libtool being stupid and using .la's from + # conflicting ABIs by using the first one in the search path + local ldpaths mosdirs + if tc_version_is_at_least 3.2 ; then + local mdir mosdir abi ldpath + for abi in $(get_all_abis TARGET) ; do + mdir=$($(XGCC) $(get_abi_CFLAGS ${abi}) --print-multi-directory) + ldpath=${LIBPATH} + [[ ${mdir} != "." ]] && ldpath+="/${mdir}" + ldpaths="${ldpath}${ldpaths:+:${ldpaths}}" + + mosdir=$($(XGCC) $(get_abi_CFLAGS ${abi}) -print-multi-os-directory) + mosdirs="${mosdir}${mosdirs:+:${mosdirs}}" + done + else + # Older gcc's didn't do multilib, so logic is simple. + ldpaths=${LIBPATH} + fi + + cat <<-EOF > ${gcc_envd_file} + GCC_PATH="${BINPATH}" + LDPATH="${ldpaths}" + MANPATH="${DATAPATH}/man" + INFOPATH="${DATAPATH}/info" + STDCXX_INCDIR="${STDCXX_INCDIR##*/}" + CTARGET="${CTARGET}" + GCC_SPECS="${gcc_specs_file}" + MULTIOSDIRS="${mosdirs}" + EOF +} + +create_revdep_rebuild_entry() { + local revdep_rebuild_base="/etc/revdep-rebuild/05cross-${CTARGET}-${GCC_CONFIG_VER}" + local revdep_rebuild_file="${ED}${revdep_rebuild_base}" + + is_crosscompile || return 0 + + dodir /etc/revdep-rebuild + cat <<-EOF > "${revdep_rebuild_file}" + # Generated by ${CATEGORY}/${PF} + # Ignore libraries built for ${CTARGET}, https://bugs.gentoo.org/692844. + SEARCH_DIRS_MASK="${LIBPATH}" + EOF +} + +copy_minispecs_gcc_specs() { + # on gcc 6 we don't need minispecs + if tc_version_is_at_least 6.0 ; then + return 0 + fi + + # setup the hardenedno* specs files and the vanilla specs file. + if hardened_gcc_works ; then + create_gcc_env_entry hardenednopiessp + fi + if hardened_gcc_works pie ; then + create_gcc_env_entry hardenednopie + fi + if hardened_gcc_works ssp ; then + create_gcc_env_entry hardenednossp + fi + create_gcc_env_entry vanilla + insinto ${LIBPATH#${EPREFIX}} + doins "${WORKDIR}"/specs/*.specs || die "failed to install specs" + # Build system specs file which, if it exists, must be a complete set of + # specs as it completely and unconditionally overrides the builtin specs. + if ! tc_version_is_at_least 4.4 ; then + $(XGCC) -dumpspecs > "${WORKDIR}"/specs/specs + cat "${WORKDIR}"/build.specs >> "${WORKDIR}"/specs/specs + doins "${WORKDIR}"/specs/specs || die "failed to install the specs file" + fi +} + +gcc_slot_java() { + local x + + # Move Java headers to compiler-specific dir + for x in "${D}${PREFIX}"/include/gc*.h "${D}${PREFIX}"/include/j*.h ; do + [[ -f ${x} ]] && mv -f "${x}" "${D}${LIBPATH}"/include/ + done + for x in gcj gnu java javax org ; do + if [[ -d ${D}${PREFIX}/include/${x} ]] ; then + dodir /${LIBPATH#${EPREFIX}}/include/${x} + mv -f "${D}${PREFIX}"/include/${x}/* "${D}${LIBPATH}"/include/${x}/ + rm -rf "${D}${PREFIX}"/include/${x} + fi + done + + if [[ -d ${D}${PREFIX}/lib/security ]] || [[ -d ${D}${PREFIX}/$(get_libdir)/security ]] ; then + dodir /${LIBPATH#${EPREFIX}}/security + mv -f "${D}${PREFIX}"/lib*/security/* "${D}${LIBPATH}"/security + rm -rf "${D}${PREFIX}"/lib*/security + fi + + # Move random gcj files to compiler-specific directories + for x in libgcj.spec logging.properties ; do + x="${D}${PREFIX}/lib/${x}" + [[ -f ${x} ]] && mv -f "${x}" "${D}${LIBPATH}"/ + done + + # Rename jar because it could clash with Kaffe's jar if this gcc is + # primary compiler (aka don't have the -<version> extension) + cd "${D}${BINPATH}" + [[ -f jar ]] && mv -f jar gcj-jar +} + +#---->> pkg_post* <<---- + +toolchain_pkg_postinst() { + do_gcc_config + if [[ ! ${ROOT%/} && -f ${EPREFIX}/usr/share/eselect/modules/compiler-shadow.eselect ]] ; then + eselect compiler-shadow update all + fi + + if ! is_crosscompile && [[ ${PN} != "kgcc64" ]] ; then + # gcc stopped installing .la files fixer in June 2020. + # Cleaning can be removed in June 2022. + rm -f "${EROOT%/}"/sbin/fix_libtool_files.sh + rm -f "${EROOT%/}"/usr/sbin/fix_libtool_files.sh + rm -f "${EROOT%/}"/usr/share/gcc-data/fixlafiles.awk + fi +} + +toolchain_pkg_postrm() { + do_gcc_config + if [[ ! ${ROOT%/} && -f ${EPREFIX}/usr/share/eselect/modules/compiler-shadow.eselect ]] ; then + eselect compiler-shadow clean all + fi + + # clean up the cruft left behind by cross-compilers + if is_crosscompile ; then + if [[ -z $(ls "${EROOT%/}"/etc/env.d/gcc/${CTARGET}* 2>/dev/null) ]] ; then + einfo "Removing last cross-compiler instance. Deleting dangling symlinks." + rm -f "${EROOT%/}"/etc/env.d/gcc/config-${CTARGET} + rm -f "${EROOT%/}"/etc/env.d/??gcc-${CTARGET} + rm -f "${EROOT%/}"/usr/bin/${CTARGET}-{gcc,{g,c}++}{,32,64} + fi + return 0 + fi + + # gcc stopped installing .la files fixer in June 2020. + # Cleaning can be removed in June 2022. + rm -f "${EROOT%/}"/sbin/fix_libtool_files.sh + rm -f "${EROOT%/}"/usr/share/gcc-data/fixlafiles.awk +} + +do_gcc_config() { + if ! should_we_gcc_config ; then + gcc-config --use-old --force + return 0 + fi + + local current_gcc_config target + + current_gcc_config=$(gcc-config -c ${CTARGET} 2>/dev/null) + if [[ -n ${current_gcc_config} ]] ; then + local current_specs use_specs + # figure out which specs-specific config is active + current_specs=$(gcc-config -S ${current_gcc_config} | awk '{print $3}') + [[ -n ${current_specs} ]] && use_specs=-${current_specs} + + if [[ -n ${use_specs} ]] && \ + [[ ! -e ${EROOT%/}/etc/env.d/gcc/${CTARGET}-${GCC_CONFIG_VER}${use_specs} ]] + then + ewarn "The currently selected specs-specific gcc config," + ewarn "${current_specs}, doesn't exist anymore. This is usually" + ewarn "due to enabling/disabling hardened or switching to a version" + ewarn "of gcc that doesnt create multiple specs files. The default" + ewarn "config will be used, and the previous preference forgotten." + use_specs="" + fi + + target="${CTARGET}-${GCC_CONFIG_VER}${use_specs}" + else + # The curent target is invalid. Attempt to switch to a valid one. + # Blindly pick the latest version. #529608 + # TODO: Should update gcc-config to accept `-l ${CTARGET}` rather than + # doing a partial grep like this. + target=$(gcc-config -l 2>/dev/null | grep " ${CTARGET}-[0-9]" | tail -1 | awk '{print $2}') + fi + + gcc-config "${target}" +} + +should_we_gcc_config() { + # if the current config is invalid, we definitely want a new one + # Note: due to bash quirkiness, the following must not be 1 line + local curr_config + curr_config=$(gcc-config -c ${CTARGET} 2>&1) || return 0 + + # if the previously selected config has the same major.minor (branch) as + # the version we are installing, then it will probably be uninstalled + # for being in the same SLOT, make sure we run gcc-config. + local curr_config_ver=$(gcc-config -S ${curr_config} | awk '{print $2}') + + local curr_branch_ver=$(ver_cut 1-2 ${curr_config_ver}) + + if [[ ${curr_branch_ver} == ${GCC_BRANCH_VER} ]] ; then + return 0 + else + # if we're installing a genuinely different compiler version, + # we should probably tell the user -how- to switch to the new + # gcc version, since we're not going to do it for him/her. + # We don't want to switch from say gcc-3.3 to gcc-3.4 right in + # the middle of an emerge operation (like an 'emerge -e world' + # which could install multiple gcc versions). + # Only warn if we're installing a pkg as we might be called from + # the pkg_{pre,post}rm steps. #446830 + if [[ ${EBUILD_PHASE} == *"inst" ]] ; then + einfo "The current gcc config appears valid, so it will not be" + einfo "automatically switched for you. If you would like to" + einfo "switch to the newly installed gcc version, do the" + einfo "following:" + echo + einfo "gcc-config ${CTARGET}-${GCC_CONFIG_VER}" + einfo "source /etc/profile" + echo + fi + return 1 + fi +} + +#---->> support and misc functions <<---- + +# This is to make sure we don't accidentally try to enable support for a +# language that doesnt exist. GCC 3.4 supports f77, while 4.0 supports f95, etc. +# +# Also add a hook so special ebuilds (kgcc64) can control which languages +# exactly get enabled +gcc-lang-supported() { + grep ^language=\"${1}\" "${S}"/gcc/*/config-lang.in > /dev/null || return 1 + [[ -z ${TOOLCHAIN_ALLOWED_LANGS} ]] && return 0 + has $1 ${TOOLCHAIN_ALLOWED_LANGS} +} + +_tc_use_if_iuse() { + in_iuse $1 && use $1 +} + +is_ada() { + gcc-lang-supported ada || return 1 + _tc_use_if_iuse ada +} + +is_cxx() { + gcc-lang-supported 'c++' || return 1 + _tc_use_if_iuse cxx +} + +is_d() { + gcc-lang-supported d || return 1 + _tc_use_if_iuse d +} + +is_f77() { + gcc-lang-supported f77 || return 1 + _tc_use_if_iuse fortran +} + +is_f95() { + gcc-lang-supported f95 || return 1 + _tc_use_if_iuse fortran +} + +is_fortran() { + gcc-lang-supported fortran || return 1 + _tc_use_if_iuse fortran +} + +is_gcj() { + gcc-lang-supported java || return 1 + _tc_use_if_iuse cxx && _tc_use_if_iuse gcj +} + +is_go() { + gcc-lang-supported go || return 1 + _tc_use_if_iuse cxx && _tc_use_if_iuse go +} + +is_jit() { + gcc-lang-supported jit || return 1 + # cross-compiler does not really support jit as it has + # to generate code for a target. On target like avr + # libgcclit.so can't link at all: bug #594572 + is_crosscompile && return 1 + _tc_use_if_iuse jit +} + +is_multilib() { + tc_version_is_at_least 3 || return 1 + _tc_use_if_iuse multilib +} + +is_objc() { + gcc-lang-supported objc || return 1 + _tc_use_if_iuse objc +} + +is_objcxx() { + gcc-lang-supported 'obj-c++' || return 1 + _tc_use_if_iuse cxx && _tc_use_if_iuse objc++ +} + +# Grab a variable from the build system (taken from linux-info.eclass) +get_make_var() { + local var=$1 makefile=${2:-${WORKDIR}/build/Makefile} + echo -e "e:\\n\\t@echo \$(${var})\\ninclude ${makefile}" | \ + r=${makefile%/*} emake --no-print-directory -s -f - 2>/dev/null +} + +XGCC() { get_make_var GCC_FOR_TARGET ; } + +# The gentoo piessp patches allow for 3 configurations: +# 1) PIE+SSP by default +# 2) PIE by default +# 3) SSP by default +hardened_gcc_works() { + if [[ $1 == "pie" ]] ; then + # $gcc_cv_ld_pie is unreliable as it simply take the output of + # `ld --help | grep -- -pie`, that reports the option in all cases, also if + # the loader doesn't actually load the resulting executables. + # To avoid breakage, blacklist FreeBSD here at least + [[ ${CTARGET} == *-freebsd* ]] && return 1 + + want_pie || return 1 + _tc_use_if_iuse nopie && return 1 + hardened_gcc_is_stable pie + return $? + elif [[ $1 == "ssp" ]] ; then + [[ -n ${SPECS_VER} ]] || return 1 + _tc_use_if_iuse nossp && return 1 + hardened_gcc_is_stable ssp + return $? + else + # laziness ;) + hardened_gcc_works pie || return 1 + hardened_gcc_works ssp || return 1 + return 0 + fi +} + +hardened_gcc_is_stable() { + local tocheck + if [[ $1 == "pie" ]] ; then + if [[ ${CTARGET} == *-uclibc* ]] ; then + tocheck=${PIE_UCLIBC_STABLE} + else + tocheck=${PIE_GLIBC_STABLE} + fi + elif [[ $1 == "ssp" ]] ; then + if [[ ${CTARGET} == *-uclibc* ]] ; then + tocheck=${SSP_UCLIBC_STABLE} + elif [[ ${CTARGET} == *-gnu* ]] ; then + tocheck=${SSP_STABLE} + fi + else + die "hardened_gcc_stable needs to be called with pie or ssp" + fi + + has $(tc-arch) ${tocheck} && return 0 + return 1 +} + +want_minispecs() { + # on gcc 6 we don't need minispecs + if tc_version_is_at_least 6.0 ; then + return 0 + fi + if tc_version_is_at_least 4.3.2 && _tc_use_if_iuse hardened ; then + if ! want_pie ; then + ewarn "PIE_VER or SPECS_VER is not defined in the GCC ebuild." + elif use vanilla ; then + ewarn "You will not get hardened features if you have the vanilla USE-flag." + elif _tc_use_if_iuse nopie && _tc_use_if_iuse nossp ; then + ewarn "You will not get hardened features if you have the nopie and nossp USE-flag." + elif ! hardened_gcc_works ; then + ewarn "Your $(tc-arch) arch is not supported." + else + return 0 + fi + ewarn "Hope you know what you are doing. Hardened will not work." + return 0 + fi + return 1 +} + +want_pie() { + ! _tc_use_if_iuse hardened && [[ -n ${PIE_VER} ]] \ + && _tc_use_if_iuse nopie && return 1 + [[ -n ${PIE_VER} ]] && [[ -n ${SPECS_VER} ]] && return 0 + tc_version_is_at_least 4.3.2 && return 1 + [[ -z ${PIE_VER} ]] && return 1 + _tc_use_if_iuse nopie || return 0 + return 1 +} + +has toolchain_death_notice ${EBUILD_DEATH_HOOKS} || EBUILD_DEATH_HOOKS+=" toolchain_death_notice" +toolchain_death_notice() { + if [[ -e "${WORKDIR}"/build ]] ; then + pushd "${WORKDIR}"/build >/dev/null + (echo '' | $(tc-getCC ${CTARGET}) ${CFLAGS} -v -E - 2>&1) > gccinfo.log + [[ -e "${T}"/build.log ]] && cp "${T}"/build.log . + tar jcf "${WORKDIR}"/gcc-build-logs.tar.bz2 \ + gccinfo.log build.log $(find -name config.log) + rm gccinfo.log build.log + eerror + eerror "Please include ${WORKDIR}/gcc-build-logs.tar.bz2 in your bug report." + eerror + popd >/dev/null + fi +} + +# Note [implicitly enabled flags] +# ------------------------------- +# Usually configure-based packages handle explicit feature requests +# like +# ./configure --enable-foo +# as explicit request to check for support of 'foo' and bail out at +# configure time. +# +# GCC does not follow this pattern and instead overrides autodetection +# of the feature and enables it unconditionally. +# See bugs: +# https://gcc.gnu.org/PR85663 (libsanitizer on mips) +# https://bugs.gentoo.org/661252 (libvtv on powerpc64) +# +# Thus safer way to enable/disable the feature is to rely on implicit +# enabled-by-default state: +# econf $(usex foo '' --disable-foo) diff --git a/eclass/udev.eclass b/eclass/udev.eclass new file mode 100644 index 0000000..2873ae9 --- /dev/null +++ b/eclass/udev.eclass @@ -0,0 +1,127 @@ +# Copyright 1999-2018 Gentoo Authors +# Distributed under the terms of the GNU General Public License v2 + +# @ECLASS: udev.eclass +# @MAINTAINER: +# udev-bugs@gentoo.org +# @SUPPORTED_EAPIS: 0 1 2 3 4 5 6 7 +# @BLURB: Default eclass for determining udev directories. +# @DESCRIPTION: +# Default eclass for determining udev directories. +# @EXAMPLE: +# +# @CODE +# inherit udev +# +# # Example of the eclass usage: +# RDEPEND="virtual/udev" +# DEPEND="${RDEPEND}" +# +# src_configure() { +# econf --with-rulesdir="$(get_udevdir)"/rules.d +# } +# +# src_install() { +# default +# # udev_dorules contrib/99-foomatic +# # udev_newrules contrib/98-foomatic 99-foomatic +# } +# @CODE + +if [[ -z ${_UDEV_ECLASS} ]]; then +_UDEV_ECLASS=1 + +inherit toolchain-funcs + +case ${EAPI:-0} in + 0|1|2|3|4|5|6|7) ;; + *) die "${ECLASS}.eclass API in EAPI ${EAPI} not yet established." +esac + +if [[ ${EAPI:-0} == [0123456] ]]; then + RDEPEND="" + DEPEND="virtual/pkgconfig" +else + BDEPEND="virtual/pkgconfig" +fi + +# @FUNCTION: _udev_get_udevdir +# @INTERNAL +# @DESCRIPTION: +# Get unprefixed udevdir. +_udev_get_udevdir() { + if $($(tc-getPKG_CONFIG) --exists udev); then + local udevdir="$($(tc-getPKG_CONFIG) --variable=udevdir udev)" + echo "${udevdir#${EPREFIX%/}}" + else + echo /lib/udev + fi +} + +# @FUNCTION: udev_get_udevdir +# @DESCRIPTION: +# Use the short version $(get_udevdir) instead! +udev_get_udevdir() { + debug-print-function ${FUNCNAME} "${@}" + + eerror "This ebuild should be using the get_udevdir() function instead of the deprecated udev_get_udevdir()" + die "Deprecated function call: udev_get_udevdir(), please report to (overlay) maintainers." +} + +# @FUNCTION: get_udevdir +# @DESCRIPTION: +# Output the path for the udev directory (not including ${D}). +# This function always succeeds, even if udev is not installed. +# The fallback value is set to /lib/udev +get_udevdir() { + debug-print-function ${FUNCNAME} "${@}" + + echo "$(_udev_get_udevdir)" +} + +# @FUNCTION: udev_dorules +# @USAGE: <rule> [...] +# @DESCRIPTION: +# Install udev rule(s). Uses doins, thus it is fatal in EAPI 4 +# and non-fatal in earlier EAPIs. +udev_dorules() { + debug-print-function ${FUNCNAME} "${@}" + + ( + insopts -m 0644 + insinto "$(_udev_get_udevdir)"/rules.d + doins "${@}" + ) +} + +# @FUNCTION: udev_newrules +# @USAGE: <oldname> <newname> +# @DESCRIPTION: +# Install udev rule with a new name. Uses newins, thus it is fatal +# in EAPI 4 and non-fatal in earlier EAPIs. +udev_newrules() { + debug-print-function ${FUNCNAME} "${@}" + + ( + insopts -m 0644 + insinto "$(_udev_get_udevdir)"/rules.d + newins "${@}" + ) +} + +# @FUNCTION: udev_reload +# @DESCRIPTION: +# Run udevadm control --reload to refresh rules and databases +udev_reload() { + if [[ ${ROOT} != "" ]] && [[ ${ROOT} != "/" ]]; then + return 0 + fi + + if [[ -d ${ROOT}/run/udev ]]; then + ebegin "Running udev control --reload for reloading rules and databases" + udevadm control --reload + eend $? + fi +} + +fi diff --git a/eclass/unpacker.eclass b/eclass/unpacker.eclass new file mode 100644 index 0000000..3a1dc9f --- /dev/null +++ b/eclass/unpacker.eclass @@ -0,0 +1,475 @@ +# Copyright 1999-2020 Gentoo Authors +# Distributed under the terms of the GNU General Public License v2 + +# @ECLASS: unpacker.eclass +# @MAINTAINER: +# base-system@gentoo.org +# @BLURB: helpers for extraneous file formats and consistent behavior across EAPIs +# @DESCRIPTION: +# Some extraneous file formats are not part of PMS, or are only in certain +# EAPIs. Rather than worrying about that, support the crazy cruft here +# and for all EAPI versions. + +# Possible todos: +# - merge rpm unpacking +# - support partial unpacks? + +if [[ -z ${_UNPACKER_ECLASS} ]]; then +_UNPACKER_ECLASS=1 + +inherit toolchain-funcs + +# @ECLASS-VARIABLE: UNPACKER_BZ2 +# @DEFAULT_UNSET +# @DESCRIPTION: +# Utility to use to decompress bzip2 files. Will dynamically pick between +# `pbzip2` and `bzip2`. Make sure your choice accepts the "-dc" options. +# Note: this is meant for users to set, not ebuilds. + +# @ECLASS-VARIABLE: UNPACKER_LZIP +# @DEFAULT_UNSET +# @DESCRIPTION: +# Utility to use to decompress lzip files. Will dynamically pick between +# `plzip`, `pdlzip` and `lzip`. Make sure your choice accepts the "-dc" options. +# Note: this is meant for users to set, not ebuilds. + +# for internal use only (unpack_pdv and unpack_makeself) +find_unpackable_file() { + local src=$1 + if [[ -z ${src} ]] ; then + src=${DISTDIR}/${A} + else + if [[ ${src} == ./* ]] ; then + : # already what we want + elif [[ -e ${DISTDIR}/${src} ]] ; then + src=${DISTDIR}/${src} + elif [[ -e ${PWD}/${src} ]] ; then + src=${PWD}/${src} + elif [[ -e ${src} ]] ; then + src=${src} + fi + fi + [[ ! -e ${src} ]] && return 1 + echo "${src}" +} + +unpack_banner() { + echo ">>> Unpacking ${1##*/} to ${PWD}" +} + +# @FUNCTION: unpack_pdv +# @USAGE: <file to unpack> <size of off_t> +# @DESCRIPTION: +# Unpack those pesky pdv generated files ... +# They're self-unpacking programs with the binary package stuffed in +# the middle of the archive. Valve seems to use it a lot ... too bad +# it seems to like to segfault a lot :(. So lets take it apart ourselves. +# +# You have to specify the off_t size ... I have no idea how to extract that +# information out of the binary executable myself. Basically you pass in +# the size of the off_t type (in bytes) on the machine that built the pdv +# archive. +# +# One way to determine this is by running the following commands: +# +# @CODE +# strings <pdv archive> | grep lseek +# strace -elseek <pdv archive> +# @CODE +# +# Basically look for the first lseek command (we do the strings/grep because +# sometimes the function call is _llseek or something) and steal the 2nd +# parameter. Here is an example: +# +# @CODE +# $ strings hldsupdatetool.bin | grep lseek +# lseek +# $ strace -elseek ./hldsupdatetool.bin +# lseek(3, -4, SEEK_END) = 2981250 +# @CODE +# +# Thus we would pass in the value of '4' as the second parameter. +unpack_pdv() { + local src=$(find_unpackable_file "$1") + local sizeoff_t=$2 + + [[ -z ${src} ]] && die "Could not locate source for '$1'" + [[ -z ${sizeoff_t} ]] && die "No idea what off_t size was used for this pdv :(" + + unpack_banner "${src}" + + local metaskip=$(tail -c ${sizeoff_t} "${src}" | hexdump -e \"%i\") + local tailskip=$(tail -c $((${sizeoff_t}*2)) "${src}" | head -c ${sizeoff_t} | hexdump -e \"%i\") + + # grab metadata for debug reasons + local metafile="${T}/${FUNCNAME}.meta" + tail -c +$((${metaskip}+1)) "${src}" > "${metafile}" + + # rip out the final file name from the metadata + local datafile=$(tail -c +$((${metaskip}+1)) "${src}" | strings | head -n 1) + datafile=$(basename "${datafile}") + + # now lets uncompress/untar the file if need be + local tmpfile="${T}/${FUNCNAME}" + tail -c +$((${tailskip}+1)) ${src} 2>/dev/null | head -c 512 > "${tmpfile}" + + local iscompressed=$(file -b "${tmpfile}") + if [[ ${iscompressed:0:8} == "compress" ]] ; then + iscompressed=1 + mv "${tmpfile}"{,.Z} + gunzip "${tmpfile}" + else + iscompressed=0 + fi + local istar=$(file -b "${tmpfile}") + if [[ ${istar:0:9} == "POSIX tar" ]] ; then + istar=1 + else + istar=0 + fi + + #for some reason gzip dies with this ... dd cant provide buffer fast enough ? + #dd if=${src} ibs=${metaskip} count=1 \ + # | dd ibs=${tailskip} skip=1 \ + # | gzip -dc \ + # > ${datafile} + if [ ${iscompressed} -eq 1 ] ; then + if [ ${istar} -eq 1 ] ; then + tail -c +$((${tailskip}+1)) "${src}" 2>/dev/null \ + | head -c $((${metaskip}-${tailskip})) \ + | tar -xzf - + else + tail -c +$((${tailskip}+1)) "${src}" 2>/dev/null \ + | head -c $((${metaskip}-${tailskip})) \ + | gzip -dc \ + > ${datafile} + fi + else + if [ ${istar} -eq 1 ] ; then + tail -c +$((${tailskip}+1)) "${src}" 2>/dev/null \ + | head -c $((${metaskip}-${tailskip})) \ + | tar --no-same-owner -xf - + else + tail -c +$((${tailskip}+1)) "${src}" 2>/dev/null \ + | head -c $((${metaskip}-${tailskip})) \ + > ${datafile} + fi + fi + true + #[ -s "${datafile}" ] || die "failure unpacking pdv ('${metaskip}' '${tailskip}' '${datafile}')" + #assert "failure unpacking pdv ('${metaskip}' '${tailskip}' '${datafile}')" +} + +# @FUNCTION: unpack_makeself +# @USAGE: [file to unpack] [offset] [tail|dd] +# @DESCRIPTION: +# Unpack those pesky makeself generated files ... +# They're shell scripts with the binary package tagged onto +# the end of the archive. Loki utilized the format as does +# many other game companies. +# +# If the file is not specified, then ${A} is used. If the +# offset is not specified then we will attempt to extract +# the proper offset from the script itself. +unpack_makeself() { + local src_input=${1:-${A}} + local src=$(find_unpackable_file "${src_input}") + local skip=$2 + local exe=$3 + + [[ -z ${src} ]] && die "Could not locate source for '${src_input}'" + + unpack_banner "${src}" + + if [[ -z ${skip} ]] ; then + local ver=$(grep -m1 -a '#.*Makeself' "${src}" | awk '{print $NF}') + local skip=0 + exe=tail + case ${ver} in + 1.5.*|1.6.0-nv*) # tested 1.5.{3,4,5} ... guessing 1.5.x series is same + skip=$(grep -a ^skip= "${src}" | cut -d= -f2) + ;; + 2.0|2.0.1) + skip=$(grep -a ^$'\t'tail "${src}" | awk '{print $2}' | cut -b2-) + ;; + 2.1.1) + skip=$(grep -a ^offset= "${src}" | awk '{print $2}' | cut -b2-) + (( skip++ )) + ;; + 2.1.2) + skip=$(grep -a ^offset= "${src}" | awk '{print $3}' | head -n 1) + (( skip++ )) + ;; + 2.1.3) + skip=`grep -a ^offset= "${src}" | awk '{print $3}'` + (( skip++ )) + ;; + 2.1.4|2.1.5|2.1.6|2.2.0|2.4.0) + skip=$(grep -a offset=.*head.*wc "${src}" | awk '{print $3}' | head -n 1) + skip=$(head -n ${skip} "${src}" | wc -c) + exe="dd" + ;; + *) + eerror "I'm sorry, but I was unable to support the Makeself file." + eerror "The version I detected was '${ver}'." + eerror "Please file a bug about the file ${src##*/} at" + eerror "https://bugs.gentoo.org/ so that support can be added." + die "makeself version '${ver}' not supported" + ;; + esac + debug-print "Detected Makeself version ${ver} ... using ${skip} as offset" + fi + case ${exe} in + tail) exe=( tail -n +${skip} "${src}" );; + dd) exe=( dd ibs=${skip} skip=1 if="${src}" );; + *) die "makeself cant handle exe '${exe}'" + esac + + # lets grab the first few bytes of the file to figure out what kind of archive it is + local filetype tmpfile="${T}/${FUNCNAME}" + "${exe[@]}" 2>/dev/null | head -c 512 > "${tmpfile}" + filetype=$(file -b "${tmpfile}") || die + case ${filetype} in + *tar\ archive*) + "${exe[@]}" | tar --no-same-owner -xf - + ;; + bzip2*) + "${exe[@]}" | bzip2 -dc | tar --no-same-owner -xf - + ;; + gzip*) + "${exe[@]}" | tar --no-same-owner -xzf - + ;; + compress*) + "${exe[@]}" | gunzip | tar --no-same-owner -xf - + ;; + XZ*) + "${exe[@]}" | unxz | tar --no-same-owner -xf - + ;; + *) + eerror "Unknown filetype \"${filetype}\" ?" + false + ;; + esac + assert "failure unpacking (${filetype}) makeself ${src##*/} ('${ver}' +${skip})" +} + +# @FUNCTION: unpack_deb +# @USAGE: <one deb to unpack> +# @DESCRIPTION: +# Unpack a Debian .deb archive in style. +unpack_deb() { + [[ $# -eq 1 ]] || die "Usage: ${FUNCNAME} <file>" + + local deb=$(find_unpackable_file "$1") + + unpack_banner "${deb}" + + # on AIX ar doesn't work out as their ar used a different format + # from what GNU ar (and thus what .deb files) produce + if [[ -n ${EPREFIX} ]] ; then + { + read # global header + [[ ${REPLY} = "!<arch>" ]] || die "${deb} does not seem to be a deb archive" + local f timestamp uid gid mode size magic + while read f timestamp uid gid mode size magic ; do + [[ -n ${f} && -n ${size} ]] || continue # ignore empty lines + if [[ ${f} = "data.tar"* ]] ; then + head -c "${size}" > "${f}" + else + head -c "${size}" > /dev/null # trash it + fi + done + } < "${deb}" + else + $(tc-getBUILD_AR) x "${deb}" || die + fi + + unpacker ./data.tar* + + # Clean things up #458658. No one seems to actually care about + # these, so wait until someone requests to do something else ... + rm -f debian-binary {control,data}.tar* +} + +# @FUNCTION: unpack_cpio +# @USAGE: <one cpio to unpack> +# @DESCRIPTION: +# Unpack a cpio archive, file "-" means stdin. +unpack_cpio() { + [[ $# -eq 1 ]] || die "Usage: ${FUNCNAME} <file>" + + # needed as cpio always reads from stdin + local cpio_cmd=( cpio --make-directories --extract --preserve-modification-time ) + if [[ $1 == "-" ]] ; then + unpack_banner "stdin" + "${cpio_cmd[@]}" + else + local cpio=$(find_unpackable_file "$1") + unpack_banner "${cpio}" + "${cpio_cmd[@]}" <"${cpio}" + fi +} + +# @FUNCTION: unpack_zip +# @USAGE: <zip file> +# @DESCRIPTION: +# Unpack zip archives. +# This function ignores all non-fatal errors (i.e. warnings). +# That is useful for zip archives with extra crap attached +# (e.g. self-extracting archives). +unpack_zip() { + [[ $# -eq 1 ]] || die "Usage: ${FUNCNAME} <file>" + + local zip=$(find_unpackable_file "$1") + unpack_banner "${zip}" + unzip -qo "${zip}" + + [[ $? -le 1 ]] || die "unpacking ${zip} failed (arch=unpack_zip)" +} + +# @FUNCTION: _unpacker +# @USAGE: <one archive to unpack> +# @INTERNAL +# @DESCRIPTION: +# Unpack the specified archive. We only operate on one archive here +# to keep down on the looping logic (that is handled by `unpacker`). +_unpacker() { + [[ $# -eq 1 ]] || die "Usage: ${FUNCNAME} <file>" + + local a=$1 + local m=$(echo "${a}" | tr '[:upper:]' '[:lower:]') + a=$(find_unpackable_file "${a}") + + # first figure out the decompression method + local comp="" + case ${m} in + *.bz2|*.tbz|*.tbz2) + local bzcmd=${PORTAGE_BZIP2_COMMAND:-$(type -P pbzip2 || type -P bzip2)} + local bzuncmd=${PORTAGE_BUNZIP2_COMMAND:-${bzcmd} -d} + : ${UNPACKER_BZ2:=${bzuncmd}} + comp="${UNPACKER_BZ2} -c" + ;; + *.z|*.gz|*.tgz) + comp="gzip -dc" ;; + *.lzma|*.xz|*.txz) + comp="xz -dc" ;; + *.lz) + : ${UNPACKER_LZIP:=$(type -P plzip || type -P pdlzip || type -P lzip)} + comp="${UNPACKER_LZIP} -dc" ;; + *.zst) + comp="zstd -dfc" ;; + esac + + # then figure out if there are any archiving aspects + local arch="" + case ${m} in + *.tgz|*.tbz|*.tbz2|*.txz|*.tar.*|*.tar) + arch="tar --no-same-owner -xof" ;; + *.cpio.*|*.cpio) + arch="unpack_cpio" ;; + *.deb) + arch="unpack_deb" ;; + *.run) + arch="unpack_makeself" ;; + *.sh) + # Not all shell scripts are makeself + if head -n 30 "${a}" | grep -qs '#.*Makeself' ; then + arch="unpack_makeself" + fi + ;; + *.bin) + # Makeself archives can be annoyingly named + if head -c 100 "${a}" | grep -qs '#.*Makeself' ; then + arch="unpack_makeself" + fi + ;; + *.zip) + arch="unpack_zip" ;; + esac + + # finally do the unpack + if [[ -z ${arch}${comp} ]] ; then + unpack "$1" + return $? + fi + + [[ ${arch} != unpack_* ]] && unpack_banner "${a}" + + if [[ -z ${arch} ]] ; then + # Need to decompress the file into $PWD #408801 + local _a=${a%.*} + ${comp} "${a}" > "${_a##*/}" + elif [[ -z ${comp} ]] ; then + ${arch} "${a}" + else + ${comp} "${a}" | ${arch} - + fi + + assert "unpacking ${a} failed (comp=${comp} arch=${arch})" +} + +# @FUNCTION: unpacker +# @USAGE: [archives to unpack] +# @DESCRIPTION: +# This works in the same way that `unpack` does. If you don't specify +# any files, it will default to ${A}. +unpacker() { + local a + [[ $# -eq 0 ]] && set -- ${A} + for a ; do _unpacker "${a}" ; done +} + +# @FUNCTION: unpacker_src_unpack +# @DESCRIPTION: +# Run `unpacker` to unpack all our stuff. +unpacker_src_unpack() { + unpacker +} + +# @FUNCTION: unpacker_src_uri_depends +# @USAGE: [archives that we will unpack] +# @RETURN: Dependencies needed to unpack all the archives +# @DESCRIPTION: +# Walk all the specified files (defaults to $SRC_URI) and figure out the +# dependencies that are needed to unpack things. +# +# Note: USE flags are not yet handled. +unpacker_src_uri_depends() { + local uri deps d + + if [[ $# -eq 0 ]] ; then + # Disable path expansion for USE conditionals. #654960 + set -f + set -- ${SRC_URI} + set +f + fi + + for uri in "$@" ; do + case ${uri} in + *.cpio.*|*.cpio) + d="app-arch/cpio" ;; + *.deb) + # platforms like AIX don't have a good ar + d="kernel_AIX? ( app-arch/deb2targz )" ;; + *.rar|*.RAR) + d="app-arch/unrar" ;; + *.7z) + d="app-arch/p7zip" ;; + *.xz) + d="app-arch/xz-utils" ;; + *.zip) + d="app-arch/unzip" ;; + *.lz) + d="|| ( app-arch/plzip app-arch/pdlzip app-arch/lzip )" ;; + *.zst) + d="app-arch/zstd" ;; + esac + deps+=" ${d}" + done + + echo "${deps}" +} + +EXPORT_FUNCTIONS src_unpack + +fi diff --git a/eclass/user-info.eclass b/eclass/user-info.eclass new file mode 100644 index 0000000..15e9238 --- /dev/null +++ b/eclass/user-info.eclass @@ -0,0 +1,158 @@ +# Copyright 1999-2020 Gentoo Authors +# Distributed under the terms of the GNU General Public License v2 + +# @ECLASS: user-info.eclass +# @MAINTAINER: +# base-system@gentoo.org (Linux) +# Michał Górny <mgorny@gentoo.org> (NetBSD) +# @BLURB: Read-only access to user and group information + +if [[ -z ${_USER_INFO_ECLASS} ]]; then +_USER_INFO_ECLASS=1 + +# @FUNCTION: egetent +# @USAGE: <database> <key> +# @DESCRIPTION: +# Small wrapper for getent (Linux), nidump (< Mac OS X 10.5), +# dscl (Mac OS X 10.5), and pw (FreeBSD) used in enewuser()/enewgroup(). +# +# Supported databases: group passwd +egetent() { + local db=$1 key=$2 + + [[ $# -ge 3 ]] && die "usage: egetent <database> <key>" + + case ${db} in + passwd|group) ;; + *) die "sorry, database '${db}' not yet supported; file a bug" ;; + esac + + case ${CHOST} in + *-freebsd*|*-dragonfly*) + case ${db} in + passwd) db="user" ;; + *) ;; + esac + + # lookup by uid/gid + local opts + if [[ ${key} == [[:digit:]]* ]] ; then + [[ ${db} == "user" ]] && opts="-u" || opts="-g" + fi + + pw show ${db} ${opts} "${key}" -q + ;; + *-openbsd*) + grep "${key}:\*:" /etc/${db} + ;; + *) + # ignore nscd output if we're not running as root + type -p nscd >/dev/null && nscd -i "${db}" 2>/dev/null + getent "${db}" "${key}" + ;; + esac +} + +# @FUNCTION: egetusername +# @USAGE: <uid> +# @DESCRIPTION: +# Gets the username for given UID. +egetusername() { + [[ $# -eq 1 ]] || die "usage: egetusername <uid>" + + egetent passwd "$1" | cut -d: -f1 +} + +# @FUNCTION: egetgroupname +# @USAGE: <gid> +# @DESCRIPTION: +# Gets the group name for given GID. +egetgroupname() { + [[ $# -eq 1 ]] || die "usage: egetgroupname <gid>" + + egetent group "$1" | cut -d: -f1 +} + +# @FUNCTION: egethome +# @USAGE: <user> +# @DESCRIPTION: +# Gets the home directory for the specified user. +egethome() { + local pos + + [[ $# -eq 1 ]] || die "usage: egethome <user>" + + case ${CHOST} in + *-freebsd*|*-dragonfly*) + pos=9 + ;; + *) # Linux, NetBSD, OpenBSD, etc... + pos=6 + ;; + esac + + egetent passwd "$1" | cut -d: -f${pos} +} + +# @FUNCTION: egetshell +# @USAGE: <user> +# @DESCRIPTION: +# Gets the shell for the specified user. +egetshell() { + local pos + + [[ $# -eq 1 ]] || die "usage: egetshell <user>" + + case ${CHOST} in + *-freebsd*|*-dragonfly*) + pos=10 + ;; + *) # Linux, NetBSD, OpenBSD, etc... + pos=7 + ;; + esac + + egetent passwd "$1" | cut -d: -f${pos} +} + +# @FUNCTION: egetcomment +# @USAGE: <user> +# @DESCRIPTION: +# Gets the comment field for the specified user. +egetcomment() { + local pos + + [[ $# -eq 1 ]] || die "usage: egetcomment <user>" + + case ${CHOST} in + *-freebsd*|*-dragonfly*) + pos=8 + ;; + *) # Linux, NetBSD, OpenBSD, etc... + pos=5 + ;; + esac + + egetent passwd "$1" | cut -d: -f${pos} +} + +# @FUNCTION: egetgroups +# @USAGE: <user> +# @DESCRIPTION: +# Gets all the groups user belongs to. The primary group is returned +# first, then all supplementary groups. Groups are ','-separated. +egetgroups() { + [[ $# -eq 1 ]] || die "usage: egetgroups <user>" + + local egroups_arr + read -r -a egroups_arr < <(id -G -n "$1") + + local g groups=${egroups_arr[0]} + # sort supplementary groups to make comparison possible + while read -r g; do + [[ -n ${g} ]] && groups+=",${g}" + done < <(printf '%s\n' "${egroups_arr[@]:1}" | sort) + echo "${groups}" +} + +fi diff --git a/eclass/user.eclass b/eclass/user.eclass new file mode 100644 index 0000000..f8993b8 --- /dev/null +++ b/eclass/user.eclass @@ -0,0 +1,586 @@ +# Copyright 1999-2020 Gentoo Authors +# Distributed under the terms of the GNU General Public License v2 + +# @ECLASS: user.eclass +# @MAINTAINER: +# base-system@gentoo.org (Linux) +# Michał Górny <mgorny@gentoo.org> (NetBSD) +# @BLURB: user management in ebuilds +# @DEPRECATED: acct-user/acct-group packages +# @DESCRIPTION: +# The user eclass contains a suite of functions that allow ebuilds +# to quickly make sure users in the installed system are sane. + +if [[ -z ${_USER_ECLASS} ]]; then +_USER_ECLASS=1 + +case ${EAPI:-0} in + 0|1|2|3|4|5|6|7) ;; + *) + if [[ ${CATEGORY} != acct-* ]]; then + eerror "In EAPI ${EAPI}, packages must not inherit user.eclass" + eerror "unless they are in the acct-user or acct-group category." + eerror "Migrate your package to GLEP 81 user/group management," + eerror "or inherit user-info if you need only the query functions." + die "Invalid \"inherit user\" in EAPI ${EAPI}" + fi + ;; +esac + +inherit user-info + +# @FUNCTION: _assert_pkg_ebuild_phase +# @INTERNAL +# @USAGE: <calling func name> +_assert_pkg_ebuild_phase() { + case ${EBUILD_PHASE} in + setup|preinst|postinst|prerm|postrm) ;; + *) + eerror "'$1()' called from '${EBUILD_PHASE}' phase which is not OK:" + eerror "You may only call from pkg_{setup,{pre,post}{inst,rm}} functions." + eerror "Package fails at QA and at life. Please file a bug." + die "Bad package! $1 is only for use in some pkg_* functions!" + esac +} + +# @FUNCTION: user_get_nologin +# @INTERNAL +# @DESCRIPTION: +# Find an appropriate 'nologin' shell for the platform, and output +# its path. +user_get_nologin() { + local eshell + + for eshell in /sbin/nologin /usr/sbin/nologin /bin/false /usr/bin/false /dev/null ; do + [[ -x ${ROOT}${eshell} ]] && break + done + + if [[ ${eshell} == "/dev/null" ]] ; then + ewarn "Unable to identify the shell to use, proceeding with userland default." + case ${USERLAND} in + GNU) eshell="/bin/false" ;; + BSD) eshell="/sbin/nologin" ;; + Darwin) eshell="/usr/sbin/nologin" ;; + *) die "Unable to identify the default shell for userland ${USERLAND}" + esac + fi + + echo "${eshell}" +} + +# @FUNCTION: enewuser +# @USAGE: <user> [-F] [-M] [uid] [shell] [homedir] [groups] +# @DESCRIPTION: +# Same as enewgroup, you are not required to understand how to properly add +# a user to the system. The only required parameter is the username. +# Default uid is (pass -1 for this) next available, default shell is +# /bin/false, default homedir is /dev/null, and there are no default groups. +# +# If -F is passed, enewuser will always enforce specified UID and fail if it +# can not be assigned. +# If -M is passed, enewuser does not create the home directory if it does not +# exist. +enewuser() { + if [[ ${EUID} != 0 ]] ; then + ewarn "Insufficient privileges to execute ${FUNCNAME[0]}" + return 0 + fi + _assert_pkg_ebuild_phase ${FUNCNAME} + + local create_home=1 force_uid= + while [[ $1 == -* ]]; do + case $1 in + -F) force_uid=1;; + -M) create_home=;; + *) die "${FUNCNAME}: invalid option ${1}";; + esac + shift + done + + # get the username + local euser=$1; shift + if [[ -z ${euser} ]] ; then + eerror "No username specified !" + die "Cannot call enewuser without a username" + fi + + # lets see if the username already exists + if [[ -n $(egetent passwd "${euser}") ]] ; then + return 0 + fi + elog "Adding user '${euser}' to your system ..." + + # options to pass to useradd + local opts=() + + # handle uid + local euid=$1; shift + if [[ -n ${euid} && ${euid} != -1 ]] ; then + if [[ ${euid} -gt 0 ]] ; then + if [[ -n $(egetent passwd ${euid}) ]] ; then + [[ -n ${force_uid} ]] && die "${FUNCNAME}: UID ${euid} already taken" + euid="next" + fi + else + eerror "Userid given but is not greater than 0 !" + die "${euid} is not a valid UID" + fi + else + [[ -n ${force_uid} ]] && die "${FUNCNAME}: -F with uid==-1 makes no sense" + euid="next" + fi + if [[ ${euid} == "next" ]] ; then + for ((euid = 999; euid >= 101; euid--)); do + [[ -z $(egetent passwd ${euid}) ]] && break + done + [[ ${euid} -ge 101 ]] || die "${FUNCNAME}: no free UID found" + fi + opts+=( -u ${euid} ) + elog " - Userid: ${euid}" + + # handle shell + local eshell=$1; shift + if [[ ! -z ${eshell} ]] && [[ ${eshell} != "-1" ]] ; then + if [[ ! -e ${ROOT}${eshell} ]] ; then + eerror "A shell was specified but it does not exist !" + die "${eshell} does not exist in ${ROOT}" + fi + if [[ ${eshell} == */false || ${eshell} == */nologin ]] ; then + eerror "Do not specify ${eshell} yourself, use -1" + die "Pass '-1' as the shell parameter" + fi + else + eshell=$(user_get_nologin) + fi + elog " - Shell: ${eshell}" + opts+=( -s "${eshell}" ) + + # handle homedir + local ehome=$1; shift + if [[ -z ${ehome} ]] || [[ ${ehome} == "-1" ]] ; then + ehome="/dev/null" + fi + elog " - Home: ${ehome}" + opts+=( -d "${ehome}" ) + + # handle groups + local egroups=$1; shift + local g egroups_arr + IFS="," read -r -a egroups_arr <<<"${egroups}" + if [[ ${#egroups_arr[@]} -gt 0 ]] ; then + local defgroup exgroups + for g in "${egroups_arr[@]}" ; do + if [[ -z $(egetent group "${g}") ]] ; then + eerror "You must add group ${g} to the system first" + die "${g} is not a valid GID" + fi + if [[ -z ${defgroup} ]] ; then + defgroup=${g} + else + exgroups+=",${g}" + fi + done + opts+=( -g "${defgroup}" ) + if [[ ! -z ${exgroups} ]] ; then + opts+=( -G "${exgroups:1}" ) + fi + fi + elog " - Groups: ${egroups:-(none)}" + + # handle extra args + if [[ $# -gt 0 ]] ; then + die "extra arguments no longer supported; please file a bug" + else + local comment="added by portage for ${PN}" + opts+=( -c "${comment}" ) + elog " - GECOS: ${comment}" + fi + + # add the user + case ${CHOST} in + *-freebsd*|*-dragonfly*) + pw useradd "${euser}" "${opts[@]}" || die + ;; + + *-netbsd*) + useradd "${opts[@]}" "${euser}" || die + ;; + + *-openbsd*) + # all ops the same, except the -g vs -g/-G ... + useradd -u ${euid} -s "${eshell}" \ + -d "${ehome}" -g "${egroups}" "${euser}" || die + ;; + + *) + useradd -M -N -r "${opts[@]}" "${euser}" || die + ;; + esac + + if [[ -n ${create_home} && ! -e ${ROOT}/${ehome} ]] ; then + elog " - Creating ${ehome} in ${ROOT}" + mkdir -p "${ROOT}/${ehome}" + chown "${euser}" "${ROOT}/${ehome}" + chmod 755 "${ROOT}/${ehome}" + fi +} + +# @FUNCTION: enewgroup +# @USAGE: <group> [gid] +# @DESCRIPTION: +# This function does not require you to understand how to properly add a +# group to the system. Just give it a group name to add and enewgroup will +# do the rest. You may specify the gid for the group or allow the group to +# allocate the next available one. +# +# If -F is passed, enewgroup will always enforce specified GID and fail if it +# can not be assigned. +enewgroup() { + if [[ ${EUID} != 0 ]] ; then + ewarn "Insufficient privileges to execute ${FUNCNAME[0]}" + return 0 + fi + _assert_pkg_ebuild_phase ${FUNCNAME} + + local force_gid= + while [[ $1 == -* ]]; do + case $1 in + -F) force_gid=1;; + *) die "${FUNCNAME}: invalid option ${1}";; + esac + shift + done + + # get the group + local egroup=$1; shift + if [[ -z ${egroup} ]] ; then + eerror "No group specified !" + die "Cannot call enewgroup without a group" + fi + + # see if group already exists + if [[ -n $(egetent group "${egroup}") ]] ; then + return 0 + fi + elog "Adding group '${egroup}' to your system ..." + + # handle gid + local egid=$1; shift + if [[ -n ${egid} && ${egid} != -1 ]] ; then + if [[ ${egid} -gt 0 ]] ; then + if [[ -n $(egetent group ${egid}) ]] ; then + [[ -n ${force_gid} ]] && die "${FUNCNAME}: GID ${egid} already taken" + egid="next available; requested gid taken" + fi + else + eerror "Groupid given but is not greater than 0 !" + die "${egid} is not a valid GID" + fi + else + [[ -n ${force_gid} ]] && die "${FUNCNAME}: -F with gid==-1 makes no sense" + egid="next available" + fi + elog " - Groupid: ${egid}" + + # handle extra + if [[ $# -gt 0 ]] ; then + die "extra arguments no longer supported; please file a bug" + fi + + # Some targets need to find the next available GID manually + _enewgroup_next_gid() { + if [[ ${egid} == *[!0-9]* ]] ; then + # Non numeric + for ((egid = 999; egid >= 101; egid--)) ; do + [[ -z $(egetent group ${egid}) ]] && break + done + [[ ${egid} -ge 101 ]] || die "${FUNCNAME}: no free GID found" + fi + } + + # add the group + case ${CHOST} in + *-freebsd*|*-dragonfly*) + _enewgroup_next_gid + pw groupadd "${egroup}" -g ${egid} || die + ;; + + *-netbsd*) + _enewgroup_next_gid + groupadd -g ${egid} "${egroup}" || die + ;; + + *) + local opts + if [[ ${egid} == *[!0-9]* ]] ; then + # Non numeric; let groupadd figure out a GID for us + opts="" + else + opts="-g ${egid}" + fi + # We specify -r so that we get a GID in the system range from login.defs + groupadd -r ${opts} "${egroup}" || die + ;; + esac +} + +# @FUNCTION: esethome +# @USAGE: <user> <homedir> +# @DESCRIPTION: +# Update the home directory in a platform-agnostic way. +# Required parameters is the username and the new home directory. +# Specify -1 if you want to set home to the enewuser default +# of /dev/null. +# If the new home directory does not exist, it is created. +# Any previously existing home directory is NOT moved. +esethome() { + _assert_pkg_ebuild_phase ${FUNCNAME} + + # get the username + local euser=$1; shift + if [[ -z ${euser} ]] ; then + eerror "No username specified !" + die "Cannot call esethome without a username" + fi + + # lets see if the username already exists + if [[ -z $(egetent passwd "${euser}") ]] ; then + ewarn "User does not exist, cannot set home dir -- skipping." + return 1 + fi + + # handle homedir + local ehome=$1; shift + if [[ -z ${ehome} ]] ; then + eerror "No home directory specified !" + die "Cannot call esethome without a home directory or '-1'" + fi + + if [[ ${ehome} == "-1" ]] ; then + ehome="/dev/null" + fi + + # exit with no message if home dir is up to date + if [[ $(egethome "${euser}") == ${ehome} ]]; then + return 0 + fi + + elog "Updating home for user '${euser}' ..." + elog " - Home: ${ehome}" + + # ensure home directory exists, otherwise update will fail + if [[ ! -e ${ROOT}/${ehome} ]] ; then + elog " - Creating ${ehome} in ${ROOT}" + mkdir -p "${ROOT}/${ehome}" + chown "${euser}" "${ROOT}/${ehome}" + chmod 755 "${ROOT}/${ehome}" + fi + + # update the home directory + case ${CHOST} in + *-freebsd*|*-dragonfly*) + pw usermod "${euser}" -d "${ehome}" && return 0 + [[ $? == 8 ]] && eerror "${euser} is in use, cannot update home" + eerror "There was an error when attempting to update the home directory for ${euser}" + eerror "Please update it manually on your system:" + eerror "\t pw usermod \"${euser}\" -d \"${ehome}\"" + ;; + + *) + usermod -d "${ehome}" "${euser}" && return 0 + [[ $? == 8 ]] && eerror "${euser} is in use, cannot update home" + eerror "There was an error when attempting to update the home directory for ${euser}" + eerror "Please update it manually on your system (as root):" + eerror "\t usermod -d \"${ehome}\" \"${euser}\"" + ;; + esac +} + +# @FUNCTION: esetshell +# @USAGE: <user> <shell> +# @DESCRIPTION: +# Update the shell in a platform-agnostic way. +# Required parameters is the username and the new shell. +# Specify -1 if you want to set shell to platform-specific nologin. +esetshell() { + _assert_pkg_ebuild_phase ${FUNCNAME} + + # get the username + local euser=$1; shift + if [[ -z ${euser} ]] ; then + eerror "No username specified !" + die "Cannot call esetshell without a username" + fi + + # lets see if the username already exists + if [[ -z $(egetent passwd "${euser}") ]] ; then + ewarn "User does not exist, cannot set shell -- skipping." + return 1 + fi + + # handle shell + local eshell=$1; shift + if [[ -z ${eshell} ]] ; then + eerror "No shell specified !" + die "Cannot call esetshell without a shell or '-1'" + fi + + if [[ ${eshell} == "-1" ]] ; then + eshell=$(user_get_nologin) + fi + + # exit with no message if shell is up to date + if [[ $(egetshell "${euser}") == ${eshell} ]]; then + return 0 + fi + + elog "Updating shell for user '${euser}' ..." + elog " - Shell: ${eshell}" + + # update the shell + case ${CHOST} in + *-freebsd*|*-dragonfly*) + pw usermod "${euser}" -s "${eshell}" && return 0 + [[ $? == 8 ]] && eerror "${euser} is in use, cannot update shell" + eerror "There was an error when attempting to update the shell for ${euser}" + eerror "Please update it manually on your system:" + eerror "\t pw usermod \"${euser}\" -s \"${eshell}\"" + ;; + + *) + usermod -s "${eshell}" "${euser}" && return 0 + [[ $? == 8 ]] && eerror "${euser} is in use, cannot update shell" + eerror "There was an error when attempting to update the shell for ${euser}" + eerror "Please update it manually on your system (as root):" + eerror "\t usermod -s \"${eshell}\" \"${euser}\"" + ;; + esac +} + +# @FUNCTION: esetcomment +# @USAGE: <user> <comment> +# @DESCRIPTION: +# Update the comment field in a platform-agnostic way. +# Required parameters is the username and the new comment. +esetcomment() { + _assert_pkg_ebuild_phase ${FUNCNAME} + + # get the username + local euser=$1; shift + if [[ -z ${euser} ]] ; then + eerror "No username specified !" + die "Cannot call esetcomment without a username" + fi + + # lets see if the username already exists + if [[ -z $(egetent passwd "${euser}") ]] ; then + ewarn "User does not exist, cannot set comment -- skipping." + return 1 + fi + + # handle comment + local ecomment=$1; shift + if [[ -z ${ecomment} ]] ; then + eerror "No comment specified !" + die "Cannot call esetcomment without a comment" + fi + + # exit with no message if comment is up to date + if [[ $(egetcomment "${euser}") == ${ecomment} ]]; then + return 0 + fi + + elog "Updating comment for user '${euser}' ..." + elog " - Comment: ${ecomment}" + + # update the comment + case ${CHOST} in + *-freebsd*|*-dragonfly*) + pw usermod "${euser}" -c "${ecomment}" && return 0 + [[ $? == 8 ]] && eerror "${euser} is in use, cannot update comment" + eerror "There was an error when attempting to update the comment for ${euser}" + eerror "Please update it manually on your system:" + eerror "\t pw usermod \"${euser}\" -c \"${ecomment}\"" + ;; + + *) + usermod -c "${ecomment}" "${euser}" && return 0 + [[ $? == 8 ]] && eerror "${euser} is in use, cannot update comment" + eerror "There was an error when attempting to update the comment for ${euser}" + eerror "Please update it manually on your system (as root):" + eerror "\t usermod -c \"${ecomment}\" \"${euser}\"" + ;; + esac +} + +# @FUNCTION: esetgroups +# @USAGE: <user> <groups> +# @DESCRIPTION: +# Update the group field in a platform-agnostic way. +# Required parameters is the username and the new list of groups, +# primary group first. +esetgroups() { + _assert_pkg_ebuild_phase ${FUNCNAME} + + [[ ${#} -eq 2 ]] || die "Usage: ${FUNCNAME} <user> <groups>" + + # get the username + local euser=$1; shift + + # lets see if the username already exists + if [[ -z $(egetent passwd "${euser}") ]] ; then + ewarn "User does not exist, cannot set group -- skipping." + return 1 + fi + + # handle group + local egroups=$1; shift + + local g egroups_arr=() + IFS="," read -r -a egroups_arr <<<"${egroups}" + [[ ${#egroups_arr[@]} -gt 0 ]] || die "${FUNCNAME}: no groups specified" + + for g in "${egroups_arr[@]}" ; do + if [[ -z $(egetent group "${g}") ]] ; then + eerror "You must add group ${g} to the system first" + die "${g} is not a valid GID" + fi + done + + local defgroup=${egroups_arr[0]} exgroups_arr=() + # sort supplementary groups to make comparison possible + readarray -t exgroups_arr < <(printf '%s\n' "${egroups_arr[@]:1}" | sort) + local exgroups=${exgroups_arr[*]} + exgroups=${exgroups// /,} + egroups=${defgroup}${exgroups:+,${exgroups}} + + # exit with no message if group membership is up to date + if [[ $(egetgroups "${euser}") == ${egroups} ]]; then + return 0 + fi + + local opts=( -g "${defgroup}" -G "${exgroups}" ) + elog "Updating groups for user '${euser}' ..." + elog " - Groups: ${egroups}" + + # update the group + case ${CHOST} in + *-freebsd*|*-dragonfly*) + pw usermod "${euser}" "${opts[@]}" && return 0 + [[ $? == 8 ]] && eerror "${euser} is in use, cannot update groups" + eerror "There was an error when attempting to update the groups for ${euser}" + eerror "Please update it manually on your system:" + eerror "\t pw usermod \"${euser}\" ${opts[*]}" + ;; + + *) + usermod "${opts[@]}" "${euser}" && return 0 + [[ $? == 8 ]] && eerror "${euser} is in use, cannot update groups" + eerror "There was an error when attempting to update the groups for ${euser}" + eerror "Please update it manually on your system (as root):" + eerror "\t usermod ${opts[*]} \"${euser}\"" + ;; + esac +} + +fi diff --git a/eclass/usr-ldscript.eclass b/eclass/usr-ldscript.eclass new file mode 100644 index 0000000..4ee129b --- /dev/null +++ b/eclass/usr-ldscript.eclass @@ -0,0 +1,164 @@ +# Copyright 2019 Gentoo Authors +# Distributed under the terms of the GNU General Public License v2 + +# @ECLASS: usr-ldscript.eclass +# @MAINTAINER: +# Toolchain Ninjas <toolchain@gentoo.org> +# @SUPPORTED_EAPIS: 4 5 6 7 +# @BLURB: Defines the gen_usr_ldscript function. + +if [[ -z ${_USR_LDSCRIPT_ECLASS} ]]; then +_USR_LDSCRIPT_ECLASS=1 + +case ${EAPI:-0} in + 4|5|6|7) ;; + *) die "EAPI=${EAPI} is not supported" ;; +esac + +inherit multilib toolchain-funcs + +IUSE="split-usr" + +# @FUNCTION: gen_usr_ldscript +# @USAGE: [-a] <list of libs to create linker scripts for> +# @DESCRIPTION: +# This function generate linker scripts in /usr/lib for dynamic +# libs in /lib. This is to fix linking problems when you have +# the .so in /lib, and the .a in /usr/lib. What happens is that +# in some cases when linking dynamic, the .a in /usr/lib is used +# instead of the .so in /lib due to gcc/libtool tweaking ld's +# library search path. This causes many builds to fail. +# See bug #4411 for more info. +# +# Note that you should in general use the unversioned name of +# the library (libfoo.so), as ldconfig should usually update it +# correctly to point to the latest version of the library present. +gen_usr_ldscript() { + local lib libdir=$(get_libdir) output_format="" auto=false suffix=$(get_libname) + + tc-is-static-only && return + use prefix && return + + # We only care about stuffing / for the native ABI. #479448 + if [[ $(type -t multilib_is_native_abi) == "function" ]] ; then + multilib_is_native_abi || return 0 + fi + + # Eventually we'd like to get rid of this func completely #417451 + case ${CTARGET:-${CHOST}} in + *-darwin*) ;; + *-android*) return 0 ;; + *linux*|*-freebsd*|*-openbsd*|*-netbsd*) + use prefix && return 0 + use split-usr || return 0 + ;; + *) return 0 ;; + esac + + # Just make sure it exists + dodir /usr/${libdir} + + if [[ $1 == "-a" ]] ; then + auto=true + shift + dodir /${libdir} + fi + + # OUTPUT_FORMAT gives hints to the linker as to what binary format + # is referenced ... makes multilib saner + local flags=( ${CFLAGS} ${LDFLAGS} -Wl,--verbose ) + if $(tc-getLD) --version | grep -q 'GNU gold' ; then + # If they're using gold, manually invoke the old bfd. #487696 + local d="${T}/bfd-linker" + mkdir -p "${d}" + ln -sf $(which ${CHOST}-ld.bfd) "${d}"/ld + flags+=( -B"${d}" ) + fi + output_format=$($(tc-getCC) "${flags[@]}" 2>&1 | sed -n 's/^OUTPUT_FORMAT("\([^"]*\)",.*/\1/p') + [[ -n ${output_format} ]] && output_format="OUTPUT_FORMAT ( ${output_format} )" + + for lib in "$@" ; do + local tlib + if ${auto} ; then + lib="lib${lib}${suffix}" + else + # Ensure /lib/${lib} exists to avoid dangling scripts/symlinks. + # This especially is for AIX where $(get_libname) can return ".a", + # so /lib/${lib} might be moved to /usr/lib/${lib} (by accident). + [[ -r ${ED%/}/${libdir}/${lib} ]] || continue + #TODO: better die here? + fi + + case ${CTARGET:-${CHOST}} in + *-darwin*) + if ${auto} ; then + tlib=$(scanmacho -qF'%S#F' "${ED%/}"/usr/${libdir}/${lib}) + else + tlib=$(scanmacho -qF'%S#F' "${ED%/}"/${libdir}/${lib}) + fi + [[ -z ${tlib} ]] && die "unable to read install_name from ${lib}" + tlib=${tlib##*/} + + if ${auto} ; then + mv "${ED%/}"/usr/${libdir}/${lib%${suffix}}.*${suffix#.} "${ED%/}"/${libdir}/ || die + # some install_names are funky: they encode a version + if [[ ${tlib} != ${lib%${suffix}}.*${suffix#.} ]] ; then + mv "${ED%/}"/usr/${libdir}/${tlib%${suffix}}.*${suffix#.} "${ED%/}"/${libdir}/ || die + fi + rm -f "${ED%/}"/${libdir}/${lib} + fi + + # Mach-O files have an id, which is like a soname, it tells how + # another object linking against this lib should reference it. + # Since we moved the lib from usr/lib into lib this reference is + # wrong. Hence, we update it here. We don't configure with + # libdir=/lib because that messes up libtool files. + # Make sure we don't lose the specific version, so just modify the + # existing install_name + if [[ ! -w "${ED%/}/${libdir}/${tlib}" ]] ; then + chmod u+w "${ED%/}/${libdir}/${tlib}" # needed to write to it + local nowrite=yes + fi + install_name_tool \ + -id "${EPREFIX}"/${libdir}/${tlib} \ + "${ED%/}"/${libdir}/${tlib} || die "install_name_tool failed" + [[ -n ${nowrite} ]] && chmod u-w "${ED%/}/${libdir}/${tlib}" + # Now as we don't use GNU binutils and our linker doesn't + # understand linker scripts, just create a symlink. + pushd "${ED%/}/usr/${libdir}" > /dev/null + ln -snf "../../${libdir}/${tlib}" "${lib}" + popd > /dev/null + ;; + *) + if ${auto} ; then + tlib=$(scanelf -qF'%S#F' "${ED%/}"/usr/${libdir}/${lib}) + [[ -z ${tlib} ]] && die "unable to read SONAME from ${lib}" + mv "${ED%/}"/usr/${libdir}/${lib}* "${ED%/}"/${libdir}/ || die + # some SONAMEs are funky: they encode a version before the .so + if [[ ${tlib} != ${lib}* ]] ; then + mv "${ED%/}"/usr/${libdir}/${tlib}* "${ED%/}"/${libdir}/ || die + fi + rm -f "${ED%/}"/${libdir}/${lib} + else + tlib=${lib} + fi + cat > "${ED%/}/usr/${libdir}/${lib}" <<-END_LDSCRIPT + /* GNU ld script + Since Gentoo has critical dynamic libraries in /lib, and the static versions + in /usr/lib, we need to have a "fake" dynamic lib in /usr/lib, otherwise we + run into linking problems. This "fake" dynamic lib is a linker script that + redirects the linker to the real lib. And yes, this works in the cross- + compiling scenario as the sysroot-ed linker will prepend the real path. + + See bug https://bugs.gentoo.org/4411 for more info. + */ + ${output_format} + GROUP ( ${EPREFIX}/${libdir}/${tlib} ) + END_LDSCRIPT + ;; + esac + fperms a+x "/usr/${libdir}/${lib}" || die "could not change perms on ${lib}" + done +} + +fi # _USR_LDSCRIPT_ECLASS diff --git a/eclass/vala.eclass b/eclass/vala.eclass new file mode 100644 index 0000000..88c5231 --- /dev/null +++ b/eclass/vala.eclass @@ -0,0 +1,172 @@ +# Copyright 1999-2020 Gentoo Authors +# Distributed under the terms of the GNU General Public License v2 + +# @ECLASS: vala.eclass +# @MAINTAINER: +# gnome@gentoo.org +# @AUTHOR: +# Alexandre Rostovtsev <tetromino@gentoo.org> +# @SUPPORTED_EAPIS: 1 2 3 4 5 6 7 +# @BLURB: Sets up the environment for using a specific version of vala. +# @DESCRIPTION: +# This eclass sets up commonly used environment variables for using a specific +# version of dev-lang/vala to configure and build a package. It is needed for +# packages whose build systems assume the existence of certain unversioned vala +# executables, pkgconfig files, etc., which Gentoo does not provide. +# +# This eclass provides one phase function: src_prepare. + +inherit eutils multilib + +case "${EAPI:-0}" in + 0) die "EAPI=0 is not supported" ;; + 1) ;; + *) EXPORT_FUNCTIONS src_prepare ;; +esac + +# @ECLASS-VARIABLE: VALA_MIN_API_VERSION +# @DESCRIPTION: +# Minimum vala API version (e.g. 0.36). +VALA_MIN_API_VERSION=${VALA_MIN_API_VERSION:-0.36} + +# @ECLASS-VARIABLE: VALA_MAX_API_VERSION +# @DESCRIPTION: +# Maximum vala API version (e.g. 0.36). +VALA_MAX_API_VERSION=${VALA_MAX_API_VERSION:-0.50} + +# @ECLASS-VARIABLE: VALA_USE_DEPEND +# @DEFAULT_UNSET +# @DESCRIPTION: +# USE dependencies that vala must be built with (e.g. vapigen). + +# @FUNCTION: vala_api_versions +# @DESCRIPTION: +# Outputs a list of vala API versions from VALA_MAX_API_VERSION down to +# VALA_MIN_API_VERSION. +vala_api_versions() { + [[ ${VALA_MIN_API_VERSION} =~ ^0\.[[:digit:]]+$ ]] || die "Invalid syntax of VALA_MIN_API_VERSION" + [[ ${VALA_MAX_API_VERSION} =~ ^0\.[[:digit:]]+$ ]] || die "Invalid syntax of VALA_MAX_API_VERSION" + + local minimal_supported_minor_version minor_version + + # Dependency atoms are not generated for Vala versions older than 0.${minimal_supported_minor_version}. + minimal_supported_minor_version="36" + + for ((minor_version = ${VALA_MAX_API_VERSION#*.}; minor_version >= ${VALA_MIN_API_VERSION#*.}; minor_version = minor_version - 2)); do + # 0.38 was never in main tree; remove the special case once minimal_supported_minor_version >= 40 + # 0.42 is EOL and removed from tree; remove special case once minimal_support_minor_version >= 44 + if ((minor_version >= minimal_supported_minor_version)) && ((minor_version != 38)) && ((minor_version != 42)); then + echo "0.${minor_version}" + fi + done +} + +# Outputs VALA_USE_DEPEND as a a USE-dependency string +_vala_use_depend() { + local u="" vala_use + + if [[ -n ${VALA_USE_DEPEND} ]]; then + for vala_use in ${VALA_USE_DEPEND}; do + case ${vala_use} in + vapigen) u="${u},${vala_use}(+)" ;; + valadoc) u="${u},${vala_use}(-)" ;; + esac + done + u="[${u#,}]" + fi + + echo -n "${u}" +} + +# @FUNCTION: vala_depend +# @DESCRIPTION: +# Outputs a ||-dependency string on vala from VALA_MAX_API_VERSION down to +# VALA_MIN_API_VERSION +vala_depend() { + local u v + u=$(_vala_use_depend) + + echo -n "|| (" + for v in $(vala_api_versions); do + echo -n " dev-lang/vala:${v}${u}" + done + echo " )" +} + +# @FUNCTION: vala_best_api_version +# @DESCRIPTION: +# Returns the highest installed vala API version satisfying +# VALA_MAX_API_VERSION, VALA_MIN_API_VERSION, and VALA_USE_DEPEND. +vala_best_api_version() { + local u v + u=$(_vala_use_depend) + + for v in $(vala_api_versions); do + has_version $([[ $EAPI == [1-6] ]] || echo -b) "dev-lang/vala:${v}${u}" && echo "${v}" && return + done +} + +# @FUNCTION: vala_src_prepare +# @USAGE: [--ignore-use] [--vala-api-version api_version] +# @DESCRIPTION: +# Sets up the environment variables and pkgconfig files for the +# specified API version, or, if no version is specified, for the +# highest installed vala API version satisfying +# VALA_MAX_API_VERSION, VALA_MIN_API_VERSION, and VALA_USE_DEPEND. +# Is a no-op if called without --ignore-use when USE=-vala. +# Dies if the USE check is passed (or ignored) and a suitable vala +# version is not available. +vala_src_prepare() { + local p d valafoo version ignore_use + + while [[ $1 ]]; do + case $1 in + "--ignore-use" ) + ignore_use=1 ;; + "--vala-api-version" ) + shift + version=$1 + [[ ${version} ]] || die "'--vala-api-version' option requires API version parameter." + esac + shift + done + + if [[ -z ${ignore_use} ]]; then + in_iuse vala && ! use vala && return 0 + fi + + if [[ ${version} ]]; then + has_version $([[ $EAPI == [1-6] ]] || echo -b) "dev-lang/vala:${version}" || die "No installed vala:${version}" + else + version=$(vala_best_api_version) + [[ ${version} ]] || die "No installed vala in $(vala_depend)" + fi + + export VALAC=$(type -P valac-${version}) + + valafoo=$(type -P vala-gen-introspect-${version}) + [[ ${valafoo} ]] && export VALA_GEN_INTROSPECT="${valafoo}" + + valafoo=$(type -P vapigen-${version}) + [[ ${valafoo} ]] && export VAPIGEN="${valafoo}" + + valafoo=$(type -P valadoc-${version}) + [[ ${valafoo} ]] && has valadoc ${VALA_USE_DEPEND} && export VALADOC="${valafoo}" + + valafoo="${EPREFIX}/usr/share/vala/Makefile.vapigen" + [[ -e ${valafoo} ]] && export VAPIGEN_MAKEFILE="${valafoo}" + + export VAPIGEN_VAPIDIR="${EPREFIX}/usr/share/vala/vapi" + + mkdir -p "${T}/pkgconfig" || die "mkdir failed" + for p in libvala vapigen; do + for d in "${EPREFIX}/usr/$(get_libdir)/pkgconfig" "${EPREFIX}/usr/share/pkgconfig"; do + if [[ -e ${d}/${p}-${version}.pc ]]; then + ln -s "${d}/${p}-${version}.pc" "${T}/pkgconfig/${p}.pc" || die "ln failed" + break + fi + done + done + : ${PKG_CONFIG_PATH:="${EPREFIX}/usr/$(get_libdir)/pkgconfig:${EPREFIX}/usr/share/pkgconfig"} + export PKG_CONFIG_PATH="${T}/pkgconfig:${PKG_CONFIG_PATH}" +} diff --git a/eclass/vcs-clean.eclass b/eclass/vcs-clean.eclass new file mode 100644 index 0000000..649a9e3 --- /dev/null +++ b/eclass/vcs-clean.eclass @@ -0,0 +1,40 @@ +# Copyright 1999-2018 Gentoo Foundation +# Distributed under the terms of the GNU General Public License v2 + +# @ECLASS: vcs-clean.eclass +# @MAINTAINER: +# base-system@gentoo.org +# @AUTHOR: +# Benedikt Böhm <hollow@gentoo.org> +# @BLURB: helper functions to remove VCS directories + +# @FUNCTION: ecvs_clean +# @USAGE: [list of dirs] +# @DESCRIPTION: +# Remove CVS directories and .cvs* files recursively. Useful when a +# source tarball contains internal CVS directories. Defaults to ${PWD}. +ecvs_clean() { + [[ $# -eq 0 ]] && set -- . + find "$@" '(' -type d -name 'CVS' -prune -o -type f -name '.cvs*' ')' \ + -exec rm -rf '{}' + +} + +# @FUNCTION: esvn_clean +# @USAGE: [list of dirs] +# @DESCRIPTION: +# Remove .svn directories recursively. Useful when a source tarball +# contains internal Subversion directories. Defaults to ${PWD}. +esvn_clean() { + [[ $# -eq 0 ]] && set -- . + find "$@" -type d -name '.svn' -prune -exec rm -rf '{}' + +} + +# @FUNCTION: egit_clean +# @USAGE: [list of dirs] +# @DESCRIPTION: +# Remove .git* directories recursively. Useful when a source tarball +# contains internal Git directories. Defaults to ${PWD}. +egit_clean() { + [[ $# -eq 0 ]] && set -- . + find "$@" -type d -name '.git*' -prune -exec rm -rf '{}' + +} diff --git a/eclass/vcs-snapshot.eclass b/eclass/vcs-snapshot.eclass new file mode 100644 index 0000000..05d9639 --- /dev/null +++ b/eclass/vcs-snapshot.eclass @@ -0,0 +1,112 @@ +# Copyright 1999-2019 Gentoo Authors +# Distributed under the terms of the GNU General Public License v2 + +# @ECLASS: vcs-snapshot.eclass +# @MAINTAINER: +# mgorny@gentoo.org +# @SUPPORTED_EAPIS: 0 1 2 3 4 5 6 7 +# @BLURB: support eclass for unpacking VCS snapshot tarballs +# @DESCRIPTION: +# THIS ECLASS IS NOT NECESSARY FOR MODERN GITHUB AND GITLAB SNAPSHOTS. +# THEIR DIRECTORY STRUCTURE IS ENTIRELY PREDICTABLE, SO UPDATE YOUR +# EBUILD TO USE /ARCHIVE/ URI AND SET S IF NECESSARY. +# +# This eclass provides a convenience src_unpack() which does unpack all +# the tarballs in SRC_URI to locations matching their (local) names, +# discarding the original parent directory. +# +# The typical use case are VCS tag snapshots coming from BitBucket +# (but not GitHub or GitLab). They have hash appended to the directory +# name which makes extracting them a painful experience. But if you are +# using a SRC_URI arrow to rename them (which quite likely you have to +# do anyway), vcs-snapshot will just extract them into matching +# directories. +# +# Please note that this eclass handles only tarballs (.tar, .tar.gz, +# .tar.bz2 & .tar.xz). For any other file format (or suffix) it will +# fall back to regular unpack. Support for additional formats may be +# added in the future if necessary. +# +# @EXAMPLE: +# +# @CODE +# EAPI=7 +# inherit vcs-snapshot +# +# SRC_URI=" +# https://bitbucket.org/foo/bar/get/${PV}.tar.bz2 -> ${P}.tar.bz2 +# https://bitbucket.org/foo/bar-otherstuff/get/${PV}.tar.bz2 +# -> ${P}-otherstuff.tar.bz2" +# @CODE +# +# and however the tarballs were originally packed, all files will appear +# in ${WORKDIR}/${P} and ${WORKDIR}/${P}-otherstuff respectively. + +case ${EAPI:-0} in + 0|1|2|3|4|5|6|7) ;; + *) die "vcs-snapshot.eclass API in EAPI ${EAPI} not yet established." +esac + +EXPORT_FUNCTIONS src_unpack + +# @FUNCTION: vcs-snapshot_src_unpack +# @DESCRIPTION: +# Extract all the archives from ${A}. The .tar, .tar.gz, .tar.bz2 +# and .tar.xz archives will be unpacked to directories matching their +# local names. Other archive types will be passed down to regular +# unpack. +vcs-snapshot_src_unpack() { + debug-print-function ${FUNCNAME} "${@}" + + local renamed_any= + local f + + for f in ${A} + do + case "${f}" in + *.tar|*.tar.gz|*.tar.bz2|*.tar.xz) + local destdir=${WORKDIR}/${f%.tar*} + + debug-print "${FUNCNAME}: unpacking ${f} to ${destdir}" + + local l topdirs=() + while read -r l; do + topdirs+=( "${l}" ) + done < <(tar -t -f "${DISTDIR}/${f}" | cut -d/ -f1 | sort -u) + if [[ ${#topdirs[@]} -gt 1 ]]; then + eerror "The archive ${f} contains multiple or no top directory." + eerror "It is impossible for vcs-snapshot to unpack this correctly." + eerror "Top directories found:" + local d + for d in "${topdirs[@]}"; do + eerror " ${d}" + done + die "${FUNCNAME}: Invalid directory structure in archive ${f}" + fi + [[ ${topdirs[0]} != ${f%.tar*} ]] && renamed_any=1 + + mkdir "${destdir}" || die + # -o (--no-same-owner) to avoid restoring original owner + einfo "Unpacking ${f}" + tar -C "${destdir}" -x -o --strip-components 1 \ + -f "${DISTDIR}/${f}" || die + ;; + *) + debug-print "${FUNCNAME}: falling back to unpack for ${f}" + + # fall back to the default method + unpack "${f}" + ;; + esac + done + + if [[ ! ${renamed_any} ]]; then + local w=eerror + [[ ${EAPI} == [0123456] ]] && w=eqawarn + "${w}" "${FUNCNAME} did not find any archives that needed renaming." + "${w}" "Please verify that its usage is really necessary, and remove" + "${w}" "the inherit if it is not." + + [[ ${w} == eerror ]] && die "${FUNCNAME}: Unnecessary usage detected" + fi +} diff --git a/eclass/vdr-plugin-2.eclass b/eclass/vdr-plugin-2.eclass new file mode 100644 index 0000000..ebd1e39 --- /dev/null +++ b/eclass/vdr-plugin-2.eclass @@ -0,0 +1,614 @@ +# Copyright 1999-2020 Gentoo Authors +# Distributed under the terms of the GNU General Public License v2 + +# @ECLASS: vdr-plugin-2.eclass +# @MAINTAINER: +# Gentoo VDR Project <vdr@gentoo.org> +# @AUTHOR: +# Matthias Schwarzott <zzam@gentoo.org> +# Joerg Bornkessel <hd_brummy@gentoo.org> +# Christian Ruppert <idl0r@gentoo.org> +# (undisclosed contributors) +# @SUPPORTED_EAPIS: 5 6 7 +# @BLURB: common vdr plugin ebuild functions +# @DESCRIPTION: +# Eclass for easing maintenance of vdr plugin ebuilds + +# @ECLASS-VARIABLE: VDR_CONFD_FILE +# @DEFAULT_UNSET +# @DESCRIPTION: +# A plugin config file can be specified through the $VDR_CONFD_FILE variable, it +# defaults to ${FILESDIR}/confd. Each config file will be installed as e.g. +# ${D}/etc/conf.d/vdr.${VDRPLUGIN} + +# @ECLASS-VARIABLE: VDR_RCADDON_FILE +# @DEFAULT_UNSET +# @DESCRIPTION: +# Installing rc-addon files is basically the same as for plugin config files +# (see above), it's just using the $VDR_RCADDON_FILE variable instead. +# The default value when $VDR_RCADDON_FILE is undefined is: +# ${FILESDIR}/rc-addon.sh and will be installed as +# ${VDR_RC_DIR}/plugin-${VDRPLUGIN}.sh +# +# The rc-addon files will be sourced by the startscript when the specific plugin +# has been enabled. +# rc-addon files may be used to prepare everything that is necessary for the +# plugin start/stop, like passing extra command line options and so on. +# +# NOTE: rc-addon files must be valid shell scripts! + +# @ECLASS-VARIABLE: GENTOO_VDR_CONDITIONAL +# @DEFAULT_UNSET +# @DESCRIPTION: +# This is a hack for ebuilds like vdr-xineliboutput that want to +# conditionally install a vdr-plugin + +# @ECLASS-VARIABLE: PO_SUBDIR +# @DEFAULT_UNSET +# @DESCRIPTION: +# By default, translation are found in"${S}"/po but this +# default can be overridden by defining PO_SUBDIR. +# +# Example: +# @CODE +# PO_SUBDIR="bla foo/bla" +# @CODE + +# @FUNCTION: fix_vdr_libsi_include +# @DESCRIPTION: +# Plugins failed on compile with wrong path of libsi includes, +# this can be fixed by 'function + space separated list of files' +# +# Example: +# @CODE +# fix_vdr_libsi_include bla.c foo.c +# @CODE + +# @FUNCTION: vdr_remove_i18n_include +# @DESCRIPTION: +# Compile will fail if plugin still use the old i18n language handling, +# most parts are fixed by vdr-plugin-2.eclass internal functions itself. +# Remove unneeded i18.n includes from files, if they are still wrong there, +# this can be fixed by 'function + space separated list of files" +# +# Example: +# @CODE +# vdr_remove_i18n_include bla.n foo.n +# @CODE + +# Applying your own local/user patches: +# This is done by using the +# (EAPI = 5) epatch_user() function of the eutils.eclass, +# (EAPI = 6,7) eapply_user function integrated in EAPI = 6. +# Simply add your patches into one of these directories: +# /etc/portage/patches/<CATEGORY>/<PF|P|PN>/ +# Quote: where the first of these three directories to exist will be the one to +# use, ignoring any more general directories which might exist as well. +# +# For more details about it please take a look at the eutils.class. + +[[ ${EAPI} == [5] ]] && inherit multilib +[[ ${EAPI} == [56] ]] && inherit eutils +inherit flag-o-matic toolchain-funcs unpacker + +case ${EAPI:-0} in + 5|6|7) + ;; + *) die "EAPI ${EAPI} unsupported." + ;; +esac + +EXPORT_FUNCTIONS pkg_setup src_unpack src_prepare src_compile src_install pkg_postinst pkg_postrm pkg_config + +IUSE="" + +# Name of the plugin stripped from all vdrplugin-, vdr- and -cvs pre- and postfixes +VDRPLUGIN="${PN/#vdrplugin-/}" +VDRPLUGIN="${VDRPLUGIN/#vdr-/}" +VDRPLUGIN="${VDRPLUGIN/%-cvs/}" + +DESCRIPTION="vdr Plugin: ${VDRPLUGIN} (based on vdr-plugin-2.eclass)" + +# Works in most cases +S="${WORKDIR}/${VDRPLUGIN}-${PV}" + +# depend on headers for DVB-driver +COMMON_DEPEND=">=media-tv/gentoo-vdr-scripts-0.4.2" + +DEPEND="${COMMON_DEPEND} + virtual/linuxtv-dvb-headers" +RDEPEND="${COMMON_DEPEND} + >=app-eselect/eselect-vdr-0.0.2" + +if [[ "${GENTOO_VDR_CONDITIONAL:-no}" = "yes" ]]; then + IUSE="${IUSE} vdr" + DEPEND="vdr? ( ${DEPEND} )" + RDEPEND="vdr? ( ${RDEPEND} )" +fi + +# New method of storing plugindb +# Called from src_install +# file maintained by normal portage-methods +vdr_create_plugindb_file() { + local NEW_VDRPLUGINDB_DIR=/usr/share/vdr/vdrplugin-rebuild/ + local DB_FILE="${NEW_VDRPLUGINDB_DIR}/${CATEGORY}-${PF}" + insinto "${NEW_VDRPLUGINDB_DIR}" + +# BUG: portage-2.1.4_rc9 will delete the EBUILD= line, so we cannot use this code. +# cat <<-EOT > "${D}/${DB_FILE}" +# VDRPLUGIN_DB=1 +# CREATOR=ECLASS +# EBUILD=${CATEGORY}/${PN} +# EBUILD_V=${PVR} +# EOT +# obsolet? fix me later... + { + echo "VDRPLUGIN_DB=1" + echo "CREATOR=ECLASS" + echo "EBUILD=${CATEGORY}/${PN}" + echo "EBUILD_V=${PVR}" + echo "PLUGINS=\"$@\"" + } > "${D%/}/${DB_FILE}" +} + +vdr_create_header_checksum_file() { + # Danger: Not using $ROOT here, as compile will also not use it !!! + # If vdr in $ROOT and / differ, plugins will not run anyway + + local CHKSUM="header-md5-vdr" + + if [[ -f ${VDR_CHECKSUM_DIR}/header-md5-vdr ]]; then + cp "${VDR_CHECKSUM_DIR}/header-md5-vdr" "${CHKSUM}" + elif type -p md5sum >/dev/null 2>&1; then + ( + cd "${VDR_INCLUDE_DIR}" + md5sum *.h libsi/*.h|LC_ALL=C sort --key=2 + ) > "${CHKSUM}" + else + die "Could not create md5 checksum of headers" + fi + + insinto "${VDR_CHECKSUM_DIR}" + local p_name + for p_name; do + newins "${CHKSUM}" "header-md5-${p_name}" + done +} + +fix_vdr_libsi_include() { + eqawarn "Fixing include of libsi-headers" + local f + for f; do + sed -i "${f}" \ + -e '/#include/s:"\(.*libsi.*\)":<\1>:' \ + -e '/#include/s:<.*\(libsi/.*\)>:<vdr/\1>:' + done +} + +vdr_patchmakefile() { + einfo "Patching Makefile" + [[ -e Makefile ]] || die "Makefile of plugin can not be found!" + cp Makefile "${WORKDIR}"/Makefile.before + + # plugin makefiles use VDRDIR in strange ways + # assumptions: + # 1. $(VDRDIR) contains Make.config + # 2. $(VDRDIR) contains config.h + # 3. $(VDRDIR)/include/vdr contains the headers + # 4. $(VDRDIR) contains main vdr Makefile + # 5. $(VDRDIR)/locale exists + # 6. $(VDRDIR) allows to access vdr source files + # + # We only have one directory (for now /usr/include/vdr), + # that contains vdr-headers and Make.config. + # To satisfy 1-3 we do this: + # Set VDRDIR=/usr/include/vdr + # Set VDRINCDIR=/usr/include + # Change $(VDRDIR)/include to $(VDRINCDIR) + + sed -i Makefile \ + -e "s:^VDRDIR.*$:VDRDIR = ${VDR_INCLUDE_DIR}:" \ + -e "/^VDRDIR/a VDRINCDIR = ${VDR_INCLUDE_DIR%/vdr}" \ + -e '/VDRINCDIR.*=/!s:$(VDRDIR)/include:$(VDRINCDIR):' \ + \ + -e 's:-I$(DVBDIR)/include::' \ + -e 's:-I$(DVBDIR)::' + + if ! grep -q APIVERSION Makefile; then + ebegin " Converting to APIVERSION" + sed -i Makefile \ + -e 's:^APIVERSION = :APIVERSION ?= :' \ + -e 's:$(LIBDIR)/$@.$(VDRVERSION):$(LIBDIR)/$@.$(APIVERSION):' \ + -e '/VDRVERSION =/a\APIVERSION = $(shell sed -ne '"'"'/define APIVERSION/s/^.*"\\(.*\\)".*$$/\\1/p'"'"' $(VDRDIR)/config.h)' + eend $? + fi + + # Correcting Compile-Flags + # Do not overwrite CXXFLAGS, add LDFLAGS if missing + sed -i Makefile \ + -e '/^CXXFLAGS[[:space:]]*=/s/=/?=/' \ + -e '/LDFLAGS/!s:-shared:$(LDFLAGS) -shared:' + + # Disabling file stripping, the package manager takes care of it + sed -i Makefile \ + -e '/@.*strip/d' \ + -e '/strip \$(LIBDIR)\/\$@/d' \ + -e 's/STRIP.*=.*$/STRIP = true/' + + # Use a file instead of a variable as single-stepping via ebuild + # destroys environment. + touch "${WORKDIR}"/.vdr-plugin_makefile_patched +} + +vdr_gettext_missing() { + # plugins without converting to gettext + + local GETTEXT_MISSING=$( grep xgettext Makefile ) + if [[ -z ${GETTEXT_MISSING} ]]; then + eqawarn "Plugin isn't converted to gettext handling!" + fi +} + +vdr_detect_po_dir() { +# helper function to find the +# DIR ${S}/po or DIR ${S]/_subdir_/po + + [[ -f po ]] && local po_dir="${S}" + local po_subdir=( ${S}/${PO_SUBDIR} ) + local f + + pofile_dir=( ${po_dir} ${po_subdir[*]} ) +} + +vdr_linguas_support() { +# Patching Makefile for linguas support. +# Only locales, enabled through the LINGUAS (make.conf) variable will be +# compiled and installed. + + einfo "Patching for Linguas support" + einfo "available Languages for ${P} are:" + + vdr_detect_po_dir + + for f in ${pofile_dir[*]}; do + if [[ -d ${f}/po ]]; then + PLUGIN_LINGUAS=$( ls ${f}/po --ignore="*.pot" | sed -e "s:.po::g" | cut -d_ -f1 | tr \\\012 ' ' ) + fi + einfo "LINGUAS=\"${PLUGIN_LINGUAS}\"" + + sed -i ${f}/Makefile \ + -e 's:\$(wildcard[[:space:]]*\$(PODIR)/\*.po):\$(foreach dir,\$(LINGUAS),\$(wildcard \$(PODIR)\/\$(dir)\*.po)):' \ + || die "sed failed for Linguas" + done + + strip-linguas ${PLUGIN_LINGUAS} en +} + +vdr_i18n() { +# i18n handling was deprecated since >=media-video/vdr-1.5.9, +# finally with >=media-video/vdr-1.7.27 it has been dropped entirely and some +# plugins will fail to compile because they're still using the old variant. +# Simply remove the i18n.o object from Makefile (OBJECT) and +# remove "static const tI18nPhrase*" from i18n.h. + + vdr_gettext_missing + + local I18N_OBJECT=$( grep i18n.o Makefile ) + if [[ -n ${I18N_OBJECT} ]]; then + + if [[ "${KEEP_I18NOBJECT:-no}" = "yes" ]]; then + eqawarn "Forced to keep i18n.o" + else + sed -i "s:i18n.o::g" Makefile + eqawarn "OBJECT i18n.o found, removed per sed" + fi + fi + + local I18N_STRING=$( [[ -e i18n.h ]] && grep tI18nPhrase i18n.h ) + if [[ -n ${I18N_STRING} ]]; then + sed -i "s:^extern[[:space:]]*const[[:space:]]*tI18nPhrase://static const tI18nPhrase:" i18n.h + eqawarn "obsolete tI18nPhrase found, disabled per sed, please recheck" + fi +} + +vdr_remove_i18n_include() { + # remove uneeded i18.n includes + + local f + for f; do + sed -i "${f}" \ + -e "s:^#include[[:space:]]*\"i18n.h\"://:" + done + + eqawarn "removed i18n.h include in ${@}" +} + +vdr-plugin-2_print_enable_command() { + local p_name c=0 l="" + for p_name in ${vdr_plugin_list}; do + c=$(( c+1 )) + l="$l ${p_name#vdr-}" + done + + elog + case $c in + 1) elog "Installed plugin${l}" ;; + *) elog "Installed $c plugins:${l}" ;; + esac + elog "To activate a plugin execute this command:" + elog "\teselect vdr-plugin enable <plugin_name> ..." + elog +} + +has_vdr() { + [[ -f "${VDR_INCLUDE_DIR}"/config.h ]] +} + +## exported functions + +vdr-plugin-2_pkg_setup() { + # missing ${chost}- tag + tc-export CC CXX + + # -fPIC is needed for shared objects on some platforms (amd64 and others) + append-flags -fPIC + + # Plugins need to be compiled with position independent code, otherwise linking + # VDR against it will fail + append-cxxflags -D_FILE_OFFSET_BITS=64 -D_LARGEFILE_SOURCE -D_LARGEFILE64_SOURCE + + # Where should the plugins live in the filesystem + VDR_PLUGIN_DIR=$(pkg-config --variable=libdir vdr) + + VDR_CHECKSUM_DIR="${VDR_PLUGIN_DIR%/plugins}/checksums" + + VDR_RC_DIR="/usr/share/vdr/rcscript" + + # Pathes to includes + VDR_INCLUDE_DIR="/usr/include/vdr" + DVB_INCLUDE_DIR="/usr/include" + + TMP_LOCALE_DIR="${WORKDIR}/tmp-locale" + + LOCDIR=$(pkg-config --variable=locdir vdr) + + if ! has_vdr; then + # set to invalid values to detect abuses + VDRVERSION="eclass_no_vdr_installed" + APIVERSION="eclass_no_vdr_installed" + + if [[ "${GENTOO_VDR_CONDITIONAL:-no}" = "yes" ]] && ! use vdr; then + einfo "VDR not found!" + else + # if vdr is required + die "VDR not found!" + fi + return + fi + + VDRVERSION=$(awk -F'"' '/define VDRVERSION/ {print $2}' "${VDR_INCLUDE_DIR}"/config.h) + APIVERSION=$(pkg-config --variable=apiversion vdr) + + einfo "Compiling against" + einfo "\tvdr-${VDRVERSION} [API version ${APIVERSION}]" + + if [[ -n "${VDR_LOCAL_PATCHES_DIR}" ]]; then + eerror "Using VDR_LOCAL_PATCHES_DIR is deprecated!" + eerror "Please move all your patches into" + eerror "${EROOT%/}/etc/portage/patches/${CATEGORY}/${P}" + eerror "and remove or unset the VDR_LOCAL_PATCHES_DIR variable." + die + fi +} + +vdr-plugin-2_src_util() { + while [ "$1" ]; do + case "$1" in + all) + vdr-plugin-2_src_util unpack add_local_patch patchmakefile linguas_patch i18n + ;; + prepare) + vdr-plugin-2_src_util add_local_patch patchmakefile linguas_patch i18n + ;; + unpack) + unpacker_src_unpack + ;; + add_local_patch) + cd "${S}" || die "Could not change to plugin-source-directory (src_util)" + if [[ ${EAPI} != [5] ]]; then + eapply_user + else + epatch_user + fi + ;; + patchmakefile) + cd "${S}" || die "Could not change to plugin-source-directory (src_util)" + vdr_patchmakefile + ;; + i18n) + vdr_i18n + ;; + linguas_patch) + vdr_linguas_support + ;; + esac + + shift + done +} + +vdr-plugin-2_src_unpack() { + if [[ -z ${VDR_INCLUDE_DIR} ]]; then + eerror "Wrong use of vdr-plugin-2.eclass." + eerror "An ebuild for a vdr-plugin will not work without calling vdr-plugin-2_src_unpack." + echo + eerror "Please report this at bugs.gentoo.org." + die "vdr-plugin-2_src_unpack not called!" + fi + + if [ -z "$1" ]; then + vdr-plugin-2_src_util unpack + else + vdr-plugin-2_src_util $@ + fi +} + +vdr-plugin-2_src_prepare() { + if [[ -z ${VDR_INCLUDE_DIR} ]]; then + eerror "Wrong use of vdr-plugin-2.eclass." + eerror "An ebuild for a vdr-plugin will not work without calling vdr-plugin-2_src_prepare." + echo + eerror "Please report this at bugs.gentoo.org." + die "vdr-plugin-2_src_prepare not called!" + fi + + [[ ${EAPI} == [5] ]] && [[ ${PATCHES[@]} ]] && epatch "${PATCHES[@]}" + [[ ${EAPI} != [5] ]] && [[ ${PATCHES[@]} ]] && eapply "${PATCHES[@]}" + + debug-print "$FUNCNAME: applying user patches" + + vdr-plugin-2_src_util prepare +} + +vdr-plugin-2_src_compile() { + [ -z "$1" ] && vdr-plugin-2_src_compile compile + + while [ "$1" ]; do + case "$1" in + compile) + if [[ ! -f ${WORKDIR}/.vdr-plugin_makefile_patched ]]; then + eerror "Wrong use of vdr-plugin-2.eclass." + eerror "An ebuild for a vdr-plugin will not work without" + eerror "calling vdr-plugin-2_src_compile to patch the Makefile." + echo + eerror "Please report this at bugs.gentoo.org." + die "vdr-plugin-2_src_compile not called!" + fi + cd "${S}" || die "could not change to plugin source directory (src_compile)" + + emake all ${BUILD_PARAMS} \ + LOCALEDIR="${TMP_LOCALE_DIR}" \ + LOCDIR="${TMP_LOCALE_DIR}" \ + LIBDIR="${S}" \ + TMPDIR="${T}" \ + || die "emake all failed" + ;; + esac + + shift + done +} + +vdr-plugin-2_src_install() { + if [[ -z ${VDR_INCLUDE_DIR} ]]; then + eerror "Wrong use of vdr-plugin-2.eclass." + eerror "An ebuild for a vdr-plugin will not work without calling vdr-plugin-2_src_install." + echo + eerror "Please report this at bugs.gentoo.org." + die "vdr-plugin-2_src_install not called!" + fi + + cd "${WORKDIR}" || die "could not change to plugin workdir directory (src_install)" + + if [[ -n ${VDR_MAINTAINER_MODE} ]]; then + local mname="${P}-Makefile" + cp "${S}"/Makefile "${mname}.patched" + cp Makefile.before "${mname}.before" + + diff -u "${mname}.before" "${mname}.patched" > "${mname}.diff" + + insinto "/usr/share/vdr/maintainer-data/makefile-changes" + doins "${mname}.diff" + + insinto "/usr/share/vdr/maintainer-data/makefile-before" + doins "${mname}.before" + + insinto "/usr/share/vdr/maintainer-data/makefile-patched" + doins "${mname}.patched" + + fi + + cd "${S}" || die "could not change to plugin source directory (src_install)" + + local SOFILE_STRING=$(grep SOFILE Makefile) + if [[ -n ${SOFILE_STRING} ]]; then + emake install \ + ${BUILD_PARAMS} \ + TMPDIR="${T}" \ + DESTDIR="${D%/}" \ + || die "emake install (makefile target) failed" + else + eqawarn "Plugin use still the old Makefile handling" + insinto "${VDR_PLUGIN_DIR}" + doins libvdr-*.so.* + fi + + if [[ -d ${TMP_LOCALE_DIR} ]]; then + einfo "Installing locales" + cd "${TMP_LOCALE_DIR}" || die "could not change to TMP_LOCALE_DIR" + + local linguas + for linguas in ${LINGUAS[*]}; do + insinto "${LOCDIR}" + cp -r --parents ${linguas}* ${D%/}/${LOCDIR} + done + fi + + cd "${D%/}/usr/$(get_libdir)/vdr/plugins" || die "could not change to D/usr/libdir/vdr/plugins" + + # create list of all created plugin libs + vdr_plugin_list="" + local p_name + for p in libvdr-*.so.*; do + p_name="${p%.so*}" + p_name="${p_name#lib}" + vdr_plugin_list="${vdr_plugin_list} ${p_name}" + done + + cd "${S}" || die "could not change to plugin source directory (src_install)" + + vdr_create_header_checksum_file ${vdr_plugin_list} + vdr_create_plugindb_file ${vdr_plugin_list} + + if [[ ${EAPI} != [45] ]]; then + einstalldocs + else + local docfile + for docfile in README* HISTORY CHANGELOG; do + [[ -f ${docfile} ]] && dodoc ${docfile} + done + fi + + # if VDR_CONFD_FILE is empty and ${FILESDIR}/confd exists take it + [[ -z ${VDR_CONFD_FILE} ]] && [[ -e ${FILESDIR}/confd ]] && VDR_CONFD_FILE=${FILESDIR}/confd + + if [[ -n ${VDR_CONFD_FILE} ]]; then + newconfd "${VDR_CONFD_FILE}" vdr.${VDRPLUGIN} + fi + + # if VDR_RCADDON_FILE is empty and ${FILESDIR}/rc-addon.sh exists take it + [[ -z ${VDR_RCADDON_FILE} ]] && [[ -e ${FILESDIR}/rc-addon.sh ]] && VDR_RCADDON_FILE=${FILESDIR}/rc-addon.sh + + if [[ -n ${VDR_RCADDON_FILE} ]]; then + insinto "${VDR_RC_DIR}" + newins "${VDR_RCADDON_FILE}" plugin-${VDRPLUGIN}.sh + fi +} + +vdr-plugin-2_pkg_postinst() { + vdr-plugin-2_print_enable_command + + if [[ -n "${VDR_CONFD_FILE}" ]]; then + elog "Please have a look at the config-file" + elog "\t/etc/conf.d/vdr.${VDRPLUGIN}" + elog + fi +} + +vdr-plugin-2_pkg_postrm() { +: +} + +vdr-plugin-2_pkg_config() { +: +} diff --git a/eclass/verify-sig.eclass b/eclass/verify-sig.eclass new file mode 100644 index 0000000..e3ef7f2 --- /dev/null +++ b/eclass/verify-sig.eclass @@ -0,0 +1,271 @@ +# Copyright 2020 Gentoo Authors +# Distributed under the terms of the GNU General Public License v2 + +# @ECLASS: verify-sig.eclass +# @MAINTAINER: +# Michał Górny <mgorny@gentoo.org> +# @SUPPORTED_EAPIS: 7 +# @BLURB: Eclass to verify upstream signatures on distfiles +# @DESCRIPTION: +# verify-sig eclass provides a streamlined approach to verifying +# upstream signatures on distfiles. Its primary purpose is to permit +# developers to easily verify signatures while bumping packages. +# The eclass removes the risk of developer forgetting to perform +# the verification, or performing it incorrectly, e.g. due to additional +# keys in the local keyring. It also permits users to verify +# the developer's work. +# +# To use the eclass, start by packaging the upstream's key +# as app-crypt/openpgp-keys-*. Then inherit the eclass, add detached +# signatures to SRC_URI and set VERIFY_SIG_OPENPGP_KEY_PATH. The eclass +# provides verify-sig USE flag to toggle the verification. +# +# Example use: +# @CODE +# inherit verify-sig +# +# SRC_URI="https://example.org/${P}.tar.gz +# verify-sig? ( https://example.org/${P}.tar.gz.sig )" +# BDEPEND=" +# verify-sig? ( app-crypt/openpgp-keys-example )" +# +# VERIFY_SIG_OPENPGP_KEY_PATH=/usr/share/openpgp-keys/example.asc +# @CODE + +case "${EAPI:-0}" in + 0|1|2|3|4|5|6) + die "Unsupported EAPI=${EAPI} (obsolete) for ${ECLASS}" + ;; + 7) + ;; + *) + die "Unsupported EAPI=${EAPI} (unknown) for ${ECLASS}" + ;; +esac + +EXPORT_FUNCTIONS src_unpack + +if [[ ! ${_VERIFY_SIG_ECLASS} ]]; then + +IUSE="verify-sig" + +BDEPEND=" + verify-sig? ( + app-crypt/gnupg + >=app-portage/gemato-16 + )" + +# @ECLASS-VARIABLE: VERIFY_SIG_OPENPGP_KEY_PATH +# @DEFAULT_UNSET +# @DESCRIPTION: +# Path to key bundle used to perform the verification. This is required +# when using default src_unpack. Alternatively, the key path can be +# passed directly to the verification functions. + +# @ECLASS-VARIABLE: VERIFY_SIG_OPENPGP_KEYSERVER +# @DEFAULT_UNSET +# @DESCRIPTION: +# Keyserver used to refresh keys. If not specified, the keyserver +# preference from the key will be respected. If no preference +# is specified by the key, the GnuPG default will be used. + +# @ECLASS-VARIABLE: VERIFY_SIG_OPENPGP_KEY_REFRESH +# @USER_VARIABLE +# @DESCRIPTION: +# Attempt to refresh keys via WKD/keyserver. Set it to "yes" +# in make.conf to enable. Note that this requires working Internet +# connection. +: ${VERIFY_SIG_OPENPGP_KEY_REFRESH:=no} + +# @FUNCTION: verify-sig_verify_detached +# @USAGE: <file> <sig-file> [<key-file>] +# @DESCRIPTION: +# Read the detached signature from <sig-file> and verify <file> against +# it. <key-file> can either be passed directly, or it defaults +# to VERIFY_SIG_OPENPGP_KEY_PATH. The function dies if verification +# fails. +verify-sig_verify_detached() { + local file=${1} + local sig=${2} + local key=${3:-${VERIFY_SIG_OPENPGP_KEY_PATH}} + + [[ -n ${key} ]] || + die "${FUNCNAME}: no key passed and VERIFY_SIG_OPENPGP_KEY_PATH unset" + + local extra_args=() + [[ ${VERIFY_SIG_OPENPGP_KEY_REFRESH} == yes ]] || extra_args+=( -R ) + [[ -n ${VERIFY_SIG_OPENPGP_KEYSERVER+1} ]] && extra_args+=( + --keyserver "${VERIFY_SIG_OPENPGP_KEYSERVER}" + ) + + # GPG upstream knows better than to follow the spec, so we can't + # override this directory. However, there is a clean fallback + # to GNUPGHOME. + addpredict /run/user + + local filename=${file##*/} + [[ ${file} == - ]] && filename='(stdin)' + einfo "Verifying ${filename} ..." + gemato gpg-wrap -K "${key}" "${extra_args[@]}" -- \ + gpg --verify "${sig}" "${file}" || + die "PGP signature verification failed" +} + +# @FUNCTION: verify-sig_verify_message +# @USAGE: <file> <output-file> [<key-file>] +# @DESCRIPTION: +# Verify that the file ('-' for stdin) contains a valid, signed PGP +# message and write the message into <output-file> ('-' for stdout). +# <key-file> can either be passed directly, or it defaults +# to VERIFY_SIG_OPENPGP_KEY_PATH. The function dies if verification +# fails. Note that using output from <output-file> is important as it +# prevents the injection of unsigned data. +verify-sig_verify_message() { + local file=${1} + local output_file=${2} + local key=${3:-${VERIFY_SIG_OPENPGP_KEY_PATH}} + + [[ -n ${key} ]] || + die "${FUNCNAME}: no key passed and VERIFY_SIG_OPENPGP_KEY_PATH unset" + + local extra_args=() + [[ ${VERIFY_SIG_OPENPGP_KEY_REFRESH} == yes ]] || extra_args+=( -R ) + [[ -n ${VERIFY_SIG_OPENPGP_KEYSERVER+1} ]] && extra_args+=( + --keyserver "${VERIFY_SIG_OPENPGP_KEYSERVER}" + ) + + # GPG upstream knows better than to follow the spec, so we can't + # override this directory. However, there is a clean fallback + # to GNUPGHOME. + addpredict /run/user + + local filename=${file##*/} + [[ ${file} == - ]] && filename='(stdin)' + einfo "Verifying ${filename} ..." + gemato gpg-wrap -K "${key}" "${extra_args[@]}" -- \ + gpg --verify --output="${output_file}" "${file}" || + die "PGP signature verification failed" +} + +# @FUNCTION: verify-sig_verify_signed_checksums +# @USAGE: <checksum-file> <algo> <files> [<key-file>] +# @DESCRIPTION: +# Verify the checksums for all files listed in the space-separated list +# <files> (akin to ${A}) using a PGP-signed <checksum-file>. <algo> +# specified the checksum algorithm (e.g. sha256). <key-file> can either +# be passed directly, or it defaults to VERIFY_SIG_OPENPGP_KEY_PATH. +# +# The function dies if PGP verification fails, the checksum file +# contains unsigned data, one of the files do not match checksums +# or are missing from the checksum file. +verify-sig_verify_signed_checksums() { + local checksum_file=${1} + local algo=${2} + local files=() + read -r -d '' -a files <<<"${3}" + local key=${4:-${VERIFY_SIG_OPENPGP_KEY_PATH}} + + local chksum_prog chksum_len + case ${algo} in + sha256) + chksum_prog=sha256sum + chksum_len=64 + ;; + *) + die "${FUNCNAME}: unknown checksum algo ${algo}" + ;; + esac + + [[ -n ${key} ]] || + die "${FUNCNAME}: no key passed and VERIFY_SIG_OPENPGP_KEY_PATH unset" + + local checksum filename junk ret=0 count=0 + while read -r checksum filename junk; do + [[ ${#checksum} -eq ${chksum_len} ]] || continue + [[ -z ${checksum//[0-9a-f]} ]] || continue + has "${filename}" "${files[@]}" || continue + [[ -z ${junk} ]] || continue + + "${chksum_prog}" -c --strict - <<<"${checksum} ${filename}" + if [[ ${?} -eq 0 ]]; then + (( count++ )) + else + ret=1 + fi + done < <(verify-sig_verify_message "${checksum_file}" - "${key}") + + [[ ${ret} -eq 0 ]] || + die "${FUNCNAME}: at least one file did not verify successfully" + [[ ${count} -eq ${#files[@]} ]] || + die "${FUNCNAME}: checksums for some of the specified files were missing" +} + +# @FUNCTION: verify-sig_src_unpack +# @DESCRIPTION: +# Default src_unpack override that verifies signatures for all +# distfiles if 'verify-sig' flag is enabled. The function dies if any +# of the signatures fails to verify or if any distfiles are not signed. +# Please write src_unpack() yourself if you need to perform partial +# verification. +verify-sig_src_unpack() { + if use verify-sig; then + local f suffix found + local distfiles=() signatures=() nosigfound=() straysigs=() + + # find all distfiles and signatures, and combine them + for f in ${A}; do + found= + for suffix in .asc .sig; do + if [[ ${f} == *${suffix} ]]; then + signatures+=( "${f}" ) + found=sig + break + else + if has "${f}${suffix}" ${A}; then + distfiles+=( "${f}" ) + found=dist+sig + break + fi + fi + done + if [[ ! ${found} ]]; then + nosigfound+=( "${f}" ) + fi + done + + # check if all distfiles are signed + if [[ ${#nosigfound[@]} -gt 0 ]]; then + eerror "The following distfiles lack detached signatures:" + for f in "${nosigfound[@]}"; do + eerror " ${f}" + done + die "Unsigned distfiles found" + fi + + # check if there are no stray signatures + for f in "${signatures[@]}"; do + if ! has "${f%.*}" "${distfiles[@]}"; then + straysigs+=( "${f}" ) + fi + done + if [[ ${#straysigs[@]} -gt 0 ]]; then + eerror "The following signatures do not match any distfiles:" + for f in "${straysigs[@]}"; do + eerror " ${f}" + done + die "Unused signatures found" + fi + + # now perform the verification + for f in "${signatures[@]}"; do + verify-sig_verify_detached \ + "${DISTDIR}/${f%.*}" "${DISTDIR}/${f}" + done + fi + + # finally, unpack the distfiles + default_src_unpack +} + +_VERIFY_SIG_ECLASS=1 +fi diff --git a/eclass/versionator.eclass b/eclass/versionator.eclass new file mode 100644 index 0000000..8a1066a --- /dev/null +++ b/eclass/versionator.eclass @@ -0,0 +1,518 @@ +# Copyright 1999-2020 Gentoo Authors +# Distributed under the terms of the GNU General Public License v2 + +# @ECLASS: versionator.eclass +# @MAINTAINER: +# Jonathan Callen <jcallen@gentoo.org> +# base-system@gentoo.org +# @SUPPORTED_EAPIS: 0 1 2 3 4 5 6 +# @BLURB: functions which simplify manipulation of ${PV} and similar version strings +# @DEPRECATED: ver_* functions from EAPI 7 +# @DESCRIPTION: +# This eclass provides functions which simplify manipulating $PV and similar +# variables. Most functions default to working with $PV, although other +# values can be used. +# @EXAMPLE: +# Simple Example 1: $PV is 1.2.3b, we want 1_2.3b: +# MY_PV=$(replace_version_separator 1 '_' ) +# +# Simple Example 2: $PV is 1.4.5, we want 1: +# MY_MAJORV=$(get_major_version ) +# +# Rather than being a number, the index parameter can be a separator character +# such as '-', '.' or '_'. In this case, the first separator of this kind is +# selected. +# +# There's also: +# version_is_at_least want have +# which may be buggy, so use with caution. + +if [[ -z ${_VERSIONATOR_ECLASS} ]]; then +_VERSIONATOR_ECLASS=1 + +case ${EAPI:-0} in + 0|1|2|3|4|5|6) + ;; + *) + die "${ECLASS}: banned in EAPI=${EAPI}; use ver_* instead";; +esac + +inherit estack + +# @FUNCTION: get_all_version_components +# @USAGE: [version] +# @DESCRIPTION: +# Split up a version string into its component parts. If no parameter is +# supplied, defaults to $PV. +# 0.8.3 -> 0 . 8 . 3 +# 7c -> 7 c +# 3.0_p2 -> 3 . 0 _ p2 +# 20040905 -> 20040905 +# 3.0c-r1 -> 3 . 0 c - r1 +get_all_version_components() { + eshopts_push -s extglob + local ver_str=${1:-${PV}} result + result=() + + # sneaky cache trick cache to avoid having to parse the same thing several + # times. + if [[ ${VERSIONATOR_CACHE_VER_STR} == ${ver_str} ]] ; then + echo ${VERSIONATOR_CACHE_RESULT} + eshopts_pop + return + fi + export VERSIONATOR_CACHE_VER_STR=${ver_str} + + while [[ -n $ver_str ]] ; do + case "${ver_str::1}" in + # number: parse whilst we have a number + [[:digit:]]) + result+=("${ver_str%%[^[:digit:]]*}") + ver_str=${ver_str##+([[:digit:]])} + ;; + + # separator: single character + [-_.]) + result+=("${ver_str::1}") + ver_str=${ver_str:1} + ;; + + # letter: grab the letters plus any following numbers + [[:alpha:]]) + local not_match=${ver_str##+([[:alpha:]])*([[:digit:]])} + # Can't say "${ver_str::-${#not_match}}" in Bash 3.2 + result+=("${ver_str::${#ver_str} - ${#not_match}}") + ver_str=${not_match} + ;; + + # huh? + *) + result+=("${ver_str::1}") + ver_str=${ver_str:1} + ;; + esac + done + + export VERSIONATOR_CACHE_RESULT=${result[*]} + echo ${result[@]} + eshopts_pop +} + +# @FUNCTION: get_version_components +# @USAGE: [version] +# @DESCRIPTION: +# Get the important version components, excluding '.', '-' and '_'. Defaults to +# $PV if no parameter is supplied. +# 0.8.3 -> 0 8 3 +# 7c -> 7 c +# 3.0_p2 -> 3 0 p2 +# 20040905 -> 20040905 +# 3.0c-r1 -> 3 0 c r1 +get_version_components() { + local c=$(get_all_version_components "${1:-${PV}}") + echo ${c//[-._]/ } +} + +# @FUNCTION: get_major_version +# @USAGE: [version] +# @DESCRIPTION: +# Get the major version of a value. Defaults to $PV if no parameter is supplied. +# 0.8.3 -> 0 +# 7c -> 7 +# 3.0_p2 -> 3 +# 20040905 -> 20040905 +# 3.0c-r1 -> 3 +get_major_version() { + local c=($(get_all_version_components "${1:-${PV}}")) + echo ${c[0]} +} + +# @FUNCTION: get_version_component_range +# @USAGE: <range> [version] +# @DESCRIPTION: +# Get a particular component or range of components from the version. If no +# version parameter is supplied, defaults to $PV. +# 1 1.2.3 -> 1 +# 1-2 1.2.3 -> 1.2 +# 2- 1.2.3 -> 2.3 +get_version_component_range() { + eshopts_push -s extglob + local c v="${2:-${PV}}" range="${1}" range_start range_end + local -i i=-1 j=0 + c=($(get_all_version_components "${v}")) + range_start=${range%-*}; range_start=${range_start:-1} + range_end=${range#*-} ; range_end=${range_end:-${#c[@]}} + + while ((j < range_start)); do + i+=1 + ((i > ${#c[@]})) && eshopts_pop && return + [[ -n "${c[i]//[-._]}" ]] && j+=1 + done + + while ((j <= range_end)); do + echo -n ${c[i]} + ((i > ${#c[@]})) && eshopts_pop && return + [[ -n "${c[i]//[-._]}" ]] && j+=1 + i+=1 + done + eshopts_pop +} + +# @FUNCTION: get_after_major_version +# @USAGE: [version] +# @DESCRIPTION: +# Get everything after the major version and its separator (if present) of a +# value. Defaults to $PV if no parameter is supplied. +# 0.8.3 -> 8.3 +# 7c -> c +# 3.0_p2 -> 0_p2 +# 20040905 -> (empty string) +# 3.0c-r1 -> 0c-r1 +get_after_major_version() { + echo $(get_version_component_range 2- "${1:-${PV}}") +} + +# @FUNCTION: replace_version_separator +# @USAGE: <search> <replacement> [subject] +# @DESCRIPTION: +# Replace the $1th separator with $2 in $3 (defaults to $PV if $3 is not +# supplied). If there are fewer than $1 separators, don't change anything. +# 1 '_' 1.2.3 -> 1_2.3 +# 2 '_' 1.2.3 -> 1.2_3 +# 1 '_' 1b-2.3 -> 1b_2.3 +# Rather than being a number, $1 can be a separator character such as '-', '.' +# or '_'. In this case, the first separator of this kind is selected. +replace_version_separator() { + eshopts_push -s extglob + local w c v="${3:-${PV}}" + declare -i i found=0 + w=${1:-1} + c=($(get_all_version_components ${v})) + if [[ ${w} != *[[:digit:]]* ]] ; then + # it's a character, not an index + for ((i = 0; i < ${#c[@]}; i++)); do + if [[ ${c[i]} == ${w} ]]; then + c[i]=${2} + break + fi + done + else + for ((i = 0; i < ${#c[@]}; i++)); do + if [[ -n "${c[i]//[^-._]}" ]]; then + found+=1 + if ((found == w)); then + c[i]=${2} + break + fi + fi + done + fi + c=${c[*]} + echo ${c// } + eshopts_pop +} + +# @FUNCTION: replace_all_version_separators +# @USAGE: <replacement> [subject] +# @DESCRIPTION: +# Replace all version separators in $2 (defaults to $PV) with $1. +# '_' 1b.2.3 -> 1b_2_3 +replace_all_version_separators() { + local c=($(get_all_version_components "${2:-${PV}}")) + c=${c[@]//[-._]/$1} + echo ${c// } +} + +# @FUNCTION: delete_version_separator +# @USAGE: <search> [subject] +# @DESCRIPTION: +# Delete the $1th separator in $2 (defaults to $PV if $2 is not supplied). If +# there are fewer than $1 separators, don't change anything. +# 1 1.2.3 -> 12.3 +# 2 1.2.3 -> 1.23 +# 1 1b-2.3 -> 1b2.3 +# Rather than being a number, $1 can be a separator character such as '-', '.' +# or '_'. In this case, the first separator of this kind is deleted. +delete_version_separator() { + replace_version_separator "${1}" "" "${2}" +} + +# @FUNCTION: delete_all_version_separators +# @USAGE: [subject] +# @DESCRIPTION: +# Delete all version separators in $1 (defaults to $PV). +# 1b.2.3 -> 1b23 +delete_all_version_separators() { + replace_all_version_separators "" "${1}" +} + +# @FUNCTION: get_version_component_count +# @USAGE: [version] +# @DESCRIPTION: +# How many version components are there in $1 (defaults to $PV)? +# 1.0.1 -> 3 +# 3.0c-r1 -> 4 +get_version_component_count() { + local a=($(get_version_components "${1:-${PV}}")) + echo ${#a[@]} +} + +# @FUNCTION: get_last_version_component_index +# @USAGE: [version] +# @DESCRIPTION: +# What is the index of the last version component in $1 (defaults to $PV)? +# Equivalent to get_version_component_count - 1. +# 1.0.1 -> 2 +# 3.0c-r1 -> 3 +get_last_version_component_index() { + echo $(($(get_version_component_count "${1:-${PV}}" ) - 1)) +} + +# @FUNCTION: version_is_at_least +# @USAGE: <want> [have] +# @DESCRIPTION: +# Is $2 (defaults to $PVR) at least version $1? Intended for use in eclasses +# only. May not be reliable, be sure to do very careful testing before actually +# using this. +version_is_at_least() { + local want_s="$1" have_s="${2:-${PVR}}" r + version_compare "${want_s}" "${have_s}" + r=$? + case $r in + 1|2) + return 0 + ;; + 3) + return 1 + ;; + *) + die "versionator compare bug [atleast, ${want_s}, ${have_s}, ${r}]" + ;; + esac +} + +# @FUNCTION: version_compare +# @USAGE: <A> <B> +# @DESCRIPTION: +# Takes two parameters (A, B) which are versions. If A is an earlier version +# than B, returns 1. If A is identical to B, return 2. If A is later than B, +# return 3. You probably want version_is_at_least rather than this function. +# May not be very reliable. Test carefully before using this. +version_compare() { + eshopts_push -s extglob + local ver_a=${1} ver_b=${2} parts_a parts_b + local cur_tok_a cur_tok_b num_part_a num_part_b + local -i cur_idx_a=0 cur_idx_b=0 prev_idx_a prev_idx_b + parts_a=( $(get_all_version_components "${ver_a}" ) ) + parts_b=( $(get_all_version_components "${ver_b}" ) ) + + ### compare number parts. + local -i inf_loop=0 + while true; do + inf_loop+=1 + ((inf_loop > 20)) && \ + die "versionator compare bug [numbers, ${ver_a}, ${ver_b}]" + + # Store the current index to test later + prev_idx_a=cur_idx_a + prev_idx_b=cur_idx_b + + # grab the current number components + cur_tok_a=${parts_a[cur_idx_a]} + cur_tok_b=${parts_b[cur_idx_b]} + + # number? + if [[ -n ${cur_tok_a} ]] && [[ -z ${cur_tok_a//[[:digit:]]} ]] ; then + cur_idx_a+=1 + [[ ${parts_a[cur_idx_a]} == . ]] \ + && cur_idx_a+=1 + else + cur_tok_a= + fi + + if [[ -n ${cur_tok_b} ]] && [[ -z ${cur_tok_b//[[:digit:]]} ]] ; then + cur_idx_b+=1 + [[ ${parts_b[cur_idx_b]} == . ]] \ + && cur_idx_b+=1 + else + cur_tok_b= + fi + + # done with number components? + [[ -z ${cur_tok_a} && -z ${cur_tok_b} ]] && break + + # if a component is blank, then it is the lesser value + [[ -z ${cur_tok_a} ]] && eshopts_pop && return 1 + [[ -z ${cur_tok_b} ]] && eshopts_pop && return 3 + + # According to PMS, if we are *not* in the first number part, and either + # token begins with "0", then we use a different algorithm (that + # effectively does floating point comparison) + if (( prev_idx_a != 0 && prev_idx_b != 0 )) \ + && [[ ${cur_tok_a} == 0* || ${cur_tok_b} == 0* ]] ; then + + # strip trailing zeros + cur_tok_a=${cur_tok_a%%+(0)} + cur_tok_b=${cur_tok_b%%+(0)} + + # do a *string* comparison of the resulting values: 2 > 11 + [[ ${cur_tok_a} < ${cur_tok_b} ]] && eshopts_pop && return 1 + [[ ${cur_tok_a} > ${cur_tok_b} ]] && eshopts_pop && return 3 + else + # to avoid going into octal mode, strip any leading zeros. otherwise + # bash will throw a hissy fit on versions like 6.3.068. + cur_tok_a=${cur_tok_a##+(0)} + cur_tok_b=${cur_tok_b##+(0)} + + # now if a component is blank, it was originally 0 -- make it so + : ${cur_tok_a:=0} + : ${cur_tok_b:=0} + + # compare + ((cur_tok_a < cur_tok_b)) && eshopts_pop && return 1 + ((cur_tok_a > cur_tok_b)) && eshopts_pop && return 3 + fi + done + + ### number parts equal. compare letter parts. + local letter_a= + letter_a=${parts_a[cur_idx_a]} + if [[ ${#letter_a} -eq 1 && -z ${letter_a/[a-z]} ]] ; then + cur_idx_a+=1 + else + letter_a=@ + fi + + local letter_b= + letter_b=${parts_b[cur_idx_b]} + if [[ ${#letter_b} -eq 1 && -z ${letter_b/[a-z]} ]] ; then + cur_idx_b+=1 + else + letter_b=@ + fi + + # compare + [[ ${letter_a} < ${letter_b} ]] && eshopts_pop && return 1 + [[ ${letter_a} > ${letter_b} ]] && eshopts_pop && return 3 + + ### letter parts equal. compare suffixes in order. + inf_loop=0 + while true ; do + inf_loop+=1 + ((inf_loop > 20)) && \ + die "versionator compare bug [numbers, ${ver_a}, ${ver_b}]" + [[ ${parts_a[cur_idx_a]} == _ ]] && ((cur_idx_a++)) + [[ ${parts_b[cur_idx_b]} == _ ]] && ((cur_idx_b++)) + + cur_tok_a=${parts_a[cur_idx_a]} + cur_tok_b=${parts_b[cur_idx_b]} + num_part_a=0 + num_part_b=0 + + if has ${cur_tok_a%%+([0-9])} "alpha" "beta" "pre" "rc" "p"; then + cur_idx_a+=1 + num_part_a=${cur_tok_a##+([a-z])} + # I don't like octal + num_part_a=${num_part_a##+(0)} + : ${num_part_a:=0} + cur_tok_a=${cur_tok_a%%+([0-9])} + else + cur_tok_a= + fi + + if has ${cur_tok_b%%+([0-9])} alpha beta pre rc p; then + cur_idx_b+=1 + num_part_b=${cur_tok_b##+([a-z])} + # I still don't like octal + num_part_b=${num_part_b##+(0)} + : ${num_part_b:=0} + cur_tok_b=${cur_tok_b%%+([0-9])} + else + cur_tok_b= + fi + + if [[ ${cur_tok_a} != ${cur_tok_b} ]]; then + local suffix + for suffix in alpha beta pre rc "" p; do + [[ ${cur_tok_a} == ${suffix} ]] && eshopts_pop && return 1 + [[ ${cur_tok_b} == ${suffix} ]] && eshopts_pop && return 3 + done + elif [[ -z ${cur_tok_a} && -z ${cur_tok_b} ]]; then + break + else + ((num_part_a < num_part_b)) && eshopts_pop && return 1 + ((num_part_a > num_part_b)) && eshopts_pop && return 3 + fi + done + + # At this point, the only thing that should be left is the -r# part + [[ ${parts_a[cur_idx_a]} == - ]] && ((cur_idx_a++)) + [[ ${parts_b[cur_idx_b]} == - ]] && ((cur_idx_b++)) + + # Sanity check + if [[ ${parts_a[cur_idx_a]/r+([0-9])} || ${parts_b[cur_idx_b]/r+([0-9])} ]]; then + die "versionator compare bug [revisions, ${ver_a}, ${ver_b}]" + fi + + num_part_a=${parts_a[cur_idx_a]#r} + num_part_a=${num_part_a##+(0)} + : ${num_part_a:=0} + num_part_b=${parts_b[cur_idx_b]#r} + num_part_b=${num_part_b##+(0)} + : ${num_part_b:=0} + + ((num_part_a < num_part_b)) && eshopts_pop && return 1 + ((num_part_a > num_part_b)) && eshopts_pop && return 3 + + ### no differences. + eshopts_pop + return 2 +} + +# @FUNCTION: version_sort +# @USAGE: <version> [more versions...] +# @DESCRIPTION: +# Returns its parameters sorted, highest version last. We're using a quadratic +# algorithm for simplicity, so don't call it with more than a few dozen items. +# Uses version_compare, so be careful. +version_sort() { + eshopts_push -s extglob + local items= + local -i left=0 + items=("$@") + while ((left < ${#items[@]})); do + local -i lowest_idx=left + local -i idx=lowest_idx+1 + while ((idx < ${#items[@]})); do + version_compare "${items[lowest_idx]}" "${items[idx]}" + [[ $? -eq 3 ]] && lowest_idx=idx + idx+=1 + done + local tmp=${items[lowest_idx]} + items[lowest_idx]=${items[left]} + items[left]=${tmp} + left+=1 + done + echo ${items[@]} + eshopts_pop +} + +# @FUNCTION: version_format_string +# @USAGE: <format> [version] +# @DESCRIPTION: +# Reformat complicated version strings. The first argument is the string +# to reformat with while the rest of the args are passed on to the +# get_version_components function. You should make sure to single quote +# the first argument since it'll have variables that get delayed expansions. +# @EXAMPLE: +# P="cow-hat-1.2.3_p4" +# MY_P=$(version_format_string '${PN}_source_$1_$2-$3_$4') +# Now MY_P will be: cow-hat_source_1_2-3_p4 +version_format_string() { + local fstr=$1 + shift + set -- $(get_version_components "$@") + eval echo "${fstr}" +} + +fi diff --git a/eclass/vim-doc.eclass b/eclass/vim-doc.eclass new file mode 100644 index 0000000..70a6e94 --- /dev/null +++ b/eclass/vim-doc.eclass @@ -0,0 +1,72 @@ +# Copyright 1999-2020 Gentoo Authors +# Distributed under the terms of the GNU General Public License v2 +# +# This eclass is used by vim.eclass and vim-plugin.eclass to update +# the documentation tags. This is necessary since vim doesn't look in +# /usr/share/vim/vimfiles/doc for documentation; it only uses the +# versioned directory, for example /usr/share/vim/vim62/doc +# +# We depend on vim being installed, which is satisfied by either the +# DEPEND in vim-plugin or by whatever version of vim is being +# installed by the eclass. + + +update_vim_helptags() { + has "${EAPI:-0}" 0 1 2 && ! use prefix && EROOT="${ROOT}" + local vimfiles vim d s + + # This is where vim plugins are installed + vimfiles="${EROOT}"/usr/share/vim/vimfiles + + if [[ $PN != vim-core ]]; then + # Find a suitable vim binary for updating tags :helptags + vim=$(type -P vim 2>/dev/null) + [[ -z "$vim" ]] && vim=$(type -P gvim 2>/dev/null) + [[ -z "$vim" ]] && vim=$(type -P kvim 2>/dev/null) + if [[ -z "$vim" ]]; then + ewarn "No suitable vim binary to rebuild documentation tags" + fi + fi + + # Make vim not try to connect to X. See :help gui-x11-start + # in vim for how this evil trickery works. + if [[ -n "${vim}" ]] ; then + ln -s "${vim}" "${T}/tagvim" + vim="${T}/tagvim" + fi + + # Install the documentation symlinks into the versioned vim + # directory and run :helptags + for d in "${EROOT%/}"/usr/share/vim/vim[0-9]*; do + [[ -d "$d/doc" ]] || continue # catch a failed glob + + # Remove links, and possibly remove stale dirs + find $d/doc -name \*.txt -type l | while read s; do + [[ $(readlink "$s") = $vimfiles/* ]] && rm -f "$s" + done + if [[ -f "$d/doc/tags" && $(find "$d" | wc -l | tr -d ' ') = 3 ]]; then + # /usr/share/vim/vim61 + # /usr/share/vim/vim61/doc + # /usr/share/vim/vim61/doc/tags + einfo "Removing $d" + rm -r "$d" + continue + fi + + # Re-create / install new links + if [[ -d $vimfiles/doc ]]; then + ln -s $vimfiles/doc/*.txt $d/doc 2>/dev/null + fi + + # Update tags; need a vim binary for this + if [[ -n "$vim" ]]; then + einfo "Updating documentation tags in $d" + DISPLAY= $vim -u NONE -U NONE -T xterm -X -n -f \ + '+set nobackup nomore' \ + "+helptags $d/doc" \ + '+qa!' </dev/null &>/dev/null + fi + done + + [[ -n "${vim}" && -f "${vim}" ]] && rm "${vim}" +} diff --git a/eclass/vim-plugin.eclass b/eclass/vim-plugin.eclass new file mode 100644 index 0000000..a0ba714 --- /dev/null +++ b/eclass/vim-plugin.eclass @@ -0,0 +1,186 @@ +# Copyright 1999-2017 Gentoo Foundation +# Distributed under the terms of the GNU General Public License v2 + +# @ECLASS: vim-plugin.eclass +# @MAINTAINER: +# vim@gentoo.org +# @BLURB: used for installing vim plugins +# @DESCRIPTION: +# This eclass simplifies installation of app-vim plugins into +# /usr/share/vim/vimfiles. This is a version-independent directory +# which is read automatically by vim. The only exception is +# documentation, for which we make a special case via vim-doc.eclass. + +inherit estack vim-doc +EXPORT_FUNCTIONS src_install pkg_postinst pkg_postrm + +VIM_PLUGIN_VIM_VERSION="${VIM_PLUGIN_VIM_VERSION:-7.3}" + +DEPEND="|| ( >=app-editors/vim-${VIM_PLUGIN_VIM_VERSION} + >=app-editors/gvim-${VIM_PLUGIN_VIM_VERSION} )" +RDEPEND="${DEPEND}" +if [[ ${PV} != 9999* ]] ; then + SRC_URI="mirror://gentoo/${P}.tar.bz2 + https://dev.gentoo.org/~radhermit/vim/${P}.tar.bz2" +fi +SLOT="0" + +# @FUNCTION: vim-plugin_src_install +# @DESCRIPTION: +# Overrides the default src_install phase. In order, this function: +# * fixes file permission across all files in ${S}. +# * installs help and documentation files. +# * installs all files in "${ED}"/usr/share/vim/vimfiles. +vim-plugin_src_install() { + has "${EAPI:-0}" 0 1 2 && ! use prefix && ED="${D}" + local f + + # When globbing, if nothing exists, the shell literally returns the glob + # pattern. So turn on nullglob and extglob options to avoid this. + eshopts_push -s extglob + eshopts_push -s nullglob + + ebegin "Cleaning up unwanted files and directories" + # We're looking for dotfiles, dotdirectories and Makefiles here. + local obj + eval "local matches=(@(.[^.]|.??*|Makefile*))" + for obj in "${matches[@]}"; do + rm -rv "${obj}" || die "cannot remove ${obj}" + done + eend $? + + # Turn those options back off. + eshopts_pop + eshopts_pop + + # Install non-vim-help-docs + cd "${S}" || die "couldn't cd in ${S}" + local f + for f in *; do + [[ -f "${f}" ]] || continue + if [[ "${f}" = *.html ]]; then + dohtml "${f}" + else + dodoc "${f}" + fi + rm "${f}" || die + done + + # Install remainder of plugin + cd "${WORKDIR}" || die "couldn't cd in ${WORKDIR}" + dodir /usr/share/vim + mv "${S}" "${ED}"/usr/share/vim/vimfiles || die \ + "couldn't move ${S} to ${ED}/usr/share/vim/vimfiles" + + # Set permissions + fperms -R a+rX /usr/share/vim/vimfiles +} + +# @FUNCTION: vim-plugin_pkg_postinst +# @DESCRIPTION: +# Overrides the pkg_postinst phase for this eclass. +# The following functions are called: +# * update_vim_helptags +# * update_vim_afterscripts +# * display_vim_plugin_help +vim-plugin_pkg_postinst() { + update_vim_helptags # from vim-doc + update_vim_afterscripts # see below + display_vim_plugin_help # see below +} + +# @FUNCTION: vim-plugin_pkg_postrm +# @DESCRIPTION: +# Overrides the pkg_postrm phase for this eclass. +# This function calls the update_vim_helptags and update_vim_afterscripts +# functions and eventually removes a bunch of empty directories. +vim-plugin_pkg_postrm() { + has "${EAPI:-0}" 0 1 2 && ! use prefix && EPREFIX= + update_vim_helptags # from vim-doc + update_vim_afterscripts # see below + + # Remove empty dirs; this allows + # /usr/share/vim to be removed if vim-core is unmerged + find "${EPREFIX}/usr/share/vim/vimfiles" -depth -type d -exec rmdir {} \; 2>/dev/null || \ + die "rmdir failed" +} + +# @FUNCTION: update_vim_afterscripts +# @DESCRIPTION: +# Creates scripts in /usr/share/vim/vimfiles/after/* +# comprised of the snippets in /usr/share/vim/vimfiles/after/*/*.d +update_vim_afterscripts() { + has "${EAPI:-0}" 0 1 2 && ! use prefix && EROOT="${ROOT}" + has "${EAPI:-0}" 0 1 2 && ! use prefix && EPREFIX= + local d f afterdir="${EROOT}"/usr/share/vim/vimfiles/after + + # Nothing to do if the dir isn't there + [ -d "${afterdir}" ] || return 0 + + einfo "Updating scripts in ${EPREFIX}/usr/share/vim/vimfiles/after" + find "${afterdir}" -type d -name \*.vim.d | while read d; do + echo '" Generated by update_vim_afterscripts' > "${d%.d}" || die + find "${d}" -name \*.vim -type f -maxdepth 1 -print0 | sort -z | \ + xargs -0 cat >> "${d%.d}" || die "update_vim_afterscripts failed" + done + + einfo "Removing dead scripts in ${EPREFIX}/usr/share/vim/vimfiles/after" + find "${afterdir}" -type f -name \*.vim | \ + while read f; do + [[ "$(head -n 1 ${f})" == '" Generated by update_vim_afterscripts' ]] \ + || continue + # This is a generated file, but might be abandoned. Check + # if there's no corresponding .d directory, or if the + # file's effectively empty + if [[ ! -d "${f}.d" || -z "$(grep -v '^"' "${f}")" ]]; then + rm "${f}" || die + fi + done +} + +# @FUNCTION: display_vim_plugin_help +# @DESCRIPTION: +# Displays a message with the plugin's help file if one is available. Uses the +# VIM_PLUGIN_HELPFILES env var. If multiple help files are available, they +# should be separated by spaces. If no help files are available, but the env +# var VIM_PLUGIN_HELPTEXT is set, that is displayed instead. Finally, if we +# have nothing else, this functions displays a link to VIM_PLUGIN_HELPURI. An +# extra message regarding enabling filetype plugins is displayed if +# VIM_PLUGIN_MESSAGES includes the word "filetype". +display_vim_plugin_help() { + local h + + if ! has_version ${CATEGORY}/${PN} ; then + if [[ -n "${VIM_PLUGIN_HELPFILES}" ]] ; then + elog " " + elog "This plugin provides documentation via vim's help system. To" + elog "view it, use:" + for h in ${VIM_PLUGIN_HELPFILES} ; do + elog " :help ${h}" + done + elog " " + + elif [[ -n "${VIM_PLUGIN_HELPTEXT}" ]] ; then + elog " " + while read h ; do + elog "$h" + done <<<"${VIM_PLUGIN_HELPTEXT}" + elog " " + + elif [[ -n "${VIM_PLUGIN_HELPURI}" ]] ; then + elog " " + elog "Documentation for this plugin is available online at:" + elog " ${VIM_PLUGIN_HELPURI}" + elog " " + fi + + if has "filetype" "${VIM_PLUGIN_MESSAGES}" ; then + elog "This plugin makes use of filetype settings. To enable these," + elog "add lines like:" + elog " filetype plugin on" + elog " filetype indent on" + elog "to your ~/.vimrc file." + elog " " + fi + fi +} diff --git a/eclass/vim-spell.eclass b/eclass/vim-spell.eclass new file mode 100644 index 0000000..828a453 --- /dev/null +++ b/eclass/vim-spell.eclass @@ -0,0 +1,153 @@ +# Copyright 1999-2017 Gentoo Foundation +# Distributed under the terms of the GNU General Public License v2 + +# @ECLASS: vim-spell.eclass +# @MAINTAINER: +# Vim Maintainers <vim@gentoo.org> +# @AUTHOR: +# Ciaran McCreesh <ciaranm@gentoo.org> +# @BLURB: Eclass for managing Vim spell files. +# @DESCRIPTION: +# How to make a vim spell file package using prebuilt spell lists +# from upstream (${CODE} is the language's two letter code): +# +# * Get the ${CODE}.*.spl, ${CODE}.*.sug (if your language has them) and +# README_${CODE}.txt files. Currently they're at +# ftp://ftp.vim.org/pub/vim/unstable/runtime/spell/ (except for English, +# which should be taken from CVS instead). +# +# * Stick them in vim-spell-${CODE}-$(date --iso | tr -d - ).tar.bz2 . Make sure +# that they're in the appropriately named subdirectory to avoid having to mess +# with S=. +# +# * Upload the tarball to the Gentoo mirrors. +# +# * Add your spell file to package.mask next to the other vim things. Vim +# Project members will handle unmasking your spell packages when vim comes out +# of package.mask. +# +# * Create the app-vim/vim-spell-${CODE} package. You should base your ebuild +# upon app-vim/vim-spell-en. You will need to change VIM_SPELL_LANGUAGE, +# KEYWORDS and LICENSE. Check the license carefully! The README will tell +# you what it is. +# +# * Don't forget metadata.xml. You should list the Vim project and yourself +# as maintainers. There is no need to join the Vim project just for spell +# files. Here's an example of a metadata.xml file: +# +# <?xml version="1.0" encoding="UTF-8"?> +# <!DOCTYPE pkgmetadata SYSTEM "https://www.gentoo.org/dtd/metadata.dtd"> +# <pkgmetadata> +# <maintainer type="person"> +# <email>your@email.tld</email> +# <name>Your Name</name> +# </maintainer> +# <maintainer type="project"> +# <email>vim@gentoo.org</email> +# <name>Vim Maintainers</name> +# </maintainer> +# +# <longdescription lang="en"> +# Vim spell files for French (fr). Supported character sets are +# UTF-8 and latin1. +# </longdescription> +# </pkgmetadata> +# +# * Send an email to vim@gentoo.org to let us know. +# +# Don't forget to update your package as necessary. +# +# If there isn't an upstream-provided pregenerated spell file for your language +# yet, read :help spell.txt from inside vim for instructions on how to create +# spell files. It's best to let upstream know if you've generated spell files +# for another language rather than keeping them Gentoo-specific. + +inherit eutils + +EXPORT_FUNCTIONS src_install pkg_postinst + +SRC_URI="mirror://gentoo/${P}.tar.bz2" +SLOT="0" + +# @ECLASS-VARIABLE: VIM_SPELL_LANGUAGE +# @DESCRIPTION: +# This variable defines the language for the spell package being +# installed. +# The default value is "English". +: ${VIM_SPELL_LANGUAGE:="English"} + +# @ECLASS-VARIABLE: VIM_SPELL_LOCALE +# @INTERNAL +# @DESCRIPTION: +# This variable defines the locale for the current ebuild. +# The default value is ${PN} stripped of the "vim-spell-" string. +: ${VIM_SPELL_LOCALE:="${PN/vim-spell-/}"} + +# @ECLASS-VARIABLE: VIM_SPELL_DIRECTORY +# @INTERNAL +# @DESCRIPTION: +# This variable defines the path to Vim spell files. +: ${VIM_SPELL_DIRECTORY:="${EPREFIX}/usr/share/vim/vimfiles/spell/"} + +# @ECLASS-VARIABLE: DESCRIPTION +# @DESCRIPTION: +# This variable defines the DESCRIPTION for Vim spell ebuilds. +: ${DESCRIPTION:="vim spell files: ${VIM_SPELL_LANGUAGE} (${VIM_SPELL_LOCALE})"} + +# @ECLASS-VARIABLE: HOMEPAGE +# @DESCRIPTION: +# This variable defines the HOMEPAGE for Vim spell ebuilds. +: ${HOMEPAGE:="https://www.vim.org"} + +# @FUNCTION: vim-spell_src_install +# @DESCRIPTION: +# This function installs Vim spell files. +vim-spell_src_install() { + dodir "${VIM_SPELL_DIRECTORY}" + insinto "${VIM_SPELL_DIRECTORY}" + + local had_spell_file= + local f + for f in *.spl; do + if [[ -f "${f}" ]]; then + doins "${f}" + had_spell_file="yes" + fi + done + + for f in *.sug; do + if [[ -f "${f}" ]]; then + doins "${f}" + fi + done + + for f in README*; do + dodoc "${f}" + done + + [[ -z "${had_spell_file}" ]] && die "Didn't install any spell files?" +} + +# @FUNCTION: vim-spell_pkg_postinst +# @DESCRIPTION: +# This function displays installed Vim spell files. +vim-spell_pkg_postinst() { + has "${EAPI:-0}" 0 1 2 && ! use prefix && EROOT="${ROOT}" + echo + elog "To enable ${VIM_SPELL_LANGUAGE} spell checking, use" + elog " :setlocal spell spelllang=${VIM_SPELL_LOCALE}" + echo + elog "The following (Vim internal, not file) encodings are supported for" + elog "this language:" + local f enc + for f in "${EROOT}${VIM_SPELL_DIRECTORY}/${VIM_SPELL_LOCALE}".*.spl; do + enc="${f##*/${VIM_SPELL_LOCALE}.}" + enc="${enc%.spl}" + [[ -z "${enc}" ]] && continue + elog " ${enc}" + done + echo + elog "For further documentation, use:" + elog " :help spell" + echo +} diff --git a/eclass/virtualx.eclass b/eclass/virtualx.eclass new file mode 100644 index 0000000..fa16784 --- /dev/null +++ b/eclass/virtualx.eclass @@ -0,0 +1,274 @@ +# Copyright 1999-2019 Gentoo Authors +# Distributed under the terms of the GNU General Public License v2 + +# @ECLASS: virtualx.eclass +# @MAINTAINER: +# x11@gentoo.org +# @AUTHOR: +# Original author: Martin Schlemmer <azarah@gentoo.org> +# @SUPPORTED_EAPIS: 4 5 6 7 +# @BLURB: This eclass can be used for packages that needs a working X environment to build. + +if [[ ! ${_VIRTUAL_X} ]]; then + +case "${EAPI:-0}" in + 0|1|2|3) + die "virtualx.eclass: EAPI ${EAPI} is too old." + ;; + 4|5|6|7) + ;; + *) + die "virtualx.eclass: EAPI ${EAPI} is not supported yet." + ;; +esac + +[[ ${EAPI} == [45] ]] && inherit eutils + +# @ECLASS-VARIABLE: VIRTUALX_REQUIRED +# @DESCRIPTION: +# Variable specifying the dependency on xorg-server and xhost. +# Possible special values are "always" and "manual", which specify +# the dependency to be set unconditionaly or not at all. +# Any other value is taken as useflag desired to be in control of +# the dependency (eg. VIRTUALX_REQUIRED="kde" will add the dependency +# into "kde? ( )" and add kde into IUSE. +: ${VIRTUALX_REQUIRED:=test} + +# @ECLASS-VARIABLE: VIRTUALX_DEPEND +# @DESCRIPTION: +# Dep string available for use outside of eclass, in case a more +# complicated dep is needed. +# You can specify the variable BEFORE inherit to add more dependencies. +VIRTUALX_DEPEND="${VIRTUALX_DEPEND} + x11-base/xorg-server[xvfb] + x11-apps/xhost +" + +# @ECLASS-VARIABLE: VIRTUALX_COMMAND +# @DESCRIPTION: +# Command (or eclass function call) to be run in the X11 environment +# (within virtualmake function). +: ${VIRTUALX_COMMAND:="emake"} + +case ${VIRTUALX_REQUIRED} in + manual) + ;; + always) + if [[ ${EAPI:-0} != [0123456] ]]; then + BDEPEND="${VIRTUALX_DEPEND}" + else + DEPEND="${VIRTUALX_DEPEND}" + fi + RDEPEND="" + ;; + optional|tests) + [[ ${EAPI} == [45] ]] \ + || die 'Values "optional" and "tests" for VIRTUALX_REQUIRED are banned in EAPI > 5' + # deprecated section YAY. + eqawarn "VIRTUALX_REQUIRED=optional and VIRTUALX_REQUIRED=tests are deprecated." + eqawarn "You can drop the variable definition completely from ebuild," + eqawarn "because it is default behaviour." + + if [[ -n ${VIRTUALX_USE} ]]; then + # so they like to specify the useflag + eqawarn "VIRTUALX_USE variable is deprecated." + eqawarn "Please read eclass manpage to find out how to use VIRTUALX_REQUIRED" + eqawarn "to achieve the same behaviour." + fi + + [[ -z ${VIRTUALX_USE} ]] && VIRTUALX_USE="test" + DEPEND="${VIRTUALX_USE}? ( ${VIRTUALX_DEPEND} )" + RDEPEND="" + IUSE="${VIRTUALX_USE}" + ;; + *) + if [[ ${EAPI:-0} != [0123456] ]]; then + BDEPEND="${VIRTUALX_REQUIRED}? ( ${VIRTUALX_DEPEND} )" + else + DEPEND="${VIRTUALX_REQUIRED}? ( ${VIRTUALX_DEPEND} )" + fi + RDEPEND="" + IUSE="${VIRTUALX_REQUIRED}" + [[ ${VIRTUALX_REQUIRED} == test ]] && + RESTRICT+=" !test? ( test )" + ;; +esac + +# @FUNCTION: virtualmake +# @DESCRIPTION: +# Function which start new Xvfb session +# where the VIRTUALX_COMMAND variable content gets executed. +virtualmake() { + debug-print-function ${FUNCNAME} "$@" + + [[ ${EAPI} == [45] ]] \ + || die "${FUNCNAME} is unsupported in EAPI > 5, please use virtx" + + # backcompat for maketype + if [[ -n ${maketype} ]]; then + [[ ${EAPI} == [45] ]] || die "maketype is banned in EAPI > 5" + eqawarn "ebuild is exporting \$maketype=${maketype}" + eqawarn "Ebuild should be migrated to use 'virtx command' instead." + VIRTUALX_COMMAND=${maketype} + fi + + virtx "${VIRTUALX_COMMAND}" "${@}" +} + + +# @FUNCTION: virtx +# @USAGE: <command> [command arguments] +# @DESCRIPTION: +# Start new Xvfb session and run commands in it. +# +# IMPORTANT: The command is run nonfatal !!! +# +# This means we are checking for the return code and raise an exception if it +# isn't 0. So you need to make sure that all commands return a proper +# code and not just die. All eclass function used should support nonfatal +# calls properly. +# +# The rational behind this is the tear down of the started Xfvb session. A +# straight die would leave a running session behind. +# +# Example: +# +# @CODE +# src_test() { +# virtx default +# } +# @CODE +# +# @CODE +# python_test() { +# virtx py.test --verbose +# } +# @CODE +# +# @CODE +# my_test() { +# some_command +# return $? +# } +# +# src_test() { +# virtx my_test +# } +# @CODE +virtx() { + debug-print-function ${FUNCNAME} "$@" + + [[ $# -lt 1 ]] && die "${FUNCNAME} needs at least one argument" + + local i=0 + local retval=0 + local OLD_SANDBOX_ON="${SANDBOX_ON}" + local XVFB XHOST XDISPLAY + local xvfbargs="-screen 0 1280x1024x24 +extension RANDR" + XVFB=$(type -p Xvfb) || die + XHOST=$(type -p xhost) || die + + debug-print "${FUNCNAME}: running Xvfb hack" + export XAUTHORITY= + # The following is derived from Mandrake's hack to allow + # compiling without the X display + + einfo "Scanning for an open DISPLAY to start Xvfb ..." + # If we are in a chrooted environment, and there is already a + # X server started outside of the chroot, Xvfb will fail to start + # on the same display (most cases this is :0 ), so make sure + # Xvfb is started, else bump the display number + # + # Azarah - 5 May 2002 + # GNOME GDM may have started X on DISPLAY :0 with a + # lock file /tmp/.X1024-lock, therefore start the search at 1. + # Else a leftover /tmp/.X1-lock will prevent finding an available display. + XDISPLAY=$(i=1; while [[ -f /tmp/.X${i}-lock ]] ; do ((i++));done; echo ${i}) + debug-print "${FUNCNAME}: XDISPLAY=${XDISPLAY}" + + # We really do not want SANDBOX enabled here + export SANDBOX_ON="0" + + debug-print "${FUNCNAME}: ${XVFB} :${XDISPLAY} ${xvfbargs}" + ${XVFB} :${XDISPLAY} ${xvfbargs} &>/dev/null & + sleep 2 + + local start=${XDISPLAY} + while [[ ! -f /tmp/.X${XDISPLAY}-lock ]]; do + # Stop trying after 15 tries + if ((XDISPLAY - start > 15)) ; then + eerror "'${XVFB} :${XDISPLAY} ${xvfbargs}' returns:" + echo + ${XVFB} :${XDISPLAY} ${xvfbargs} + echo + eerror "If possible, correct the above error and try your emerge again." + die "Unable to start Xvfb" + fi + ((XDISPLAY++)) + debug-print "${FUNCNAME}: ${XVFB} :${XDISPLAY} ${xvfbargs}" + ${XVFB} :${XDISPLAY} ${xvfbargs} &>/dev/null & + sleep 2 + done + + # Now enable SANDBOX again if needed. + export SANDBOX_ON="${OLD_SANDBOX_ON}" + + einfo "Starting Xvfb on \$DISPLAY=${XDISPLAY} ..." + + export DISPLAY=:${XDISPLAY} + # Do not break on error, but setup $retval, as we need + # to kill Xvfb + debug-print "${FUNCNAME}: $@" + nonfatal "$@" + retval=$? + + # Now kill Xvfb + kill $(cat /tmp/.X${XDISPLAY}-lock) + + # die if our command failed + [[ ${retval} -ne 0 ]] && die "Failed to run '$@'" + + return 0 # always return 0, it can be altered by failed kill for Xvfb +} + +# @FUNCTION: Xmake +# @DESCRIPTION: +# Same as "make", but set up the Xvfb hack if needed. +# Deprecated call. +Xmake() { + debug-print-function ${FUNCNAME} "$@" + + [[ ${EAPI} == [45] ]] \ + || die "${FUNCNAME} is unsupported in EAPI > 5, please use 'virtx emake -j1 ....'" + + eqawarn "you should not execute make directly" + eqawarn "rather execute Xemake -j1 if you have issues with parallel make" + VIRTUALX_COMMAND="emake -j1" virtualmake "$@" +} + +# @FUNCTION: Xemake +# @DESCRIPTION: +# Same as "emake", but set up the Xvfb hack if needed. +Xemake() { + debug-print-function ${FUNCNAME} "$@" + + [[ ${EAPI} == [45] ]] \ + || die "${FUNCNAME} is unsupported in EAPI > 5, please use 'virtx emake ....'" + + VIRTUALX_COMMAND="emake" virtualmake "$@" +} + +# @FUNCTION: Xeconf +# @DESCRIPTION: +# Same as "econf", but set up the Xvfb hack if needed. +Xeconf() { + debug-print-function ${FUNCNAME} "$@" + + [[ ${EAPI} == [45] ]] \ + || die "${FUNCNAME} is unsupported in EAPI > 5, please use 'virtx econf ....'" + + VIRTUALX_COMMAND="econf" virtualmake "$@" +} + +_VIRTUAL_X=1 +fi diff --git a/eclass/waf-utils.eclass b/eclass/waf-utils.eclass new file mode 100644 index 0000000..f224608 --- /dev/null +++ b/eclass/waf-utils.eclass @@ -0,0 +1,131 @@ +# Copyright 1999-2019 Gentoo Authors +# Distributed under the terms of the GNU General Public License v2 + +# @ECLASS: waf-utils.eclass +# @MAINTAINER: +# maintainer-needed@gentoo.org +# @AUTHOR: +# Original Author: Gilles Dartiguelongue <eva@gentoo.org> +# Various improvements based on cmake-utils.eclass: Tomáš Chvátal <scarabeus@gentoo.org> +# Proper prefix support: Jonathan Callen <jcallen@gentoo.org> +# @SUPPORTED_EAPIS: 4 5 6 7 +# @BLURB: common ebuild functions for waf-based packages +# @DESCRIPTION: +# The waf-utils eclass contains functions that make creating ebuild for +# waf-based packages much easier. +# Its main features are support of common portage default settings. + +[[ ${EAPI} == [45] ]] && inherit eutils +inherit multilib toolchain-funcs multiprocessing + +case ${EAPI:-0} in + 4|5|6|7) EXPORT_FUNCTIONS src_configure src_compile src_install ;; + *) die "EAPI=${EAPI} is not supported" ;; +esac + +# @ECLASS-VARIABLE: WAF_VERBOSE +# @DESCRIPTION: +# Set to OFF to disable verbose messages during compilation +# this is _not_ meant to be set in ebuilds +: ${WAF_VERBOSE:=ON} + +# @FUNCTION: waf-utils_src_configure +# @DESCRIPTION: +# General function for configuring with waf. +waf-utils_src_configure() { + debug-print-function ${FUNCNAME} "$@" + + local fail + if [[ ! ${_PYTHON_ANY_R1} && ! ${_PYTHON_SINGLE_R1} && ! ${_PYTHON_R1} ]]; then + eerror "Using waf-utils.eclass without any python-r1 suite eclass is not supported." + eerror "Please make sure to configure and inherit appropriate -r1 eclass." + eerror "For more information and examples, please see:" + eerror " https://wiki.gentoo.org/wiki/Project:Python/waf-utils_integration" + fail=1 + else + if [[ ! ${EPYTHON} ]]; then + eerror "EPYTHON is unset while calling waf-utils. This most likely means that" + eerror "the ebuild did not call the appropriate eclass function before calling waf." + if [[ ${_PYTHON_ANY_R1} ]]; then + eerror "Please ensure that python-any-r1_pkg_setup is called in pkg_setup()." + elif [[ ${_PYTHON_SINGLE_R1} ]]; then + eerror "Please ensure that python-single-r1_pkg_setup is called in pkg_setup()." + else # python-r1 + eerror "Please ensure that python_setup is called before waf-utils_src_configure()," + eerror "or that the latter is used within python_foreach_impl as appropriate." + fi + eerror + fail=1 + fi + + if [[ ${PYTHON_REQ_USE} != *threads* ]]; then + eerror "Waf requires threading support in Python. To accomodate this requirement," + eerror "please add 'threads(+)' to PYTHON_REQ_USE variable (above inherit line)." + eerror "For more information and examples, please see:" + eerror " https://wiki.gentoo.org/wiki/Project:Python/waf-utils_integration" + fail=1 + fi + fi + + [[ ${fail} ]] && die "Invalid use of waf-utils.eclass" + + # @ECLASS-VARIABLE: WAF_BINARY + # @DESCRIPTION: + # Eclass can use different waf executable. Usually it is located in "${S}/waf". + : ${WAF_BINARY:="${S}/waf"} + + local conf_args=() + + local waf_help=$("${WAF_BINARY}" --help 2>/dev/null) + if [[ ${waf_help} == *--docdir* ]]; then + conf_args+=( --docdir="${EPREFIX}"/usr/share/doc/${PF} ) + fi + if [[ ${waf_help} == *--htmldir* ]]; then + conf_args+=( --htmldir="${EPREFIX}"/usr/share/doc/${PF}/html ) + fi + if [[ ${waf_help} == *--libdir* ]]; then + conf_args+=( --libdir="${EPREFIX}/usr/$(get_libdir)" ) + fi + + tc-export AR CC CPP CXX RANLIB + + local CMD=( + CCFLAGS="${CFLAGS}" + LINKFLAGS="${CFLAGS} ${LDFLAGS}" + PKGCONFIG="$(tc-getPKG_CONFIG)" + "${WAF_BINARY}" + "--prefix=${EPREFIX}/usr" + "${conf_args[@]}" + "${@}" + configure + ) + + echo "${CMD[@]@Q}" >&2 + env "${CMD[@]}" || die "configure failed" +} + +# @FUNCTION: waf-utils_src_compile +# @DESCRIPTION: +# General function for compiling with waf. +waf-utils_src_compile() { + debug-print-function ${FUNCNAME} "$@" + local _mywafconfig + [[ ${WAF_VERBOSE} == ON ]] && _mywafconfig="--verbose" + + local jobs="--jobs=$(makeopts_jobs)" + echo "\"${WAF_BINARY}\" build ${_mywafconfig} ${jobs} ${*}" + "${WAF_BINARY}" ${_mywafconfig} ${jobs} "${@}" || die "build failed" +} + +# @FUNCTION: waf-utils_src_install +# @DESCRIPTION: +# Function for installing the package. +waf-utils_src_install() { + debug-print-function ${FUNCNAME} "$@" + + echo "\"${WAF_BINARY}\" --destdir=\"${D}\" ${*} install" + "${WAF_BINARY}" --destdir="${D}" "${@}" install || die "Make install failed" + + # Manual document installation + einstalldocs +} diff --git a/eclass/webapp.eclass b/eclass/webapp.eclass new file mode 100644 index 0000000..b0a8f7a --- /dev/null +++ b/eclass/webapp.eclass @@ -0,0 +1,577 @@ +# Copyright 1999-2019 Gentoo Authors +# Distributed under the terms of the GNU General Public License v2 + +# @ECLASS: webapp.eclass +# @MAINTAINER: +# web-apps@gentoo.org +# @BLURB: functions for installing applications to run under a web server +# @DESCRIPTION: +# The webapp eclass contains functions to handle web applications with +# webapp-config. Part of the implementation of GLEP #11 + +# @ECLASS-VARIABLE: WEBAPP_DEPEND +# @DESCRIPTION: +# An ebuild should use WEBAPP_DEPEND if a custom DEPEND needs to be built, most +# notably in combination with WEBAPP_OPTIONAL. +WEBAPP_DEPEND=">=app-admin/webapp-config-1.50.15" + +# @ECLASS-VARIABLE: WEBAPP_NO_AUTO_INSTALL +# @DESCRIPTION: +# An ebuild sets this to `yes' if an automatic installation and/or upgrade is +# not possible. The ebuild should overwrite pkg_postinst() and explain the +# reason for this BEFORE calling webapp_pkg_postinst(). + +# @ECLASS-VARIABLE: WEBAPP_OPTIONAL +# @DESCRIPTION: +# An ebuild sets this to `yes' to make webapp support optional, in which case +# you also need to take care of USE-flags and dependencies. + +if [[ "${WEBAPP_OPTIONAL}" != "yes" ]]; then + [[ "${WEBAPP_NO_AUTO_INSTALL}" == "yes" ]] || IUSE="vhosts" + SLOT="${PVR}" + DEPEND="${WEBAPP_DEPEND}" + RDEPEND="${DEPEND}" +fi + +EXPORT_FUNCTIONS pkg_postinst pkg_setup src_install pkg_prerm + +INSTALL_DIR="/${PN}" +IS_UPGRADE=0 +IS_REPLACE=0 + +INSTALL_CHECK_FILE="installed_by_webapp_eclass" +SETUP_CHECK_FILE="setup_by_webapp_eclass" + +ETC_CONFIG="${ROOT%/}/etc/vhosts/webapp-config" +WEBAPP_CONFIG="${ROOT%/}/usr/sbin/webapp-config" +WEBAPP_CLEANER="${ROOT%/}/usr/sbin/webapp-cleaner" + +# ============================================================================== +# INTERNAL FUNCTIONS +# ============================================================================== + +# Load the config file /etc/vhosts/webapp-config +# Supports both the old bash version, and the new python version +webapp_read_config() { + debug-print-function $FUNCNAME $* + + if has_version '>=app-admin/webapp-config-1.50'; then + ENVVAR=$(${WEBAPP_CONFIG} --query ${PN} ${PVR}) || die "Could not read settings from webapp-config!" + eval ${ENVVAR} + elif [[ "${WEBAPP_OPTIONAL}" != "yes" ]]; then + # ETC_CONFIG might not be available + . ${ETC_CONFIG} || die "Unable to read ${ETC_CONFIG}" + elif [[ -f "${ETC_CONFIG}" ]]; then + # WEBAPP_OPTIONAL is set to yes + # and this must run only if ETC_CONFIG actually exists + . ${ETC_CONFIG} || die "Unable to read ${ETC_CONFIG}" + fi +} + +# Check whether a specified file exists in the given directory (`.' by default) +webapp_checkfileexists() { + debug-print-function $FUNCNAME $* + + local my_prefix=${2:+${2}/} + + if [[ ! -e "${my_prefix}${1}" ]]; then + msg="ebuild fault: file '${1}' not found" + eerror "$msg" + eerror "Please report this as a bug at https://bugs.gentoo.org/" + die "$msg" + fi +} + +webapp_check_installedat() { + debug-print-function $FUNCNAME $* + ${WEBAPP_CONFIG} --show-installed -h localhost -d "${INSTALL_DIR}" 2> /dev/null +} + +webapp_strip_appdir() { + debug-print-function $FUNCNAME $* + echo "${1#${MY_APPDIR}/}" +} + +webapp_strip_d() { + debug-print-function $FUNCNAME $* + echo "${1#${D}}" +} + +webapp_strip_cwd() { + debug-print-function $FUNCNAME $* + echo "${1/#.\///}" +} + +webapp_getinstalltype() { + debug-print-function $FUNCNAME $* + + if ! has vhosts ${IUSE} || use vhosts; then + return + fi + + local my_output + my_output="$(webapp_check_installedat)" + + if [[ $? -eq 0 ]]; then + # something is already installed there + # make sure it isn't the same version + + local my_pn="$(echo ${my_output} | awk '{ print $1 }')" + local my_pvr="$(echo ${my_output} | awk '{ print $2 }')" + + REMOVE_PKG="${my_pn}-${my_pvr}" + + if [[ "${my_pn}" == "${PN}" ]]; then + if [[ "${my_pvr}" != "${PVR}" ]]; then + elog "This is an upgrade" + IS_UPGRADE=1 + # for binpkgs, reset status, var declared in global scope + IS_REPLACE=0 + else + elog "This is a re-installation" + IS_REPLACE=1 + # for binpkgs, reset status, var declared in global scope + IS_UPGRADE=0 + fi + else + elog "${my_output} is installed there" + fi + else + # for binpkgs, reset status, var declared in global scope + IS_REPLACE=0 + IS_UPGRADE=0 + elog "This is an installation" + fi +} + +# ============================================================================== +# PUBLIC FUNCTIONS +# ============================================================================== + +# @FUNCTION: need_httpd +# @DESCRIPTION: +# Call this function AFTER your ebuilds DEPEND line if any of the available +# webservers are able to run this application. +need_httpd() { + DEPEND="${DEPEND} + || ( virtual/httpd-basic virtual/httpd-cgi virtual/httpd-fastcgi )" +} + +# @FUNCTION: need_httpd_cgi +# @DESCRIPTION: +# Call this function AFTER your ebuilds DEPEND line if any of the available +# CGI-capable webservers are able to run this application. +need_httpd_cgi() { + DEPEND="${DEPEND} + || ( virtual/httpd-cgi virtual/httpd-fastcgi )" +} + +# @FUNCTION: need_httpd_fastcgi +# @DESCRIPTION: +# Call this function AFTER your ebuilds DEPEND line if any of the available +# FastCGI-capabale webservers are able to run this application. +need_httpd_fastcgi() { + DEPEND="${DEPEND} + virtual/httpd-fastcgi" +} + +# @FUNCTION: webapp_configfile +# @USAGE: <file> [more files ...] +# @DESCRIPTION: +# Mark a file config-protected for a web-based application. +webapp_configfile() { + debug-print-function $FUNCNAME $* + + local m + for m in "$@"; do + webapp_checkfileexists "${m}" "${D}" + + local my_file="$(webapp_strip_appdir "${m}")" + my_file="$(webapp_strip_cwd "${my_file}")" + + elog "(config) ${my_file}" + echo "${my_file}" >> ${D}/${WA_CONFIGLIST} + done +} + +# @FUNCTION: webapp_hook_script +# @USAGE: <file> +# @DESCRIPTION: +# Install a script that will run after a virtual copy is created, and +# before a virtual copy has been removed. +webapp_hook_script() { + debug-print-function $FUNCNAME $* + + webapp_checkfileexists "${1}" + + elog "(hook) ${1}" + cp "${1}" "${D}/${MY_HOOKSCRIPTSDIR}/$(basename "${1}")" || die "Unable to install ${1} into ${D}/${MY_HOOKSCRIPTSDIR}/" + chmod 555 "${D}/${MY_HOOKSCRIPTSDIR}/$(basename "${1}")" +} + +# @FUNCTION: webapp_postinst_txt +# @USAGE: <lang> <file> +# @DESCRIPTION: +# Install a text file containing post-installation instructions. +webapp_postinst_txt() { + debug-print-function $FUNCNAME $* + + webapp_checkfileexists "${2}" + + elog "(info) ${2} (lang: ${1})" + cp "${2}" "${D}/${MY_APPDIR}/postinst-${1}.txt" +} + +# @FUNCTION: webapp_postupgrade_txt +# @USAGE: <lang> <file> +# @DESCRIPTION: +# Install a text file containing post-upgrade instructions. +webapp_postupgrade_txt() { + debug-print-function $FUNCNAME $* + + webapp_checkfileexists "${2}" + + elog "(info) ${2} (lang: ${1})" + cp "${2}" "${D}/${MY_APPDIR}/postupgrade-${1}.txt" +} + +# helper for webapp_serverowned() +_webapp_serverowned() { + debug-print-function $FUNCNAME $* + + webapp_checkfileexists "${1}" "${D}" + local my_file="$(webapp_strip_appdir "${1}")" + my_file="$(webapp_strip_cwd "${my_file}")" + + echo "${my_file}" >> "${D}/${WA_SOLIST}" +} + +# @FUNCTION: webapp_serverowned +# @USAGE: [-R] <file> [more files ...] +# @DESCRIPTION: +# Identify a file which must be owned by the webserver's user:group settings. +# The ownership of the file is NOT set until the application is installed using +# the webapp-config tool. If -R is given directories are handled recursively. +webapp_serverowned() { + debug-print-function $FUNCNAME $* + + local a m + if [[ "${1}" == "-R" ]]; then + shift + for m in "$@"; do + find "${D}${m}" | while read a; do + a=$(webapp_strip_d "${a}") + _webapp_serverowned "${a}" + done + done + else + for m in "$@"; do + _webapp_serverowned "${m}" + done + fi +} + +# @FUNCTION: webapp_server_configfile +# @USAGE: <server> <file> [new name] +# @DESCRIPTION: +# Install a configuration file for the webserver. You need to specify a +# webapp-config supported <server>. if no new name is given `basename $2' is +# used by default. Note: this function will automagically prepend $1 to the +# front of your config file's name. +webapp_server_configfile() { + debug-print-function $FUNCNAME $* + + webapp_checkfileexists "${2}" + + # WARNING: + # + # do NOT change the naming convention used here without changing all + # the other scripts that also rely upon these names + + local my_file="${1}-${3:-$(basename "${2}")}" + + elog "(${1}) config file '${my_file}'" + cp "${2}" "${D}/${MY_SERVERCONFIGDIR}/${my_file}" +} + +# @FUNCTION: webapp_sqlscript +# @USAGE: <db> <file> [version] +# @DESCRIPTION: +# Install a SQL script that creates/upgrades a database schema for the web +# application. Currently supported database engines are mysql and postgres. +# If a version is given the script should upgrade the database schema from +# the given version to $PVR. +webapp_sqlscript() { + debug-print-function $FUNCNAME $* + + webapp_checkfileexists "${2}" + + dodir "${MY_SQLSCRIPTSDIR}/${1}" + + # WARNING: + # + # do NOT change the naming convention used here without changing all + # the other scripts that also rely upon these names + + if [[ -n "${3}" ]]; then + elog "(${1}) upgrade script for ${PN}-${3} to ${PVR}" + cp "${2}" "${D}${MY_SQLSCRIPTSDIR}/${1}/${3}_to_${PVR}.sql" + chmod 600 "${D}${MY_SQLSCRIPTSDIR}/${1}/${3}_to_${PVR}.sql" + else + elog "(${1}) create script for ${PN}-${PVR}" + cp "${2}" "${D}/${MY_SQLSCRIPTSDIR}/${1}/${PVR}_create.sql" + chmod 600 "${D}/${MY_SQLSCRIPTSDIR}/${1}/${PVR}_create.sql" + fi +} + +# @FUNCTION: webapp_src_preinst +# @DESCRIPTION: +# You need to call this function in src_install() BEFORE anything else has run. +# For now we just create required webapp-config directories. +webapp_src_preinst() { + debug-print-function $FUNCNAME $* + + # sanity checks, to catch bugs in the ebuild + if [[ ! -f "${T}/${SETUP_CHECK_FILE}" ]]; then + eerror + eerror "This ebuild did not call webapp_pkg_setup() at the beginning" + eerror "of the pkg_setup() function" + eerror + eerror "Please log a bug on https://bugs.gentoo.org" + eerror + eerror "You should use emerge -C to remove this package, as the" + eerror "installation is incomplete" + eerror + die "Ebuild did not call webapp_pkg_setup() - report to https://bugs.gentoo.org" + fi + + # Hint, see the webapp_read_config() function to find where these are + # defined. + dodir "${MY_HTDOCSDIR}" + dodir "${MY_HOSTROOTDIR}" + dodir "${MY_CGIBINDIR}" + dodir "${MY_ICONSDIR}" + dodir "${MY_ERRORSDIR}" + dodir "${MY_SQLSCRIPTSDIR}" + dodir "${MY_HOOKSCRIPTSDIR}" + dodir "${MY_SERVERCONFIGDIR}" +} + +# ============================================================================== +# EXPORTED FUNCTIONS +# ============================================================================== + +# @FUNCTION: webapp_pkg_setup +# @DESCRIPTION: +# The default pkg_setup() for this eclass. This will gather required variables +# from webapp-config and check if there is an application installed to +# `${ROOT%/}/var/www/localhost/htdocs/${PN}/' if USE=vhosts is not set. +# +# You need to call this function BEFORE anything else has run in your custom +# pkg_setup(). +webapp_pkg_setup() { + debug-print-function $FUNCNAME $* + + # to test whether or not the ebuild has correctly called this function + # we add an empty file to the filesystem + # + # we used to just set a variable in the shell script, but we can + # no longer rely on Portage calling both webapp_pkg_setup() and + # webapp_src_install() within the same shell process + touch "${T}/${SETUP_CHECK_FILE}" + + # special case - some ebuilds *do* need to overwride the SLOT + if [[ "${SLOT}+" != "${PVR}+" && "${WEBAPP_MANUAL_SLOT}" != "yes" ]]; then + die "Set WEBAPP_MANUAL_SLOT=\"yes\" if you need to SLOT manually" + fi + + # pull in the shared configuration file + G_HOSTNAME="localhost" + webapp_read_config + + local my_dir="${ROOT%/}/${VHOST_ROOT}/${MY_HTDOCSBASE}/${PN}" + + # if USE=vhosts is enabled OR no application is installed we're done here + if ! has vhosts ${IUSE} || use vhosts || [[ ! -d "${my_dir}" ]]; then + return + fi + + local my_output + my_output="$(webapp_check_installedat)" + + if [[ $? -ne 0 ]]; then + # okay, whatever is there, it isn't webapp-config-compatible + echo + ewarn + ewarn "You already have something installed in ${my_dir}" + ewarn + ewarn "Whatever is in ${my_dir}, it's not" + ewarn "compatible with webapp-config." + ewarn + ewarn "This ebuild may be overwriting important files." + ewarn + echo + elif [[ "$(echo ${my_output} | awk '{ print $1 }')" != "${PN}" ]]; then + echo + eerror "You already have ${my_output} installed in ${my_dir}" + eerror + eerror "I cannot upgrade a different application" + eerror + echo + die "Cannot upgrade contents of ${my_dir}" + fi + +} + +# @FUNCTION: webapp_src_install +# @DESCRIPTION: +# This is the default src_install(). For now, we just make sure that root owns +# everything, and that there are no setuid files. +# +# You need to call this function AFTER everything else has run in your custom +# src_install(). +webapp_src_install() { + debug-print-function $FUNCNAME $* + + # to test whether or not the ebuild has correctly called this function + # we add an empty file to the filesystem + # + # we used to just set a variable in the shell script, but we can + # no longer rely on Portage calling both webapp_src_install() and + # webapp_pkg_postinst() within the same shell process + touch "${D}/${MY_APPDIR}/${INSTALL_CHECK_FILE}" + + chown -R "${VHOST_DEFAULT_UID}:${VHOST_DEFAULT_GID}" "${D}/" + chmod -R u-s "${D}/" + chmod -R g-s "${D}/" + + keepdir "${MY_PERSISTDIR}" + fowners "root:0" "${MY_PERSISTDIR}" + fperms 755 "${MY_PERSISTDIR}" +} + +# @FUNCTION: webapp_pkg_postinst +# @DESCRIPTION: +# The default pkg_postinst() for this eclass. This installs the web application to +# `${ROOT%/}/var/www/localhost/htdocs/${PN}/' if USE=vhosts is not set. Otherwise +# display a short notice how to install this application with webapp-config. +# +# You need to call this function AFTER everything else has run in your custom +# pkg_postinst(). +webapp_pkg_postinst() { + debug-print-function $FUNCNAME $* + + webapp_read_config + + # sanity checks, to catch bugs in the ebuild + if [[ ! -f "${ROOT%/}/${MY_APPDIR}/${INSTALL_CHECK_FILE}" ]]; then + eerror + eerror "This ebuild did not call webapp_src_install() at the end" + eerror "of the src_install() function" + eerror + eerror "Please log a bug on https://bugs.gentoo.org" + eerror + eerror "You should use emerge -C to remove this package, as the" + eerror "installation is incomplete" + eerror + die "Ebuild did not call webapp_src_install() - report to https://bugs.gentoo.org" + fi + + if has vhosts ${IUSE}; then + if ! use vhosts; then + echo + elog "vhosts USE flag not set - auto-installing using webapp-config" + + G_HOSTNAME="localhost" + webapp_read_config + + local my_mode=-I + webapp_getinstalltype + + if [[ "${IS_REPLACE}" == "1" ]]; then + elog "${PN}-${PVR} is already installed - replacing" + my_mode=-I + elif [[ "${IS_UPGRADE}" == "1" ]]; then + elog "${REMOVE_PKG} is already installed - upgrading" + my_mode=-U + else + elog "${PN}-${PVR} is not installed - using install mode" + fi + + my_cmd="${WEBAPP_CONFIG} -h localhost -u root -d ${INSTALL_DIR} ${my_mode} ${PN} ${PVR}" + elog "Running ${my_cmd}" + ${my_cmd} + + echo + local cleaner="${WEBAPP_CLEANER} -p -C ${CATEGORY}/${PN}" + einfo "Running ${cleaner}" + ${cleaner} + else + elog + elog "The 'vhosts' USE flag is switched ON" + elog "This means that Portage will not automatically run webapp-config to" + elog "complete the installation." + elog + elog "To install ${PN}-${PVR} into a virtual host, run the following command:" + elog + elog " webapp-config -h <host> -d ${PN} -I ${PN} ${PVR}" + elog + elog "For more details, see the webapp-config(8) man page" + fi + else + elog + elog "This ebuild does not support the 'vhosts' USE flag." + elog "This means that Portage will not automatically run webapp-config to" + elog "complete the installation." + elog + elog "To install ${PN}-${PVR} into a virtual host, run the following command:" + elog + elog " webapp-config -h <host> -d ${PN} -I ${PN} ${PVR}" + elog + elog "For more details, see the webapp-config(8) man page" + fi +} + +# @FUNCTION: webapp_pkg_prerm +# @DESCRIPTION: +# This is the default pkg_prerm() for this eclass. If USE=vhosts is not set +# remove all installed copies of this web application. Otherwise instruct the +# user to manually remove those copies. See bug #136959. +webapp_pkg_prerm() { + debug-print-function $FUNCNAME $* + + local my_output= + my_output="$(${WEBAPP_CONFIG} --list-installs ${PN} ${PVR})" + [[ $? -ne 0 ]] && return + + local x + if has vhosts ${IUSE} && ! use vhosts; then + echo "${my_output}" | while read x; do + if [[ -f "${x}"/.webapp ]]; then + . "${x}"/.webapp + if [[ -n "${WEB_HOSTNAME}" && -n "${WEB_INSTALLDIR}" ]]; then + ${WEBAPP_CONFIG} -h ${WEB_HOSTNAME} -d ${WEB_INSTALLDIR} -C ${PN} ${PVR} + fi + else + ewarn "Cannot find file ${x}/.webapp" + fi + done + elif [[ "${my_output}" != "" ]]; then + echo + ewarn + ewarn "Don't forget to use webapp-config to remove any copies of" + ewarn "${PN}-${PVR} installed in" + ewarn + + echo "${my_output}" | while read x; do + if [[ -f "${x}"/.webapp ]]; then + ewarn " ${x}" + else + ewarn "Cannot find file ${x}/.webapp" + fi + done + + ewarn + echo + fi +} diff --git a/eclass/wrapper.eclass b/eclass/wrapper.eclass new file mode 100644 index 0000000..399c7cc --- /dev/null +++ b/eclass/wrapper.eclass @@ -0,0 +1,59 @@ +# Copyright 1999-2020 Gentoo Authors +# Distributed under the terms of the GNU General Public License v2 + +# @ECLASS: wrapper.eclass +# @MAINTAINER: +# base-system@gentoo.org +# @BLURB: create a shell wrapper script + +if [[ -z ${_WRAPPER_ECLASS} ]]; then +_WRAPPER_ECLASS=1 + +# @FUNCTION: make_wrapper +# @USAGE: <wrapper> <target> [chdir] [libpaths] [installpath] +# @DESCRIPTION: +# Create a shell wrapper script named wrapper in installpath +# (defaults to the bindir) to execute target (default of wrapper) +# by first optionally setting LD_LIBRARY_PATH to the colon-delimited +# libpaths followed by optionally changing directory to chdir. +make_wrapper() { + local wrapper=$1 bin=$2 chdir=$3 libdir=$4 path=$5 + local tmpwrapper="${T}/tmp.wrapper.${wrapper##*/}" + has "${EAPI:-0}" 0 1 2 && local EPREFIX="" + + ( + echo '#!/bin/sh' + if [[ -n ${libdir} ]] ; then + local var + if [[ ${CHOST} == *-darwin* ]] ; then + var=DYLD_LIBRARY_PATH + else + var=LD_LIBRARY_PATH + fi + cat <<-EOF + if [ "\${${var}+set}" = "set" ] ; then + export ${var}="\${${var}}:${EPREFIX}${libdir}" + else + export ${var}="${EPREFIX}${libdir}" + fi + EOF + fi + [[ -n ${chdir} ]] && printf 'cd "%s" &&\n' "${EPREFIX}${chdir}" + # We don't want to quote ${bin} so that people can pass complex + # things as ${bin} ... "./someprog --args" + printf 'exec %s "$@"\n' "${bin/#\//${EPREFIX}/}" + ) > "${tmpwrapper}" + chmod go+rx "${tmpwrapper}" + + if [[ -n ${path} ]] ; then + ( + exeopts -m 0755 + exeinto "${path}" + newexe "${tmpwrapper}" "${wrapper}" + ) || die + else + newbin "${tmpwrapper}" "${wrapper}" || die + fi +} + +fi diff --git a/eclass/wxwidgets.eclass b/eclass/wxwidgets.eclass new file mode 100644 index 0000000..9b37074 --- /dev/null +++ b/eclass/wxwidgets.eclass @@ -0,0 +1,142 @@ +# Copyright 1999-2019 Gentoo Authors +# Distributed under the terms of the GNU General Public License v2 + +# @ECLASS: wxwidgets.eclass +# @MAINTAINER: +# wxwidgets@gentoo.org +# @SUPPORTED_EAPIS: 0 1 2 3 4 5 6 7 +# @BLURB: Manages build configuration for wxGTK-using packages. +# @DESCRIPTION: +# This eclass sets up the proper environment for ebuilds using the wxGTK +# libraries. Ebuilds using wxPython do not need to inherit this eclass. +# +# More specifically, this eclass controls the configuration chosen by the +# /usr/bin/wx-config wrapper. +# +# Using the eclass is simple: +# +# - set WX_GTK_VER equal to a SLOT of wxGTK +# - call setup-wxwidgets() +# +# The configuration chosen is based on the version required and the flags +# wxGTK was built with. + +if [[ -z ${_WXWIDGETS_ECLASS} ]]; then + +inherit flag-o-matic + +case ${EAPI:-0} in + 0|1|2|3|4|5) + inherit eutils multilib + + # This was used to set up a sane default for ebuilds so they could + # avoid calling need-wxwidgets if they didn't need a particular build. + # This was a bad idea for a couple different reasons, and because + # get_libdir() is now illegal in global scope in EAPI 6 we can't do it + # anymore. All ebuilds must now use setup-wxwidgets and this code is + # only here for backwards compatability. + if [[ -z ${WX_CONFIG} ]]; then + if [[ -n ${WX_GTK_VER} ]]; then + for _wxtoolkit in mac gtk2 base; do + # newer versions don't have a seperate debug config + for _wxdebug in xxx release- debug-; do + _wxconf="${_wxtoolkit}-unicode-${_wxdebug/xxx/}${WX_GTK_VER}" + + [[ -f ${EPREFIX}/usr/$(get_libdir)/wx/config/${_wxconf} ]] \ + || continue + + WX_CONFIG="${EPREFIX}/usr/$(get_libdir)/wx/config/${_wxconf}" + WX_ECLASS_CONFIG="${WX_CONFIG}" + break + done + [[ -n ${WX_CONFIG} ]] && break + done + [[ -n ${WX_CONFIG} ]] && export WX_CONFIG WX_ECLASS_CONFIG + fi + fi + unset _wxtoolkit + unset _wxdebug + unset _wxconf + ;; + 6) inherit multilib ;; # compatibility only, not needed by eclass + 7) ;; + *) die "${ECLASS}: EAPI ${EAPI:-0} is not supported" ;; +esac + +# @FUNCTION: setup-wxwidgets +# @DESCRIPTION: +# Call this in your ebuild to set up the environment for wxGTK. Besides +# controlling the wx-config wrapper this exports WX_CONFIG containing +# the path to the config in case it needs to be passed to a build system. +# +# In wxGTK-2.9 and later it also controls the level of debugging output +# from the libraries. In these versions debugging features are enabled +# by default and need to be disabled at the package level. Because this +# causes many warning dialogs to pop up during runtime we add -DNDEBUG to +# CPPFLAGS to disable debugging features (unless your ebuild has a debug +# USE flag and it's enabled). If you don't like this behavior you can set +# WX_DISABLE_NDEBUG to override it. +# +# See: http://docs.wxwidgets.org/trunk/overview_debugging.html + +setup-wxwidgets() { + local wxtoolkit wxdebug wxconf + + [[ -z ${WX_GTK_VER} ]] \ + && die "WX_GTK_VER must be set before calling $FUNCNAME." + + case "${WX_GTK_VER}" in + 3.0-gtk3) + wxtoolkit=gtk3 + if [[ -z ${WX_DISABLE_NDEBUG} ]]; then + ( in_iuse debug && use debug ) || append-cppflags -DNDEBUG + fi + ;; + 2.9|3.0) + wxtoolkit=gtk2 + if [[ -z ${WX_DISABLE_NDEBUG} ]]; then + ( in_iuse debug && use debug ) || append-cppflags -DNDEBUG + fi + ;; + 2.8) + wxtoolkit=gtk2 + wxdebug="release-" + has_version x11-libs/wxGTK:${WX_GTK_VER}[debug] && wxdebug="debug-" + ;; + *) + die "Invalid WX_GTK_VER: must be set to a valid wxGTK SLOT" + ;; + esac + + # toolkit overrides + if has_version "x11-libs/wxGTK:${WX_GTK_VER}[aqua]"; then + wxtoolkit="mac" + elif ! has_version "x11-libs/wxGTK:${WX_GTK_VER}[X]"; then + wxtoolkit="base" + fi + + wxconf="${wxtoolkit}-unicode-${wxdebug}${WX_GTK_VER}" + + [[ ! -f ${EPREFIX}/usr/$(get_libdir)/wx/config/${wxconf} ]] \ + && die "Failed to find configuration ${wxconf}" + + export WX_CONFIG="${EPREFIX}/usr/$(get_libdir)/wx/config/${wxconf}" + export WX_ECLASS_CONFIG="${WX_CONFIG}" + + echo + einfo "Requested wxWidgets: ${WX_GTK_VER}" + einfo "Using wxWidgets: ${wxconf}" + echo +} + +case ${EAPI:-0} in + 0|1|2|3|4|5|6) + # deprecated + need-wxwidgets() { + setup-wxwidgets + } + ;; +esac + +_WXWIDGETS_ECLASS=1 +fi diff --git a/eclass/xdg-utils.eclass b/eclass/xdg-utils.eclass new file mode 100644 index 0000000..738df86 --- /dev/null +++ b/eclass/xdg-utils.eclass @@ -0,0 +1,135 @@ +# Copyright 2004-2019 Gentoo Authors +# Distributed under the terms of the GNU General Public License v2 + +# @ECLASS: xdg-utils.eclass +# @MAINTAINER: +# gnome@gentoo.org +# freedesktop-bugs@gentoo.org +# @AUTHOR: +# Original author: Gilles Dartiguelongue <eva@gentoo.org> +# @SUPPORTED_EAPIS: 0 1 2 3 4 5 6 7 +# @BLURB: Auxiliary functions commonly used by XDG compliant packages. +# @DESCRIPTION: +# This eclass provides a set of auxiliary functions needed by most XDG +# compliant packages. +# It provides XDG stack related functions such as: +# * GTK/Qt5 icon theme cache management +# * XDG .desktop files cache management +# * XDG mime information database management + +case "${EAPI:-0}" in + 0|1|2|3|4|5|6|7) ;; + *) die "EAPI=${EAPI} is not supported" ;; +esac + +# @ECLASS-VARIABLE: DESKTOP_DATABASE_DIR +# @INTERNAL +# @DESCRIPTION: +# Directory where .desktop files database is stored +: ${DESKTOP_DATABASE_DIR="/usr/share/applications"} + +# @ECLASS-VARIABLE: MIMEINFO_DATABASE_DIR +# @INTERNAL +# @DESCRIPTION: +# Directory where .desktop files database is stored +: ${MIMEINFO_DATABASE_DIR:="/usr/share/mime"} + +# @FUNCTION: xdg_environment_reset +# @DESCRIPTION: +# Clean up environment for clean builds. +xdg_environment_reset() { + # Prepare XDG base directories + export XDG_DATA_HOME="${HOME}/.local/share" + export XDG_CONFIG_HOME="${HOME}/.config" + export XDG_CACHE_HOME="${HOME}/.cache" + export XDG_RUNTIME_DIR="${T}/run" + mkdir -p "${XDG_DATA_HOME}" "${XDG_CONFIG_HOME}" "${XDG_CACHE_HOME}" \ + "${XDG_RUNTIME_DIR}" || die + # This directory needs to be owned by the user, and chmod 0700 + # https://standards.freedesktop.org/basedir-spec/basedir-spec-latest.html + chmod 0700 "${XDG_RUNTIME_DIR}" || die + + unset DBUS_SESSION_BUS_ADDRESS +} + +# @FUNCTION: xdg_desktop_database_update +# @DESCRIPTION: +# Updates the .desktop files database. +# Generates a list of mimetypes linked to applications that can handle them +xdg_desktop_database_update() { + if [[ ${EBUILD_PHASE} != post* ]] ; then + die "xdg_desktop_database_update must be used in pkg_post* phases." + fi + + if ! type update-desktop-database &>/dev/null; then + debug-print "update-desktop-database is not found" + return + fi + + ebegin "Updating .desktop files database" + update-desktop-database -q "${EROOT%/}${DESKTOP_DATABASE_DIR}" + eend $? +} + +# @FUNCTION: xdg_icon_cache_update +# @DESCRIPTION: +# Updates icon theme cache files under /usr/share/icons. +# This function should be called from pkg_postinst and pkg_postrm. +xdg_icon_cache_update() { + if [[ ${EBUILD_PHASE} != post* ]] ; then + die "xdg_icon_cache_update must be used in pkg_post* phases." + fi + + if ! type gtk-update-icon-cache &>/dev/null; then + debug-print "gtk-update-icon-cache is not found" + return + fi + + ebegin "Updating icons cache" + local dir f retval=0 + local fails=( ) + for dir in "${EROOT%/}"/usr/share/icons/* + do + if [[ -f "${dir}/index.theme" ]] ; then + local rv=0 + gtk-update-icon-cache -qf "${dir}" + rv=$? + if [[ ! $rv -eq 0 ]] ; then + debug-print "Updating cache failed on ${dir}" + # Add to the list of failures + fails+=( "${dir}" ) + retval=2 + fi + elif [[ $(ls "${dir}") = "icon-theme.cache" ]]; then + # Clear stale cache files after theme uninstallation + rm "${dir}/icon-theme.cache" + fi + if [[ -z $(ls "${dir}") ]]; then + # Clear empty theme directories after theme uninstallation + rmdir "${dir}" + fi + done + eend ${retval} + for f in "${fails[@]}" ; do + eerror "Failed to update cache with icon $f" + done +} + +# @FUNCTION: xdg_mimeinfo_database_update +# @DESCRIPTION: +# Update the mime database. +# Creates a general list of mime types from several sources +xdg_mimeinfo_database_update() { + if [[ ${EBUILD_PHASE} != post* ]] ; then + die "xdg_mimeinfo_database_update must be used in pkg_post* phases." + fi + + if ! type update-mime-database &>/dev/null; then + debug-print "update-mime-database is not found" + return + fi + + ebegin "Updating shared mime info database" + update-mime-database "${EROOT%/}${MIMEINFO_DATABASE_DIR}" + eend $? +} diff --git a/eclass/xdg.eclass b/eclass/xdg.eclass new file mode 100644 index 0000000..219be71 --- /dev/null +++ b/eclass/xdg.eclass @@ -0,0 +1,110 @@ +# Copyright 1999-2019 Gentoo Authors +# Distributed under the terms of the GNU General Public License v2 + +# @ECLASS: xdg.eclass +# @MAINTAINER: +# freedesktop-bugs@gentoo.org +# @AUTHOR: +# Original author: Gilles Dartiguelongue <eva@gentoo.org> +# @SUPPORTED_EAPIS: 4 5 6 7 +# @BLURB: Provides phases for XDG compliant packages. +# @DESCRIPTION: +# Utility eclass to update the desktop, icon and shared mime info as laid +# out in the freedesktop specs & implementations + +inherit xdg-utils + +case "${EAPI:-0}" in + 4|5|6|7) + EXPORT_FUNCTIONS src_prepare pkg_preinst pkg_postinst pkg_postrm + ;; + *) die "EAPI=${EAPI} is not supported" ;; +esac + +# Avoid dependency loop as both depend on glib-2 +if [[ ${CATEGORY}/${P} != dev-libs/glib-2.* ]] ; then +DEPEND=" + dev-util/desktop-file-utils + x11-misc/shared-mime-info +" +fi + +# @FUNCTION: xdg_src_prepare +# @DESCRIPTION: +# Prepare sources to work with XDG standards. +xdg_src_prepare() { + xdg_environment_reset + + [[ ${EAPI:-0} != [45] ]] && default +} + +# @FUNCTION: xdg_pkg_preinst +# @DESCRIPTION: +# Finds .desktop, icon and mime info files for later handling in pkg_postinst. +# Locations are stored in XDG_ECLASS_DESKTOPFILES, XDG_ECLASS_ICONFILES +# and XDG_ECLASS_MIMEINFOFILES respectively. +xdg_pkg_preinst() { + local f + + XDG_ECLASS_DESKTOPFILES=() + while IFS= read -r -d '' f; do + XDG_ECLASS_DESKTOPFILES+=( ${f} ) + done < <(cd "${ED}" && find 'usr/share/applications' -type f -print0 2>/dev/null) + + XDG_ECLASS_ICONFILES=() + while IFS= read -r -d '' f; do + XDG_ECLASS_ICONFILES+=( ${f} ) + done < <(cd "${ED}" && find 'usr/share/icons' -type f -print0 2>/dev/null) + + XDG_ECLASS_MIMEINFOFILES=() + while IFS= read -r -d '' f; do + XDG_ECLASS_MIMEINFOFILES+=( ${f} ) + done < <(cd "${ED}" && find 'usr/share/mime' -type f -print0 2>/dev/null) +} + +# @FUNCTION: xdg_pkg_postinst +# @DESCRIPTION: +# Handle desktop, icon and mime info database updates. +xdg_pkg_postinst() { + if [[ ${#XDG_ECLASS_DESKTOPFILES[@]} -gt 0 ]]; then + xdg_desktop_database_update + else + debug-print "No .desktop files to add to database" + fi + + if [[ ${#XDG_ECLASS_ICONFILES[@]} -gt 0 ]]; then + xdg_icon_cache_update + else + debug-print "No icon files to add to cache" + fi + + if [[ ${#XDG_ECLASS_MIMEINFOFILES[@]} -gt 0 ]]; then + xdg_mimeinfo_database_update + else + debug-print "No mime info files to add to database" + fi +} + +# @FUNCTION: xdg_pkg_postrm +# @DESCRIPTION: +# Handle desktop, icon and mime info database updates. +xdg_pkg_postrm() { + if [[ ${#XDG_ECLASS_DESKTOPFILES[@]} -gt 0 ]]; then + xdg_desktop_database_update + else + debug-print "No .desktop files to add to database" + fi + + if [[ ${#XDG_ECLASS_ICONFILES[@]} -gt 0 ]]; then + xdg_icon_cache_update + else + debug-print "No icon files to add to cache" + fi + + if [[ ${#XDG_ECLASS_MIMEINFOFILES[@]} -gt 0 ]]; then + xdg_mimeinfo_database_update + else + debug-print "No mime info files to add to database" + fi +} + diff --git a/eclass/xemacs-packages.eclass b/eclass/xemacs-packages.eclass new file mode 100644 index 0000000..a40487b --- /dev/null +++ b/eclass/xemacs-packages.eclass @@ -0,0 +1,59 @@ +# Copyright 1999-2017 Gentoo Foundation +# Distributed under the terms of the GNU General Public License v2 + +# @ECLASS: xemacs-packages.eclass +# @MAINTAINER: +# xemacs@gentoo.org +# @BLURB: Eclass to support elisp packages distributed by XEmacs. +# @DESCRIPTION: +# This eclass supports ebuilds for packages distributed by XEmacs. + +# @ECLASS-VARIABLE: XEMACS_PKG_CAT +# @REQUIRED +# @DESCRIPTION: +# The package category that the package is in. Can be either standard, +# mule, or contrib. + +# @ECLASS-VARIABLE: XEMACS_EXPERIMENTAL +# @DEFAULT_UNSET +# @DESCRIPTION: +# If set then the package is downloaded from the experimental packages +# repository, which is the staging area for packages upstream. Packages +# in the experimental repository are auto-generated from XEmacs VCS, so +# they may not be well-tested. + +EXPORT_FUNCTIONS src_unpack src_install + +RDEPEND="app-editors/xemacs" +S="${WORKDIR}" + +: ${HOMEPAGE:="http://xemacs.org/"} +: ${LICENSE:="GPL-2+"} + +# Backwards compatibility code, to be removed after 2017-05-03 +: ${XEMACS_PKG_CAT:=${PKG_CAT}} +: ${XEMACS_EXPERIMENTAL:=${EXPERIMENTAL}} + +if [[ -n ${XEMACS_EXPERIMENTAL} ]]; then + : ${SRC_URI:="http://ftp.xemacs.org/pub/xemacs/beta/experimental/packages/${P}-pkg.tar.gz"} +else + : ${SRC_URI:="http://ftp.xemacs.org/pub/xemacs/packages/${P}-pkg.tar.gz"} +fi + +xemacs-packages_src_unpack() { :; } + +xemacs-packages_src_install() { + local install_dir + + case ${XEMACS_PKG_CAT} in + standard) install_dir="/usr/lib/xemacs/xemacs-packages" ;; + mule) install_dir="/usr/lib/xemacs/mule-packages" ;; + contrib) install_dir="/usr/lib/xemacs/site-packages" ;; + *) die "Unsupported package category in XEMACS_PKG_CAT (or unset)" ;; + esac + debug-print "install_dir is ${install_dir}" + + dodir "${install_dir}" + cd "${D}${EPREFIX}${install_dir}" || die + unpack ${A} +} diff --git a/eclass/xorg-2.eclass b/eclass/xorg-2.eclass new file mode 100644 index 0000000..99b1f89 --- /dev/null +++ b/eclass/xorg-2.eclass @@ -0,0 +1,559 @@ +# Copyright 1999-2021 Gentoo Authors +# Distributed under the terms of the GNU General Public License v2 + +# @ECLASS: xorg-2.eclass +# @MAINTAINER: +# x11@gentoo.org +# @AUTHOR: +# Author: Tomáš Chvátal <scarabeus@gentoo.org> +# Author: Donnie Berkholz <dberkholz@gentoo.org> +# @SUPPORTED_EAPIS: 4 5 +# @BLURB: Reduces code duplication in the modularized X11 ebuilds. +# @DESCRIPTION: +# This eclass makes trivial X ebuilds possible for apps, fonts, drivers, +# and more. Many things that would normally be done in various functions +# can be accessed by setting variables instead, such as patching, +# running eautoreconf, passing options to configure and installing docs. +# +# All you need to do in a basic ebuild is inherit this eclass and set +# DESCRIPTION, KEYWORDS and RDEPEND/DEPEND. If your package is hosted +# with the other X packages, you don't need to set SRC_URI. Pretty much +# everything else should be automatic. + +GIT_ECLASS="" +if [[ ${PV} == *9999* ]]; then + GIT_ECLASS="git-r3" + XORG_EAUTORECONF="yes" +fi + +# If we're a font package, but not the font.alias one +FONT_ECLASS="" +if [[ ${CATEGORY} = media-fonts ]]; then + case ${PN} in + font-alias|font-util) + ;; + font*) + # Activate font code in the rest of the eclass + FONT="yes" + FONT_ECLASS="font" + ;; + esac +fi + +# @ECLASS-VARIABLE: XORG_MULTILIB +# @DESCRIPTION: +# If set to 'yes', the multilib support for package will be enabled. Set +# before inheriting this eclass. +: ${XORG_MULTILIB:="no"} + +# we need to inherit autotools first to get the deps +inherit autotools autotools-utils eutils libtool multilib toolchain-funcs \ + flag-o-matic ${FONT_ECLASS} ${GIT_ECLASS} + +if [[ ${XORG_MULTILIB} == yes ]]; then + inherit autotools-multilib +fi + +EXPORTED_FUNCTIONS="src_unpack src_compile src_install pkg_postinst pkg_postrm" +case "${EAPI:-0}" in + 4|5) EXPORTED_FUNCTIONS="${EXPORTED_FUNCTIONS} src_prepare src_configure" ;; + *) die "EAPI=${EAPI} is not supported" ;; +esac + +# exports must be ALWAYS after inherit +EXPORT_FUNCTIONS ${EXPORTED_FUNCTIONS} + +IUSE="" + +# @ECLASS-VARIABLE: XORG_EAUTORECONF +# @DESCRIPTION: +# If set to 'yes' and configure.ac exists, eautoreconf will run. Set +# before inheriting this eclass. +: ${XORG_EAUTORECONF:="no"} + +# @ECLASS-VARIABLE: XORG_BASE_INDIVIDUAL_URI +# @DESCRIPTION: +# Set up SRC_URI for individual modular releases. If set to an empty +# string, no SRC_URI will be provided by the eclass. +: ${XORG_BASE_INDIVIDUAL_URI="https://www.x.org/releases/individual"} + +# @ECLASS-VARIABLE: XORG_MODULE +# @DESCRIPTION: +# The subdirectory to download source from. Possible settings are app, +# doc, data, util, driver, font, lib, proto, xserver. Set above the +# inherit to override the default autoconfigured module. +: ${XORG_MODULE:="auto"} +if [[ ${XORG_MODULE} == auto ]]; then + case ${CATEGORY} in + app-doc) XORG_MODULE=doc/ ;; + media-fonts) XORG_MODULE=font/ ;; + x11-apps|x11-wm) XORG_MODULE=app/ ;; + x11-misc|x11-themes) XORG_MODULE=util/ ;; + x11-base) XORG_MODULE=xserver/ ;; + x11-drivers) XORG_MODULE=driver/ ;; + x11-libs) XORG_MODULE=lib/ ;; + *) XORG_MODULE= ;; + esac +fi + +# @ECLASS-VARIABLE: XORG_PACKAGE_NAME +# @DESCRIPTION: +# For git checkout the git repository might differ from package name. +# This variable can be used for proper directory specification +: ${XORG_PACKAGE_NAME:=${PN}} + +HOMEPAGE="https://www.x.org/wiki/ https://gitlab.freedesktop.org/xorg/${XORG_MODULE}${XORG_PACKAGE_NAME}" + +if [[ -n ${GIT_ECLASS} ]]; then + : ${EGIT_REPO_URI:="https://gitlab.freedesktop.org/xorg/${XORG_MODULE}${XORG_PACKAGE_NAME}.git"} +elif [[ -n ${XORG_BASE_INDIVIDUAL_URI} ]]; then + SRC_URI="${XORG_BASE_INDIVIDUAL_URI}/${XORG_MODULE}${P}.tar.bz2" +fi + +: ${SLOT:=0} + +# Set the license for the package. This can be overridden by setting +# LICENSE after the inherit. Nearly all FreeDesktop-hosted X packages +# are under the MIT license. (This is what Red Hat does in their rpms) +: ${LICENSE:=MIT} + +# Set up autotools shared dependencies +# Remember that all versions here MUST be stable +XORG_EAUTORECONF_ARCHES="x86-winnt" +EAUTORECONF_DEPEND+=" + >=sys-devel/libtool-2.2.6a + sys-devel/m4" +if [[ ${PN} != util-macros ]] ; then + EAUTORECONF_DEPEND+=" >=x11-misc/util-macros-1.18" + # Required even by xorg-server + [[ ${PN} == "font-util" ]] || EAUTORECONF_DEPEND+=" >=media-fonts/font-util-1.2.0" +fi +WANT_AUTOCONF="latest" +WANT_AUTOMAKE="latest" +for arch in ${XORG_EAUTORECONF_ARCHES}; do + EAUTORECONF_DEPENDS+=" ${arch}? ( ${EAUTORECONF_DEPEND} )" +done +DEPEND+=" ${EAUTORECONF_DEPENDS}" +[[ ${XORG_EAUTORECONF} != no ]] && DEPEND+=" ${EAUTORECONF_DEPEND}" +unset EAUTORECONF_DEPENDS +unset EAUTORECONF_DEPEND + +if [[ ${FONT} == yes ]]; then + RDEPEND+=" media-fonts/encodings + >=x11-apps/mkfontscale-1.2.0" + PDEPEND+=" media-fonts/font-alias" + DEPEND+=" >=media-fonts/font-util-1.2.0 + >=x11-apps/mkfontscale-1.2.0" + + # @ECLASS-VARIABLE: FONT_DIR + # @DESCRIPTION: + # If you're creating a font package and the suffix of PN is not equal to + # the subdirectory of /usr/share/fonts/ it should install into, set + # FONT_DIR to that directory or directories. Set before inheriting this + # eclass. + [[ -z ${FONT_DIR} ]] && FONT_DIR=${PN##*-} + + # Fix case of font directories + FONT_DIR=${FONT_DIR/ttf/TTF} + FONT_DIR=${FONT_DIR/otf/OTF} + FONT_DIR=${FONT_DIR/type1/Type1} + FONT_DIR=${FONT_DIR/speedo/Speedo} + + # Set up configure options, wrapped so ebuilds can override if need be + [[ -z ${FONT_OPTIONS} ]] && FONT_OPTIONS="--with-fontdir=\"${EPREFIX}/usr/share/fonts/${FONT_DIR}\"" + + [[ ${PN} = font-misc-misc || ${PN} = font-schumacher-misc || ${PN##*-} = 75dpi || ${PN##*-} = 100dpi || ${PN##*-} = cyrillic ]] && IUSE+=" nls" +fi + +# If we're a driver package, then enable DRIVER case +[[ ${PN} == xf86-video-* || ${PN} == xf86-input-* ]] && DRIVER="yes" + +DEPEND+=" virtual/pkgconfig" + +# @ECLASS-VARIABLE: XORG_DRI +# @DESCRIPTION: +# Possible values are "always" or the value of the useflag DRI capabilities +# are required for. Default value is "no" +# +# Eg. XORG_DRI="opengl" will pull all dri dependant deps for opengl useflag +: ${XORG_DRI:="no"} + +DRI_COMMON_DEPEND=" + x11-base/xorg-server[-minimal] + x11-libs/libdrm +" +case ${XORG_DRI} in + no) + ;; + always) + COMMON_DEPEND+=" ${DRI_COMMON_DEPEND}" + ;; + *) + COMMON_DEPEND+=" ${XORG_DRI}? ( ${DRI_COMMON_DEPEND} )" + IUSE+=" ${XORG_DRI}" + ;; +esac +unset DRI_COMMON_DEPEND + +if [[ -n "${DRIVER}" ]]; then + COMMON_DEPEND+=" + x11-base/xorg-server[xorg] + " +fi +if [[ -n "${DRIVER}" && ${PN} == xf86-input-* ]]; then + DEPEND+=" x11-base/xorg-proto" +fi +if [[ -n "${DRIVER}" && ${PN} == xf86-video-* ]]; then + COMMON_DEPEND+=" + x11-libs/libpciaccess + " + DEPEND+=" x11-base/xorg-proto" +fi + +# @ECLASS-VARIABLE: XORG_DOC +# @DESCRIPTION: +# Possible values are "always" or the value of the useflag doc packages +# are required for. Default value is "no" +# +# Eg. XORG_DOC="manual" will pull all doc dependant deps for manual useflag +: ${XORG_DOC:="no"} + +DOC_DEPEND=" + doc? ( + || ( app-text/asciidoc dev-ruby/asciidoctor ) + app-text/xmlto + app-doc/doxygen + app-text/docbook-xml-dtd:4.1.2 + app-text/docbook-xml-dtd:4.2 + app-text/docbook-xml-dtd:4.3 + ) +" +case ${XORG_DOC} in + no) + ;; + always) + DEPEND+=" ${DOC_DEPEND}" + ;; + *) + DEPEND+=" ${XORG_DOC}? ( ${DOC_DEPEND} )" + IUSE+=" ${XORG_DOC}" + ;; +esac +unset DOC_DEPEND + +if [[ ${DRIVER} == yes ]]; then + case ${EAPI} in + 4) + ;; + *) + RDEPEND+=" x11-base/xorg-server:=" + ;; + esac +fi + +DEPEND+=" ${COMMON_DEPEND}" +RDEPEND+=" ${COMMON_DEPEND}" +unset COMMON_DEPEND + +debug-print "${LINENO} ${ECLASS} ${FUNCNAME}: DEPEND=${DEPEND}" +debug-print "${LINENO} ${ECLASS} ${FUNCNAME}: RDEPEND=${RDEPEND}" +debug-print "${LINENO} ${ECLASS} ${FUNCNAME}: PDEPEND=${PDEPEND}" + +# @FUNCTION: xorg-2_pkg_setup +# @DESCRIPTION: +# Setup prefix compat +xorg-2_pkg_setup() { + debug-print-function ${FUNCNAME} "$@" + + [[ ${FONT} == yes ]] && font_pkg_setup "$@" +} + +# @FUNCTION: xorg-2_src_unpack +# @DESCRIPTION: +# Simply unpack source code. +xorg-2_src_unpack() { + debug-print-function ${FUNCNAME} "$@" + + if [[ -n ${GIT_ECLASS} ]]; then + git-r3_src_unpack + else + unpack ${A} + fi + + [[ -n ${FONT_OPTIONS} ]] && einfo "Detected font directory: ${FONT_DIR}" +} + +# @FUNCTION: xorg-2_patch_source +# @DESCRIPTION: +# Apply all patches +xorg-2_patch_source() { + debug-print-function ${FUNCNAME} "$@" + + # Use standardized names and locations with bulk patching + # Patch directory is ${WORKDIR}/patch + # See epatch() in eutils.eclass for more documentation + EPATCH_SUFFIX=${EPATCH_SUFFIX:=patch} + + [[ -d "${EPATCH_SOURCE}" ]] && epatch +} + +# @FUNCTION: xorg-2_reconf_source +# @DESCRIPTION: +# Run eautoreconf if necessary, and run elibtoolize. +xorg-2_reconf_source() { + debug-print-function ${FUNCNAME} "$@" + + case ${CHOST} in + *-aix* | *-winnt*) + # some hosts need full eautoreconf + [[ -e "./configure.ac" || -e "./configure.in" ]] \ + && AUTOTOOLS_AUTORECONF=1 + ;; + *) + # elibtoolize required for BSD + [[ ${XORG_EAUTORECONF} != no && ( -e "./configure.ac" || -e "./configure.in" ) ]] \ + && AUTOTOOLS_AUTORECONF=1 + ;; + esac +} + +# @FUNCTION: xorg-2_src_prepare +# @DESCRIPTION: +# Prepare a package after unpacking, performing all X-related tasks. +xorg-2_src_prepare() { + debug-print-function ${FUNCNAME} "$@" + + xorg-2_patch_source + xorg-2_reconf_source + autotools-utils_src_prepare "$@" +} + +# @FUNCTION: xorg-2_font_configure +# @DESCRIPTION: +# If a font package, perform any necessary configuration steps +xorg-2_font_configure() { + debug-print-function ${FUNCNAME} "$@" + + if has nls ${IUSE//+} && ! use nls; then + if grep -q -s "disable-all-encodings" ${ECONF_SOURCE:-.}/configure; then + FONT_OPTIONS+=" + --disable-all-encodings + --enable-iso8859-1" + else + FONT_OPTIONS+=" + --disable-iso8859-2 + --disable-iso8859-3 + --disable-iso8859-4 + --disable-iso8859-5 + --disable-iso8859-6 + --disable-iso8859-7 + --disable-iso8859-8 + --disable-iso8859-9 + --disable-iso8859-10 + --disable-iso8859-11 + --disable-iso8859-12 + --disable-iso8859-13 + --disable-iso8859-14 + --disable-iso8859-15 + --disable-iso8859-16 + --disable-jisx0201 + --disable-koi8-r" + fi + fi +} + +# @FUNCTION: xorg-2_flags_setup +# @DESCRIPTION: +# Set up CFLAGS for a debug build +xorg-2_flags_setup() { + debug-print-function ${FUNCNAME} "$@" + + # Win32 require special define + [[ ${CHOST} == *-winnt* ]] && append-cppflags -DWIN32 -D__STDC__ + # hardened ldflags + [[ ${PN} = xorg-server || -n ${DRIVER} ]] && append-ldflags -Wl,-z,lazy + + # Quite few libraries fail on runtime without these: + if has static-libs ${IUSE//+}; then + filter-flags -Wl,-Bdirect + filter-ldflags -Bdirect + filter-ldflags -Wl,-Bdirect + fi +} + +# @FUNCTION: xorg-2_src_configure +# @DESCRIPTION: +# Perform any necessary pre-configuration steps, then run configure +xorg-2_src_configure() { + debug-print-function ${FUNCNAME} "$@" + + xorg-2_flags_setup + + # @VARIABLE: XORG_CONFIGURE_OPTIONS + # @DESCRIPTION: + # Array of an additional options to pass to configure. + # @DEFAULT_UNSET + if [[ $(declare -p XORG_CONFIGURE_OPTIONS 2>&-) != "declare -a"* ]]; then + # fallback to CONFIGURE_OPTIONS, deprecated. + if [[ -n "${CONFIGURE_OPTIONS}" ]]; then + eqawarn "CONFIGURE_OPTIONS are deprecated. Please migrate to XORG_CONFIGURE_OPTIONS" + eqawarn "to preserve namespace." + fi + + local xorgconfadd=(${CONFIGURE_OPTIONS} ${XORG_CONFIGURE_OPTIONS}) + else + local xorgconfadd=("${XORG_CONFIGURE_OPTIONS[@]}") + fi + + [[ -n "${FONT}" ]] && xorg-2_font_configure + + # Check if package supports disabling of dep tracking + # Fixes warnings like: + # WARNING: unrecognized options: --disable-dependency-tracking + if grep -q -s "disable-depencency-tracking" ${ECONF_SOURCE:-.}/configure; then + local dep_track="--disable-dependency-tracking" + fi + + # Check if package supports disabling of selective -Werror=... + if grep -q -s "disable-selective-werror" ${ECONF_SOURCE:-.}/configure; then + local selective_werror="--disable-selective-werror" + fi + + # Check if package supports disabling of static libraries + if grep -q -s "able-static" ${ECONF_SOURCE:-.}/configure; then + local no_static="--disable-static" + fi + + local myeconfargs=( + ${dep_track} + ${selective_werror} + ${no_static} + ${FONT_OPTIONS} + "${xorgconfadd[@]}" + ) + + if [[ ${XORG_MULTILIB} == yes ]]; then + autotools-multilib_src_configure "$@" + else + autotools-utils_src_configure "$@" + fi +} + +# @FUNCTION: xorg-2_src_compile +# @DESCRIPTION: +# Compile a package, performing all X-related tasks. +xorg-2_src_compile() { + debug-print-function ${FUNCNAME} "$@" + + if [[ ${XORG_MULTILIB} == yes ]]; then + autotools-multilib_src_compile "$@" + else + autotools-utils_src_compile "$@" + fi +} + +# @FUNCTION: xorg-2_src_install +# @DESCRIPTION: +# Install a built package to ${D}, performing any necessary steps. +# Creates a ChangeLog from git if using live ebuilds. +xorg-2_src_install() { + debug-print-function ${FUNCNAME} "$@" + + local install_args=( docdir="${EPREFIX}/usr/share/doc/${PF}" ) + + if [[ ${XORG_MULTILIB} == yes ]]; then + autotools-multilib_src_install "${install_args[@]}" + else + autotools-utils_src_install "${install_args[@]}" + fi + + if [[ -n ${GIT_ECLASS} ]]; then + pushd "${EGIT_STORE_DIR}/${EGIT_CLONE_DIR}" > /dev/null || die + git log ${EGIT_COMMIT} > "${S}"/ChangeLog + popd > /dev/null || die + fi + + if [[ -e "${S}"/ChangeLog ]]; then + dodoc "${S}"/ChangeLog || die "dodoc failed" + fi + + # Don't install libtool archives (even for modules) + find "${D}" -type f -name '*.la' -delete || die + + [[ -n ${FONT} ]] && remove_font_metadata +} + +# @FUNCTION: xorg-2_pkg_postinst +# @DESCRIPTION: +# Run X-specific post-installation tasks on the live filesystem. The +# only task right now is some setup for font packages. +xorg-2_pkg_postinst() { + debug-print-function ${FUNCNAME} "$@" + + if [[ -n ${FONT} ]]; then + create_fonts_scale + create_fonts_dir + font_pkg_postinst "$@" + + ewarn "Installed fonts changed. Run 'xset fp rehash' if you are using non-fontconfig applications." + fi +} + +# @FUNCTION: xorg-2_pkg_postrm +# @DESCRIPTION: +# Run X-specific post-removal tasks on the live filesystem. The only +# task right now is some cleanup for font packages. +xorg-2_pkg_postrm() { + debug-print-function ${FUNCNAME} "$@" + + if [[ -n ${FONT} ]]; then + # if we're doing an upgrade, postinst will do + if [[ -z ${REPLACED_BY_VERSION} ]]; then + create_fonts_scale + create_fonts_dir + font_pkg_postrm "$@" + fi + fi +} + +# @FUNCTION: remove_font_metadata +# @DESCRIPTION: +# Don't let the package install generated font files that may overlap +# with other packages. Instead, they're generated in pkg_postinst(). +remove_font_metadata() { + debug-print-function ${FUNCNAME} "$@" + + if [[ ${FONT_DIR} != Speedo && ${FONT_DIR} != CID ]]; then + einfo "Removing font metadata" + rm -rf "${ED}"/usr/share/fonts/${FONT_DIR}/fonts.{scale,dir,cache-1} + fi +} + +# @FUNCTION: create_fonts_scale +# @DESCRIPTION: +# Create fonts.scale file, used by the old server-side fonts subsystem. +create_fonts_scale() { + debug-print-function ${FUNCNAME} "$@" + + if [[ ${FONT_DIR} != Speedo && ${FONT_DIR} != CID ]]; then + ebegin "Generating fonts.scale" + mkfontscale \ + -a "${EROOT}/usr/share/fonts/encodings/encodings.dir" \ + -- "${EROOT}/usr/share/fonts/${FONT_DIR}" + eend $? + fi +} + +# @FUNCTION: create_fonts_dir +# @DESCRIPTION: +# Create fonts.dir file, used by the old server-side fonts subsystem. +create_fonts_dir() { + debug-print-function ${FUNCNAME} "$@" + + ebegin "Generating fonts.dir" + mkfontdir \ + -e "${EROOT}"/usr/share/fonts/encodings \ + -e "${EROOT}"/usr/share/fonts/encodings/large \ + -- "${EROOT}/usr/share/fonts/${FONT_DIR}" + eend $? +} diff --git a/eclass/xorg-3.eclass b/eclass/xorg-3.eclass new file mode 100644 index 0000000..811168e --- /dev/null +++ b/eclass/xorg-3.eclass @@ -0,0 +1,525 @@ +# Copyright 1999-2020 Gentoo Authors +# Distributed under the terms of the GNU General Public License v2 + +# @ECLASS: xorg-3.eclass +# @MAINTAINER: +# x11@gentoo.org +# @AUTHOR: +# Author: Tomáš Chvátal <scarabeus@gentoo.org> +# Author: Donnie Berkholz <dberkholz@gentoo.org> +# Author: Matt Turner <mattst88@gentoo.org> +# @SUPPORTED_EAPIS: 7 +# @BLURB: Reduces code duplication in the modularized X11 ebuilds. +# @DESCRIPTION: +# This eclass makes trivial X ebuilds possible for apps, drivers, +# and more. Many things that would normally be done in various functions +# can be accessed by setting variables instead, such as patching, +# running eautoreconf, passing options to configure and installing docs. +# +# All you need to do in a basic ebuild is inherit this eclass and set +# DESCRIPTION, KEYWORDS and RDEPEND/DEPEND. If your package is hosted +# with the other X packages, you don't need to set SRC_URI. Pretty much +# everything else should be automatic. + +GIT_ECLASS="" +if [[ ${PV} == *9999* ]]; then + GIT_ECLASS="git-r3" + XORG_EAUTORECONF="yes" +fi + +# If we're a font package, but not the font.alias one +FONT_ECLASS="" +if [[ ${CATEGORY} = media-fonts ]]; then + case ${PN} in + font-alias|font-util) + ;; + font*) + # Activate font code in the rest of the eclass + FONT="yes" + FONT_ECLASS="font" + ;; + esac +fi + +# @ECLASS-VARIABLE: XORG_MULTILIB +# @DESCRIPTION: +# If set to 'yes', the multilib support for package will be enabled. Set +# before inheriting this eclass. +: ${XORG_MULTILIB:="no"} + +# we need to inherit autotools first to get the deps +inherit autotools libtool multilib toolchain-funcs flag-o-matic \ + ${FONT_ECLASS} ${GIT_ECLASS} + +if [[ ${XORG_MULTILIB} == yes ]]; then + inherit multilib-minimal +fi + +EXPORTED_FUNCTIONS="src_prepare src_configure src_unpack src_compile src_install pkg_postinst pkg_postrm" +case "${EAPI:-0}" in + 7) ;; + *) die "EAPI=${EAPI} is not supported" ;; +esac + +# exports must be ALWAYS after inherit +EXPORT_FUNCTIONS ${EXPORTED_FUNCTIONS} + +IUSE="" + +# @ECLASS-VARIABLE: XORG_EAUTORECONF +# @DESCRIPTION: +# If set to 'yes' and configure.ac exists, eautoreconf will run. Set +# before inheriting this eclass. +: ${XORG_EAUTORECONF:="no"} + +# @ECLASS-VARIABLE: XORG_BASE_INDIVIDUAL_URI +# @DESCRIPTION: +# Set up SRC_URI for individual modular releases. If set to an empty +# string, no SRC_URI will be provided by the eclass. +: ${XORG_BASE_INDIVIDUAL_URI="https://www.x.org/releases/individual"} + +# @ECLASS-VARIABLE: XORG_MODULE +# @DESCRIPTION: +# The subdirectory to download source from. Possible settings are app, +# doc, data, util, driver, font, lib, proto, xserver. Set above the +# inherit to override the default autoconfigured module. +: ${XORG_MODULE:="auto"} +if [[ ${XORG_MODULE} == auto ]]; then + case "${CATEGORY}/${P}" in + app-doc/*) XORG_MODULE=doc/ ;; + media-fonts/*) XORG_MODULE=font/ ;; + x11-apps/*|x11-wm/*) XORG_MODULE=app/ ;; + x11-misc/*|x11-themes/*) XORG_MODULE=util/ ;; + x11-base/*) XORG_MODULE=xserver/ ;; + x11-drivers/*) XORG_MODULE=driver/ ;; + x11-libs/xcb-util-*) XORG_MODULE=xcb/ ;; + x11-libs/*) XORG_MODULE=lib/ ;; + *) XORG_MODULE= ;; + esac +fi + +# @ECLASS-VARIABLE: XORG_PACKAGE_NAME +# @DESCRIPTION: +# For git checkout the git repository might differ from package name. +# This variable can be used for proper directory specification +: ${XORG_PACKAGE_NAME:=${PN}} + +HOMEPAGE="https://www.x.org/wiki/ https://gitlab.freedesktop.org/xorg/${XORG_MODULE}${XORG_PACKAGE_NAME}" + +# @ECLASS-VARIABLE: XORG_TARBALL_SUFFIX +# @DESCRIPTION: +# Most X11 projects provide tarballs as tar.bz2 or tar.xz. This eclass defaults +# to bz2. +: ${XORG_TARBALL_SUFFIX:="bz2"} + +if [[ -n ${GIT_ECLASS} ]]; then + : ${EGIT_REPO_URI:="https://gitlab.freedesktop.org/xorg/${XORG_MODULE}${XORG_PACKAGE_NAME}.git"} +elif [[ -n ${XORG_BASE_INDIVIDUAL_URI} ]]; then + SRC_URI="${XORG_BASE_INDIVIDUAL_URI}/${XORG_MODULE}${P}.tar.${XORG_TARBALL_SUFFIX}" +fi + +: ${SLOT:=0} + +# Set the license for the package. This can be overridden by setting +# LICENSE after the inherit. Nearly all FreeDesktop-hosted X packages +# are under the MIT license. (This is what Red Hat does in their rpms) +: ${LICENSE:=MIT} + +# Set up autotools shared dependencies +# Remember that all versions here MUST be stable +XORG_EAUTORECONF_ARCHES="x86-winnt" +EAUTORECONF_DEPEND+=" + >=sys-devel/libtool-2.2.6a + sys-devel/m4" +if [[ ${PN} != util-macros ]] ; then + EAUTORECONF_DEPEND+=" >=x11-misc/util-macros-1.18" + # Required even by xorg-server + [[ ${PN} == "font-util" ]] || EAUTORECONF_DEPEND+=" >=media-fonts/font-util-1.2.0" +fi +WANT_AUTOCONF="latest" +WANT_AUTOMAKE="latest" +for arch in ${XORG_EAUTORECONF_ARCHES}; do + EAUTORECONF_DEPENDS+=" ${arch}? ( ${EAUTORECONF_DEPEND} )" +done +unset arch +BDEPEND+=" ${EAUTORECONF_DEPENDS}" +[[ ${XORG_EAUTORECONF} != no ]] && BDEPEND+=" ${EAUTORECONF_DEPEND}" +unset EAUTORECONF_DEPENDS +unset EAUTORECONF_DEPEND + +if [[ ${FONT} == yes ]]; then + RDEPEND+=" media-fonts/encodings + >=x11-apps/mkfontscale-1.2.0" + PDEPEND+=" media-fonts/font-alias" + DEPEND+=" >=media-fonts/font-util-1.2.0 + >=x11-apps/mkfontscale-1.2.0" + BDEPEND+=" x11-apps/bdftopcf" + + # @ECLASS-VARIABLE: FONT_DIR + # @DESCRIPTION: + # If you're creating a font package and the suffix of PN is not equal to + # the subdirectory of /usr/share/fonts/ it should install into, set + # FONT_DIR to that directory or directories. Set before inheriting this + # eclass. + [[ -z ${FONT_DIR} ]] && FONT_DIR=${PN##*-} + + # Fix case of font directories + FONT_DIR=${FONT_DIR/ttf/TTF} + FONT_DIR=${FONT_DIR/otf/OTF} + FONT_DIR=${FONT_DIR/type1/Type1} + FONT_DIR=${FONT_DIR/speedo/Speedo} +fi +BDEPEND+=" virtual/pkgconfig" + +# @ECLASS-VARIABLE: XORG_DRI +# @DESCRIPTION: +# Possible values are "always" or the value of the useflag DRI capabilities +# are required for. Default value is "no" +# +# Eg. XORG_DRI="opengl" will pull all dri dependent deps for opengl useflag +: ${XORG_DRI:="no"} + +DRI_COMMON_DEPEND=" + x11-base/xorg-server[-minimal] + x11-libs/libdrm +" +case ${XORG_DRI} in + no) + ;; + always) + COMMON_DEPEND+=" ${DRI_COMMON_DEPEND}" + ;; + *) + COMMON_DEPEND+=" ${XORG_DRI}? ( ${DRI_COMMON_DEPEND} )" + IUSE+=" ${XORG_DRI}" + ;; +esac +unset DRI_COMMON_DEPEND + +if [[ ${PN} == xf86-video-* || ${PN} == xf86-input-* ]]; then + DEPEND+=" x11-base/xorg-proto" + RDEPEND+=" x11-base/xorg-server:=" + COMMON_DEPEND+=" >=x11-base/xorg-server-1.20[xorg]" + [[ ${PN} == xf86-video-* ]] && COMMON_DEPEND+=" >=x11-libs/libpciaccess-0.14" +fi + + +# @ECLASS-VARIABLE: XORG_DOC +# @DESCRIPTION: +# Possible values are "always" or the value of the useflag doc packages +# are required for. Default value is "no" +# +# Eg. XORG_DOC="manual" will pull all doc dependent deps for manual useflag +: ${XORG_DOC:="no"} + +DOC_DEPEND=" + doc? ( + || ( app-text/asciidoc dev-ruby/asciidoctor ) + app-text/xmlto + app-doc/doxygen + app-text/docbook-xml-dtd:4.1.2 + app-text/docbook-xml-dtd:4.2 + app-text/docbook-xml-dtd:4.3 + ) +" +case ${XORG_DOC} in + no) + ;; + always) + BDEPEND+=" ${DOC_DEPEND}" + ;; + *) + BDEPEND+=" ${XORG_DOC}? ( ${DOC_DEPEND} )" + IUSE+=" ${XORG_DOC}" + ;; +esac +unset DOC_DEPEND + +DEPEND+=" ${COMMON_DEPEND}" +RDEPEND+=" ${COMMON_DEPEND}" +unset COMMON_DEPEND + +debug-print "${LINENO} ${ECLASS} ${FUNCNAME}: DEPEND=${DEPEND}" +debug-print "${LINENO} ${ECLASS} ${FUNCNAME}: RDEPEND=${RDEPEND}" +debug-print "${LINENO} ${ECLASS} ${FUNCNAME}: PDEPEND=${PDEPEND}" +debug-print "${LINENO} ${ECLASS} ${FUNCNAME}: BDEPEND=${BDEPEND}" + +# @FUNCTION: xorg-3_pkg_setup +# @DESCRIPTION: +# Setup prefix compat +xorg-3_pkg_setup() { + debug-print-function ${FUNCNAME} "$@" + + [[ ${FONT} == yes ]] && font_pkg_setup "$@" +} + +# @FUNCTION: xorg-3_src_unpack +# @DESCRIPTION: +# Simply unpack source code. +xorg-3_src_unpack() { + debug-print-function ${FUNCNAME} "$@" + + if [[ -n ${GIT_ECLASS} ]]; then + git-r3_src_unpack + else + unpack ${A} + fi + + [[ -n ${FONT_OPTIONS} ]] && einfo "Detected font directory: ${FONT_DIR}" +} + +# @FUNCTION: xorg-3_reconf_source +# @DESCRIPTION: +# Run eautoreconf if necessary, and run elibtoolize. +xorg-3_reconf_source() { + debug-print-function ${FUNCNAME} "$@" + + case ${CHOST} in + *-aix* | *-winnt*) + # some hosts need full eautoreconf + [[ -e "./configure.ac" || -e "./configure.in" ]] \ + && XORG_EAUTORECONF=yes + ;; + *) + # elibtoolize required for BSD + [[ ${XORG_EAUTORECONF} != no && ( -e "./configure.ac" || -e "./configure.in" ) ]] \ + && XORG_EAUTORECONF=yes + ;; + esac + + [[ ${XORG_EAUTORECONF} != no ]] && eautoreconf + elibtoolize --patch-only +} + +# @FUNCTION: xorg-3_src_prepare +# @DESCRIPTION: +# Prepare a package after unpacking, performing all X-related tasks. +xorg-3_src_prepare() { + debug-print-function ${FUNCNAME} "$@" + + default + xorg-3_reconf_source +} + +# @FUNCTION: xorg-3_font_configure +# @DESCRIPTION: +# If a font package, perform any necessary configuration steps +xorg-3_font_configure() { + debug-print-function ${FUNCNAME} "$@" + + if has nls ${IUSE//+} && ! use nls; then + if ! grep -q -s "disable-all-encodings" ${ECONF_SOURCE:-.}/configure; then + die "--disable-all-encodings option not available in configure" + fi + FONT_OPTIONS+=" + --disable-all-encodings + --enable-iso8859-1" + fi +} + +# @FUNCTION: xorg-3_flags_setup +# @DESCRIPTION: +# Set up CFLAGS for a debug build +xorg-3_flags_setup() { + debug-print-function ${FUNCNAME} "$@" + + # Win32 require special define + [[ ${CHOST} == *-winnt* ]] && append-cppflags -DWIN32 -D__STDC__ + # hardened ldflags + [[ ${PN} == xorg-server || ${PN} == xf86-video-* || ${PN} == xf86-input-* ]] \ + && append-ldflags -Wl,-z,lazy + + # Quite few libraries fail on runtime without these: + if has static-libs ${IUSE//+}; then + filter-flags -Wl,-Bdirect + filter-ldflags -Bdirect + filter-ldflags -Wl,-Bdirect + fi +} + +multilib_src_configure() { + ECONF_SOURCE="${S}" econf "${econfargs[@]}" +} + +# @FUNCTION: xorg-3_src_configure +# @DESCRIPTION: +# Perform any necessary pre-configuration steps, then run configure +xorg-3_src_configure() { + debug-print-function ${FUNCNAME} "$@" + + xorg-3_flags_setup + + # @VARIABLE: XORG_CONFIGURE_OPTIONS + # @DESCRIPTION: + # Array of an additional options to pass to configure. + # @DEFAULT_UNSET + local xorgconfadd=("${XORG_CONFIGURE_OPTIONS[@]}") + + [[ -n "${FONT}" ]] && xorg-3_font_configure + + # Check if package supports disabling of dep tracking + # Fixes warnings like: + # WARNING: unrecognized options: --disable-dependency-tracking + if grep -q -s "disable-depencency-tracking" ${ECONF_SOURCE:-.}/configure; then + local dep_track="--disable-dependency-tracking" + fi + + # Check if package supports disabling of selective -Werror=... + if grep -q -s "disable-selective-werror" ${ECONF_SOURCE:-.}/configure; then + local selective_werror="--disable-selective-werror" + fi + + # Check if package supports disabling of static libraries + if grep -q -s "able-static" ${ECONF_SOURCE:-.}/configure; then + local no_static="--disable-static" + fi + + local econfargs=( + ${dep_track} + ${selective_werror} + ${no_static} + ${FONT_OPTIONS} + "${xorgconfadd[@]}" + ) + + # Handle static-libs found in IUSE, disable them by default + if in_iuse static-libs; then + econfargs+=( + --enable-shared + $(use_enable static-libs static) + ) + fi + + if [[ ${XORG_MULTILIB} == yes ]]; then + multilib-minimal_src_configure "$@" + else + econf "${econfargs[@]}" "$@" + fi +} + +multilib_src_compile() { + emake "$@" || die 'emake failed' +} + +# @FUNCTION: xorg-3_src_compile +# @DESCRIPTION: +# Compile a package, performing all X-related tasks. +xorg-3_src_compile() { + debug-print-function ${FUNCNAME} "$@" + + if [[ ${XORG_MULTILIB} == yes ]]; then + multilib-minimal_src_compile "$@" + else + emake "$@" || die 'emake failed' + fi +} + +multilib_src_install() { + emake DESTDIR="${D}" "${install_args[@]}" "$@" install || die "emake install failed" +} + +# @FUNCTION: xorg-3_src_install +# @DESCRIPTION: +# Install a built package to ${D}, performing any necessary steps. +xorg-3_src_install() { + debug-print-function ${FUNCNAME} "$@" + + local install_args=( docdir="${EPREFIX}/usr/share/doc/${PF}" ) + + if [[ ${XORG_MULTILIB} == yes ]]; then + multilib-minimal_src_install "$@" + else + emake DESTDIR="${D}" "${install_args[@]}" "$@" install || die "emake install failed" + einstalldocs + fi + + # Many X11 libraries unconditionally install developer documentation + if [[ -d "${D}"/usr/share/man/man3 ]]; then + ! in_iuse doc && eqawarn "ebuild should set XORG_DOC=doc since package installs library documentation" + fi + + if in_iuse doc && ! use doc; then + rm -rf "${D}"/usr/share/man/man3 + rmdir "${D}"/usr{/share{/man,},} 2>/dev/null + fi + + # Don't install libtool archives (even for modules) + find "${D}" -type f -name '*.la' -delete || die + + [[ -n ${FONT} ]] && remove_font_metadata +} + +# @FUNCTION: xorg-3_pkg_postinst +# @DESCRIPTION: +# Run X-specific post-installation tasks on the live filesystem. The +# only task right now is some setup for font packages. +xorg-3_pkg_postinst() { + debug-print-function ${FUNCNAME} "$@" + + if [[ -n ${FONT} ]]; then + create_fonts_scale + create_fonts_dir + font_pkg_postinst "$@" + + ewarn "Installed fonts changed. Run 'xset fp rehash' if you are using non-fontconfig applications." + fi +} + +# @FUNCTION: xorg-3_pkg_postrm +# @DESCRIPTION: +# Run X-specific post-removal tasks on the live filesystem. The only +# task right now is some cleanup for font packages. +xorg-3_pkg_postrm() { + debug-print-function ${FUNCNAME} "$@" + + if [[ -n ${FONT} ]]; then + # if we're doing an upgrade, postinst will do + if [[ -z ${REPLACED_BY_VERSION} ]]; then + create_fonts_scale + create_fonts_dir + font_pkg_postrm "$@" + fi + fi +} + +# @FUNCTION: remove_font_metadata +# @DESCRIPTION: +# Don't let the package install generated font files that may overlap +# with other packages. Instead, they're generated in pkg_postinst(). +remove_font_metadata() { + debug-print-function ${FUNCNAME} "$@" + + if [[ ${FONT_DIR} != Speedo && ${FONT_DIR} != CID ]]; then + einfo "Removing font metadata" + rm -rf "${ED}"/usr/share/fonts/${FONT_DIR}/fonts.{scale,dir,cache-1} + fi +} + +# @FUNCTION: create_fonts_scale +# @DESCRIPTION: +# Create fonts.scale file, used by the old server-side fonts subsystem. +create_fonts_scale() { + debug-print-function ${FUNCNAME} "$@" + + if [[ ${FONT_DIR} != Speedo && ${FONT_DIR} != CID ]]; then + ebegin "Generating fonts.scale" + mkfontscale \ + -a "${EROOT}/usr/share/fonts/encodings/encodings.dir" \ + -- "${EROOT}/usr/share/fonts/${FONT_DIR}" + eend $? + fi +} + +# @FUNCTION: create_fonts_dir +# @DESCRIPTION: +# Create fonts.dir file, used by the old server-side fonts subsystem. +create_fonts_dir() { + debug-print-function ${FUNCNAME} "$@" + + ebegin "Generating fonts.dir" + mkfontdir \ + -e "${EROOT}"/usr/share/fonts/encodings \ + -e "${EROOT}"/usr/share/fonts/encodings/large \ + -- "${EROOT}/usr/share/fonts/${FONT_DIR}" + eend $? +}