CMake: cleanup
[blender-staging.git] / build_files / cmake / project_info.py
1 #!/usr/bin/env python3
2
3 # ***** BEGIN GPL LICENSE BLOCK *****
4 #
5 # This program is free software; you can redistribute it and/or
6 # modify it under the terms of the GNU General Public License
7 # as published by the Free Software Foundation; either version 2
8 # of the License, or (at your option) any later version.
9 #
10 # This program is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 # GNU General Public License for more details.
14 #
15 # You should have received a copy of the GNU General Public License
16 # along with this program; if not, write to the Free Software Foundation,
17 # Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 #
19 # Contributor(s): Campbell Barton, M.G. Kishalmi
20 #
21 # ***** END GPL LICENSE BLOCK *****
22
23 # <pep8 compliant>
24
25 """
26 Module for accessing project file data for Blender.
27
28 Before use, call init(cmake_build_dir).
29 """
30
31 __all__ = (
32     "SIMPLE_PROJECTFILE",
33     "SOURCE_DIR",
34     "CMAKE_DIR",
35     "PROJECT_DIR",
36     "source_list",
37     "is_project_file",
38     "is_c_header",
39     "is_py",
40     "cmake_advanced_info",
41     "cmake_compiler_defines",
42     "project_name_get",
43     "init",
44 )
45
46
47 import sys
48 if not sys.version.startswith("3"):
49     print("\nPython3.x needed, found %s.\nAborting!\n" %
50           sys.version.partition(" ")[0])
51     sys.exit(1)
52
53
54 import os
55 from os.path import join, dirname, normpath, abspath, splitext, exists
56
57 SOURCE_DIR = join(dirname(__file__), "..", "..")
58 SOURCE_DIR = normpath(SOURCE_DIR)
59 SOURCE_DIR = abspath(SOURCE_DIR)
60
61 SIMPLE_PROJECTFILE = False
62
63 # must initialize from 'init'
64 CMAKE_DIR = None
65
66
67 def init(cmake_path):
68     global CMAKE_DIR, PROJECT_DIR
69
70     # get cmake path
71     cmake_path = cmake_path or ""
72
73     if (not cmake_path) or (not exists(join(cmake_path, "CMakeCache.txt"))):
74         cmake_path = os.getcwd()
75     if not exists(join(cmake_path, "CMakeCache.txt")):
76         print("CMakeCache.txt not found in %r or %r\n"
77               "    Pass CMake build dir as an argument, or run from that dir, aborting" %
78               (cmake_path, os.getcwd()))
79         return False
80
81     PROJECT_DIR = CMAKE_DIR = cmake_path
82     return True
83
84
85 def source_list(path, filename_check=None):
86     for dirpath, dirnames, filenames in os.walk(path):
87         # skip '.git'
88         dirnames[:] = [d for d in dirnames if not d.startswith(".")]
89
90         for filename in filenames:
91             filepath = join(dirpath, filename)
92             if filename_check is None or filename_check(filepath):
93                 yield filepath
94
95
96 # extension checking
97 def is_cmake(filename):
98     ext = splitext(filename)[1]
99     return (ext == ".cmake") or (filename.endswith("CMakeLists.txt"))
100
101
102 def is_c_header(filename):
103     ext = splitext(filename)[1]
104     return (ext in {".h", ".hpp", ".hxx", ".hh"})
105
106
107 def is_py(filename):
108     ext = splitext(filename)[1]
109     return (ext == ".py")
110
111
112 def is_glsl(filename):
113     ext = splitext(filename)[1]
114     return (ext == ".glsl")
115
116
117 def is_c(filename):
118     ext = splitext(filename)[1]
119     return (ext in {".c", ".cpp", ".cxx", ".m", ".mm", ".rc", ".cc", ".inl", ".osl"})
120
121
122 def is_c_any(filename):
123     return is_c(filename) or is_c_header(filename)
124
125
126 def is_svn_file(filename):
127     dn, fn = os.path.split(filename)
128     filename_svn = join(dn, ".svn", "text-base", "%s.svn-base" % fn)
129     return exists(filename_svn)
130
131
132 def is_project_file(filename):
133     return (is_c_any(filename) or is_cmake(filename) or is_glsl(filename))  # and is_svn_file(filename)
134
135
136 def cmake_advanced_info():
137     """ Extract includes and defines from cmake.
138     """
139
140     make_exe = cmake_cache_var("CMAKE_MAKE_PROGRAM")
141     make_exe_basename = os.path.basename(make_exe)
142
143     def create_eclipse_project():
144         print("CMAKE_DIR %r" % CMAKE_DIR)
145         if sys.platform == "win32":
146             raise Exception("Error: win32 is not supported")
147         else:
148             if make_exe_basename.startswith(("make", "gmake")):
149                 cmd = 'cmake "%s" -G"Eclipse CDT4 - Unix Makefiles"' % CMAKE_DIR
150             elif make_exe_basename.startswith("ninja"):
151                 cmd = 'cmake "%s" -G"Eclipse CDT4 - Ninja"' % CMAKE_DIR
152             else:
153                 raise Exception("Unknown make program %r" % make_exe)
154
155         os.system(cmd)
156         return join(CMAKE_DIR, ".cproject")
157
158     includes = []
159     defines = []
160
161     project_path = create_eclipse_project()
162
163     if not exists(project_path):
164         print("Generating Eclipse Prokect File Failed: %r not found" % project_path)
165         return None, None
166
167     from xml.dom.minidom import parse
168     tree = parse(project_path)
169
170     # to check on nicer xml
171     # f = open(".cproject_pretty", 'w')
172     # f.write(tree.toprettyxml(indent="    ", newl=""))
173
174     ELEMENT_NODE = tree.ELEMENT_NODE
175
176     cproject, = tree.getElementsByTagName("cproject")
177     for storage in cproject.childNodes:
178         if storage.nodeType != ELEMENT_NODE:
179             continue
180
181         if storage.attributes["moduleId"].value == "org.eclipse.cdt.core.settings":
182             cconfig = storage.getElementsByTagName("cconfiguration")[0]
183             for substorage in cconfig.childNodes:
184                 if substorage.nodeType != ELEMENT_NODE:
185                     continue
186
187                 moduleId = substorage.attributes["moduleId"].value
188
189                 # org.eclipse.cdt.core.settings
190                 # org.eclipse.cdt.core.language.mapping
191                 # org.eclipse.cdt.core.externalSettings
192                 # org.eclipse.cdt.core.pathentry
193                 # org.eclipse.cdt.make.core.buildtargets
194
195                 if moduleId == "org.eclipse.cdt.core.pathentry":
196                     for path in substorage.childNodes:
197                         if path.nodeType != ELEMENT_NODE:
198                             continue
199                         kind = path.attributes["kind"].value
200
201                         if kind == "mac":
202                             # <pathentry kind="mac" name="PREFIX" path="" value="&quot;/opt/blender25&quot;"/>
203                             defines.append((path.attributes["name"].value, path.attributes["value"].value))
204                         elif kind == "inc":
205                             # <pathentry include="/data/src/blender/blender/source/blender/editors/include" kind="inc" path="" system="true"/>
206                             includes.append(path.attributes["include"].value)
207                         else:
208                             pass
209
210     return includes, defines
211
212
213 def cmake_cache_var(var):
214     cache_file = open(join(CMAKE_DIR, "CMakeCache.txt"), encoding='utf-8')
215     lines = [
216         l_strip for l in cache_file
217         for l_strip in (l.strip(),)
218         if l_strip
219         if not l_strip.startswith(("//", "#"))
220     ]
221     cache_file.close()
222
223     for l in lines:
224         if l.split(":")[0] == var:
225             return l.split("=", 1)[-1]
226     return None
227
228
229 def cmake_compiler_defines():
230     compiler = cmake_cache_var("CMAKE_C_COMPILER")  # could do CXX too
231
232     if compiler is None:
233         print("Couldn't find the compiler, os defines will be omitted...")
234         return
235
236     import tempfile
237     temp_c = tempfile.mkstemp(suffix=".c")[1]
238     temp_def = tempfile.mkstemp(suffix=".def")[1]
239
240     os.system("%s -dM -E %s > %s" % (compiler, temp_c, temp_def))
241
242     temp_def_file = open(temp_def)
243     lines = [l.strip() for l in temp_def_file if l.strip()]
244     temp_def_file.close()
245
246     os.remove(temp_c)
247     os.remove(temp_def)
248     return lines
249
250
251 def project_name_get():
252     return cmake_cache_var("CMAKE_PROJECT_NAME")