3 # Copyright (c) 2007, Simon Edwards <simon@simonzone.com>
4 # Copyright (c) 2012, Luca Beltrame <lbeltrame@kde.org>
5 # Copyright (c) 2012, Rolf Eike Beer <eike@sf-mail.de>
7 # Redistribution and use is allowed according to the terms of the BSD license.
8 # For details see the accompanying COPYING-CMAKE-SCRIPTS file.
10 # This file defines the following macros:
12 # PYTHON_INSTALL (SOURCE_FILE DESTINATION_DIR)
13 # Install the SOURCE_FILE, which is a Python .py file, into the
14 # destination directory during install. The file will be byte compiled
15 # and both the .py file and .pyc file will be installed.
17 set(PYTHON_MACROS_MODULE_PATH ${CMAKE_CURRENT_LIST_DIR})
19 macro(PYTHON_INSTALL SOURCE_FILE DESTINATION_DIR)
21 find_file(_python_compile_py PythonCompile.py PATHS ${CMAKE_MODULE_PATH})
23 # Install the source file.
24 install(FILES ${SOURCE_FILE} DESTINATION ${DESTINATION_DIR})
26 # Byte compile and install the .pyc file, unless explicitly prevented by env..
27 if("$ENV{PYTHONDONTWRITEBYTECODE}" STREQUAL "")
28 get_filename_component(_absfilename ${SOURCE_FILE} ABSOLUTE)
29 get_filename_component(_filename ${SOURCE_FILE} NAME)
30 get_filename_component(_filenamebase ${SOURCE_FILE} NAME_WE)
31 get_filename_component(_basepath ${SOURCE_FILE} PATH)
35 string(REGEX REPLACE "^[a-zA-Z]:/" "/" _basepath "${_basepath}")
38 set(_bin_py ${CMAKE_CURRENT_BINARY_DIR}/${_basepath}/${_filename})
40 # Python 3.2 changed the pyc file location
41 if(PYTHON_VERSION_STRING VERSION_GREATER 3.1)
42 # To get the right version for suffix
43 set(_bin_pyc "${CMAKE_CURRENT_BINARY_DIR}/${_basepath}/__pycache__/${_filenamebase}.cpython-${PYTHON_VERSION_MAJOR}${PYTHON_VERSION_MINOR}.pyc")
44 set(_py_install_dir "${DESTINATION_DIR}/__pycache__/")
46 set(_bin_pyc "${CMAKE_CURRENT_BINARY_DIR}/${_basepath}/${_filenamebase}.pyc")
47 set(_py_install_dir "${DESTINATION_DIR}")
50 file(MAKE_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/${_basepath})
52 # Setting because it will be displayed later, in compile_python_files
53 set(_message "Byte-compiling ${_bin_py} to ${_bin_pyc}")
55 string(REPLACE "/" "_" _rule_name "${_basepath}/${_bin_pyc}")
56 add_custom_target("${_rule_name}" ALL)
58 get_filename_component(_abs_bin_py ${_bin_py} ABSOLUTE)
59 if(_abs_bin_py STREQUAL _absfilename) # Don't copy the file onto itself.
61 TARGET "${_rule_name}"
62 COMMAND "${CMAKE_COMMAND}" -E echo "${_message}"
63 COMMAND "${PYTHON_EXECUTABLE}" "${_python_compile_py}" "${_bin_py}"
64 DEPENDS "${_absfilename}"
68 TARGET "${_rule_name}"
69 COMMAND "${CMAKE_COMMAND}" -E echo "${_message}"
70 COMMAND "${CMAKE_COMMAND}" -E copy "${_absfilename}" "${_bin_py}"
71 COMMAND "${PYTHON_EXECUTABLE}" "${_python_compile_py}" "${_bin_py}"
72 DEPENDS "${_absfilename}"
76 install(FILES ${_bin_pyc} DESTINATION "${_py_install_dir}")
77 unset(_py_install_dir)
80 endif("$ENV{PYTHONDONTWRITEBYTECODE}" STREQUAL "")
82 endmacro(PYTHON_INSTALL)