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