gn_to_cmake.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735
  1. #!/usr/bin/env python
  2. #
  3. # Copyright 2016 Google Inc.
  4. #
  5. # Use of this source code is governed by a BSD-style license that can be
  6. # found in the LICENSE file.
  7. """
  8. Usage: gn_to_cmake.py <json_file_name>
  9. gn gen out/config --ide=json --json-ide-script=../../gn/gn_to_cmake.py
  10. or
  11. gn gen out/config --ide=json
  12. python gn/gn_to_cmake.py out/config/project.json
  13. The first is recommended, as it will auto-update.
  14. """
  15. import itertools
  16. import functools
  17. import json
  18. import posixpath
  19. import os
  20. import string
  21. import sys
  22. def CMakeStringEscape(a):
  23. """Escapes the string 'a' for use inside a CMake string.
  24. This means escaping
  25. '\' otherwise it may be seen as modifying the next character
  26. '"' otherwise it will end the string
  27. ';' otherwise the string becomes a list
  28. The following do not need to be escaped
  29. '#' when the lexer is in string state, this does not start a comment
  30. """
  31. return a.replace('\\', '\\\\').replace(';', '\\;').replace('"', '\\"')
  32. def CMakeTargetEscape(a):
  33. """Escapes the string 'a' for use as a CMake target name.
  34. CMP0037 in CMake 3.0 restricts target names to "^[A-Za-z0-9_.:+-]+$"
  35. The ':' is only allowed for imported targets.
  36. """
  37. def Escape(c):
  38. if c in string.ascii_letters or c in string.digits or c in '_.+-':
  39. return c
  40. else:
  41. return '__'
  42. return ''.join(map(Escape, a))
  43. def SetVariable(out, variable_name, value):
  44. """Sets a CMake variable."""
  45. out.write('set("')
  46. out.write(CMakeStringEscape(variable_name))
  47. out.write('" "')
  48. out.write(CMakeStringEscape(value))
  49. out.write('")\n')
  50. def SetVariableList(out, variable_name, values):
  51. """Sets a CMake variable to a list."""
  52. if not values:
  53. return SetVariable(out, variable_name, "")
  54. if len(values) == 1:
  55. return SetVariable(out, variable_name, values[0])
  56. out.write('list(APPEND "')
  57. out.write(CMakeStringEscape(variable_name))
  58. out.write('"\n "')
  59. out.write('"\n "'.join([CMakeStringEscape(value) for value in values]))
  60. out.write('")\n')
  61. def SetFilesProperty(output, variable, property_name, values, sep):
  62. """Given a set of source files, sets the given property on them."""
  63. output.write('set_source_files_properties(')
  64. WriteVariable(output, variable)
  65. output.write(' PROPERTIES ')
  66. output.write(property_name)
  67. output.write(' "')
  68. for value in values:
  69. output.write(CMakeStringEscape(value))
  70. output.write(sep)
  71. output.write('")\n')
  72. def SetCurrentTargetProperty(out, property_name, values, sep=''):
  73. """Given a target, sets the given property."""
  74. out.write('set_target_properties("${target}" PROPERTIES ')
  75. out.write(property_name)
  76. out.write(' "')
  77. for value in values:
  78. out.write(CMakeStringEscape(value))
  79. out.write(sep)
  80. out.write('")\n')
  81. def WriteVariable(output, variable_name, prepend=None):
  82. if prepend:
  83. output.write(prepend)
  84. output.write('${')
  85. output.write(variable_name)
  86. output.write('}')
  87. # See GetSourceFileType in gn
  88. source_file_types = {
  89. '.cc': 'cxx',
  90. '.cpp': 'cxx',
  91. '.cxx': 'cxx',
  92. '.m': 'objc',
  93. '.mm': 'objcc',
  94. '.c': 'c',
  95. '.s': 'asm',
  96. '.S': 'asm',
  97. '.asm': 'asm',
  98. '.o': 'obj',
  99. '.obj': 'obj',
  100. }
  101. class CMakeTargetType(object):
  102. def __init__(self, command, modifier, property_modifier, is_linkable):
  103. self.command = command
  104. self.modifier = modifier
  105. self.property_modifier = property_modifier
  106. self.is_linkable = is_linkable
  107. CMakeTargetType.custom = CMakeTargetType('add_custom_target', 'SOURCES',
  108. None, False)
  109. # See GetStringForOutputType in gn
  110. cmake_target_types = {
  111. 'unknown': CMakeTargetType.custom,
  112. 'group': CMakeTargetType.custom,
  113. 'executable': CMakeTargetType('add_executable', None, 'RUNTIME', True),
  114. 'loadable_module': CMakeTargetType('add_library', 'MODULE', 'LIBRARY', True),
  115. 'shared_library': CMakeTargetType('add_library', 'SHARED', 'LIBRARY', True),
  116. 'static_library': CMakeTargetType('add_library', 'STATIC', 'ARCHIVE', True),
  117. 'source_set': CMakeTargetType('add_library', 'OBJECT', None, False),
  118. 'copy': CMakeTargetType.custom,
  119. 'action': CMakeTargetType.custom,
  120. 'action_foreach': CMakeTargetType.custom,
  121. 'bundle_data': CMakeTargetType.custom,
  122. 'create_bundle': CMakeTargetType.custom,
  123. }
  124. def FindFirstOf(s, a):
  125. return min(s.find(i) for i in a if i in s)
  126. class Project(object):
  127. def __init__(self, project_json):
  128. self.targets = project_json['targets']
  129. build_settings = project_json['build_settings']
  130. self.root_path = build_settings['root_path']
  131. self.build_path = posixpath.join(self.root_path,
  132. build_settings['build_dir'][2:])
  133. def GetAbsolutePath(self, path):
  134. if path.startswith("//"):
  135. return self.root_path + "/" + path[2:]
  136. else:
  137. return path
  138. def GetObjectSourceDependencies(self, gn_target_name, object_dependencies):
  139. """All OBJECT libraries whose sources have not been absorbed."""
  140. dependencies = self.targets[gn_target_name].get('deps', [])
  141. for dependency in dependencies:
  142. dependency_type = self.targets[dependency].get('type', None)
  143. if dependency_type == 'source_set':
  144. object_dependencies.add(dependency)
  145. if dependency_type not in gn_target_types_that_absorb_objects:
  146. self.GetObjectSourceDependencies(dependency, object_dependencies)
  147. def GetObjectLibraryDependencies(self, gn_target_name, object_dependencies):
  148. """All OBJECT libraries whose libraries have not been absorbed."""
  149. dependencies = self.targets[gn_target_name].get('deps', [])
  150. for dependency in dependencies:
  151. dependency_type = self.targets[dependency].get('type', None)
  152. if dependency_type == 'source_set':
  153. object_dependencies.add(dependency)
  154. self.GetObjectLibraryDependencies(dependency, object_dependencies)
  155. def GetCMakeTargetName(self, gn_target_name):
  156. # See <chromium>/src/tools/gn/label.cc#Resolve
  157. # //base/test:test_support(//build/toolchain/win:msvc)
  158. path_separator = FindFirstOf(gn_target_name, (':', '('))
  159. location = None
  160. name = None
  161. toolchain = None
  162. if not path_separator:
  163. location = gn_target_name[2:]
  164. else:
  165. location = gn_target_name[2:path_separator]
  166. toolchain_separator = gn_target_name.find('(', path_separator)
  167. if toolchain_separator == -1:
  168. name = gn_target_name[path_separator + 1:]
  169. else:
  170. if toolchain_separator > path_separator:
  171. name = gn_target_name[path_separator + 1:toolchain_separator]
  172. assert gn_target_name.endswith(')')
  173. toolchain = gn_target_name[toolchain_separator + 1:-1]
  174. assert location or name
  175. cmake_target_name = None
  176. if location.endswith('/' + name):
  177. cmake_target_name = location
  178. elif location:
  179. cmake_target_name = location + '_' + name
  180. else:
  181. cmake_target_name = name
  182. if toolchain:
  183. cmake_target_name += '--' + toolchain
  184. return CMakeTargetEscape(cmake_target_name)
  185. class Target(object):
  186. def __init__(self, gn_target_name, project):
  187. self.gn_name = gn_target_name
  188. self.properties = project.targets[self.gn_name]
  189. self.cmake_name = project.GetCMakeTargetName(self.gn_name)
  190. self.gn_type = self.properties.get('type', None)
  191. self.cmake_type = cmake_target_types.get(self.gn_type, None)
  192. def WriteAction(out, target, project, sources, synthetic_dependencies):
  193. outputs = []
  194. output_directories = set()
  195. for output in target.properties.get('outputs', []):
  196. output_abs_path = project.GetAbsolutePath(output)
  197. outputs.append(output_abs_path)
  198. output_directory = posixpath.dirname(output_abs_path)
  199. if output_directory:
  200. output_directories.add(output_directory)
  201. outputs_name = '${target}__output'
  202. SetVariableList(out, outputs_name, outputs)
  203. out.write('add_custom_command(OUTPUT ')
  204. WriteVariable(out, outputs_name)
  205. out.write('\n')
  206. if output_directories:
  207. out.write(' COMMAND ${CMAKE_COMMAND} -E make_directory "')
  208. out.write('" "'.join(map(CMakeStringEscape, output_directories)))
  209. out.write('"\n')
  210. script = target.properties['script']
  211. arguments = target.properties['args']
  212. out.write(' COMMAND python "')
  213. out.write(CMakeStringEscape(project.GetAbsolutePath(script)))
  214. out.write('"')
  215. if arguments:
  216. out.write('\n "')
  217. out.write('"\n "'.join(map(CMakeStringEscape, arguments)))
  218. out.write('"')
  219. out.write('\n')
  220. out.write(' DEPENDS ')
  221. for sources_type_name in sources.values():
  222. WriteVariable(out, sources_type_name, ' ')
  223. out.write('\n')
  224. #TODO: CMake 3.7 is introducing DEPFILE
  225. out.write(' WORKING_DIRECTORY "')
  226. out.write(CMakeStringEscape(project.build_path))
  227. out.write('"\n')
  228. out.write(' COMMENT "Action: ${target}"\n')
  229. out.write(' VERBATIM)\n')
  230. synthetic_dependencies.add(outputs_name)
  231. def ExpandPlaceholders(source, a):
  232. source_dir, source_file_part = posixpath.split(source)
  233. source_name_part, _ = posixpath.splitext(source_file_part)
  234. #TODO: {{source_gen_dir}}, {{source_out_dir}}, {{response_file_name}}
  235. return a.replace('{{source}}', source) \
  236. .replace('{{source_file_part}}', source_file_part) \
  237. .replace('{{source_name_part}}', source_name_part) \
  238. .replace('{{source_dir}}', source_dir) \
  239. .replace('{{source_root_relative_dir}}', source_dir)
  240. def WriteActionForEach(out, target, project, sources, synthetic_dependencies):
  241. all_outputs = target.properties.get('outputs', [])
  242. inputs = target.properties.get('sources', [])
  243. # TODO: consider expanding 'output_patterns' instead.
  244. outputs_per_input = len(all_outputs) / len(inputs)
  245. for count, source in enumerate(inputs):
  246. source_abs_path = project.GetAbsolutePath(source)
  247. outputs = []
  248. output_directories = set()
  249. for output in all_outputs[outputs_per_input * count:
  250. outputs_per_input * (count+1)]:
  251. output_abs_path = project.GetAbsolutePath(output)
  252. outputs.append(output_abs_path)
  253. output_directory = posixpath.dirname(output_abs_path)
  254. if output_directory:
  255. output_directories.add(output_directory)
  256. outputs_name = '${target}__output_' + str(count)
  257. SetVariableList(out, outputs_name, outputs)
  258. out.write('add_custom_command(OUTPUT ')
  259. WriteVariable(out, outputs_name)
  260. out.write('\n')
  261. if output_directories:
  262. out.write(' COMMAND ${CMAKE_COMMAND} -E make_directory "')
  263. out.write('" "'.join(map(CMakeStringEscape, output_directories)))
  264. out.write('"\n')
  265. script = target.properties['script']
  266. # TODO: need to expand {{xxx}} in arguments
  267. arguments = target.properties['args']
  268. out.write(' COMMAND python "')
  269. out.write(CMakeStringEscape(project.GetAbsolutePath(script)))
  270. out.write('"')
  271. if arguments:
  272. out.write('\n "')
  273. expand = functools.partial(ExpandPlaceholders, source_abs_path)
  274. out.write('"\n "'.join(map(CMakeStringEscape, map(expand,arguments))))
  275. out.write('"')
  276. out.write('\n')
  277. out.write(' DEPENDS')
  278. if 'input' in sources:
  279. WriteVariable(out, sources['input'], ' ')
  280. out.write(' "')
  281. out.write(CMakeStringEscape(source_abs_path))
  282. out.write('"\n')
  283. #TODO: CMake 3.7 is introducing DEPFILE
  284. out.write(' WORKING_DIRECTORY "')
  285. out.write(CMakeStringEscape(project.build_path))
  286. out.write('"\n')
  287. out.write(' COMMENT "Action ${target} on ')
  288. out.write(CMakeStringEscape(source_abs_path))
  289. out.write('"\n')
  290. out.write(' VERBATIM)\n')
  291. synthetic_dependencies.add(outputs_name)
  292. def WriteCopy(out, target, project, sources, synthetic_dependencies):
  293. inputs = target.properties.get('sources', [])
  294. raw_outputs = target.properties.get('outputs', [])
  295. # TODO: consider expanding 'output_patterns' instead.
  296. outputs = []
  297. for output in raw_outputs:
  298. output_abs_path = project.GetAbsolutePath(output)
  299. outputs.append(output_abs_path)
  300. outputs_name = '${target}__output'
  301. SetVariableList(out, outputs_name, outputs)
  302. out.write('add_custom_command(OUTPUT ')
  303. WriteVariable(out, outputs_name)
  304. out.write('\n')
  305. for src, dst in zip(inputs, outputs):
  306. abs_src_path = CMakeStringEscape(project.GetAbsolutePath(src))
  307. # CMake distinguishes between copying files and copying directories but
  308. # gn does not. We assume if the src has a period in its name then it is
  309. # a file and otherwise a directory.
  310. if "." in os.path.basename(abs_src_path):
  311. out.write(' COMMAND ${CMAKE_COMMAND} -E copy "')
  312. else:
  313. out.write(' COMMAND ${CMAKE_COMMAND} -E copy_directory "')
  314. out.write(abs_src_path)
  315. out.write('" "')
  316. out.write(CMakeStringEscape(dst))
  317. out.write('"\n')
  318. out.write(' DEPENDS ')
  319. for sources_type_name in sources.values():
  320. WriteVariable(out, sources_type_name, ' ')
  321. out.write('\n')
  322. out.write(' WORKING_DIRECTORY "')
  323. out.write(CMakeStringEscape(project.build_path))
  324. out.write('"\n')
  325. out.write(' COMMENT "Copy ${target}"\n')
  326. out.write(' VERBATIM)\n')
  327. synthetic_dependencies.add(outputs_name)
  328. def WriteCompilerFlags(out, target, project, sources):
  329. # Hack, set linker language to c if no c or cxx files present.
  330. if not 'c' in sources and not 'cxx' in sources:
  331. SetCurrentTargetProperty(out, 'LINKER_LANGUAGE', ['C'])
  332. # Mark uncompiled sources as uncompiled.
  333. if 'input' in sources:
  334. SetFilesProperty(out, sources['input'], 'HEADER_FILE_ONLY', ('True',), '')
  335. if 'other' in sources:
  336. SetFilesProperty(out, sources['other'], 'HEADER_FILE_ONLY', ('True',), '')
  337. # Mark object sources as linkable.
  338. if 'obj' in sources:
  339. SetFilesProperty(out, sources['obj'], 'EXTERNAL_OBJECT', ('True',), '')
  340. # TODO: 'output_name', 'output_dir', 'output_extension'
  341. # This includes using 'source_outputs' to direct compiler output.
  342. # Includes
  343. includes = target.properties.get('include_dirs', [])
  344. if includes:
  345. out.write('set_property(TARGET "${target}" ')
  346. out.write('APPEND PROPERTY INCLUDE_DIRECTORIES')
  347. for include_dir in includes:
  348. out.write('\n "')
  349. out.write(project.GetAbsolutePath(include_dir))
  350. out.write('"')
  351. out.write(')\n')
  352. # Defines
  353. defines = target.properties.get('defines', [])
  354. if defines:
  355. SetCurrentTargetProperty(out, 'COMPILE_DEFINITIONS', defines, ';')
  356. # Compile flags
  357. # "arflags", "asmflags", "cflags",
  358. # "cflags_c", "clfags_cc", "cflags_objc", "clfags_objcc"
  359. # CMake does not have per target lang compile flags.
  360. # TODO: $<$<COMPILE_LANGUAGE:CXX>:cflags_cc style generator expression.
  361. # http://public.kitware.com/Bug/view.php?id=14857
  362. flags = []
  363. flags.extend(target.properties.get('cflags', []))
  364. cflags_asm = target.properties.get('asmflags', [])
  365. cflags_c = target.properties.get('cflags_c', [])
  366. cflags_cxx = target.properties.get('cflags_cc', [])
  367. cflags_objc = cflags_c[:]
  368. cflags_objc.extend(target.properties.get('cflags_objc', []))
  369. cflags_objcc = cflags_cxx[:]
  370. cflags_objcc.extend(target.properties.get('cflags_objcc', []))
  371. if 'c' in sources and not any(k in sources for k in ('asm', 'cxx', 'objc', 'objcc')):
  372. flags.extend(cflags_c)
  373. elif 'cxx' in sources and not any(k in sources for k in ('asm', 'c', 'objc', 'objcc')):
  374. flags.extend(cflags_cxx)
  375. elif 'objc' in sources and not any(k in sources for k in ('asm', 'c', 'cxx', 'objcc')):
  376. flags.extend(cflags_objc)
  377. elif 'objcc' in sources and not any(k in sources for k in ('asm', 'c', 'cxx', 'objc')):
  378. flags.extend(cflags_objcc)
  379. else:
  380. # TODO: This is broken, one cannot generally set properties on files,
  381. # as other targets may require different properties on the same files.
  382. if 'asm' in sources and cflags_asm:
  383. SetFilesProperty(out, sources['asm'], 'COMPILE_FLAGS', cflags_asm, ' ')
  384. if 'c' in sources and cflags_c:
  385. SetFilesProperty(out, sources['c'], 'COMPILE_FLAGS', cflags_c, ' ')
  386. if 'cxx' in sources and cflags_cxx:
  387. SetFilesProperty(out, sources['cxx'], 'COMPILE_FLAGS', cflags_cxx, ' ')
  388. if 'objc' in sources and cflags_objc:
  389. SetFilesProperty(out, sources['objc'], 'COMPILE_FLAGS', cflags_objc, ' ')
  390. if 'objcc' in sources and cflags_objcc:
  391. SetFilesProperty(out, sources['objcc'], 'COMPILE_FLAGS', cflags_objcc, ' ')
  392. if flags:
  393. SetCurrentTargetProperty(out, 'COMPILE_FLAGS', flags, ' ')
  394. # Linker flags
  395. ldflags = target.properties.get('ldflags', [])
  396. if ldflags:
  397. SetCurrentTargetProperty(out, 'LINK_FLAGS', ldflags, ' ')
  398. gn_target_types_that_absorb_objects = (
  399. 'executable',
  400. 'loadable_module',
  401. 'shared_library',
  402. 'static_library'
  403. )
  404. def WriteSourceVariables(out, target, project):
  405. # gn separates the sheep from the goats based on file extensions.
  406. # A full separation is done here because of flag handing (see Compile flags).
  407. source_types = {'cxx':[], 'c':[], 'asm':[], 'objc':[], 'objcc':[],
  408. 'obj':[], 'obj_target':[], 'input':[], 'other':[]}
  409. all_sources = target.properties.get('sources', [])
  410. # As of cmake 3.11 add_library must have sources. If there are
  411. # no sources, add empty.cpp as the file to compile.
  412. if len(all_sources) == 0:
  413. all_sources.append(posixpath.join(project.build_path, 'empty.cpp'))
  414. # TODO .def files on Windows
  415. for source in all_sources:
  416. _, ext = posixpath.splitext(source)
  417. source_abs_path = project.GetAbsolutePath(source)
  418. source_types[source_file_types.get(ext, 'other')].append(source_abs_path)
  419. for input_path in target.properties.get('inputs', []):
  420. input_abs_path = project.GetAbsolutePath(input_path)
  421. source_types['input'].append(input_abs_path)
  422. # OBJECT library dependencies need to be listed as sources.
  423. # Only executables and non-OBJECT libraries may reference an OBJECT library.
  424. # https://gitlab.kitware.com/cmake/cmake/issues/14778
  425. if target.gn_type in gn_target_types_that_absorb_objects:
  426. object_dependencies = set()
  427. project.GetObjectSourceDependencies(target.gn_name, object_dependencies)
  428. for dependency in object_dependencies:
  429. cmake_dependency_name = project.GetCMakeTargetName(dependency)
  430. obj_target_sources = '$<TARGET_OBJECTS:' + cmake_dependency_name + '>'
  431. source_types['obj_target'].append(obj_target_sources)
  432. sources = {}
  433. for source_type, sources_of_type in source_types.items():
  434. if sources_of_type:
  435. sources[source_type] = '${target}__' + source_type + '_srcs'
  436. SetVariableList(out, sources[source_type], sources_of_type)
  437. return sources
  438. def WriteTarget(out, target, project):
  439. out.write('\n#')
  440. out.write(target.gn_name)
  441. out.write('\n')
  442. if target.cmake_type is None:
  443. print ('Target %s has unknown target type %s, skipping.' %
  444. ( target.gn_name, target.gn_type ) )
  445. return
  446. SetVariable(out, 'target', target.cmake_name)
  447. sources = WriteSourceVariables(out, target, project)
  448. synthetic_dependencies = set()
  449. if target.gn_type == 'action':
  450. WriteAction(out, target, project, sources, synthetic_dependencies)
  451. if target.gn_type == 'action_foreach':
  452. WriteActionForEach(out, target, project, sources, synthetic_dependencies)
  453. if target.gn_type == 'copy':
  454. WriteCopy(out, target, project, sources, synthetic_dependencies)
  455. out.write(target.cmake_type.command)
  456. out.write('("${target}"')
  457. if target.cmake_type.modifier is not None:
  458. out.write(' ')
  459. out.write(target.cmake_type.modifier)
  460. for sources_type_name in sources.values():
  461. WriteVariable(out, sources_type_name, ' ')
  462. if synthetic_dependencies:
  463. out.write(' DEPENDS')
  464. for synthetic_dependencie in synthetic_dependencies:
  465. WriteVariable(out, synthetic_dependencie, ' ')
  466. out.write(')\n')
  467. if target.cmake_type.command != 'add_custom_target':
  468. WriteCompilerFlags(out, target, project, sources)
  469. libraries = set()
  470. nonlibraries = set()
  471. dependencies = set(target.properties.get('deps', []))
  472. # Transitive OBJECT libraries are in sources.
  473. # Those sources are dependent on the OBJECT library dependencies.
  474. # Those sources cannot bring in library dependencies.
  475. object_dependencies = set()
  476. if target.gn_type != 'source_set':
  477. project.GetObjectLibraryDependencies(target.gn_name, object_dependencies)
  478. for object_dependency in object_dependencies:
  479. dependencies.update(project.targets.get(object_dependency).get('deps', []))
  480. for dependency in dependencies:
  481. gn_dependency_type = project.targets.get(dependency, {}).get('type', None)
  482. cmake_dependency_type = cmake_target_types.get(gn_dependency_type, None)
  483. cmake_dependency_name = project.GetCMakeTargetName(dependency)
  484. if cmake_dependency_type.command != 'add_library':
  485. nonlibraries.add(cmake_dependency_name)
  486. elif cmake_dependency_type.modifier != 'OBJECT':
  487. if target.cmake_type.is_linkable:
  488. libraries.add(cmake_dependency_name)
  489. else:
  490. nonlibraries.add(cmake_dependency_name)
  491. # Non-library dependencies.
  492. if nonlibraries:
  493. out.write('add_dependencies("${target}"')
  494. for nonlibrary in nonlibraries:
  495. out.write('\n "')
  496. out.write(nonlibrary)
  497. out.write('"')
  498. out.write(')\n')
  499. # Non-OBJECT library dependencies.
  500. external_libraries = target.properties.get('libs', [])
  501. if target.cmake_type.is_linkable and (external_libraries or libraries):
  502. library_dirs = target.properties.get('lib_dirs', [])
  503. if library_dirs:
  504. SetVariableList(out, '${target}__library_directories', library_dirs)
  505. system_libraries = []
  506. for external_library in external_libraries:
  507. if '/' in external_library:
  508. libraries.add(project.GetAbsolutePath(external_library))
  509. else:
  510. if external_library.endswith('.framework'):
  511. external_library = external_library[:-len('.framework')]
  512. system_library = 'library__' + external_library
  513. if library_dirs:
  514. system_library = system_library + '__for_${target}'
  515. out.write('find_library("')
  516. out.write(CMakeStringEscape(system_library))
  517. out.write('" "')
  518. out.write(CMakeStringEscape(external_library))
  519. out.write('"')
  520. if library_dirs:
  521. out.write(' PATHS "')
  522. WriteVariable(out, '${target}__library_directories')
  523. out.write('"')
  524. out.write(')\n')
  525. system_libraries.append(system_library)
  526. out.write('target_link_libraries("${target}"')
  527. for library in libraries:
  528. out.write('\n "')
  529. out.write(CMakeStringEscape(library))
  530. out.write('"')
  531. for system_library in system_libraries:
  532. WriteVariable(out, system_library, '\n "')
  533. out.write('"')
  534. out.write(')\n')
  535. def WriteProject(project):
  536. out = open(posixpath.join(project.build_path, 'CMakeLists.txt'), 'w+')
  537. extName = posixpath.join(project.build_path, 'CMakeLists.ext')
  538. out.write('# Generated by gn_to_cmake.py.\n')
  539. out.write('cmake_minimum_required(VERSION 2.8.8 FATAL_ERROR)\n')
  540. out.write('cmake_policy(VERSION 2.8.8)\n\n')
  541. out.write('file(WRITE "')
  542. out.write(CMakeStringEscape(posixpath.join(project.build_path, "empty.cpp")))
  543. out.write('")\n')
  544. # Update the gn generated ninja build.
  545. # If a build file has changed, this will update CMakeLists.ext if
  546. # gn gen out/config --ide=json --json-ide-script=../../gn/gn_to_cmake.py
  547. # style was used to create this config.
  548. out.write('execute_process(COMMAND\n')
  549. out.write(' ninja -C "')
  550. out.write(CMakeStringEscape(project.build_path))
  551. out.write('" build.ninja\n')
  552. out.write(' RESULT_VARIABLE ninja_result)\n')
  553. out.write('if (ninja_result)\n')
  554. out.write(' message(WARNING ')
  555. out.write('"Regeneration failed running ninja: ${ninja_result}")\n')
  556. out.write('endif()\n')
  557. out.write('include("')
  558. out.write(CMakeStringEscape(extName))
  559. out.write('")\n')
  560. out.close()
  561. out = open(extName, 'w+')
  562. out.write('# Generated by gn_to_cmake.py.\n')
  563. out.write('cmake_minimum_required(VERSION 2.8.8 FATAL_ERROR)\n')
  564. out.write('cmake_policy(VERSION 2.8.8)\n')
  565. # The following appears to be as-yet undocumented.
  566. # http://public.kitware.com/Bug/view.php?id=8392
  567. out.write('enable_language(ASM)\n\n')
  568. # ASM-ATT does not support .S files.
  569. # output.write('enable_language(ASM-ATT)\n')
  570. # Current issues with automatic re-generation:
  571. # The gn generated build.ninja target uses build.ninja.d
  572. # but build.ninja.d does not contain the ide or gn.
  573. # Currently the ide is not run if the project.json file is not changed
  574. # but the ide needs to be run anyway if it has itself changed.
  575. # This can be worked around by deleting the project.json file.
  576. out.write('file(READ "')
  577. gn_deps_file = posixpath.join(project.build_path, 'build.ninja.d')
  578. out.write(CMakeStringEscape(gn_deps_file))
  579. out.write('" "gn_deps_string" OFFSET ')
  580. out.write(str(len('build.ninja: ')))
  581. out.write(')\n')
  582. # One would think this would need to worry about escaped spaces
  583. # but gn doesn't escape spaces here (it generates invalid .d files).
  584. out.write('string(REPLACE " " ";" "gn_deps" ${gn_deps_string})\n')
  585. out.write('foreach("gn_dep" ${gn_deps})\n')
  586. out.write(' configure_file("')
  587. out.write(CMakeStringEscape(project.build_path))
  588. out.write('${gn_dep}" "CMakeLists.devnull" COPYONLY)\n')
  589. out.write('endforeach("gn_dep")\n')
  590. out.write('list(APPEND other_deps "')
  591. out.write(CMakeStringEscape(os.path.abspath(__file__)))
  592. out.write('")\n')
  593. out.write('foreach("other_dep" ${other_deps})\n')
  594. out.write(' configure_file("${other_dep}" "CMakeLists.devnull" COPYONLY)\n')
  595. out.write('endforeach("other_dep")\n')
  596. for target_name in project.targets.keys():
  597. out.write('\n')
  598. WriteTarget(out, Target(target_name, project), project)
  599. def main():
  600. if len(sys.argv) != 2:
  601. print('Usage: ' + sys.argv[0] + ' <json_file_name>')
  602. exit(1)
  603. json_path = sys.argv[1]
  604. project = None
  605. with open(json_path, 'r') as json_file:
  606. project = json.loads(json_file.read())
  607. WriteProject(Project(project))
  608. if __name__ == "__main__":
  609. main()