cmake_consistency_check.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337
  1. #!/usr/bin/env python3
  2. # ***** BEGIN GPL LICENSE BLOCK *****
  3. #
  4. # This program is free software; you can redistribute it and/or
  5. # modify it under the terms of the GNU General Public License
  6. # as published by the Free Software Foundation; either version 2
  7. # of the License, or (at your option) any later version.
  8. #
  9. # This program is distributed in the hope that it will be useful,
  10. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. # GNU General Public License for more details.
  13. #
  14. # You should have received a copy of the GNU General Public License
  15. # along with this program; if not, write to the Free Software Foundation,
  16. # Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
  17. #
  18. # Contributor(s): Campbell Barton
  19. #
  20. # ***** END GPL LICENSE BLOCK *****
  21. # <pep8 compliant>
  22. import sys
  23. if not sys.version.startswith("3"):
  24. print("\nPython3.x needed, found %s.\nAborting!\n" %
  25. sys.version.partition(" ")[0])
  26. sys.exit(1)
  27. from cmake_consistency_check_config import (
  28. IGNORE,
  29. UTF8_CHECK,
  30. SOURCE_DIR,
  31. BUILD_DIR,
  32. )
  33. import os
  34. from os.path import join, dirname, normpath, splitext
  35. global_h = set()
  36. global_c = set()
  37. global_refs = {}
  38. def replace_line(f, i, text, keep_indent=True):
  39. file_handle = open(f, 'r')
  40. data = file_handle.readlines()
  41. file_handle.close()
  42. l = data[i]
  43. ws = l[:len(l) - len(l.lstrip())]
  44. data[i] = "%s%s\n" % (ws, text)
  45. file_handle = open(f, 'w')
  46. file_handle.writelines(data)
  47. file_handle.close()
  48. def source_list(path, filename_check=None):
  49. for dirpath, dirnames, filenames in os.walk(path):
  50. # skip '.git'
  51. dirnames[:] = [d for d in dirnames if not d.startswith(".")]
  52. for filename in filenames:
  53. if filename_check is None or filename_check(filename):
  54. yield os.path.join(dirpath, filename)
  55. # extension checking
  56. def is_cmake(filename):
  57. ext = splitext(filename)[1]
  58. return (ext == ".cmake") or (filename == "CMakeLists.txt")
  59. def is_c_header(filename):
  60. ext = splitext(filename)[1]
  61. return (ext in {".h", ".hpp", ".hxx", ".hh"})
  62. def is_c(filename):
  63. ext = splitext(filename)[1]
  64. return (ext in {".c", ".cpp", ".cxx", ".m", ".mm", ".rc", ".cc", ".inl"})
  65. def is_c_any(filename):
  66. return is_c(filename) or is_c_header(filename)
  67. def cmake_get_src(f):
  68. sources_h = []
  69. sources_c = []
  70. filen = open(f, "r", encoding="utf8")
  71. it = iter(filen)
  72. found = False
  73. i = 0
  74. # print(f)
  75. def is_definition(l, f, i, name):
  76. if l.startswith("unset("):
  77. return False
  78. if ('set(%s' % name) in l or ('set(' in l and l.endswith(name)):
  79. if len(l.split()) > 1:
  80. raise Exception("strict formatting not kept 'set(%s*' %s:%d" % (name, f, i))
  81. return True
  82. if ("list(APPEND %s" % name) in l or ('list(APPEND ' in l and l.endswith(name)):
  83. if l.endswith(")"):
  84. raise Exception("strict formatting not kept 'list(APPEND %s...)' on 1 line %s:%d" % (name, f, i))
  85. return True
  86. while it is not None:
  87. context_name = ""
  88. while it is not None:
  89. i += 1
  90. try:
  91. l = next(it)
  92. except StopIteration:
  93. it = None
  94. break
  95. l = l.strip()
  96. if not l.startswith("#"):
  97. found = is_definition(l, f, i, "SRC")
  98. if found:
  99. context_name = "SRC"
  100. break
  101. found = is_definition(l, f, i, "INC")
  102. if found:
  103. context_name = "INC"
  104. break
  105. if found:
  106. cmake_base = dirname(f)
  107. cmake_base_bin = os.path.join(BUILD_DIR, os.path.relpath(cmake_base, SOURCE_DIR))
  108. while it is not None:
  109. i += 1
  110. try:
  111. l = next(it)
  112. except StopIteration:
  113. it = None
  114. break
  115. l = l.strip()
  116. if not l.startswith("#"):
  117. if ")" in l:
  118. if l.strip() != ")":
  119. raise Exception("strict formatting not kept '*)' %s:%d" % (f, i))
  120. break
  121. # replace dirs
  122. l = l.replace("${CMAKE_CURRENT_SOURCE_DIR}", cmake_base)
  123. l = l.replace("${CMAKE_CURRENT_BINARY_DIR}", cmake_base_bin)
  124. l = l.strip('"')
  125. if not l:
  126. pass
  127. elif l.startswith("$"):
  128. if context_name == "SRC":
  129. # assume if it ends with context_name we know about it
  130. if not l.split("}")[0].endswith(context_name):
  131. print("Can't use var '%s' %s:%d" % (l, f, i))
  132. elif len(l.split()) > 1:
  133. raise Exception("Multi-line define '%s' %s:%d" % (l, f, i))
  134. else:
  135. new_file = normpath(join(cmake_base, l))
  136. if context_name == "SRC":
  137. if is_c_header(new_file):
  138. sources_h.append(new_file)
  139. global_refs.setdefault(new_file, []).append((f, i))
  140. elif is_c(new_file):
  141. sources_c.append(new_file)
  142. global_refs.setdefault(new_file, []).append((f, i))
  143. elif l in {"PARENT_SCOPE", }:
  144. # cmake var, ignore
  145. pass
  146. elif new_file.endswith(".list"):
  147. pass
  148. elif new_file.endswith(".def"):
  149. pass
  150. elif new_file.endswith(".cl"): # opencl
  151. pass
  152. elif new_file.endswith(".cu"): # cuda
  153. pass
  154. elif new_file.endswith(".osl"): # open shading language
  155. pass
  156. elif new_file.endswith(".glsl"):
  157. pass
  158. else:
  159. raise Exception("unknown file type - not c or h %s -> %s" % (f, new_file))
  160. elif context_name == "INC":
  161. if new_file.startswith(BUILD_DIR):
  162. # assume generated path
  163. pass
  164. elif os.path.isdir(new_file):
  165. new_path_rel = os.path.relpath(new_file, cmake_base)
  166. if new_path_rel != l:
  167. print("overly relative path:\n %s:%d\n %s\n %s" % (f, i, l, new_path_rel))
  168. # # Save time. just replace the line
  169. # replace_line(f, i - 1, new_path_rel)
  170. else:
  171. raise Exception("non existent include %s:%d -> %s" % (f, i, new_file))
  172. # print(new_file)
  173. global_h.update(set(sources_h))
  174. global_c.update(set(sources_c))
  175. '''
  176. if not sources_h and not sources_c:
  177. raise Exception("No sources %s" % f)
  178. sources_h_fs = list(source_list(cmake_base, is_c_header))
  179. sources_c_fs = list(source_list(cmake_base, is_c))
  180. '''
  181. # find missing C files:
  182. '''
  183. for ff in sources_c_fs:
  184. if ff not in sources_c:
  185. print(" missing: " + ff)
  186. '''
  187. # reset
  188. del sources_h[:]
  189. del sources_c[:]
  190. filen.close()
  191. def is_ignore(f, ignore_used):
  192. for index, ig in enumerate(IGNORE):
  193. if ig in f:
  194. ignore_used[index] = True
  195. return True
  196. return False
  197. def main():
  198. print("Scanning:", SOURCE_DIR)
  199. for cmake in source_list(SOURCE_DIR, is_cmake):
  200. cmake_get_src(cmake)
  201. # First do stupid check, do these files exist?
  202. print("\nChecking for missing references:")
  203. is_err = False
  204. errs = []
  205. for f in (global_h | global_c):
  206. if f.startswith(BUILD_DIR):
  207. continue
  208. if not os.path.exists(f):
  209. refs = global_refs[f]
  210. if refs:
  211. for cf, i in refs:
  212. errs.append((cf, i))
  213. else:
  214. raise Exception("CMake referenecs missing, internal error, aborting!")
  215. is_err = True
  216. errs.sort()
  217. errs.reverse()
  218. for cf, i in errs:
  219. print("%s:%d" % (cf, i))
  220. # Write a 'sed' script, useful if we get a lot of these
  221. # print("sed '%dd' '%s' > '%s.tmp' ; mv '%s.tmp' '%s'" % (i, cf, cf, cf, cf))
  222. if is_err:
  223. raise Exception("CMake referenecs missing files, aborting!")
  224. del is_err
  225. del errs
  226. ignore_used = [False] * len(IGNORE)
  227. # now check on files not accounted for.
  228. print("\nC/C++ Files CMake doesnt know about...")
  229. for cf in sorted(source_list(SOURCE_DIR, is_c)):
  230. if not is_ignore(cf, ignore_used):
  231. if cf not in global_c:
  232. print("missing_c: ", cf)
  233. # check if automake builds a corrasponding .o file.
  234. '''
  235. if cf in global_c:
  236. out1 = os.path.splitext(cf)[0] + ".o"
  237. out2 = os.path.splitext(cf)[0] + ".Po"
  238. out2_dir, out2_file = out2 = os.path.split(out2)
  239. out2 = os.path.join(out2_dir, ".deps", out2_file)
  240. if not os.path.exists(out1) and not os.path.exists(out2):
  241. print("bad_c: ", cf)
  242. '''
  243. print("\nC/C++ Headers CMake doesnt know about...")
  244. for hf in sorted(source_list(SOURCE_DIR, is_c_header)):
  245. if not is_ignore(hf, ignore_used):
  246. if hf not in global_h:
  247. print("missing_h: ", hf)
  248. if UTF8_CHECK:
  249. # test encoding
  250. import traceback
  251. for files in (global_c, global_h):
  252. for f in sorted(files):
  253. if os.path.exists(f):
  254. # ignore outside of our source tree
  255. if "extern" not in f:
  256. i = 1
  257. try:
  258. for l in open(f, "r", encoding="utf8"):
  259. i += 1
  260. except UnicodeDecodeError:
  261. print("Non utf8: %s:%d" % (f, i))
  262. if i > 1:
  263. traceback.print_exc()
  264. # Check ignores aren't stale
  265. print("\nCheck for unused 'IGNORE' paths...")
  266. for index, ig in enumerate(IGNORE):
  267. if not ignore_used[index]:
  268. print("unused ignore: %r" % ig)
  269. if __name__ == "__main__":
  270. main()