Drop $Id$ per council decision in bug #611234.
[gentoo.git] / eclass / eutils.eclass
1 # Copyright 1999-2015 Gentoo Foundation
2 # Distributed under the terms of the GNU General Public License v2
3
4 # @ECLASS: eutils.eclass
5 # @MAINTAINER:
6 # base-system@gentoo.org
7 # @BLURB: many extra (but common) functions that are used in ebuilds
8 # @DESCRIPTION:
9 # The eutils eclass contains a suite of functions that complement
10 # the ones that ebuild.sh already contain.  The idea is that the functions
11 # are not required in all ebuilds but enough utilize them to have a common
12 # home rather than having multiple ebuilds implementing the same thing.
13 #
14 # Due to the nature of this eclass, some functions may have maintainers
15 # different from the overall eclass!
16
17 if [[ -z ${_EUTILS_ECLASS} ]]; then
18 _EUTILS_ECLASS=1
19
20 inherit multilib toolchain-funcs
21
22 # @FUNCTION: eqawarn
23 # @USAGE: [message]
24 # @DESCRIPTION:
25 # Proxy to ewarn for package managers that don't provide eqawarn and use the PM
26 # implementation if available. Reuses PORTAGE_ELOG_CLASSES as set by the dev
27 # profile.
28 if ! declare -F eqawarn >/dev/null ; then
29         eqawarn() {
30                 has qa ${PORTAGE_ELOG_CLASSES} && ewarn "$@"
31                 :
32         }
33 fi
34
35 # @FUNCTION: ecvs_clean
36 # @USAGE: [list of dirs]
37 # @DESCRIPTION:
38 # Remove CVS directories recursiveley.  Useful when a source tarball contains
39 # internal CVS directories.  Defaults to $PWD.
40 ecvs_clean() {
41         [[ $# -eq 0 ]] && set -- .
42         find "$@" -type d -name 'CVS' -prune -print0 | xargs -0 rm -rf
43         find "$@" -type f -name '.cvs*' -print0 | xargs -0 rm -rf
44 }
45
46 # @FUNCTION: esvn_clean
47 # @USAGE: [list of dirs]
48 # @DESCRIPTION:
49 # Remove .svn directories recursiveley.  Useful when a source tarball contains
50 # internal Subversion directories.  Defaults to $PWD.
51 esvn_clean() {
52         [[ $# -eq 0 ]] && set -- .
53         find "$@" -type d -name '.svn' -prune -print0 | xargs -0 rm -rf
54 }
55
56 # @FUNCTION: egit_clean
57 # @USAGE: [list of dirs]
58 # @DESCRIPTION:
59 # Remove .git* directories/files recursiveley.  Useful when a source tarball
60 # contains internal Git directories.  Defaults to $PWD.
61 egit_clean() {
62         [[ $# -eq 0 ]] && set -- .
63         find "$@" -type d -name '.git*' -prune -print0 | xargs -0 rm -rf
64 }
65
66 # @FUNCTION: estack_push
67 # @USAGE: <stack> [items to push]
68 # @DESCRIPTION:
69 # Push any number of items onto the specified stack.  Pick a name that
70 # is a valid variable (i.e. stick to alphanumerics), and push as many
71 # items as you like onto the stack at once.
72 #
73 # The following code snippet will echo 5, then 4, then 3, then ...
74 # @CODE
75 #               estack_push mystack 1 2 3 4 5
76 #               while estack_pop mystack i ; do
77 #                       echo "${i}"
78 #               done
79 # @CODE
80 estack_push() {
81         [[ $# -eq 0 ]] && die "estack_push: incorrect # of arguments"
82         local stack_name="_ESTACK_$1_" ; shift
83         eval ${stack_name}+=\( \"\$@\" \)
84 }
85
86 # @FUNCTION: estack_pop
87 # @USAGE: <stack> [variable]
88 # @DESCRIPTION:
89 # Pop a single item off the specified stack.  If a variable is specified,
90 # the popped item is stored there.  If no more items are available, return
91 # 1, else return 0.  See estack_push for more info.
92 estack_pop() {
93         [[ $# -eq 0 || $# -gt 2 ]] && die "estack_pop: incorrect # of arguments"
94
95         # We use the fugly _estack_xxx var names to avoid collision with
96         # passing back the return value.  If we used "local i" and the
97         # caller ran `estack_pop ... i`, we'd end up setting the local
98         # copy of "i" rather than the caller's copy.  The _estack_xxx
99         # garbage is preferable to using $1/$2 everywhere as that is a
100         # bit harder to read.
101         local _estack_name="_ESTACK_$1_" ; shift
102         local _estack_retvar=$1 ; shift
103         eval local _estack_i=\${#${_estack_name}\[@\]}
104         # Don't warn -- let the caller interpret this as a failure
105         # or as normal behavior (akin to `shift`)
106         [[ $(( --_estack_i )) -eq -1 ]] && return 1
107
108         if [[ -n ${_estack_retvar} ]] ; then
109                 eval ${_estack_retvar}=\"\${${_estack_name}\[${_estack_i}\]}\"
110         fi
111         eval unset \"${_estack_name}\[${_estack_i}\]\"
112 }
113
114 # @FUNCTION: evar_push
115 # @USAGE: <variable to save> [more vars to save]
116 # @DESCRIPTION:
117 # This let's you temporarily modify a variable and then restore it (including
118 # set vs unset semantics).  Arrays are not supported at this time.
119 #
120 # This is meant for variables where using `local` does not work (such as
121 # exported variables, or only temporarily changing things in a func).
122 #
123 # For example:
124 # @CODE
125 #               evar_push LC_ALL
126 #               export LC_ALL=C
127 #               ... do some stuff that needs LC_ALL=C set ...
128 #               evar_pop
129 #
130 #               # You can also save/restore more than one var at a time
131 #               evar_push BUTTERFLY IN THE SKY
132 #               ... do stuff with the vars ...
133 #               evar_pop     # This restores just one var, SKY
134 #               ... do more stuff ...
135 #               evar_pop 3   # This pops the remaining 3 vars
136 # @CODE
137 evar_push() {
138         local var val
139         for var ; do
140                 [[ ${!var+set} == "set" ]] \
141                         && val=${!var} \
142                         || val="unset_76fc3c462065bb4ca959f939e6793f94"
143                 estack_push evar "${var}" "${val}"
144         done
145 }
146
147 # @FUNCTION: evar_push_set
148 # @USAGE: <variable to save> [new value to store]
149 # @DESCRIPTION:
150 # This is a handy shortcut to save and temporarily set a variable.  If a value
151 # is not specified, the var will be unset.
152 evar_push_set() {
153         local var=$1
154         evar_push ${var}
155         case $# in
156         1) unset ${var} ;;
157         2) printf -v "${var}" '%s' "$2" ;;
158         *) die "${FUNCNAME}: incorrect # of args: $*" ;;
159         esac
160 }
161
162 # @FUNCTION: evar_pop
163 # @USAGE: [number of vars to restore]
164 # @DESCRIPTION:
165 # Restore the variables to the state saved with the corresponding
166 # evar_push call.  See that function for more details.
167 evar_pop() {
168         local cnt=${1:-bad}
169         case $# in
170         0) cnt=1 ;;
171         1) isdigit "${cnt}" || die "${FUNCNAME}: first arg must be a number: $*" ;;
172         *) die "${FUNCNAME}: only accepts one arg: $*" ;;
173         esac
174
175         local var val
176         while (( cnt-- )) ; do
177                 estack_pop evar val || die "${FUNCNAME}: unbalanced push"
178                 estack_pop evar var || die "${FUNCNAME}: unbalanced push"
179                 [[ ${val} == "unset_76fc3c462065bb4ca959f939e6793f94" ]] \
180                         && unset ${var} \
181                         || printf -v "${var}" '%s' "${val}"
182         done
183 }
184
185 # @FUNCTION: eshopts_push
186 # @USAGE: [options to `set` or `shopt`]
187 # @DESCRIPTION:
188 # Often times code will want to enable a shell option to change code behavior.
189 # Since changing shell options can easily break other pieces of code (which
190 # assume the default state), eshopts_push is used to (1) push the current shell
191 # options onto a stack and (2) pass the specified arguments to set.
192 #
193 # If the first argument is '-s' or '-u', we assume you want to call `shopt`
194 # rather than `set` as there are some options only available via that.
195 #
196 # A common example is to disable shell globbing so that special meaning/care
197 # may be used with variables/arguments to custom functions.  That would be:
198 # @CODE
199 #               eshopts_push -o noglob
200 #               for x in ${foo} ; do
201 #                       if ...some check... ; then
202 #                               eshopts_pop
203 #                               return 0
204 #                       fi
205 #               done
206 #               eshopts_pop
207 # @CODE
208 eshopts_push() {
209         if [[ $1 == -[su] ]] ; then
210                 estack_push eshopts "$(shopt -p)"
211                 [[ $# -eq 0 ]] && return 0
212                 shopt "$@" || die "${FUNCNAME}: bad options to shopt: $*"
213         else
214                 estack_push eshopts $-
215                 [[ $# -eq 0 ]] && return 0
216                 set "$@" || die "${FUNCNAME}: bad options to set: $*"
217         fi
218 }
219
220 # @FUNCTION: eshopts_pop
221 # @USAGE:
222 # @DESCRIPTION:
223 # Restore the shell options to the state saved with the corresponding
224 # eshopts_push call.  See that function for more details.
225 eshopts_pop() {
226         local s
227         estack_pop eshopts s || die "${FUNCNAME}: unbalanced push"
228         if [[ ${s} == "shopt -"* ]] ; then
229                 eval "${s}" || die "${FUNCNAME}: sanity: invalid shopt options: ${s}"
230         else
231                 set +$-     || die "${FUNCNAME}: sanity: invalid shell settings: $-"
232                 set -${s}   || die "${FUNCNAME}: sanity: unable to restore saved shell settings: ${s}"
233         fi
234 }
235
236 # @FUNCTION: eumask_push
237 # @USAGE: <new umask>
238 # @DESCRIPTION:
239 # Set the umask to the new value specified while saving the previous
240 # value onto a stack.  Useful for temporarily changing the umask.
241 eumask_push() {
242         estack_push eumask "$(umask)"
243         umask "$@" || die "${FUNCNAME}: bad options to umask: $*"
244 }
245
246 # @FUNCTION: eumask_pop
247 # @USAGE:
248 # @DESCRIPTION:
249 # Restore the previous umask state.
250 eumask_pop() {
251         [[ $# -eq 0 ]] || die "${FUNCNAME}: we take no options"
252         local s
253         estack_pop eumask s || die "${FUNCNAME}: unbalanced push"
254         umask ${s} || die "${FUNCNAME}: sanity: could not restore umask: ${s}"
255 }
256
257 # @FUNCTION: isdigit
258 # @USAGE: <number> [more numbers]
259 # @DESCRIPTION:
260 # Return true if all arguments are numbers.
261 isdigit() {
262         local d
263         for d ; do
264                 [[ ${d:-bad} == *[!0-9]* ]] && return 1
265         done
266         return 0
267 }
268
269 # @VARIABLE: EPATCH_SOURCE
270 # @DESCRIPTION:
271 # Default directory to search for patches.
272 EPATCH_SOURCE="${WORKDIR}/patch"
273 # @VARIABLE: EPATCH_SUFFIX
274 # @DESCRIPTION:
275 # Default extension for patches (do not prefix the period yourself).
276 EPATCH_SUFFIX="patch.bz2"
277 # @VARIABLE: EPATCH_OPTS
278 # @DESCRIPTION:
279 # Options to pass to patch.  Meant for ebuild/package-specific tweaking
280 # such as forcing the patch level (-p#) or fuzz (-F#) factor.  Note that
281 # for single patch tweaking, you can also pass flags directly to epatch.
282 EPATCH_OPTS=""
283 # @VARIABLE: EPATCH_COMMON_OPTS
284 # @DESCRIPTION:
285 # Common options to pass to `patch`.  You probably should never need to
286 # change these.  If you do, please discuss it with base-system first to
287 # be sure.
288 # @CODE
289 #       -g0 - keep RCS, ClearCase, Perforce and SCCS happy #24571
290 #       --no-backup-if-mismatch - do not leave .orig files behind
291 #       -E - automatically remove empty files
292 # @CODE
293 EPATCH_COMMON_OPTS="-g0 -E --no-backup-if-mismatch"
294 # @VARIABLE: EPATCH_EXCLUDE
295 # @DESCRIPTION:
296 # List of patches not to apply.  Note this is only file names,
297 # and not the full path.  Globs accepted.
298 EPATCH_EXCLUDE=""
299 # @VARIABLE: EPATCH_SINGLE_MSG
300 # @DESCRIPTION:
301 # Change the printed message for a single patch.
302 EPATCH_SINGLE_MSG=""
303 # @VARIABLE: EPATCH_MULTI_MSG
304 # @DESCRIPTION:
305 # Change the printed message for multiple patches.
306 EPATCH_MULTI_MSG="Applying various patches (bugfixes/updates) ..."
307 # @VARIABLE: EPATCH_FORCE
308 # @DESCRIPTION:
309 # Only require patches to match EPATCH_SUFFIX rather than the extended
310 # arch naming style.
311 EPATCH_FORCE="no"
312 # @VARIABLE: EPATCH_USER_EXCLUDE
313 # @DEFAULT_UNSET
314 # @DESCRIPTION:
315 # List of patches not to apply.  Note this is only file names,
316 # and not the full path.  Globs accepted.
317
318 # @FUNCTION: epatch
319 # @USAGE: [options] [patches] [dirs of patches]
320 # @DESCRIPTION:
321 # epatch is designed to greatly simplify the application of patches.  It can
322 # process patch files directly, or directories of patches.  The patches may be
323 # compressed (bzip/gzip/etc...) or plain text.  You generally need not specify
324 # the -p option as epatch will automatically attempt -p0 to -p4 until things
325 # apply successfully.
326 #
327 # If you do not specify any patches/dirs, then epatch will default to the
328 # directory specified by EPATCH_SOURCE.
329 #
330 # Any options specified that start with a dash will be passed down to patch
331 # for this specific invocation.  As soon as an arg w/out a dash is found, then
332 # arg processing stops.
333 #
334 # When processing directories, epatch will apply all patches that match:
335 # @CODE
336 #       if ${EPATCH_FORCE} != "yes"
337 #               ??_${ARCH}_foo.${EPATCH_SUFFIX}
338 #       else
339 #               *.${EPATCH_SUFFIX}
340 # @CODE
341 # The leading ?? are typically numbers used to force consistent patch ordering.
342 # The arch field is used to apply patches only for the host architecture with
343 # the special value of "all" means apply for everyone.  Note that using values
344 # other than "all" is highly discouraged -- you should apply patches all the
345 # time and let architecture details be detected at configure/compile time.
346 #
347 # If EPATCH_SUFFIX is empty, then no period before it is implied when searching
348 # for patches to apply.
349 #
350 # Refer to the other EPATCH_xxx variables for more customization of behavior.
351 epatch() {
352         _epatch_draw_line() {
353                 # create a line of same length as input string
354                 [[ -z $1 ]] && set "$(printf "%65s" '')"
355                 echo "${1//?/=}"
356         }
357
358         unset P4CONFIG P4PORT P4USER # keep perforce at bay #56402
359
360         # First process options.  We localize the EPATCH_OPTS setting
361         # from above so that we can pass it on in the loop below with
362         # any additional values the user has specified.
363         local EPATCH_OPTS=( ${EPATCH_OPTS[*]} )
364         while [[ $# -gt 0 ]] ; do
365                 case $1 in
366                 -*) EPATCH_OPTS+=( "$1" ) ;;
367                 *) break ;;
368                 esac
369                 shift
370         done
371
372         # Let the rest of the code process one user arg at a time --
373         # each arg may expand into multiple patches, and each arg may
374         # need to start off with the default global EPATCH_xxx values
375         if [[ $# -gt 1 ]] ; then
376                 local m
377                 for m in "$@" ; do
378                         epatch "${m}"
379                 done
380                 return 0
381         fi
382
383         local SINGLE_PATCH="no"
384         # no args means process ${EPATCH_SOURCE}
385         [[ $# -eq 0 ]] && set -- "${EPATCH_SOURCE}"
386
387         if [[ -f $1 ]] ; then
388                 SINGLE_PATCH="yes"
389                 set -- "$1"
390                 # Use the suffix from the single patch (localize it); the code
391                 # below will find the suffix for us
392                 local EPATCH_SUFFIX=$1
393
394         elif [[ -d $1 ]] ; then
395                 # We have to force sorting to C so that the wildcard expansion is consistent #471666.
396                 evar_push_set LC_COLLATE C
397                 # Some people like to make dirs of patches w/out suffixes (vim).
398                 set -- "$1"/*${EPATCH_SUFFIX:+."${EPATCH_SUFFIX}"}
399                 evar_pop
400
401         elif [[ -f ${EPATCH_SOURCE}/$1 ]] ; then
402                 # Re-use EPATCH_SOURCE as a search dir
403                 epatch "${EPATCH_SOURCE}/$1"
404                 return $?
405
406         else
407                 # sanity check ... if it isn't a dir or file, wtf man ?
408                 [[ $# -ne 0 ]] && EPATCH_SOURCE=$1
409                 echo
410                 eerror "Cannot find \$EPATCH_SOURCE!  Value for \$EPATCH_SOURCE is:"
411                 eerror
412                 eerror "  ${EPATCH_SOURCE}"
413                 eerror "  ( ${EPATCH_SOURCE##*/} )"
414                 echo
415                 die "Cannot find \$EPATCH_SOURCE!"
416         fi
417
418         # Now that we know we're actually going to apply something, merge
419         # all of the patch options back in to a single variable for below.
420         EPATCH_OPTS="${EPATCH_COMMON_OPTS} ${EPATCH_OPTS[*]}"
421
422         local PIPE_CMD
423         case ${EPATCH_SUFFIX##*\.} in
424                 xz)      PIPE_CMD="xz -dc"    ;;
425                 lzma)    PIPE_CMD="lzma -dc"  ;;
426                 bz2)     PIPE_CMD="bzip2 -dc" ;;
427                 gz|Z|z)  PIPE_CMD="gzip -dc"  ;;
428                 ZIP|zip) PIPE_CMD="unzip -p"  ;;
429                 *)       ;;
430         esac
431
432         [[ ${SINGLE_PATCH} == "no" ]] && einfo "${EPATCH_MULTI_MSG}"
433
434         local x
435         for x in "$@" ; do
436                 # If the patch dir given contains subdirs, or our EPATCH_SUFFIX
437                 # didn't match anything, ignore continue on
438                 [[ ! -f ${x} ]] && continue
439
440                 local patchname=${x##*/}
441
442                 # Apply single patches, or forced sets of patches, or
443                 # patches with ARCH dependant names.
444                 #       ???_arch_foo.patch
445                 # Else, skip this input altogether
446                 local a=${patchname#*_} # strip the ???_
447                 a=${a%%_*}              # strip the _foo.patch
448                 if ! [[ ${SINGLE_PATCH} == "yes" || \
449                                 ${EPATCH_FORCE} == "yes" || \
450                                 ${a} == all     || \
451                                 ${a} == ${ARCH} ]]
452                 then
453                         continue
454                 fi
455
456                 # Let people filter things dynamically
457                 if [[ -n ${EPATCH_EXCLUDE}${EPATCH_USER_EXCLUDE} ]] ; then
458                         # let people use globs in the exclude
459                         eshopts_push -o noglob
460
461                         local ex
462                         for ex in ${EPATCH_EXCLUDE} ; do
463                                 if [[ ${patchname} == ${ex} ]] ; then
464                                         einfo "  Skipping ${patchname} due to EPATCH_EXCLUDE ..."
465                                         eshopts_pop
466                                         continue 2
467                                 fi
468                         done
469
470                         for ex in ${EPATCH_USER_EXCLUDE} ; do
471                                 if [[ ${patchname} == ${ex} ]] ; then
472                                         einfo "  Skipping ${patchname} due to EPATCH_USER_EXCLUDE ..."
473                                         eshopts_pop
474                                         continue 2
475                                 fi
476                         done
477
478                         eshopts_pop
479                 fi
480
481                 if [[ ${SINGLE_PATCH} == "yes" ]] ; then
482                         if [[ -n ${EPATCH_SINGLE_MSG} ]] ; then
483                                 einfo "${EPATCH_SINGLE_MSG}"
484                         else
485                                 einfo "Applying ${patchname} ..."
486                         fi
487                 else
488                         einfo "  ${patchname} ..."
489                 fi
490
491                 # Handle aliased patch command #404447 #461568
492                 local patch="patch"
493                 eval $(alias patch 2>/dev/null | sed 's:^alias ::')
494
495                 # most of the time, there will only be one run per unique name,
496                 # but if there are more, make sure we get unique log filenames
497                 local STDERR_TARGET="${T}/${patchname}.out"
498                 if [[ -e ${STDERR_TARGET} ]] ; then
499                         STDERR_TARGET="${T}/${patchname}-$$.out"
500                 fi
501
502                 printf "***** %s *****\nPWD: %s\nPATCH TOOL: %s -> %s\nVERSION INFO:\n%s\n\n" \
503                         "${patchname}" \
504                         "${PWD}" \
505                         "${patch}" \
506                         "$(type -P "${patch}")" \
507                         "$(${patch} --version)" \
508                         > "${STDERR_TARGET}"
509
510                 # Decompress the patch if need be
511                 local count=0
512                 local PATCH_TARGET
513                 if [[ -n ${PIPE_CMD} ]] ; then
514                         PATCH_TARGET="${T}/$$.patch"
515                         echo "PIPE_COMMAND:  ${PIPE_CMD} ${x} > ${PATCH_TARGET}" >> "${STDERR_TARGET}"
516
517                         if ! (${PIPE_CMD} "${x}" > "${PATCH_TARGET}") >> "${STDERR_TARGET}" 2>&1 ; then
518                                 echo
519                                 eerror "Could not extract patch!"
520                                 #die "Could not extract patch!"
521                                 count=5
522                                 break
523                         fi
524                 else
525                         PATCH_TARGET=${x}
526                 fi
527
528                 # Check for absolute paths in patches.  If sandbox is disabled,
529                 # people could (accidently) patch files in the root filesystem.
530                 # Or trigger other unpleasantries #237667.  So disallow -p0 on
531                 # such patches.
532                 local abs_paths=$(egrep -n '^[-+]{3} /' "${PATCH_TARGET}" | awk '$2 != "/dev/null" { print }')
533                 if [[ -n ${abs_paths} ]] ; then
534                         count=1
535                         printf "NOTE: skipping -p0 due to absolute paths in patch:\n%s\n" "${abs_paths}" >> "${STDERR_TARGET}"
536                 fi
537                 # Similar reason, but with relative paths.
538                 local rel_paths=$(egrep -n '^[-+]{3} [^ ]*[.][.]/' "${PATCH_TARGET}")
539                 if [[ -n ${rel_paths} ]] ; then
540                         echo
541                         eerror "Rejected Patch: ${patchname} !"
542                         eerror " ( ${PATCH_TARGET} )"
543                         eerror
544                         eerror "Your patch uses relative paths '../':"
545                         eerror "${rel_paths}"
546                         echo
547                         die "you need to fix the relative paths in patch"
548                 fi
549
550                 # Dynamically detect the correct -p# ... i'm lazy, so shoot me :/
551                 local patch_cmd
552                 while [[ ${count} -lt 5 ]] ; do
553                         patch_cmd="${patch} -p${count} ${EPATCH_OPTS}"
554
555                         # Generate some useful debug info ...
556                         (
557                         _epatch_draw_line "***** ${patchname} *****"
558                         echo
559                         echo "PATCH COMMAND:  ${patch_cmd} --dry-run -f < '${PATCH_TARGET}'"
560                         echo
561                         _epatch_draw_line "***** ${patchname} *****"
562                         ${patch_cmd} --dry-run -f < "${PATCH_TARGET}" 2>&1
563                         ret=$?
564                         echo
565                         echo "patch program exited with status ${ret}"
566                         exit ${ret}
567                         ) >> "${STDERR_TARGET}"
568
569                         if [ $? -eq 0 ] ; then
570                                 (
571                                 _epatch_draw_line "***** ${patchname} *****"
572                                 echo
573                                 echo "ACTUALLY APPLYING ${patchname} ..."
574                                 echo "PATCH COMMAND:  ${patch_cmd} < '${PATCH_TARGET}'"
575                                 echo
576                                 _epatch_draw_line "***** ${patchname} *****"
577                                 ${patch_cmd} < "${PATCH_TARGET}" 2>&1
578                                 ret=$?
579                                 echo
580                                 echo "patch program exited with status ${ret}"
581                                 exit ${ret}
582                                 ) >> "${STDERR_TARGET}"
583
584                                 if [ $? -ne 0 ] ; then
585                                         echo
586                                         eerror "A dry-run of patch command succeeded, but actually"
587                                         eerror "applying the patch failed!"
588                                         #die "Real world sux compared to the dreamworld!"
589                                         count=5
590                                 fi
591                                 break
592                         fi
593
594                         : $(( count++ ))
595                 done
596
597                 (( EPATCH_N_APPLIED_PATCHES++ ))
598
599                 # if we had to decompress the patch, delete the temp one
600                 if [[ -n ${PIPE_CMD} ]] ; then
601                         rm -f "${PATCH_TARGET}"
602                 fi
603
604                 if [[ ${count} -ge 5 ]] ; then
605                         echo
606                         eerror "Failed Patch: ${patchname} !"
607                         eerror " ( ${PATCH_TARGET} )"
608                         eerror
609                         eerror "Include in your bugreport the contents of:"
610                         eerror
611                         eerror "  ${STDERR_TARGET}"
612                         echo
613                         die "Failed Patch: ${patchname}!"
614                 fi
615
616                 # if everything worked, delete the full debug patch log
617                 rm -f "${STDERR_TARGET}"
618
619                 # then log away the exact stuff for people to review later
620                 cat <<-EOF >> "${T}/epatch.log"
621                 PATCH: ${x}
622                 CMD: ${patch_cmd}
623                 PWD: ${PWD}
624
625                 EOF
626                 eend 0
627         done
628
629         [[ ${SINGLE_PATCH} == "no" ]] && einfo "Done with patching"
630         : # everything worked
631 }
632
633 # @FUNCTION: emktemp
634 # @USAGE: [temp dir]
635 # @DESCRIPTION:
636 # Cheap replacement for when debianutils (and thus mktemp)
637 # does not exist on the users system.
638 emktemp() {
639         local exe="touch"
640         [[ $1 == -d ]] && exe="mkdir" && shift
641         local topdir=$1
642
643         if [[ -z ${topdir} ]] ; then
644                 [[ -z ${T} ]] \
645                         && topdir="/tmp" \
646                         || topdir=${T}
647         fi
648
649         if ! type -P mktemp > /dev/null ; then
650                 # system lacks `mktemp` so we have to fake it
651                 local tmp=/
652                 while [[ -e ${tmp} ]] ; do
653                         tmp=${topdir}/tmp.${RANDOM}.${RANDOM}.${RANDOM}
654                 done
655                 ${exe} "${tmp}" || ${exe} -p "${tmp}"
656                 echo "${tmp}"
657         else
658                 # the args here will give slightly wierd names on BSD,
659                 # but should produce a usable file on all userlands
660                 if [[ ${exe} == "touch" ]] ; then
661                         TMPDIR="${topdir}" mktemp -t tmp.XXXXXXXXXX
662                 else
663                         TMPDIR="${topdir}" mktemp -dt tmp.XXXXXXXXXX
664                 fi
665         fi
666 }
667
668 # @FUNCTION: edos2unix
669 # @USAGE: <file> [more files ...]
670 # @DESCRIPTION:
671 # A handy replacement for dos2unix, recode, fixdos, etc...  This allows you
672 # to remove all of these text utilities from DEPEND variables because this
673 # is a script based solution.  Just give it a list of files to convert and
674 # they will all be changed from the DOS CRLF format to the UNIX LF format.
675 edos2unix() {
676         [[ $# -eq 0 ]] && return 0
677         sed -i 's/\r$//' -- "$@" || die
678 }
679
680 # @FUNCTION: make_desktop_entry
681 # @USAGE: make_desktop_entry(<command>, [name], [icon], [type], [fields])
682 # @DESCRIPTION:
683 # Make a .desktop file.
684 #
685 # @CODE
686 # binary:   what command does the app run with ?
687 # name:     the name that will show up in the menu
688 # icon:     the icon to use in the menu entry
689 #           this can be relative (to /usr/share/pixmaps) or
690 #           a full path to an icon
691 # type:     what kind of application is this?
692 #           for categories:
693 #           https://specifications.freedesktop.org/menu-spec/latest/apa.html
694 #           if unset, function tries to guess from package's category
695 # fields:       extra fields to append to the desktop file; a printf string
696 # @CODE
697 make_desktop_entry() {
698         [[ -z $1 ]] && die "make_desktop_entry: You must specify the executable"
699
700         local exec=${1}
701         local name=${2:-${PN}}
702         local icon=${3:-${PN}}
703         local type=${4}
704         local fields=${5}
705
706         if [[ -z ${type} ]] ; then
707                 local catmaj=${CATEGORY%%-*}
708                 local catmin=${CATEGORY##*-}
709                 case ${catmaj} in
710                         app)
711                                 case ${catmin} in
712                                         accessibility) type="Utility;Accessibility";;
713                                         admin)         type=System;;
714                                         antivirus)     type=System;;
715                                         arch)          type="Utility;Archiving";;
716                                         backup)        type="Utility;Archiving";;
717                                         cdr)           type="AudioVideo;DiscBurning";;
718                                         dicts)         type="Office;Dictionary";;
719                                         doc)           type=Documentation;;
720                                         editors)       type="Utility;TextEditor";;
721                                         emacs)         type="Development;TextEditor";;
722                                         emulation)     type="System;Emulator";;
723                                         laptop)        type="Settings;HardwareSettings";;
724                                         office)        type=Office;;
725                                         pda)           type="Office;PDA";;
726                                         vim)           type="Development;TextEditor";;
727                                         xemacs)        type="Development;TextEditor";;
728                                 esac
729                                 ;;
730
731                         dev)
732                                 type="Development"
733                                 ;;
734
735                         games)
736                                 case ${catmin} in
737                                         action|fps) type=ActionGame;;
738                                         arcade)     type=ArcadeGame;;
739                                         board)      type=BoardGame;;
740                                         emulation)  type=Emulator;;
741                                         kids)       type=KidsGame;;
742                                         puzzle)     type=LogicGame;;
743                                         roguelike)  type=RolePlaying;;
744                                         rpg)        type=RolePlaying;;
745                                         simulation) type=Simulation;;
746                                         sports)     type=SportsGame;;
747                                         strategy)   type=StrategyGame;;
748                                 esac
749                                 type="Game;${type}"
750                                 ;;
751
752                         gnome)
753                                 type="Gnome;GTK"
754                                 ;;
755
756                         kde)
757                                 type="KDE;Qt"
758                                 ;;
759
760                         mail)
761                                 type="Network;Email"
762                                 ;;
763
764                         media)
765                                 case ${catmin} in
766                                         gfx)
767                                                 type=Graphics
768                                                 ;;
769                                         *)
770                                                 case ${catmin} in
771                                                         radio) type=Tuner;;
772                                                         sound) type=Audio;;
773                                                         tv)    type=TV;;
774                                                         video) type=Video;;
775                                                 esac
776                                                 type="AudioVideo;${type}"
777                                                 ;;
778                                 esac
779                                 ;;
780
781                         net)
782                                 case ${catmin} in
783                                         dialup) type=Dialup;;
784                                         ftp)    type=FileTransfer;;
785                                         im)     type=InstantMessaging;;
786                                         irc)    type=IRCClient;;
787                                         mail)   type=Email;;
788                                         news)   type=News;;
789                                         nntp)   type=News;;
790                                         p2p)    type=FileTransfer;;
791                                         voip)   type=Telephony;;
792                                 esac
793                                 type="Network;${type}"
794                                 ;;
795
796                         sci)
797                                 case ${catmin} in
798                                         astro*)  type=Astronomy;;
799                                         bio*)    type=Biology;;
800                                         calc*)   type=Calculator;;
801                                         chem*)   type=Chemistry;;
802                                         elec*)   type=Electronics;;
803                                         geo*)    type=Geology;;
804                                         math*)   type=Math;;
805                                         physics) type=Physics;;
806                                         visual*) type=DataVisualization;;
807                                 esac
808                                 type="Education;Science;${type}"
809                                 ;;
810
811                         sys)
812                                 type="System"
813                                 ;;
814
815                         www)
816                                 case ${catmin} in
817                                         client) type=WebBrowser;;
818                                 esac
819                                 type="Network;${type}"
820                                 ;;
821
822                         *)
823                                 type=
824                                 ;;
825                 esac
826         fi
827         local slot=${SLOT%/*}
828         if [[ ${slot} == "0" ]] ; then
829                 local desktop_name="${PN}"
830         else
831                 local desktop_name="${PN}-${slot}"
832         fi
833         local desktop="${T}/$(echo ${exec} | sed 's:[[:space:]/:]:_:g')-${desktop_name}.desktop"
834         #local desktop=${T}/${exec%% *:-${desktop_name}}.desktop
835
836         # Don't append another ";" when a valid category value is provided.
837         type=${type%;}${type:+;}
838
839         eshopts_push -s extglob
840         if [[ -n ${icon} && ${icon} != /* ]] && [[ ${icon} == *.xpm || ${icon} == *.png || ${icon} == *.svg ]]; then
841                 ewarn "As described in the Icon Theme Specification, icon file extensions are not"
842                 ewarn "allowed in .desktop files if the value is not an absolute path."
843                 icon=${icon%.@(xpm|png|svg)}
844         fi
845         eshopts_pop
846
847         cat <<-EOF > "${desktop}"
848         [Desktop Entry]
849         Name=${name}
850         Type=Application
851         Comment=${DESCRIPTION}
852         Exec=${exec}
853         TryExec=${exec%% *}
854         Icon=${icon}
855         Categories=${type}
856         EOF
857
858         if [[ ${fields:-=} != *=* ]] ; then
859                 # 5th arg used to be value to Path=
860                 ewarn "make_desktop_entry: update your 5th arg to read Path=${fields}"
861                 fields="Path=${fields}"
862         fi
863         [[ -n ${fields} ]] && printf '%b\n' "${fields}" >> "${desktop}"
864
865         (
866                 # wrap the env here so that the 'insinto' call
867                 # doesn't corrupt the env of the caller
868                 insinto /usr/share/applications
869                 doins "${desktop}"
870         ) || die "installing desktop file failed"
871 }
872
873 # @FUNCTION: _eutils_eprefix_init
874 # @INTERNAL
875 # @DESCRIPTION:
876 # Initialized prefix variables for EAPI<3.
877 _eutils_eprefix_init() {
878         has "${EAPI:-0}" 0 1 2 && : ${ED:=${D}} ${EPREFIX:=} ${EROOT:=${ROOT}}
879 }
880
881 # @FUNCTION: validate_desktop_entries
882 # @USAGE: [directories]
883 # @DESCRIPTION:
884 # Validate desktop entries using desktop-file-utils
885 validate_desktop_entries() {
886         _eutils_eprefix_init
887         if [[ -x "${EPREFIX}"/usr/bin/desktop-file-validate ]] ; then
888                 einfo "Checking desktop entry validity"
889                 local directories=""
890                 for d in /usr/share/applications $@ ; do
891                         [[ -d ${ED}${d} ]] && directories="${directories} ${ED}${d}"
892                 done
893                 if [[ -n ${directories} ]] ; then
894                         for FILE in $(find ${directories} -name "*\.desktop" \
895                                                         -not -path '*.hidden*' | sort -u 2>/dev/null)
896                         do
897                                 local temp=$(desktop-file-validate ${FILE} | grep -v "warning:" | \
898                                                                 sed -e "s|error: ||" -e "s|${FILE}:|--|g" )
899                                 [[ -n $temp ]] && elog ${temp/--/${FILE/${ED}/}:}
900                         done
901                 fi
902                 echo ""
903         else
904                 einfo "Passing desktop entry validity check. Install dev-util/desktop-file-utils, if you want to help to improve Gentoo."
905         fi
906 }
907
908 # @FUNCTION: make_session_desktop
909 # @USAGE: <title> <command> [command args...]
910 # @DESCRIPTION:
911 # Make a GDM/KDM Session file.  The title is the file to execute to start the
912 # Window Manager.  The command is the name of the Window Manager.
913 #
914 # You can set the name of the file via the ${wm} variable.
915 make_session_desktop() {
916         [[ -z $1 ]] && eerror "$0: You must specify the title" && return 1
917         [[ -z $2 ]] && eerror "$0: You must specify the command" && return 1
918
919         local title=$1
920         local command=$2
921         local desktop=${T}/${wm:-${PN}}.desktop
922         shift 2
923
924         cat <<-EOF > "${desktop}"
925         [Desktop Entry]
926         Name=${title}
927         Comment=This session logs you into ${title}
928         Exec=${command} $*
929         TryExec=${command}
930         Type=XSession
931         EOF
932
933         (
934         # wrap the env here so that the 'insinto' call
935         # doesn't corrupt the env of the caller
936         insinto /usr/share/xsessions
937         doins "${desktop}"
938         )
939 }
940
941 # @FUNCTION: domenu
942 # @USAGE: <menus>
943 # @DESCRIPTION:
944 # Install the list of .desktop menu files into the appropriate directory
945 # (/usr/share/applications).
946 domenu() {
947         (
948         # wrap the env here so that the 'insinto' call
949         # doesn't corrupt the env of the caller
950         local i j ret=0
951         insinto /usr/share/applications
952         for i in "$@" ; do
953                 if [[ -f ${i} ]] ; then
954                         doins "${i}"
955                         ((ret+=$?))
956                 elif [[ -d ${i} ]] ; then
957                         for j in "${i}"/*.desktop ; do
958                                 doins "${j}"
959                                 ((ret+=$?))
960                         done
961                 else
962                         ((++ret))
963                 fi
964         done
965         exit ${ret}
966         )
967 }
968
969 # @FUNCTION: newmenu
970 # @USAGE: <menu> <newname>
971 # @DESCRIPTION:
972 # Like all other new* functions, install the specified menu as newname.
973 newmenu() {
974         (
975         # wrap the env here so that the 'insinto' call
976         # doesn't corrupt the env of the caller
977         insinto /usr/share/applications
978         newins "$@"
979         )
980 }
981
982 # @FUNCTION: _iconins
983 # @INTERNAL
984 # @DESCRIPTION:
985 # function for use in doicon and newicon
986 _iconins() {
987         (
988         # wrap the env here so that the 'insinto' call
989         # doesn't corrupt the env of the caller
990         local funcname=$1; shift
991         local size dir
992         local context=apps
993         local theme=hicolor
994
995         while [[ $# -gt 0 ]] ; do
996                 case $1 in
997                 -s|--size)
998                         if [[ ${2%%x*}x${2%%x*} == "$2" ]] ; then
999                                 size=${2%%x*}
1000                         else
1001                                 size=${2}
1002                         fi
1003                         case ${size} in
1004                         16|22|24|32|36|48|64|72|96|128|192|256|512)
1005                                 size=${size}x${size};;
1006                         scalable)
1007                                 ;;
1008                         *)
1009                                 eerror "${size} is an unsupported icon size!"
1010                                 exit 1;;
1011                         esac
1012                         shift 2;;
1013                 -t|--theme)
1014                         theme=${2}
1015                         shift 2;;
1016                 -c|--context)
1017                         context=${2}
1018                         shift 2;;
1019                 *)
1020                         if [[ -z ${size} ]] ; then
1021                                 insinto /usr/share/pixmaps
1022                         else
1023                                 insinto /usr/share/icons/${theme}/${size}/${context}
1024                         fi
1025
1026                         if [[ ${funcname} == doicon ]] ; then
1027                                 if [[ -f $1 ]] ; then
1028                                         doins "${1}"
1029                                 elif [[ -d $1 ]] ; then
1030                                         shopt -s nullglob
1031                                         doins "${1}"/*.{png,svg}
1032                                         shopt -u nullglob
1033                                 else
1034                                         eerror "${1} is not a valid file/directory!"
1035                                         exit 1
1036                                 fi
1037                         else
1038                                 break
1039                         fi
1040                         shift 1;;
1041                 esac
1042         done
1043         if [[ ${funcname} == newicon ]] ; then
1044                 newins "$@"
1045         fi
1046         ) || die
1047 }
1048
1049 # @FUNCTION: doicon
1050 # @USAGE: [options] <icons>
1051 # @DESCRIPTION:
1052 # Install icon into the icon directory /usr/share/icons or into
1053 # /usr/share/pixmaps if "--size" is not set.
1054 # This is useful in conjunction with creating desktop/menu files.
1055 #
1056 # @CODE
1057 #  options:
1058 #  -s, --size
1059 #    !!! must specify to install into /usr/share/icons/... !!!
1060 #    size of the icon, like 48 or 48x48
1061 #    supported icon sizes are:
1062 #    16 22 24 32 36 48 64 72 96 128 192 256 512 scalable
1063 #  -c, --context
1064 #    defaults to "apps"
1065 #  -t, --theme
1066 #    defaults to "hicolor"
1067 #
1068 # icons: list of icons
1069 #
1070 # example 1: doicon foobar.png fuqbar.svg suckbar.png
1071 # results in: insinto /usr/share/pixmaps
1072 #             doins foobar.png fuqbar.svg suckbar.png
1073 #
1074 # example 2: doicon -s 48 foobar.png fuqbar.png blobbar.png
1075 # results in: insinto /usr/share/icons/hicolor/48x48/apps
1076 #             doins foobar.png fuqbar.png blobbar.png
1077 # @CODE
1078 doicon() {
1079         _iconins ${FUNCNAME} "$@"
1080 }
1081
1082 # @FUNCTION: newicon
1083 # @USAGE: [options] <icon> <newname>
1084 # @DESCRIPTION:
1085 # Like doicon, install the specified icon as newname.
1086 #
1087 # @CODE
1088 # example 1: newicon foobar.png NEWNAME.png
1089 # results in: insinto /usr/share/pixmaps
1090 #             newins foobar.png NEWNAME.png
1091 #
1092 # example 2: newicon -s 48 foobar.png NEWNAME.png
1093 # results in: insinto /usr/share/icons/hicolor/48x48/apps
1094 #             newins foobar.png NEWNAME.png
1095 # @CODE
1096 newicon() {
1097         _iconins ${FUNCNAME} "$@"
1098 }
1099
1100 # @FUNCTION: strip-linguas
1101 # @USAGE: [<allow LINGUAS>|<-i|-u> <directories of .po files>]
1102 # @DESCRIPTION:
1103 # Make sure that LINGUAS only contains languages that
1104 # a package can support.  The first form allows you to
1105 # specify a list of LINGUAS.  The -i builds a list of po
1106 # files found in all the directories and uses the
1107 # intersection of the lists.  The -u builds a list of po
1108 # files found in all the directories and uses the union
1109 # of the lists.
1110 strip-linguas() {
1111         local ls newls nols
1112         if [[ $1 == "-i" ]] || [[ $1 == "-u" ]] ; then
1113                 local op=$1; shift
1114                 ls=$(find "$1" -name '*.po' -exec basename {} .po ';'); shift
1115                 local d f
1116                 for d in "$@" ; do
1117                         if [[ ${op} == "-u" ]] ; then
1118                                 newls=${ls}
1119                         else
1120                                 newls=""
1121                         fi
1122                         for f in $(find "$d" -name '*.po' -exec basename {} .po ';') ; do
1123                                 if [[ ${op} == "-i" ]] ; then
1124                                         has ${f} ${ls} && newls="${newls} ${f}"
1125                                 else
1126                                         has ${f} ${ls} || newls="${newls} ${f}"
1127                                 fi
1128                         done
1129                         ls=${newls}
1130                 done
1131         else
1132                 ls="$@"
1133         fi
1134
1135         nols=""
1136         newls=""
1137         for f in ${LINGUAS} ; do
1138                 if has ${f} ${ls} ; then
1139                         newls="${newls} ${f}"
1140                 else
1141                         nols="${nols} ${f}"
1142                 fi
1143         done
1144         [[ -n ${nols} ]] \
1145                 && einfo "Sorry, but ${PN} does not support the LINGUAS:" ${nols}
1146         export LINGUAS=${newls:1}
1147 }
1148
1149 # @FUNCTION: preserve_old_lib
1150 # @USAGE: <libs to preserve> [more libs]
1151 # @DESCRIPTION:
1152 # These functions are useful when a lib in your package changes ABI SONAME.
1153 # An example might be from libogg.so.0 to libogg.so.1.  Removing libogg.so.0
1154 # would break packages that link against it.  Most people get around this
1155 # by using the portage SLOT mechanism, but that is not always a relevant
1156 # solution, so instead you can call this from pkg_preinst.  See also the
1157 # preserve_old_lib_notify function.
1158 preserve_old_lib() {
1159         _eutils_eprefix_init
1160         if [[ ${EBUILD_PHASE} != "preinst" ]] ; then
1161                 eerror "preserve_old_lib() must be called from pkg_preinst() only"
1162                 die "Invalid preserve_old_lib() usage"
1163         fi
1164         [[ -z $1 ]] && die "Usage: preserve_old_lib <library to preserve> [more libraries to preserve]"
1165
1166         # let portage worry about it
1167         has preserve-libs ${FEATURES} && return 0
1168
1169         local lib dir
1170         for lib in "$@" ; do
1171                 [[ -e ${EROOT}/${lib} ]] || continue
1172                 dir=${lib%/*}
1173                 dodir ${dir} || die "dodir ${dir} failed"
1174                 cp "${EROOT}"/${lib} "${ED}"/${lib} || die "cp ${lib} failed"
1175                 touch "${ED}"/${lib}
1176         done
1177 }
1178
1179 # @FUNCTION: preserve_old_lib_notify
1180 # @USAGE: <libs to notify> [more libs]
1181 # @DESCRIPTION:
1182 # Spit helpful messages about the libraries preserved by preserve_old_lib.
1183 preserve_old_lib_notify() {
1184         if [[ ${EBUILD_PHASE} != "postinst" ]] ; then
1185                 eerror "preserve_old_lib_notify() must be called from pkg_postinst() only"
1186                 die "Invalid preserve_old_lib_notify() usage"
1187         fi
1188
1189         # let portage worry about it
1190         has preserve-libs ${FEATURES} && return 0
1191
1192         _eutils_eprefix_init
1193
1194         local lib notice=0
1195         for lib in "$@" ; do
1196                 [[ -e ${EROOT}/${lib} ]] || continue
1197                 if [[ ${notice} -eq 0 ]] ; then
1198                         notice=1
1199                         ewarn "Old versions of installed libraries were detected on your system."
1200                         ewarn "In order to avoid breaking packages that depend on these old libs,"
1201                         ewarn "the libraries are not being removed.  You need to run revdep-rebuild"
1202                         ewarn "in order to remove these old dependencies.  If you do not have this"
1203                         ewarn "helper program, simply emerge the 'gentoolkit' package."
1204                         ewarn
1205                 fi
1206                 ewarn "  # revdep-rebuild --library '${lib}' && rm '${lib}'"
1207         done
1208 }
1209
1210 # @FUNCTION: built_with_use
1211 # @USAGE: [--hidden] [--missing <action>] [-a|-o] <DEPEND ATOM> <List of USE flags>
1212 # @DESCRIPTION:
1213 #
1214 # Deprecated: Use EAPI 2 use deps in DEPEND|RDEPEND and with has_version calls.
1215 #
1216 # A temporary hack until portage properly supports DEPENDing on USE
1217 # flags being enabled in packages.  This will check to see if the specified
1218 # DEPEND atom was built with the specified list of USE flags.  The
1219 # --missing option controls the behavior if called on a package that does
1220 # not actually support the defined USE flags (aka listed in IUSE).
1221 # The default is to abort (call die).  The -a and -o flags control
1222 # the requirements of the USE flags.  They correspond to "and" and "or"
1223 # logic.  So the -a flag means all listed USE flags must be enabled
1224 # while the -o flag means at least one of the listed IUSE flags must be
1225 # enabled.  The --hidden option is really for internal use only as it
1226 # means the USE flag we're checking is hidden expanded, so it won't be found
1227 # in IUSE like normal USE flags.
1228 #
1229 # Remember that this function isn't terribly intelligent so order of optional
1230 # flags matter.
1231 built_with_use() {
1232         _eutils_eprefix_init
1233         local hidden="no"
1234         if [[ $1 == "--hidden" ]] ; then
1235                 hidden="yes"
1236                 shift
1237         fi
1238
1239         local missing_action="die"
1240         if [[ $1 == "--missing" ]] ; then
1241                 missing_action=$2
1242                 shift ; shift
1243                 case ${missing_action} in
1244                         true|false|die) ;;
1245                         *) die "unknown action '${missing_action}'";;
1246                 esac
1247         fi
1248
1249         local opt=$1
1250         [[ ${opt:0:1} = "-" ]] && shift || opt="-a"
1251
1252         local PKG=$(best_version $1)
1253         [[ -z ${PKG} ]] && die "Unable to resolve $1 to an installed package"
1254         shift
1255
1256         local USEFILE=${EROOT}/var/db/pkg/${PKG}/USE
1257         local IUSEFILE=${EROOT}/var/db/pkg/${PKG}/IUSE
1258
1259         # if the IUSE file doesn't exist, the read will error out, we need to handle
1260         # this gracefully
1261         if [[ ! -e ${USEFILE} ]] || [[ ! -e ${IUSEFILE} && ${hidden} == "no" ]] ; then
1262                 case ${missing_action} in
1263                         true)   return 0;;
1264                         false)  return 1;;
1265                         die)    die "Unable to determine what USE flags $PKG was built with";;
1266                 esac
1267         fi
1268
1269         if [[ ${hidden} == "no" ]] ; then
1270                 local IUSE_BUILT=( $(<"${IUSEFILE}") )
1271                 # Don't check USE_EXPAND #147237
1272                 local expand
1273                 for expand in $(echo ${USE_EXPAND} | tr '[:upper:]' '[:lower:]') ; do
1274                         if [[ $1 == ${expand}_* ]] ; then
1275                                 expand=""
1276                                 break
1277                         fi
1278                 done
1279                 if [[ -n ${expand} ]] ; then
1280                         if ! has $1 ${IUSE_BUILT[@]#[-+]} ; then
1281                                 case ${missing_action} in
1282                                         true)  return 0;;
1283                                         false) return 1;;
1284                                         die)   die "$PKG does not actually support the $1 USE flag!";;
1285                                 esac
1286                         fi
1287                 fi
1288         fi
1289
1290         local USE_BUILT=$(<${USEFILE})
1291         while [[ $# -gt 0 ]] ; do
1292                 if [[ ${opt} = "-o" ]] ; then
1293                         has $1 ${USE_BUILT} && return 0
1294                 else
1295                         has $1 ${USE_BUILT} || return 1
1296                 fi
1297                 shift
1298         done
1299         [[ ${opt} = "-a" ]]
1300 }
1301
1302 # If an overlay has eclass overrides, but doesn't actually override the
1303 # libtool.eclass, we'll have ECLASSDIR pointing to the active overlay's
1304 # eclass/ dir, but libtool.eclass is still in the main Gentoo tree.  So
1305 # add a check to locate the ELT-patches/ regardless of what's going on.
1306 # Note: Duplicated in libtool.eclass.
1307 _EUTILS_ECLASSDIR_LOCAL=${BASH_SOURCE[0]%/*}
1308 eutils_elt_patch_dir() {
1309         local d="${ECLASSDIR}/ELT-patches"
1310         if [[ ! -d ${d} ]] ; then
1311                 d="${_EUTILS_ECLASSDIR_LOCAL}/ELT-patches"
1312         fi
1313         echo "${d}"
1314 }
1315
1316 # @FUNCTION: epunt_cxx
1317 # @USAGE: [dir to scan]
1318 # @DESCRIPTION:
1319 # Many configure scripts wrongly bail when a C++ compiler could not be
1320 # detected.  If dir is not specified, then it defaults to ${S}.
1321 #
1322 # https://bugs.gentoo.org/73450
1323 epunt_cxx() {
1324         local dir=$1
1325         [[ -z ${dir} ]] && dir=${S}
1326         ebegin "Removing useless C++ checks"
1327         local f p any_found
1328         while IFS= read -r -d '' f; do
1329                 for p in "$(eutils_elt_patch_dir)"/nocxx/*.patch ; do
1330                         if patch --no-backup-if-mismatch -p1 "${f}" "${p}" >/dev/null ; then
1331                                 any_found=1
1332                                 break
1333                         fi
1334                 done
1335         done < <(find "${dir}" -name configure -print0)
1336
1337         if [[ -z ${any_found} ]]; then
1338                 eqawarn "epunt_cxx called unnecessarily (no C++ checks to punt)."
1339         fi
1340         eend 0
1341 }
1342
1343 # @FUNCTION: make_wrapper
1344 # @USAGE: <wrapper> <target> [chdir] [libpaths] [installpath]
1345 # @DESCRIPTION:
1346 # Create a shell wrapper script named wrapper in installpath
1347 # (defaults to the bindir) to execute target (default of wrapper) by
1348 # first optionally setting LD_LIBRARY_PATH to the colon-delimited
1349 # libpaths followed by optionally changing directory to chdir.
1350 make_wrapper() {
1351         _eutils_eprefix_init
1352         local wrapper=$1 bin=$2 chdir=$3 libdir=$4 path=$5
1353         local tmpwrapper=$(emktemp)
1354
1355         (
1356         echo '#!/bin/sh'
1357         [[ -n ${chdir} ]] && printf 'cd "%s"\n' "${EPREFIX}${chdir}"
1358         if [[ -n ${libdir} ]] ; then
1359                 local var
1360                 if [[ ${CHOST} == *-darwin* ]] ; then
1361                         var=DYLD_LIBRARY_PATH
1362                 else
1363                         var=LD_LIBRARY_PATH
1364                 fi
1365                 cat <<-EOF
1366                         if [ "\${${var}+set}" = "set" ] ; then
1367                                 export ${var}="\${${var}}:${EPREFIX}${libdir}"
1368                         else
1369                                 export ${var}="${EPREFIX}${libdir}"
1370                         fi
1371                 EOF
1372         fi
1373         # We don't want to quote ${bin} so that people can pass complex
1374         # things as ${bin} ... "./someprog --args"
1375         printf 'exec %s "$@"\n' "${bin/#\//${EPREFIX}/}"
1376         ) > "${tmpwrapper}"
1377         chmod go+rx "${tmpwrapper}"
1378
1379         if [[ -n ${path} ]] ; then
1380                 (
1381                 exeinto "${path}"
1382                 newexe "${tmpwrapper}" "${wrapper}"
1383                 ) || die
1384         else
1385                 newbin "${tmpwrapper}" "${wrapper}" || die
1386         fi
1387 }
1388
1389 # @FUNCTION: path_exists
1390 # @USAGE: [-a|-o] <paths>
1391 # @DESCRIPTION:
1392 # Check if the specified paths exist.  Works for all types of paths
1393 # (files/dirs/etc...).  The -a and -o flags control the requirements
1394 # of the paths.  They correspond to "and" and "or" logic.  So the -a
1395 # flag means all the paths must exist while the -o flag means at least
1396 # one of the paths must exist.  The default behavior is "and".  If no
1397 # paths are specified, then the return value is "false".
1398 path_exists() {
1399         local opt=$1
1400         [[ ${opt} == -[ao] ]] && shift || opt="-a"
1401
1402         # no paths -> return false
1403         # same behavior as: [[ -e "" ]]
1404         [[ $# -eq 0 ]] && return 1
1405
1406         local p r=0
1407         for p in "$@" ; do
1408                 [[ -e ${p} ]]
1409                 : $(( r += $? ))
1410         done
1411
1412         case ${opt} in
1413                 -a) return $(( r != 0 )) ;;
1414                 -o) return $(( r == $# )) ;;
1415         esac
1416 }
1417
1418 # @FUNCTION: use_if_iuse
1419 # @USAGE: <flag>
1420 # @DESCRIPTION:
1421 # Return true if the given flag is in USE and IUSE.
1422 #
1423 # Note that this function should not be used in the global scope.
1424 use_if_iuse() {
1425         in_iuse $1 || return 1
1426         use $1
1427 }
1428
1429 # @FUNCTION: prune_libtool_files
1430 # @USAGE: [--all|--modules]
1431 # @DESCRIPTION:
1432 # Locate unnecessary libtool files (.la) and libtool static archives
1433 # (.a) and remove them from installation image.
1434 #
1435 # By default, .la files are removed whenever the static linkage can
1436 # either be performed using pkg-config or doesn't introduce additional
1437 # flags.
1438 #
1439 # If '--modules' argument is passed, .la files for modules (plugins) are
1440 # removed as well. This is usually useful when the package installs
1441 # plugins and the plugin loader does not use .la files.
1442 #
1443 # If '--all' argument is passed, all .la files are removed without
1444 # performing any heuristic on them. You shouldn't ever use that,
1445 # and instead report a bug in the algorithm instead.
1446 #
1447 # The .a files are only removed whenever corresponding .la files state
1448 # that they should not be linked to, i.e. whenever these files
1449 # correspond to plugins.
1450 #
1451 # Note: if your package installs both static libraries and .pc files
1452 # which use variable substitution for -l flags, you need to add
1453 # pkg-config to your DEPEND.
1454 prune_libtool_files() {
1455         debug-print-function ${FUNCNAME} "$@"
1456
1457         local removing_all removing_modules opt
1458         _eutils_eprefix_init
1459         for opt; do
1460                 case "${opt}" in
1461                         --all)
1462                                 removing_all=1
1463                                 removing_modules=1
1464                                 ;;
1465                         --modules)
1466                                 removing_modules=1
1467                                 ;;
1468                         *)
1469                                 die "Invalid argument to ${FUNCNAME}(): ${opt}"
1470                 esac
1471         done
1472
1473         local f
1474         local queue=()
1475         while IFS= read -r -d '' f; do # for all .la files
1476                 local archivefile=${f/%.la/.a}
1477
1478                 # The following check is done by libtool itself.
1479                 # It helps us avoid removing random files which match '*.la',
1480                 # see bug #468380.
1481                 if ! sed -n -e '/^# Generated by .*libtool/q0;4q1' "${f}"; then
1482                         continue
1483                 fi
1484
1485                 [[ ${f} != ${archivefile} ]] || die 'regex sanity check failed'
1486                 local reason= pkgconfig_scanned=
1487                 local snotlink=$(sed -n -e 's:^shouldnotlink=::p' "${f}")
1488
1489                 if [[ ${snotlink} == yes ]]; then
1490
1491                         # Remove static libs we're not supposed to link against.
1492                         if [[ -f ${archivefile} ]]; then
1493                                 einfo "Removing unnecessary ${archivefile#${D%/}} (static plugin)"
1494                                 queue+=( "${archivefile}" )
1495                         fi
1496
1497                         # The .la file may be used by a module loader, so avoid removing it
1498                         # unless explicitly requested.
1499                         if [[ ${removing_modules} ]]; then
1500                                 reason='module'
1501                         fi
1502
1503                 else
1504
1505                         # Remove .la files when:
1506                         # - user explicitly wants us to remove all .la files,
1507                         # - respective static archive doesn't exist,
1508                         # - they are covered by a .pc file already,
1509                         # - they don't provide any new information (no libs & no flags).
1510
1511                         if [[ ${removing_all} ]]; then
1512                                 reason='requested'
1513                         elif [[ ! -f ${archivefile} ]]; then
1514                                 reason='no static archive'
1515                         elif [[ ! $(sed -nre \
1516                                         "s/^(dependency_libs|inherited_linker_flags)='(.*)'$/\2/p" \
1517                                         "${f}") ]]; then
1518                                 reason='no libs & flags'
1519                         else
1520                                 if [[ ! ${pkgconfig_scanned} ]]; then
1521                                         # Create a list of all .pc-covered libs.
1522                                         local pc_libs=()
1523                                         if [[ ! ${removing_all} ]]; then
1524                                                 local pc
1525                                                 local tf=${T}/prune-lt-files.pc
1526                                                 local pkgconf=$(tc-getPKG_CONFIG)
1527
1528                                                 while IFS= read -r -d '' pc; do # for all .pc files
1529                                                         local arg libs
1530
1531                                                         # Use pkg-config if available (and works),
1532                                                         # fallback to sed.
1533                                                         if ${pkgconf} --exists "${pc}" &>/dev/null; then
1534                                                                 sed -e '/^Requires:/d' "${pc}" > "${tf}"
1535                                                                 libs=$(${pkgconf} --libs "${tf}")
1536                                                         else
1537                                                                 libs=$(sed -ne 's/^Libs://p' "${pc}")
1538                                                         fi
1539
1540                                                         for arg in ${libs}; do
1541                                                                 if [[ ${arg} == -l* ]]; then
1542                                                                         if [[ ${arg} == '*$*' ]]; then
1543                                                                                 eqawarn "${FUNCNAME}: variable substitution likely failed in ${pc}"
1544                                                                                 eqawarn "(arg: ${arg})"
1545                                                                                 eqawarn "Most likely, you need to add virtual/pkgconfig to DEPEND."
1546                                                                         fi
1547
1548                                                                         pc_libs+=( lib${arg#-l}.la )
1549                                                                 fi
1550                                                         done
1551                                                 done < <(find "${D}" -type f -name '*.pc' -print0)
1552
1553                                                 rm -f "${tf}"
1554                                         fi
1555
1556                                         pkgconfig_scanned=1
1557                                 fi # pkgconfig_scanned
1558
1559                                 has "${f##*/}" "${pc_libs[@]}" && reason='covered by .pc'
1560                         fi # removal due to .pc
1561
1562                 fi # shouldnotlink==no
1563
1564                 if [[ ${reason} ]]; then
1565                         einfo "Removing unnecessary ${f#${D%/}} (${reason})"
1566                         queue+=( "${f}" )
1567                 fi
1568         done < <(find "${ED}" -xtype f -name '*.la' -print0)
1569
1570         if [[ ${queue[@]} ]]; then
1571                 rm -f "${queue[@]}"
1572         fi
1573 }
1574
1575 # @FUNCTION: optfeature
1576 # @USAGE: <short description> <package atom to match> [other atoms]
1577 # @DESCRIPTION:
1578 # Print out a message suggesting an optional package (or packages) which
1579 # provide the described functionality
1580 #
1581 # The following snippet would suggest app-misc/foo for optional foo support,
1582 # app-misc/bar or app-misc/baz[bar] for optional bar support
1583 # and either both app-misc/a and app-misc/b or app-misc/c for alphabet support.
1584 # @CODE
1585 #       optfeature "foo support" app-misc/foo
1586 #       optfeature "bar support" app-misc/bar app-misc/baz[bar]
1587 #       optfeature "alphabet support" "app-misc/a app-misc/b" app-misc/c
1588 # @CODE
1589 optfeature() {
1590         debug-print-function ${FUNCNAME} "$@"
1591         local i j msg
1592         local desc=$1
1593         local flag=0
1594         shift
1595         for i; do
1596                 for j in ${i}; do
1597                         if has_version "${j}"; then
1598                                 flag=1
1599                         else
1600                                 flag=0
1601                                 break
1602                         fi
1603                 done
1604                 if [[ ${flag} -eq 1 ]]; then
1605                         break
1606                 fi
1607         done
1608         if [[ ${flag} -eq 0 ]]; then
1609                 for i; do
1610                         msg=" "
1611                         for j in ${i}; do
1612                                 msg+=" ${j} and"
1613                         done
1614                         msg="${msg:0: -4} for ${desc}"
1615                         elog "${msg}"
1616                 done
1617         fi
1618 }
1619
1620 check_license() {
1621         die "you no longer need this as portage supports ACCEPT_LICENSE itself"
1622 }
1623
1624 case ${EAPI:-0} in
1625 0|1|2)
1626
1627 # @FUNCTION: epause
1628 # @USAGE: [seconds]
1629 # @DESCRIPTION:
1630 # Sleep for the specified number of seconds (default of 5 seconds).  Useful when
1631 # printing a message the user should probably be reading and often used in
1632 # conjunction with the ebeep function.  If the EPAUSE_IGNORE env var is set,
1633 # don't wait at all. Defined in EAPIs 0 1 and 2.
1634 epause() {
1635         [[ -z ${EPAUSE_IGNORE} ]] && sleep ${1:-5}
1636 }
1637
1638 # @FUNCTION: ebeep
1639 # @USAGE: [number of beeps]
1640 # @DESCRIPTION:
1641 # Issue the specified number of beeps (default of 5 beeps).  Useful when
1642 # printing a message the user should probably be reading and often used in
1643 # conjunction with the epause function.  If the EBEEP_IGNORE env var is set,
1644 # don't beep at all. Defined in EAPIs 0 1 and 2.
1645 ebeep() {
1646         local n
1647         if [[ -z ${EBEEP_IGNORE} ]] ; then
1648                 for ((n=1 ; n <= ${1:-5} ; n++)) ; do
1649                         echo -ne "\a"
1650                         sleep 0.1 &>/dev/null ; sleep 0,1 &>/dev/null
1651                         echo -ne "\a"
1652                         sleep 1
1653                 done
1654         fi
1655 }
1656
1657 ;;
1658 *)
1659
1660 ebeep() {
1661         ewarn "QA Notice: ebeep is not defined in EAPI=${EAPI}, please file a bug at https://bugs.gentoo.org"
1662 }
1663
1664 epause() {
1665         ewarn "QA Notice: epause is not defined in EAPI=${EAPI}, please file a bug at https://bugs.gentoo.org"
1666 }
1667
1668 ;;
1669 esac
1670
1671 case ${EAPI:-0} in
1672 0|1|2|3|4)
1673
1674 # @FUNCTION: usex
1675 # @USAGE: <USE flag> [true output] [false output] [true suffix] [false suffix]
1676 # @DESCRIPTION:
1677 # Proxy to declare usex for package managers or EAPIs that do not provide it
1678 # and use the package manager implementation when available (i.e. EAPI >= 5).
1679 # If USE flag is set, echo [true output][true suffix] (defaults to "yes"),
1680 # otherwise echo [false output][false suffix] (defaults to "no").
1681 usex() { use "$1" && echo "${2-yes}$4" || echo "${3-no}$5" ; } #382963
1682
1683 ;;
1684 esac
1685
1686 case ${EAPI:-0} in
1687 0|1|2|3|4|5)
1688
1689 # @VARIABLE: EPATCH_USER_SOURCE
1690 # @DESCRIPTION:
1691 # Location for user patches, see the epatch_user function.
1692 # Should be set by the user. Don't set this in ebuilds.
1693 : ${EPATCH_USER_SOURCE:=${PORTAGE_CONFIGROOT%/}/etc/portage/patches}
1694
1695 # @FUNCTION: epatch_user
1696 # @USAGE:
1697 # @DESCRIPTION:
1698 # Applies user-provided patches to the source tree. The patches are
1699 # taken from /etc/portage/patches/<CATEGORY>/<P-PR|P|PN>[:SLOT]/, where the first
1700 # of these three directories to exist will be the one to use, ignoring
1701 # any more general directories which might exist as well. They must end
1702 # in ".patch" to be applied.
1703 #
1704 # User patches are intended for quick testing of patches without ebuild
1705 # modifications, as well as for permanent customizations a user might
1706 # desire. Obviously, there can be no official support for arbitrarily
1707 # patched ebuilds. So whenever a build log in a bug report mentions that
1708 # user patches were applied, the user should be asked to reproduce the
1709 # problem without these.
1710 #
1711 # Not all ebuilds do call this function, so placing patches in the
1712 # stated directory might or might not work, depending on the package and
1713 # the eclasses it inherits and uses. It is safe to call the function
1714 # repeatedly, so it is always possible to add a call at the ebuild
1715 # level. The first call is the time when the patches will be
1716 # applied.
1717 #
1718 # Ideally, this function should be called after gentoo-specific patches
1719 # have been applied, so that their code can be modified as well, but
1720 # before calls to e.g. eautoreconf, as the user patches might affect
1721 # autotool input files as well.
1722 epatch_user() {
1723         [[ $# -ne 0 ]] && die "epatch_user takes no options"
1724
1725         # Allow multiple calls to this function; ignore all but the first
1726         local applied="${T}/epatch_user.log"
1727         [[ -e ${applied} ]] && return 2
1728
1729         # don't clobber any EPATCH vars that the parent might want
1730         local EPATCH_SOURCE check
1731         for check in ${CATEGORY}/{${P}-${PR},${P},${PN}}{,:${SLOT%/*}}; do
1732                 EPATCH_SOURCE=${EPATCH_USER_SOURCE}/${CTARGET}/${check}
1733                 [[ -r ${EPATCH_SOURCE} ]] || EPATCH_SOURCE=${EPATCH_USER_SOURCE}/${CHOST}/${check}
1734                 [[ -r ${EPATCH_SOURCE} ]] || EPATCH_SOURCE=${EPATCH_USER_SOURCE}/${check}
1735                 if [[ -d ${EPATCH_SOURCE} ]] ; then
1736                         local old_n_applied_patches=${EPATCH_N_APPLIED_PATCHES:-0}
1737                         EPATCH_SOURCE=${EPATCH_SOURCE} \
1738                         EPATCH_SUFFIX="patch" \
1739                         EPATCH_FORCE="yes" \
1740                         EPATCH_MULTI_MSG="Applying user patches from ${EPATCH_SOURCE} ..." \
1741                         epatch
1742                         echo "${EPATCH_SOURCE}" > "${applied}"
1743                         if [[ ${old_n_applied_patches} -lt ${EPATCH_N_APPLIED_PATCHES} ]]; then
1744                                 has epatch_user_death_notice ${EBUILD_DEATH_HOOKS} || \
1745                                         EBUILD_DEATH_HOOKS+=" epatch_user_death_notice"
1746                         fi
1747                         return 0
1748                 fi
1749         done
1750         echo "none" > "${applied}"
1751         return 1
1752 }
1753
1754 # @FUNCTION: epatch_user_death_notice
1755 # @INTERNAL
1756 # @DESCRIPTION:
1757 # Include an explicit notice in the die message itself that user patches were
1758 # applied to this build.
1759 epatch_user_death_notice() {
1760         ewarn "!!! User patches were applied to this build!"
1761 }
1762
1763 # @FUNCTION: einstalldocs
1764 # @DESCRIPTION:
1765 # Install documentation using DOCS and HTML_DOCS.
1766 #
1767 # If DOCS is declared and non-empty, all files listed in it are
1768 # installed. The files must exist, otherwise the function will fail.
1769 # In EAPI 4 and subsequent EAPIs DOCS may specify directories as well,
1770 # in other EAPIs using directories is unsupported.
1771 #
1772 # If DOCS is not declared, the files matching patterns given
1773 # in the default EAPI implementation of src_install will be installed.
1774 # If this is undesired, DOCS can be set to empty value to prevent any
1775 # documentation from being installed.
1776 #
1777 # If HTML_DOCS is declared and non-empty, all files and/or directories
1778 # listed in it are installed as HTML docs (using dohtml).
1779 #
1780 # Both DOCS and HTML_DOCS can either be an array or a whitespace-
1781 # separated list. Whenever directories are allowed, '<directory>/.' may
1782 # be specified in order to install all files within the directory
1783 # without creating a sub-directory in docdir.
1784 #
1785 # Passing additional options to dodoc and dohtml is not supported.
1786 # If you needed such a thing, you need to call those helpers explicitly.
1787 einstalldocs() {
1788         debug-print-function ${FUNCNAME} "${@}"
1789
1790         local dodoc_opts=-r
1791         has ${EAPI} 0 1 2 3 && dodoc_opts=
1792
1793         if ! declare -p DOCS &>/dev/null ; then
1794                 local d
1795                 for d in README* ChangeLog AUTHORS NEWS TODO CHANGES \
1796                                 THANKS BUGS FAQ CREDITS CHANGELOG ; do
1797                         if [[ -s ${d} ]] ; then
1798                                 dodoc "${d}" || die
1799                         fi
1800                 done
1801         elif [[ $(declare -p DOCS) == "declare -a"* ]] ; then
1802                 if [[ ${DOCS[@]} ]] ; then
1803                         dodoc ${dodoc_opts} "${DOCS[@]}" || die
1804                 fi
1805         else
1806                 if [[ ${DOCS} ]] ; then
1807                         dodoc ${dodoc_opts} ${DOCS} || die
1808                 fi
1809         fi
1810
1811         if [[ $(declare -p HTML_DOCS 2>/dev/null) == "declare -a"* ]] ; then
1812                 if [[ ${HTML_DOCS[@]} ]] ; then
1813                         dohtml -r "${HTML_DOCS[@]}" || die
1814                 fi
1815         else
1816                 if [[ ${HTML_DOCS} ]] ; then
1817                         dohtml -r ${HTML_DOCS} || die
1818                 fi
1819         fi
1820
1821         return 0
1822 }
1823
1824 # @FUNCTION: in_iuse
1825 # @USAGE: <flag>
1826 # @DESCRIPTION:
1827 # Determines whether the given flag is in IUSE. Strips IUSE default prefixes
1828 # as necessary.
1829 #
1830 # Note that this function should not be used in the global scope.
1831 in_iuse() {
1832         debug-print-function ${FUNCNAME} "${@}"
1833         [[ ${#} -eq 1 ]] || die "Invalid args to ${FUNCNAME}()"
1834
1835         local flag=${1}
1836         local liuse=( ${IUSE} )
1837
1838         has "${flag}" "${liuse[@]#[+-]}"
1839 }
1840
1841 ;;
1842 esac
1843
1844 fi