Merge branch 'blender2.7'
[blender.git] / build_files / cmake / cmake_consistency_check.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 # ***** END GPL LICENSE BLOCK *****
20
21 # <pep8 compliant>
22
23 import sys
24 if not sys.version.startswith("3"):
25     print("\nPython3.x needed, found %s.\nAborting!\n" %
26           sys.version.partition(" ")[0])
27     sys.exit(1)
28
29 from cmake_consistency_check_config import (
30     IGNORE_SOURCE,
31     IGNORE_CMAKE,
32     UTF8_CHECK,
33     SOURCE_DIR,
34     BUILD_DIR,
35 )
36
37
38 import os
39 from os.path import join, dirname, normpath, splitext
40
41 global_h = set()
42 global_c = set()
43 global_refs = {}
44
45
46 def replace_line(f, i, text, keep_indent=True):
47     file_handle = open(f, 'r')
48     data = file_handle.readlines()
49     file_handle.close()
50
51     l = data[i]
52     ws = l[:len(l) - len(l.lstrip())]
53
54     data[i] = "%s%s\n" % (ws, text)
55
56     file_handle = open(f, 'w')
57     file_handle.writelines(data)
58     file_handle.close()
59
60
61 def source_list(path, filename_check=None):
62     for dirpath, dirnames, filenames in os.walk(path):
63         # skip '.git'
64         dirnames[:] = [d for d in dirnames if not d.startswith(".")]
65
66         for filename in filenames:
67             if filename_check is None or filename_check(filename):
68                 yield os.path.join(dirpath, filename)
69
70
71 # extension checking
72 def is_cmake(filename):
73     ext = splitext(filename)[1]
74     return (ext == ".cmake") or (filename == "CMakeLists.txt")
75
76
77 def is_c_header(filename):
78     ext = splitext(filename)[1]
79     return (ext in {".h", ".hpp", ".hxx", ".hh"})
80
81
82 def is_c(filename):
83     ext = splitext(filename)[1]
84     return (ext in {".c", ".cpp", ".cxx", ".m", ".mm", ".rc", ".cc", ".inl"})
85
86
87 def is_c_any(filename):
88     return is_c(filename) or is_c_header(filename)
89
90
91 def cmake_get_src(f):
92
93     sources_h = []
94     sources_c = []
95
96     filen = open(f, "r", encoding="utf8")
97     it = iter(filen)
98     found = False
99     i = 0
100     # print(f)
101
102     def is_definition(l, f, i, name):
103         if l.startswith("unset("):
104             return False
105
106         if ('set(%s' % name) in l or ('set(' in l and l.endswith(name)):
107             if len(l.split()) > 1:
108                 raise Exception("strict formatting not kept 'set(%s*' %s:%d" % (name, f, i))
109             return True
110
111         if ("list(APPEND %s" % name) in l or ('list(APPEND ' in l and l.endswith(name)):
112             if l.endswith(")"):
113                 raise Exception("strict formatting not kept 'list(APPEND %s...)' on 1 line %s:%d" % (name, f, i))
114             return True
115
116     while it is not None:
117         context_name = ""
118         while it is not None:
119             i += 1
120             try:
121                 l = next(it)
122             except StopIteration:
123                 it = None
124                 break
125             l = l.strip()
126             if not l.startswith("#"):
127                 found = is_definition(l, f, i, "SRC")
128                 if found:
129                     context_name = "SRC"
130                     break
131                 found = is_definition(l, f, i, "INC")
132                 if found:
133                     context_name = "INC"
134                     break
135
136         if found:
137             cmake_base = dirname(f)
138             cmake_base_bin = os.path.join(BUILD_DIR, os.path.relpath(cmake_base, SOURCE_DIR))
139
140             while it is not None:
141                 i += 1
142                 try:
143                     l = next(it)
144                 except StopIteration:
145                     it = None
146                     break
147
148                 l = l.strip()
149
150                 if not l.startswith("#"):
151
152                     if ")" in l:
153                         if l.strip() != ")":
154                             raise Exception("strict formatting not kept '*)' %s:%d" % (f, i))
155                         break
156
157                     # replace dirs
158                     l = l.replace("${CMAKE_SOURCE_DIR}", SOURCE_DIR)
159                     l = l.replace("${CMAKE_CURRENT_SOURCE_DIR}", cmake_base)
160                     l = l.replace("${CMAKE_CURRENT_BINARY_DIR}", cmake_base_bin)
161                     l = l.strip('"')
162
163                     if not l:
164                         pass
165                     elif l.startswith("$"):
166                         if context_name == "SRC":
167                             # assume if it ends with context_name we know about it
168                             if not l.split("}")[0].endswith(context_name):
169                                 print("Can't use var '%s' %s:%d" % (l, f, i))
170                     elif len(l.split()) > 1:
171                         raise Exception("Multi-line define '%s' %s:%d" % (l, f, i))
172                     else:
173                         new_file = normpath(join(cmake_base, l))
174
175                         if context_name == "SRC":
176                             if is_c_header(new_file):
177                                 sources_h.append(new_file)
178                                 global_refs.setdefault(new_file, []).append((f, i))
179                             elif is_c(new_file):
180                                 sources_c.append(new_file)
181                                 global_refs.setdefault(new_file, []).append((f, i))
182                             elif l in {"PARENT_SCOPE", }:
183                                 # cmake var, ignore
184                                 pass
185                             elif new_file.endswith(".list"):
186                                 pass
187                             elif new_file.endswith(".def"):
188                                 pass
189                             elif new_file.endswith(".cl"):  # opencl
190                                 pass
191                             elif new_file.endswith(".cu"):  # cuda
192                                 pass
193                             elif new_file.endswith(".osl"):  # open shading language
194                                 pass
195                             elif new_file.endswith(".glsl"):
196                                 pass
197                             else:
198                                 raise Exception("unknown file type - not c or h %s -> %s" % (f, new_file))
199
200                         elif context_name == "INC":
201                             if new_file.startswith(BUILD_DIR):
202                                 # assume generated path
203                                 pass
204                             elif os.path.isdir(new_file):
205                                 new_path_rel = os.path.relpath(new_file, cmake_base)
206
207                                 if new_path_rel != l:
208                                     print("overly relative path:\n  %s:%d\n  %s\n  %s" % (f, i, l, new_path_rel))
209
210                                     # # Save time. just replace the line
211                                     # replace_line(f, i - 1, new_path_rel)
212
213                             else:
214                                 raise Exception("non existent include %s:%d -> %s" % (f, i, new_file))
215
216                         # print(new_file)
217
218             global_h.update(set(sources_h))
219             global_c.update(set(sources_c))
220             '''
221             if not sources_h and not sources_c:
222                 raise Exception("No sources %s" % f)
223
224             sources_h_fs = list(source_list(cmake_base, is_c_header))
225             sources_c_fs = list(source_list(cmake_base, is_c))
226             '''
227             # find missing C files:
228             '''
229             for ff in sources_c_fs:
230                 if ff not in sources_c:
231                     print("  missing: " + ff)
232             '''
233
234             # reset
235             del sources_h[:]
236             del sources_c[:]
237
238     filen.close()
239
240
241 def is_ignore_source(f, ignore_used):
242     for index, ig in enumerate(IGNORE_SOURCE):
243         if ig in f:
244             ignore_used[index] = True
245             return True
246     return False
247
248
249 def is_ignore_cmake(f, ignore_used):
250     for index, ig in enumerate(IGNORE_CMAKE):
251         if ig in f:
252             ignore_used[index] = True
253             return True
254     return False
255
256
257 def main():
258
259     print("Scanning:", SOURCE_DIR)
260
261     ignore_used_source = [False] * len(IGNORE_SOURCE)
262     ignore_used_cmake = [False] * len(IGNORE_CMAKE)
263
264     for cmake in source_list(SOURCE_DIR, is_cmake):
265         if not is_ignore_cmake(cmake, ignore_used_cmake):
266             cmake_get_src(cmake)
267
268     # First do stupid check, do these files exist?
269     print("\nChecking for missing references:")
270     is_err = False
271     errs = []
272     for f in (global_h | global_c):
273         if f.startswith(BUILD_DIR):
274             continue
275
276         if not os.path.exists(f):
277             refs = global_refs[f]
278             if refs:
279                 for cf, i in refs:
280                     errs.append((cf, i))
281             else:
282                 raise Exception("CMake referenecs missing, internal error, aborting!")
283             is_err = True
284
285     errs.sort()
286     errs.reverse()
287     for cf, i in errs:
288         print("%s:%d" % (cf, i))
289         # Write a 'sed' script, useful if we get a lot of these
290         # print("sed '%dd' '%s' > '%s.tmp' ; mv '%s.tmp' '%s'" % (i, cf, cf, cf, cf))
291
292     if is_err:
293         raise Exception("CMake referenecs missing files, aborting!")
294     del is_err
295     del errs
296
297     # now check on files not accounted for.
298     print("\nC/C++ Files CMake does not know about...")
299     for cf in sorted(source_list(SOURCE_DIR, is_c)):
300         if not is_ignore_source(cf, ignore_used_source):
301             if cf not in global_c:
302                 print("missing_c: ", cf)
303
304             # check if automake builds a corrasponding .o file.
305             '''
306             if cf in global_c:
307                 out1 = os.path.splitext(cf)[0] + ".o"
308                 out2 = os.path.splitext(cf)[0] + ".Po"
309                 out2_dir, out2_file = out2 = os.path.split(out2)
310                 out2 = os.path.join(out2_dir, ".deps", out2_file)
311                 if not os.path.exists(out1) and not os.path.exists(out2):
312                     print("bad_c: ", cf)
313             '''
314
315     print("\nC/C++ Headers CMake does not know about...")
316     for hf in sorted(source_list(SOURCE_DIR, is_c_header)):
317         if not is_ignore_source(hf, ignore_used_source):
318             if hf not in global_h:
319                 print("missing_h: ", hf)
320
321     if UTF8_CHECK:
322         # test encoding
323         import traceback
324         for files in (global_c, global_h):
325             for f in sorted(files):
326                 if os.path.exists(f):
327                     # ignore outside of our source tree
328                     if "extern" not in f:
329                         i = 1
330                         try:
331                             for l in open(f, "r", encoding="utf8"):
332                                 i += 1
333                         except UnicodeDecodeError:
334                             print("Non utf8: %s:%d" % (f, i))
335                             if i > 1:
336                                 traceback.print_exc()
337
338     # Check ignores aren't stale
339     print("\nCheck for unused 'IGNORE_SOURCE' paths...")
340     for index, ig in enumerate(IGNORE_SOURCE):
341         if not ignore_used_source[index]:
342             print("unused ignore: %r" % ig)
343
344     # Check ignores aren't stale
345     print("\nCheck for unused 'IGNORE_CMAKE' paths...")
346     for index, ig in enumerate(IGNORE_CMAKE):
347         if not ignore_used_cmake[index]:
348             print("unused ignore: %r" % ig)
349
350
351 if __name__ == "__main__":
352     main()