07f719a62a8c1eb0fdc6c6f2f39cc9db6c5026ed
[gentoo.git] / eclass / cmake-utils.eclass
1 # Copyright 1999-2017 Gentoo Foundation
2 # Distributed under the terms of the GNU General Public License v2
3
4 # @ECLASS: cmake-utils.eclass
5 # @MAINTAINER:
6 # kde@gentoo.org
7 # @AUTHOR:
8 # Tomáš Chvátal <scarabeus@gentoo.org>
9 # Maciej Mrozowski <reavertm@gentoo.org>
10 # (undisclosed contributors)
11 # Original author: Zephyrus (zephyrus@mirach.it)
12 # @BLURB: common ebuild functions for cmake-based packages
13 # @DESCRIPTION:
14 # The cmake-utils eclass makes creating ebuilds for cmake-based packages much easier.
15 # It provides all inherited features (DOCS, HTML_DOCS, PATCHES) along with out-of-source
16 # builds (default), in-source builds and an implementation of the well-known use_enable
17 # and use_with functions for CMake.
18
19 if [[ -z ${_CMAKE_UTILS_ECLASS} ]]; then
20 _CMAKE_UTILS_ECLASS=1
21
22 # @ECLASS-VARIABLE: BUILD_DIR
23 # @DESCRIPTION:
24 # Build directory where all cmake processed files should be generated.
25 # For in-source build it's fixed to ${CMAKE_USE_DIR}.
26 # For out-of-source build it can be overridden, by default it uses
27 # ${WORKDIR}/${P}_build.
28 #
29 # This variable has been called CMAKE_BUILD_DIR formerly.
30 # It is set under that name for compatibility.
31
32 # @ECLASS-VARIABLE: CMAKE_BINARY
33 # @DESCRIPTION:
34 # Eclass can use different cmake binary than the one provided in by system.
35 : ${CMAKE_BINARY:=cmake}
36
37 # @ECLASS-VARIABLE: CMAKE_BUILD_TYPE
38 # @DESCRIPTION:
39 # Set to override default CMAKE_BUILD_TYPE. Only useful for packages
40 # known to make use of "if (CMAKE_BUILD_TYPE MATCHES xxx)".
41 # If about to be set - needs to be set before invoking cmake-utils_src_configure.
42 # You usualy do *NOT* want nor need to set it as it pulls CMake default build-type
43 # specific compiler flags overriding make.conf.
44 : ${CMAKE_BUILD_TYPE:=Gentoo}
45
46 # @ECLASS-VARIABLE: CMAKE_IN_SOURCE_BUILD
47 # @DESCRIPTION:
48 # Set to enable in-source build.
49
50 # @ECLASS-VARIABLE: CMAKE_MAKEFILE_GENERATOR
51 # @DESCRIPTION:
52 # Specify a makefile generator to be used by cmake.
53 # At this point only "emake" and "ninja" are supported.
54 : ${CMAKE_MAKEFILE_GENERATOR:=emake}
55
56 # @ECLASS-VARIABLE: CMAKE_MIN_VERSION
57 # @DESCRIPTION:
58 # Specify the minimum required CMake version.
59 : ${CMAKE_MIN_VERSION:=3.7.2}
60
61 # @ECLASS-VARIABLE: CMAKE_REMOVE_MODULES
62 # @DESCRIPTION:
63 # Do we want to remove anything? yes or whatever else for no
64 : ${CMAKE_REMOVE_MODULES:=yes}
65
66 # @ECLASS-VARIABLE: CMAKE_REMOVE_MODULES_LIST
67 # @DESCRIPTION:
68 # Space-separated list of CMake modules that will be removed in $S during src_prepare,
69 # in order to force packages to use the system version.
70 : ${CMAKE_REMOVE_MODULES_LIST:=FindBLAS FindLAPACK}
71
72 # @ECLASS-VARIABLE: CMAKE_USE_DIR
73 # @DESCRIPTION:
74 # Sets the directory where we are working with cmake.
75 # For example when application uses autotools and only one
76 # plugin needs to be done by cmake.
77 # By default it uses ${S}.
78
79 # @ECLASS-VARIABLE: CMAKE_VERBOSE
80 # @DESCRIPTION:
81 # Set to OFF to disable verbose messages during compilation
82 : ${CMAKE_VERBOSE:=ON}
83
84 # @ECLASS-VARIABLE: CMAKE_WARN_UNUSED_CLI
85 # @DESCRIPTION:
86 # Warn about variables that are declared on the command line
87 # but not used. Might give false-positives.
88 # "no" to disable (default) or anything else to enable.
89
90 # @ECLASS-VARIABLE: PREFIX
91 # @DESCRIPTION:
92 # Eclass respects PREFIX variable, though it's not recommended way to set
93 # install/lib/bin prefixes.
94 # Use -DCMAKE_INSTALL_PREFIX=... CMake variable instead.
95 : ${PREFIX:=/usr}
96
97 # @ECLASS-VARIABLE: WANT_CMAKE
98 # @DESCRIPTION:
99 # Specify if cmake-utils eclass should depend on cmake optionally or not.
100 # This is useful when only part of application is using cmake build system.
101 # Valid values are: always [default], optional (where the value is the useflag
102 # used for optionality)
103 #
104 # This is banned in EAPI 6 and later.
105 : ${WANT_CMAKE:=always}
106
107 # @ECLASS-VARIABLE: CMAKE_EXTRA_CACHE_FILE
108 # @DESCRIPTION:
109 # Specifies an extra cache file to pass to cmake. This is the analog of EXTRA_ECONF
110 # for econf and is needed to pass TRY_RUN results when cross-compiling.
111 # Should be set by user in a per-package basis in /etc/portage/package.env.
112
113 case ${EAPI} in
114         2|4|5) : ${CMAKE_WARN_UNUSED_CLI:=no} ;;
115         6) : ${CMAKE_WARN_UNUSED_CLI:=yes} ;;
116         *) die "EAPI=${EAPI:-0} is not supported" ;;
117 esac
118
119 inherit toolchain-funcs multilib flag-o-matic eutils multiprocessing versionator
120
121 EXPORT_FUNCTIONS src_prepare src_configure src_compile src_test src_install
122
123 CMAKEDEPEND=""
124 case ${WANT_CMAKE} in
125         always)
126                 ;;
127         *)
128                 [[ ${EAPI} == [2345] ]] || die "WANT_CMAKE is banned in EAPI 6 and later"
129                 IUSE+=" ${WANT_CMAKE}"
130                 CMAKEDEPEND+="${WANT_CMAKE}? ( "
131                 ;;
132 esac
133
134 case ${CMAKE_MAKEFILE_GENERATOR} in
135         emake)
136                 CMAKEDEPEND+=" sys-devel/make"
137                 ;;
138         ninja)
139                 CMAKEDEPEND+=" dev-util/ninja"
140                 ;;
141         *)
142                 eerror "Unknown value for \${CMAKE_MAKEFILE_GENERATOR}"
143                 die "Value ${CMAKE_MAKEFILE_GENERATOR} is not supported"
144                 ;;
145 esac
146
147 if [[ ${PN} != cmake ]]; then
148         CMAKEDEPEND+=" >=dev-util/cmake-${CMAKE_MIN_VERSION}"
149 fi
150
151 [[ ${WANT_CMAKE} = always ]] || CMAKEDEPEND+=" )"
152
153 DEPEND="${CMAKEDEPEND}"
154 unset CMAKEDEPEND
155
156 # Internal functions used by cmake-utils_use_*
157 _cmake_use_me_now() {
158         debug-print-function ${FUNCNAME} "$@"
159
160         local arg=$2
161         [[ ! -z $3 ]] && arg=$3
162
163         [[ ${EAPI} == [2345] ]] || die "${FUNCNAME[1]} is banned in EAPI 6 and later: use -D$1<related_CMake_variable>=\"\$(usex $2)\" instead"
164
165         local uper capitalised x
166         [[ -z $2 ]] && die "cmake-utils_use-$1 <USE flag> [<flag name>]"
167         if [[ ! -z $3 ]]; then
168                 # user specified the use name so use it
169                 echo "-D$1$3=$(use $2 && echo ON || echo OFF)"
170         else
171                 # use all various most used combinations
172                 uper=$(echo ${2} | tr '[:lower:]' '[:upper:]')
173                 capitalised=$(echo ${2} | sed 's/\<\(.\)\([^ ]*\)/\u\1\L\2/g')
174                 for x in $2 $uper $capitalised; do
175                         echo "-D$1$x=$(use $2 && echo ON || echo OFF) "
176                 done
177         fi
178 }
179 _cmake_use_me_now_inverted() {
180         debug-print-function ${FUNCNAME} "$@"
181
182         local arg=$2
183         [[ ! -z $3 ]] && arg=$3
184
185         if [[ ${EAPI} != [2345] && "${FUNCNAME[1]}" != cmake-utils_use_find_package ]] ; then
186                 die "${FUNCNAME[1]} is banned in EAPI 6 and later: use -D$1<related_CMake_variable>=\"\$(usex $2)\" instead"
187         fi
188
189         local uper capitalised x
190         [[ -z $2 ]] && die "cmake-utils_use-$1 <USE flag> [<flag name>]"
191         if [[ ! -z $3 ]]; then
192                 # user specified the use name so use it
193                 echo "-D$1$3=$(use $2 && echo OFF || echo ON)"
194         else
195                 # use all various most used combinations
196                 uper=$(echo ${2} | tr '[:lower:]' '[:upper:]')
197                 capitalised=$(echo ${2} | sed 's/\<\(.\)\([^ ]*\)/\u\1\L\2/g')
198                 for x in $2 $uper $capitalised; do
199                         echo "-D$1$x=$(use $2 && echo OFF || echo ON) "
200                 done
201         fi
202 }
203
204 # Determine using IN or OUT source build
205 _cmake_check_build_dir() {
206         : ${CMAKE_USE_DIR:=${S}}
207         if [[ -n ${CMAKE_IN_SOURCE_BUILD} ]]; then
208                 # we build in source dir
209                 BUILD_DIR="${CMAKE_USE_DIR}"
210         else
211                 # Respect both the old variable and the new one, depending
212                 # on which one was set by the ebuild.
213                 if [[ ! ${BUILD_DIR} && ${CMAKE_BUILD_DIR} ]]; then
214                         eqawarn "The CMAKE_BUILD_DIR variable has been renamed to BUILD_DIR."
215                         eqawarn "Please migrate the ebuild to use the new one."
216
217                         # In the next call, both variables will be set already
218                         # and we'd have to know which one takes precedence.
219                         _RESPECT_CMAKE_BUILD_DIR=1
220                 fi
221
222                 if [[ ${_RESPECT_CMAKE_BUILD_DIR} ]]; then
223                         BUILD_DIR=${CMAKE_BUILD_DIR:-${WORKDIR}/${P}_build}
224                 else
225                         : ${BUILD_DIR:=${WORKDIR}/${P}_build}
226                 fi
227         fi
228
229         # Backwards compatibility for getting the value.
230         CMAKE_BUILD_DIR=${BUILD_DIR}
231
232         mkdir -p "${BUILD_DIR}" || die
233         echo ">>> Working in BUILD_DIR: \"$BUILD_DIR\""
234 }
235
236 # Determine which generator to use
237 _cmake_generator_to_use() {
238         local generator_name
239
240         case ${CMAKE_MAKEFILE_GENERATOR} in
241                 ninja)
242                         # if ninja is enabled but not installed, the build could fail
243                         # this could happen if ninja is manually enabled (eg. make.conf) but not installed
244                         if ! ROOT=/ has_version dev-util/ninja; then
245                                 die "CMAKE_MAKEFILE_GENERATOR is set to ninja, but ninja is not installed. Please install dev-util/ninja or unset CMAKE_MAKEFILE_GENERATOR."
246                         fi
247                         generator_name="Ninja"
248                         ;;
249                 emake)
250                         generator_name="Unix Makefiles"
251                         ;;
252                 *)
253                         eerror "Unknown value for \${CMAKE_MAKEFILE_GENERATOR}"
254                         die "Value ${CMAKE_MAKEFILE_GENERATOR} is not supported"
255                         ;;
256         esac
257
258         echo ${generator_name}
259 }
260
261 # @FUNCTION: cmake_comment_add_subdirectory
262 # @USAGE: <subdirectory>
263 # @DESCRIPTION:
264 # Comment out one or more add_subdirectory calls in CMakeLists.txt in the current directory
265 cmake_comment_add_subdirectory() {
266         if [[ -z ${1} ]]; then
267                 die "comment_add_subdirectory must be passed at least one directory name to comment"
268         fi
269
270         if [[ -e "CMakeLists.txt" ]]; then
271                 local d
272                 for d in $@; do
273                         sed -e "/add_subdirectory[[:space:]]*([[:space:]]*${d//\//\\/}[[:space:]]*)/I s/^/#DONOTCOMPILE /" \
274                                 -i CMakeLists.txt || die "failed to comment add_subdirectory(${d})"
275                 done
276         fi
277 }
278
279 # @FUNCTION: comment_add_subdirectory
280 # @USAGE: <subdirectory>
281 # @DESCRIPTION:
282 # Comment out an add_subdirectory call in CMakeLists.txt in the current directory
283 # Banned in EAPI 6 and later - use cmake_comment_add_subdirectory instead.
284 comment_add_subdirectory() {
285         [[ ${EAPI} == [2345] ]] || die "comment_add_subdirectory is banned in EAPI 6 and later - use cmake_comment_add_subdirectory instead"
286
287         cmake_comment_add_subdirectory "$@"
288 }
289
290 # @FUNCTION: cmake-utils_use_with
291 # @USAGE: <USE flag> [flag name]
292 # @DESCRIPTION:
293 # Based on use_with. See ebuild(5).
294 #
295 # `cmake-utils_use_with foo FOO` echoes -DWITH_FOO=ON if foo is enabled
296 # and -DWITH_FOO=OFF if it is disabled.
297 cmake-utils_use_with() { _cmake_use_me_now WITH_ "$@" ; }
298
299 # @FUNCTION: cmake-utils_use_enable
300 # @USAGE: <USE flag> [flag name]
301 # @DESCRIPTION:
302 # Based on use_enable. See ebuild(5).
303 #
304 # `cmake-utils_use_enable foo FOO` echoes -DENABLE_FOO=ON if foo is enabled
305 # and -DENABLE_FOO=OFF if it is disabled.
306 cmake-utils_use_enable() { _cmake_use_me_now ENABLE_ "$@" ; }
307
308 # @FUNCTION: cmake-utils_use_find_package
309 # @USAGE: <USE flag> <package name>
310 # @DESCRIPTION:
311 # Based on use_enable. See ebuild(5).
312 #
313 # `cmake-utils_use_find_package foo LibFoo` echoes -DCMAKE_DISABLE_FIND_PACKAGE_LibFoo=OFF
314 # if foo is enabled and -DCMAKE_DISABLE_FIND_PACKAGE_LibFoo=ON if it is disabled.
315 # This can be used to make find_package optional.
316 cmake-utils_use_find_package() {
317         if [[ ${EAPI} != [2345] && "$#" != 2 ]] ; then
318                 die "Usage: cmake-utils_use_find_package <USE flag> <package name>"
319         fi
320
321         _cmake_use_me_now_inverted CMAKE_DISABLE_FIND_PACKAGE_ "$@" ;
322 }
323
324 # @FUNCTION: cmake-utils_use_disable
325 # @USAGE: <USE flag> [flag name]
326 # @DESCRIPTION:
327 # Based on inversion of use_enable. See ebuild(5).
328 #
329 # `cmake-utils_use_enable foo FOO` echoes -DDISABLE_FOO=OFF if foo is enabled
330 # and -DDISABLE_FOO=ON if it is disabled.
331 cmake-utils_use_disable() { _cmake_use_me_now_inverted DISABLE_ "$@" ; }
332
333 # @FUNCTION: cmake-utils_use_no
334 # @USAGE: <USE flag> [flag name]
335 # @DESCRIPTION:
336 # Based on use_disable. See ebuild(5).
337 #
338 # `cmake-utils_use_no foo FOO` echoes -DNO_FOO=OFF if foo is enabled
339 # and -DNO_FOO=ON if it is disabled.
340 cmake-utils_use_no() { _cmake_use_me_now_inverted NO_ "$@" ; }
341
342 # @FUNCTION: cmake-utils_use_want
343 # @USAGE: <USE flag> [flag name]
344 # @DESCRIPTION:
345 # Based on use_enable. See ebuild(5).
346 #
347 # `cmake-utils_use_want foo FOO` echoes -DWANT_FOO=ON if foo is enabled
348 # and -DWANT_FOO=OFF if it is disabled.
349 cmake-utils_use_want() { _cmake_use_me_now WANT_ "$@" ; }
350
351 # @FUNCTION: cmake-utils_use_build
352 # @USAGE: <USE flag> [flag name]
353 # @DESCRIPTION:
354 # Based on use_enable. See ebuild(5).
355 #
356 # `cmake-utils_use_build foo FOO` echoes -DBUILD_FOO=ON if foo is enabled
357 # and -DBUILD_FOO=OFF if it is disabled.
358 cmake-utils_use_build() { _cmake_use_me_now BUILD_ "$@" ; }
359
360 # @FUNCTION: cmake-utils_use_has
361 # @USAGE: <USE flag> [flag name]
362 # @DESCRIPTION:
363 # Based on use_enable. See ebuild(5).
364 #
365 # `cmake-utils_use_has foo FOO` echoes -DHAVE_FOO=ON if foo is enabled
366 # and -DHAVE_FOO=OFF if it is disabled.
367 cmake-utils_use_has() { _cmake_use_me_now HAVE_ "$@" ; }
368
369 # @FUNCTION: cmake-utils_use_use
370 # @USAGE: <USE flag> [flag name]
371 # @DESCRIPTION:
372 # Based on use_enable. See ebuild(5).
373 #
374 # `cmake-utils_use_use foo FOO` echoes -DUSE_FOO=ON if foo is enabled
375 # and -DUSE_FOO=OFF if it is disabled.
376 cmake-utils_use_use() { _cmake_use_me_now USE_ "$@" ; }
377
378 # @FUNCTION: cmake-utils_use
379 # @USAGE: <USE flag> [flag name]
380 # @DESCRIPTION:
381 # Based on use_enable. See ebuild(5).
382 #
383 # `cmake-utils_use foo FOO` echoes -DFOO=ON if foo is enabled
384 # and -DFOO=OFF if it is disabled.
385 cmake-utils_use() { _cmake_use_me_now "" "$@" ; }
386
387 # @FUNCTION: cmake-utils_useno
388 # @USAGE: <USE flag> [flag name]
389 # @DESCRIPTION:
390 # Based on use_enable. See ebuild(5).
391 #
392 # `cmake-utils_useno foo NOFOO` echoes -DNOFOO=OFF if foo is enabled
393 # and -DNOFOO=ON if it is disabled.
394 cmake-utils_useno() { _cmake_use_me_now_inverted "" "$@" ; }
395
396 # Internal function for modifying hardcoded definitions.
397 # Removes dangerous definitions that override Gentoo settings.
398 _cmake_modify-cmakelists() {
399         debug-print-function ${FUNCNAME} "$@"
400
401         # Only edit the files once
402         grep -qs "<<< Gentoo configuration >>>" "${CMAKE_USE_DIR}"/CMakeLists.txt && return 0
403
404         # Comment out all set (<some_should_be_user_defined_variable> value)
405         # TODO Add QA checker - inform when variable being checked for below is set in CMakeLists.txt
406         find "${CMAKE_USE_DIR}" -name CMakeLists.txt \
407                 -exec sed -i -e '/^[[:space:]]*[sS][eE][tT][[:space:]]*([[:space:]]*CMAKE_BUILD_TYPE.*)/{s/^/#IGNORE /g}' {} + \
408                 -exec sed -i -e '/^[[:space:]]*[sS][eE][tT][[:space:]]*([[:space:]]*CMAKE_COLOR_MAKEFILE.*)/{s/^/#IGNORE /g}' {} + \
409                 -exec sed -i -e '/^[[:space:]]*[sS][eE][tT][[:space:]]*([[:space:]]*CMAKE_INSTALL_PREFIX.*)/{s/^/#IGNORE /g}' {} + \
410                 -exec sed -i -e '/^[[:space:]]*[sS][eE][tT][[:space:]]*([[:space:]]*CMAKE_VERBOSE_MAKEFILE.*)/{s/^/#IGNORE /g}' {} + \
411                 || die "${LINENO}: failed to disable hardcoded settings"
412
413         # NOTE Append some useful summary here
414         cat >> "${CMAKE_USE_DIR}"/CMakeLists.txt <<- _EOF_ || die
415
416                 MESSAGE(STATUS "<<< Gentoo configuration >>>
417                 Build type      \${CMAKE_BUILD_TYPE}
418                 Install path    \${CMAKE_INSTALL_PREFIX}
419                 Compiler flags:
420                 C               \${CMAKE_C_FLAGS}
421                 C++             \${CMAKE_CXX_FLAGS}
422                 Linker flags:
423                 Executable      \${CMAKE_EXE_LINKER_FLAGS}
424                 Module          \${CMAKE_MODULE_LINKER_FLAGS}
425                 Shared          \${CMAKE_SHARED_LINKER_FLAGS}\n")
426         _EOF_
427 }
428
429 # temporary function for moving cmake cleanups from from src_configure -> src_prepare.
430 # bug #378850
431 _cmake_cleanup_cmake() {
432         : ${CMAKE_USE_DIR:=${S}}
433
434         if [[ "${CMAKE_REMOVE_MODULES}" == "yes" ]] ; then
435                 local name
436                 for name in ${CMAKE_REMOVE_MODULES_LIST} ; do
437                         find "${S}" -name ${name}.cmake -exec rm -v {} + || die
438                 done
439         fi
440
441         # check if CMakeLists.txt exist and if no then die
442         if [[ ! -e ${CMAKE_USE_DIR}/CMakeLists.txt ]] ; then
443                 eerror "Unable to locate CMakeLists.txt under:"
444                 eerror "\"${CMAKE_USE_DIR}/CMakeLists.txt\""
445                 eerror "Consider not inheriting the cmake eclass."
446                 die "FATAL: Unable to find CMakeLists.txt"
447         fi
448
449         # Remove dangerous things.
450         _cmake_modify-cmakelists
451 }
452
453 enable_cmake-utils_src_prepare() {
454         debug-print-function ${FUNCNAME} "$@"
455
456         pushd "${S}" > /dev/null || die
457
458         if [[ ${EAPI} != [2345] ]]; then
459                 default_src_prepare
460                 _cmake_cleanup_cmake
461         else
462                 debug-print "$FUNCNAME: PATCHES=$PATCHES"
463                 [[ ${PATCHES[@]} ]] && epatch "${PATCHES[@]}"
464
465                 debug-print "$FUNCNAME: applying user patches"
466                 epatch_user
467         fi
468
469         popd > /dev/null || die
470 }
471
472 # @VARIABLE: mycmakeargs
473 # @DEFAULT_UNSET
474 # @DESCRIPTION:
475 # Optional cmake defines as a bash array. Should be defined before calling
476 # src_configure.
477 # @CODE
478 # src_configure() {
479 #       local mycmakeargs=(
480 #               $(cmake-utils_use_with openconnect)
481 #       )
482 #
483 #       cmake-utils_src_configure
484 # }
485 # @CODE
486
487 enable_cmake-utils_src_configure() {
488         debug-print-function ${FUNCNAME} "$@"
489
490         [[ ${EAPI} == [2345] ]] && _cmake_cleanup_cmake
491
492         _cmake_check_build_dir
493
494         # Fix xdg collision with sandbox
495         local -x XDG_CONFIG_HOME="${T}"
496
497         # @SEE CMAKE_BUILD_TYPE
498         if [[ ${CMAKE_BUILD_TYPE} = Gentoo ]]; then
499                 # Handle release builds
500                 if ! has debug ${IUSE//+} || ! use debug; then
501                         local CPPFLAGS=${CPPFLAGS}
502                         append-cppflags -DNDEBUG
503                 fi
504         fi
505
506         # Prepare Gentoo override rules (set valid compiler, append CPPFLAGS etc.)
507         local build_rules=${BUILD_DIR}/gentoo_rules.cmake
508         # Since cmake-3.4.0_rc1 "<FLAGS>" no longer contains includes and thus
509         # we need to add "<INCLUDES>"
510         local includes=
511         if [[ ${PN} == cmake ]] ; then
512                 if $(version_is_at_least 3.4.0 $(get_version_component_range 1-3 ${PV})) ; then
513                         includes="<INCLUDES>"
514                 fi
515         elif ROOT=/ has_version \>=dev-util/cmake-3.4.0_rc1 ; then
516                 includes="<INCLUDES>"
517         fi
518         cat > "${build_rules}" <<- _EOF_ || die
519                 SET (CMAKE_ASM_COMPILE_OBJECT "<CMAKE_ASM_COMPILER> <DEFINES> ${includes} ${CPPFLAGS} <FLAGS> -o <OBJECT> -c <SOURCE>" CACHE STRING "ASM compile command" FORCE)
520                 SET (CMAKE_C_COMPILE_OBJECT "<CMAKE_C_COMPILER> <DEFINES> ${includes} ${CPPFLAGS} <FLAGS> -o <OBJECT> -c <SOURCE>" CACHE STRING "C compile command" FORCE)
521                 SET (CMAKE_CXX_COMPILE_OBJECT "<CMAKE_CXX_COMPILER> <DEFINES> ${includes} ${CPPFLAGS} <FLAGS> -o <OBJECT> -c <SOURCE>" CACHE STRING "C++ compile command" FORCE)
522                 SET (CMAKE_Fortran_COMPILE_OBJECT "<CMAKE_Fortran_COMPILER> <DEFINES> ${includes} ${FCFLAGS} <FLAGS> -o <OBJECT> -c <SOURCE>" CACHE STRING "Fortran compile command" FORCE)
523         _EOF_
524
525         local myCC=$(tc-getCC) myCXX=$(tc-getCXX) myFC=$(tc-getFC)
526
527         # !!! IMPORTANT NOTE !!!
528         # Single slash below is intentional. CMake is weird and wants the
529         # CMAKE_*_VARIABLES split into two elements: the first one with
530         # compiler path, and the second one with all command-line options,
531         # space separated.
532         local toolchain_file=${BUILD_DIR}/gentoo_toolchain.cmake
533         cat > ${toolchain_file} <<- _EOF_ || die
534                 SET (CMAKE_ASM_COMPILER "${myCC/ /;}")
535                 SET (CMAKE_C_COMPILER "${myCC/ /;}")
536                 SET (CMAKE_CXX_COMPILER "${myCXX/ /;}")
537                 SET (CMAKE_Fortran_COMPILER "${myFC/ /;}")
538                 SET (CMAKE_AR $(type -P $(tc-getAR)) CACHE FILEPATH "Archive manager" FORCE)
539                 SET (CMAKE_RANLIB $(type -P $(tc-getRANLIB)) CACHE FILEPATH "Archive index generator" FORCE)
540                 SET (CMAKE_SYSTEM_PROCESSOR "${CHOST%%-*}")
541         _EOF_
542
543         # We are using the C compiler for assembly by default.
544         local -x ASMFLAGS=${CFLAGS}
545         local -x PKG_CONFIG=$(tc-getPKG_CONFIG)
546
547         if tc-is-cross-compiler; then
548                 local sysname
549                 case "${KERNEL:-linux}" in
550                         Cygwin) sysname="CYGWIN_NT-5.1" ;;
551                         HPUX) sysname="HP-UX" ;;
552                         linux) sysname="Linux" ;;
553                         Winnt)
554                                 sysname="Windows"
555                                 cat >> "${toolchain_file}" <<- _EOF_ || die
556                                         SET (CMAKE_RC_COMPILER $(tc-getRC))
557                                 _EOF_
558                                 ;;
559                         *) sysname="${KERNEL}" ;;
560                 esac
561
562                 cat >> "${toolchain_file}" <<- _EOF_ || die
563                         SET (CMAKE_SYSTEM_NAME "${sysname}")
564                 _EOF_
565
566                 if [ "${SYSROOT:-/}" != "/" ] ; then
567                         # When cross-compiling with a sysroot (e.g. with crossdev's emerge wrappers)
568                         # we need to tell cmake to use libs/headers from the sysroot but programs from / only.
569                         cat >> "${toolchain_file}" <<- _EOF_ || die
570                                 set(CMAKE_FIND_ROOT_PATH "${SYSROOT}")
571                                 set(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER)
572                                 set(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY)
573                                 set(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY)
574                         _EOF_
575                 fi
576         fi
577
578         [[ ${EAPI} == 2 ]] && ! use prefix && local EPREFIX=
579
580         if [[ ${EPREFIX} ]]; then
581                 cat >> "${build_rules}" <<- _EOF_ || die
582                         # in Prefix we need rpath and must ensure cmake gets our default linker path
583                         # right ... except for Darwin hosts
584                         IF (NOT APPLE)
585                         SET (CMAKE_SKIP_RPATH OFF CACHE BOOL "" FORCE)
586                         SET (CMAKE_PLATFORM_REQUIRED_RUNTIME_PATH "${EPREFIX}/usr/${CHOST}/lib/gcc;${EPREFIX}/usr/${CHOST}/lib;${EPREFIX}/usr/$(get_libdir);${EPREFIX}/$(get_libdir)"
587                         CACHE STRING "" FORCE)
588
589                         ELSE ()
590
591                         SET(CMAKE_PREFIX_PATH "${EPREFIX}${PREFIX}" CACHE STRING "" FORCE)
592                         SET(CMAKE_SKIP_BUILD_RPATH OFF CACHE BOOL "" FORCE)
593                         SET(CMAKE_SKIP_RPATH OFF CACHE BOOL "" FORCE)
594                         SET(CMAKE_BUILD_WITH_INSTALL_RPATH TRUE CACHE BOOL "")
595                         SET(CMAKE_INSTALL_RPATH "${EPREFIX}${PREFIX}/lib;${EPREFIX}/usr/${CHOST}/lib/gcc;${EPREFIX}/usr/${CHOST}/lib;${EPREFIX}/usr/$(get_libdir);${EPREFIX}/$(get_libdir)" CACHE STRING "" FORCE)
596                         SET(CMAKE_INSTALL_RPATH_USE_LINK_PATH TRUE CACHE BOOL "" FORCE)
597                         SET(CMAKE_INSTALL_NAME_DIR "${EPREFIX}${PREFIX}/lib" CACHE STRING "" FORCE)
598
599                         ENDIF (NOT APPLE)
600                 _EOF_
601         fi
602
603         # Common configure parameters (invariants)
604         local common_config=${BUILD_DIR}/gentoo_common_config.cmake
605         local libdir=$(get_libdir)
606         cat > "${common_config}" <<- _EOF_ || die
607                 SET (CMAKE_GENTOO_BUILD ON CACHE BOOL "Indicate Gentoo package build")
608                 SET (LIB_SUFFIX ${libdir/lib} CACHE STRING "library path suffix" FORCE)
609                 SET (CMAKE_INSTALL_LIBDIR ${libdir} CACHE PATH "Output directory for libraries")
610         _EOF_
611         [[ "${NOCOLOR}" = true || "${NOCOLOR}" = yes ]] && echo 'SET (CMAKE_COLOR_MAKEFILE OFF CACHE BOOL "pretty colors during make" FORCE)' >> "${common_config}"
612
613         # Wipe the default optimization flags out of CMake
614         if [[ ${CMAKE_BUILD_TYPE} != Gentoo ]] && ! has "${EAPI}" 2 3 4 5; then
615                 cat >> ${common_config} <<- _EOF_ || die
616                         SET (CMAKE_ASM_FLAGS_${CMAKE_BUILD_TYPE^^} "" CACHE STRING "")
617                         SET (CMAKE_C_FLAGS_${CMAKE_BUILD_TYPE^^} "" CACHE STRING "")
618                         SET (CMAKE_CXX_FLAGS_${CMAKE_BUILD_TYPE^^} "" CACHE STRING "")
619                         SET (CMAKE_Fortran_FLAGS_${CMAKE_BUILD_TYPE^^} "" CACHE STRING "")
620                         SET (CMAKE_EXE_LINKER_FLAGS_${CMAKE_BUILD_TYPE^^} "" CACHE STRING "")
621                         SET (CMAKE_MODULE_LINKER_FLAGS_${CMAKE_BUILD_TYPE^^} "" CACHE STRING "")
622                         SET (CMAKE_SHARED_LINKER_FLAGS_${CMAKE_BUILD_TYPE^^} "" CACHE STRING "")
623                         SET (CMAKE_STATIC_LINKER_FLAGS_${CMAKE_BUILD_TYPE^^} "" CACHE STRING "")
624                 _EOF_
625         fi
626
627         # Convert mycmakeargs to an array, for backwards compatibility
628         # Make the array a local variable since <=portage-2.1.6.x does not
629         # support global arrays (see bug #297255).
630         local mycmakeargstype=$(declare -p mycmakeargs 2>&-)
631         if [[ "${mycmakeargstype}" != "declare -a mycmakeargs="* ]]; then
632                 if [[ -n "${mycmakeargstype}" ]] ; then
633                         if [[ ${EAPI} == [2345] ]]; then
634                                 eqawarn "Declaring mycmakeargs as a variable is deprecated. Please use an array instead."
635                         else
636                                 die "Declaring mycmakeargs as a variable is banned in EAPI=${EAPI}. Please use an array instead."
637                         fi
638                 fi
639                 local mycmakeargs_local=(${mycmakeargs})
640         else
641                 local mycmakeargs_local=("${mycmakeargs[@]}")
642         fi
643
644         if [[ ${CMAKE_WARN_UNUSED_CLI} == no ]] ; then
645                 local warn_unused_cli="--no-warn-unused-cli"
646         else
647                 local warn_unused_cli=""
648         fi
649
650         # Common configure parameters (overridable)
651         # NOTE CMAKE_BUILD_TYPE can be only overriden via CMAKE_BUILD_TYPE eclass variable
652         # No -DCMAKE_BUILD_TYPE=xxx definitions will be in effect.
653         local cmakeargs=(
654                 ${warn_unused_cli}
655                 -C "${common_config}"
656                 -G "$(_cmake_generator_to_use)"
657                 -DCMAKE_INSTALL_PREFIX="${EPREFIX}${PREFIX}"
658                 "${mycmakeargs_local[@]}"
659                 -DCMAKE_BUILD_TYPE="${CMAKE_BUILD_TYPE}"
660                 $([[ ${EAPI} == [2345] ]] && echo -DCMAKE_INSTALL_DO_STRIP=OFF)
661                 -DCMAKE_USER_MAKE_RULES_OVERRIDE="${build_rules}"
662                 -DCMAKE_TOOLCHAIN_FILE="${toolchain_file}"
663                 "${MYCMAKEARGS}"
664         )
665
666         if [[ -n "${CMAKE_EXTRA_CACHE_FILE}" ]] ; then
667                 cmakeargs+=( -C "${CMAKE_EXTRA_CACHE_FILE}" )
668         fi
669
670         pushd "${BUILD_DIR}" > /dev/null || die
671         debug-print "${LINENO} ${ECLASS} ${FUNCNAME}: mycmakeargs is ${mycmakeargs_local[*]}"
672         echo "${CMAKE_BINARY}" "${cmakeargs[@]}" "${CMAKE_USE_DIR}"
673         "${CMAKE_BINARY}" "${cmakeargs[@]}" "${CMAKE_USE_DIR}" || die "cmake failed"
674         popd > /dev/null || die
675 }
676
677 enable_cmake-utils_src_compile() {
678         debug-print-function ${FUNCNAME} "$@"
679
680         cmake-utils_src_make "$@"
681 }
682
683 _ninjaopts_from_makeopts() {
684         if [[ ${NINJAOPTS+set} == set ]]; then
685                 return 0
686         fi
687         local ninjaopts=()
688         set -- ${MAKEOPTS}
689         while (( $# )); do
690                 case $1 in
691                         -j|-l)
692                                 if [[ $# -eq 1 || $2 == -* ]]; then
693                                         if [[ $1 == -j ]]; then
694                                                 # absurdly high job limit
695                                                 ninjaopts+=( $1 9999 )
696                                         else # -l
697                                                 # remove load limit (like make does for -l)
698                                                 ninjaopts+=( $1 0 )
699                                         fi
700                                         shift 1
701                                 else
702                                         ninjaopts+=( $1 $2 )
703                                         shift 2
704                                 fi
705                                 ;;
706                         -j*|-l*)
707                                 ninjaopts+=( $1 )
708                                 shift 1
709                                 ;;
710                         -k)
711                                 # -k 0 = any number of tasks can fail
712                                 ninjaopts+=( $1 0 )
713                                 shift 1
714                                 ;;
715                         *) shift ;;
716                 esac
717         done
718         export NINJAOPTS="${ninjaopts[*]}"
719 }
720
721 # @FUNCTION: _cmake_ninja_src_make
722 # @INTERNAL
723 # @DESCRIPTION:
724 # Build the package using ninja generator
725 _cmake_ninja_src_make() {
726         debug-print-function ${FUNCNAME} "$@"
727
728         [[ -e build.ninja ]] || die "build.ninja not found. Error during configure stage."
729
730         _ninjaopts_from_makeopts
731
732         if [[ "${CMAKE_VERBOSE}" != "OFF" ]]; then
733                 set -- ninja ${NINJAOPTS} -v "$@"
734         else
735                 set -- ninja ${NINJAOPTS} "$@"
736         fi
737
738         echo "$@"
739         "$@" || die
740 }
741
742 # @FUNCTION: _cmake_emake_src_make
743 # @INTERNAL
744 # @DESCRIPTION:
745 # Build the package using make generator
746 _cmake_emake_src_make() {
747         debug-print-function ${FUNCNAME} "$@"
748
749         [[ -e Makefile ]] || die "Makefile not found. Error during configure stage."
750
751         if [[ "${CMAKE_VERBOSE}" != "OFF" ]]; then
752                 emake VERBOSE=1 "$@" || die
753         else
754                 emake "$@" || die
755         fi
756
757 }
758
759 # @FUNCTION: cmake-utils_src_make
760 # @DESCRIPTION:
761 # Function for building the package. Automatically detects the build type.
762 # All arguments are passed to emake.
763 cmake-utils_src_make() {
764         debug-print-function ${FUNCNAME} "$@"
765
766         _cmake_check_build_dir
767         pushd "${BUILD_DIR}" > /dev/null || die
768
769         _cmake_${CMAKE_MAKEFILE_GENERATOR}_src_make "$@"
770
771         popd > /dev/null || die
772 }
773
774 enable_cmake-utils_src_test() {
775         debug-print-function ${FUNCNAME} "$@"
776
777         _cmake_check_build_dir
778         pushd "${BUILD_DIR}" > /dev/null || die
779         [[ -e CTestTestfile.cmake ]] || { echo "No tests found. Skipping."; return 0 ; }
780
781         [[ -n ${TEST_VERBOSE} ]] && myctestargs+=( --extra-verbose --output-on-failure )
782
783         set -- ctest -j "$(makeopts_jobs)" --test-load "$(makeopts_loadavg)" "${myctestargs[@]}" "$@"
784         echo "$@" >&2
785         if "$@" ; then
786                 einfo "Tests succeeded."
787                 popd > /dev/null || die
788                 return 0
789         else
790                 if [[ -n "${CMAKE_YES_I_WANT_TO_SEE_THE_TEST_LOG}" ]] ; then
791                         # on request from Diego
792                         eerror "Tests failed. Test log ${BUILD_DIR}/Testing/Temporary/LastTest.log follows:"
793                         eerror "--START TEST LOG--------------------------------------------------------------"
794                         cat "${BUILD_DIR}/Testing/Temporary/LastTest.log"
795                         eerror "--END TEST LOG----------------------------------------------------------------"
796                         die "Tests failed."
797                 else
798                         die "Tests failed. When you file a bug, please attach the following file: \n\t${BUILD_DIR}/Testing/Temporary/LastTest.log"
799                 fi
800
801                 # die might not die due to nonfatal
802                 popd > /dev/null || die
803                 return 1
804         fi
805 }
806
807 enable_cmake-utils_src_install() {
808         debug-print-function ${FUNCNAME} "$@"
809
810         _cmake_check_build_dir
811         pushd "${BUILD_DIR}" > /dev/null || die
812         DESTDIR="${D}" ${CMAKE_MAKEFILE_GENERATOR} install "$@" || die "died running ${CMAKE_MAKEFILE_GENERATOR} install"
813         popd > /dev/null || die
814
815         pushd "${S}" > /dev/null || die
816         einstalldocs
817         popd > /dev/null || die
818 }
819
820 # @FUNCTION: cmake-utils_src_prepare
821 # @DESCRIPTION:
822 # Apply ebuild and user patches.
823 cmake-utils_src_prepare() {
824         _cmake_execute_optionally "src_prepare" "$@"
825 }
826
827 # @FUNCTION: cmake-utils_src_configure
828 # @DESCRIPTION:
829 # General function for configuring with cmake. Default behaviour is to start an
830 # out-of-source build.
831 cmake-utils_src_configure() {
832         _cmake_execute_optionally "src_configure" "$@"
833 }
834
835 # @FUNCTION: cmake-utils_src_compile
836 # @DESCRIPTION:
837 # General function for compiling with cmake.
838 # Automatically detects the build type. All arguments are passed to emake.
839 cmake-utils_src_compile() {
840         _cmake_execute_optionally "src_compile" "$@"
841 }
842
843 # @FUNCTION: cmake-utils_src_test
844 # @DESCRIPTION:
845 # Function for testing the package. Automatically detects the build type.
846 cmake-utils_src_test() {
847         _cmake_execute_optionally "src_test" "$@"
848 }
849
850 # @FUNCTION: cmake-utils_src_install
851 # @DESCRIPTION:
852 # Function for installing the package. Automatically detects the build type.
853 cmake-utils_src_install() {
854         _cmake_execute_optionally "src_install" "$@"
855 }
856
857 # Optionally executes phases based on WANT_CMAKE variable/USE flag.
858 _cmake_execute_optionally() {
859         local phase="$1" ; shift
860         if [[ ${WANT_CMAKE} = always ]]; then
861                 enable_cmake-utils_${phase} "$@"
862         else
863                 use ${WANT_CMAKE} && enable_cmake-utils_${phase} "$@"
864         fi
865 }
866
867 fi