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