PageRenderTime 72ms CodeModel.GetById 19ms RepoModel.GetById 0ms app.codeStats 0ms

/media/webrtc/trunk/tools/gyp/pylib/gyp/generator/msvs.py

https://bitbucket.org/hsoft/mozilla-central
Python | 3145 lines | 2908 code | 84 blank | 153 comment | 100 complexity | fac9a2be18cf168aa31f5631829288b3 MD5 | raw file
Possible License(s): JSON, LGPL-2.1, LGPL-3.0, AGPL-1.0, MIT, MPL-2.0-no-copyleft-exception, Apache-2.0, GPL-2.0, BSD-2-Clause, MPL-2.0, BSD-3-Clause, 0BSD
  1. # Copyright (c) 2012 Google Inc. All rights reserved.
  2. # Use of this source code is governed by a BSD-style license that can be
  3. # found in the LICENSE file.
  4. import copy
  5. import ntpath
  6. import os
  7. import posixpath
  8. import re
  9. import subprocess
  10. import sys
  11. import gyp.common
  12. import gyp.easy_xml as easy_xml
  13. import gyp.MSVSNew as MSVSNew
  14. import gyp.MSVSProject as MSVSProject
  15. import gyp.MSVSSettings as MSVSSettings
  16. import gyp.MSVSToolFile as MSVSToolFile
  17. import gyp.MSVSUserFile as MSVSUserFile
  18. import gyp.MSVSVersion as MSVSVersion
  19. # Regular expression for validating Visual Studio GUIDs. If the GUID
  20. # contains lowercase hex letters, MSVS will be fine. However,
  21. # IncrediBuild BuildConsole will parse the solution file, but then
  22. # silently skip building the target causing hard to track down errors.
  23. # Note that this only happens with the BuildConsole, and does not occur
  24. # if IncrediBuild is executed from inside Visual Studio. This regex
  25. # validates that the string looks like a GUID with all uppercase hex
  26. # letters.
  27. VALID_MSVS_GUID_CHARS = re.compile('^[A-F0-9\-]+$')
  28. generator_default_variables = {
  29. 'EXECUTABLE_PREFIX': '',
  30. 'EXECUTABLE_SUFFIX': '.exe',
  31. 'STATIC_LIB_PREFIX': '',
  32. 'SHARED_LIB_PREFIX': '',
  33. 'STATIC_LIB_SUFFIX': '.lib',
  34. 'SHARED_LIB_SUFFIX': '.dll',
  35. 'INTERMEDIATE_DIR': '$(IntDir)',
  36. 'SHARED_INTERMEDIATE_DIR': '$(OutDir)obj/global_intermediate',
  37. 'OS': 'win',
  38. 'PRODUCT_DIR': '$(OutDir)',
  39. 'LIB_DIR': '$(OutDir)lib',
  40. 'RULE_INPUT_ROOT': '$(InputName)',
  41. 'RULE_INPUT_DIRNAME': '$(InputDir)',
  42. 'RULE_INPUT_EXT': '$(InputExt)',
  43. 'RULE_INPUT_NAME': '$(InputFileName)',
  44. 'RULE_INPUT_PATH': '$(InputPath)',
  45. 'CONFIGURATION_NAME': '$(ConfigurationName)',
  46. }
  47. # The msvs specific sections that hold paths
  48. generator_additional_path_sections = [
  49. 'msvs_cygwin_dirs',
  50. 'msvs_props',
  51. ]
  52. generator_additional_non_configuration_keys = [
  53. 'msvs_cygwin_dirs',
  54. 'msvs_cygwin_shell',
  55. 'msvs_shard',
  56. ]
  57. # List of precompiled header related keys.
  58. precomp_keys = [
  59. 'msvs_precompiled_header',
  60. 'msvs_precompiled_source',
  61. ]
  62. cached_username = None
  63. cached_domain = None
  64. # TODO(gspencer): Switch the os.environ calls to be
  65. # win32api.GetDomainName() and win32api.GetUserName() once the
  66. # python version in depot_tools has been updated to work on Vista
  67. # 64-bit.
  68. def _GetDomainAndUserName():
  69. if sys.platform not in ('win32', 'cygwin'):
  70. return ('DOMAIN', 'USERNAME')
  71. global cached_username
  72. global cached_domain
  73. if not cached_domain or not cached_username:
  74. domain = os.environ.get('USERDOMAIN')
  75. username = os.environ.get('USERNAME')
  76. if not domain or not username:
  77. call = subprocess.Popen(['net', 'config', 'Workstation'],
  78. stdout=subprocess.PIPE)
  79. config = call.communicate()[0]
  80. username_re = re.compile('^User name\s+(\S+)', re.MULTILINE)
  81. username_match = username_re.search(config)
  82. if username_match:
  83. username = username_match.group(1)
  84. domain_re = re.compile('^Logon domain\s+(\S+)', re.MULTILINE)
  85. domain_match = domain_re.search(config)
  86. if domain_match:
  87. domain = domain_match.group(1)
  88. cached_domain = domain
  89. cached_username = username
  90. return (cached_domain, cached_username)
  91. fixpath_prefix = None
  92. def _NormalizedSource(source):
  93. """Normalize the path.
  94. But not if that gets rid of a variable, as this may expand to something
  95. larger than one directory.
  96. Arguments:
  97. source: The path to be normalize.d
  98. Returns:
  99. The normalized path.
  100. """
  101. normalized = os.path.normpath(source)
  102. if source.count('$') == normalized.count('$'):
  103. source = normalized
  104. return source
  105. def _FixPath(path):
  106. """Convert paths to a form that will make sense in a vcproj file.
  107. Arguments:
  108. path: The path to convert, may contain / etc.
  109. Returns:
  110. The path with all slashes made into backslashes.
  111. """
  112. if fixpath_prefix and path and not os.path.isabs(path) and not path[0] == '$':
  113. path = os.path.join(fixpath_prefix, path)
  114. path = path.replace('/', '\\')
  115. path = _NormalizedSource(path)
  116. if path and path[-1] == '\\':
  117. path = path[:-1]
  118. return path
  119. def _FixPaths(paths):
  120. """Fix each of the paths of the list."""
  121. return [_FixPath(i) for i in paths]
  122. def _ConvertSourcesToFilterHierarchy(sources, prefix=None, excluded=None,
  123. list_excluded=True):
  124. """Converts a list split source file paths into a vcproj folder hierarchy.
  125. Arguments:
  126. sources: A list of source file paths split.
  127. prefix: A list of source file path layers meant to apply to each of sources.
  128. excluded: A set of excluded files.
  129. Returns:
  130. A hierarchy of filenames and MSVSProject.Filter objects that matches the
  131. layout of the source tree.
  132. For example:
  133. _ConvertSourcesToFilterHierarchy([['a', 'bob1.c'], ['b', 'bob2.c']],
  134. prefix=['joe'])
  135. -->
  136. [MSVSProject.Filter('a', contents=['joe\\a\\bob1.c']),
  137. MSVSProject.Filter('b', contents=['joe\\b\\bob2.c'])]
  138. """
  139. if not prefix: prefix = []
  140. result = []
  141. excluded_result = []
  142. folders = dict()
  143. # Gather files into the final result, excluded, or folders.
  144. for s in sources:
  145. if len(s) == 1:
  146. filename = _NormalizedSource('\\'.join(prefix + s))
  147. if filename in excluded:
  148. excluded_result.append(filename)
  149. else:
  150. result.append(filename)
  151. else:
  152. if not folders.get(s[0]):
  153. folders[s[0]] = []
  154. folders[s[0]].append(s[1:])
  155. # Add a folder for excluded files.
  156. if excluded_result and list_excluded:
  157. excluded_folder = MSVSProject.Filter('_excluded_files',
  158. contents=excluded_result)
  159. result.append(excluded_folder)
  160. # Populate all the folders.
  161. for f in folders:
  162. contents = _ConvertSourcesToFilterHierarchy(folders[f], prefix=prefix + [f],
  163. excluded=excluded,
  164. list_excluded=list_excluded)
  165. contents = MSVSProject.Filter(f, contents=contents)
  166. result.append(contents)
  167. return result
  168. def _ToolAppend(tools, tool_name, setting, value, only_if_unset=False):
  169. if not value: return
  170. # TODO(bradnelson): ugly hack, fix this more generally!!!
  171. if 'Directories' in setting or 'Dependencies' in setting:
  172. if type(value) == str:
  173. value = value.replace('/', '\\')
  174. else:
  175. value = [i.replace('/', '\\') for i in value]
  176. if not tools.get(tool_name):
  177. tools[tool_name] = dict()
  178. tool = tools[tool_name]
  179. if tool.get(setting):
  180. if only_if_unset: return
  181. if type(tool[setting]) == list:
  182. tool[setting] += value
  183. else:
  184. raise TypeError(
  185. 'Appending "%s" to a non-list setting "%s" for tool "%s" is '
  186. 'not allowed, previous value: %s' % (
  187. value, setting, tool_name, str(tool[setting])))
  188. else:
  189. tool[setting] = value
  190. def _ConfigPlatform(config_data):
  191. return config_data.get('msvs_configuration_platform', 'Win32')
  192. def _ConfigBaseName(config_name, platform_name):
  193. if config_name.endswith('_' + platform_name):
  194. return config_name[0:-len(platform_name)-1]
  195. else:
  196. return config_name
  197. def _ConfigFullName(config_name, config_data):
  198. platform_name = _ConfigPlatform(config_data)
  199. return '%s|%s' % (_ConfigBaseName(config_name, platform_name), platform_name)
  200. def _BuildCommandLineForRuleRaw(spec, cmd, cygwin_shell, has_input_path,
  201. quote_cmd, do_setup_env):
  202. if [x for x in cmd if '$(InputDir)' in x]:
  203. input_dir_preamble = (
  204. 'set INPUTDIR=$(InputDir)\n'
  205. 'set INPUTDIR=%INPUTDIR:$(ProjectDir)=%\n'
  206. 'set INPUTDIR=%INPUTDIR:~0,-1%\n'
  207. )
  208. else:
  209. input_dir_preamble = ''
  210. if cygwin_shell:
  211. # Find path to cygwin.
  212. cygwin_dir = _FixPath(spec.get('msvs_cygwin_dirs', ['.'])[0])
  213. # Prepare command.
  214. direct_cmd = cmd
  215. direct_cmd = [i.replace('$(IntDir)',
  216. '`cygpath -m "${INTDIR}"`') for i in direct_cmd]
  217. direct_cmd = [i.replace('$(OutDir)',
  218. '`cygpath -m "${OUTDIR}"`') for i in direct_cmd]
  219. direct_cmd = [i.replace('$(InputDir)',
  220. '`cygpath -m "${INPUTDIR}"`') for i in direct_cmd]
  221. if has_input_path:
  222. direct_cmd = [i.replace('$(InputPath)',
  223. '`cygpath -m "${INPUTPATH}"`')
  224. for i in direct_cmd]
  225. direct_cmd = ['\\"%s\\"' % i.replace('"', '\\\\\\"') for i in direct_cmd]
  226. #direct_cmd = gyp.common.EncodePOSIXShellList(direct_cmd)
  227. direct_cmd = ' '.join(direct_cmd)
  228. # TODO(quote): regularize quoting path names throughout the module
  229. cmd = ''
  230. if do_setup_env:
  231. cmd += 'call "$(ProjectDir)%(cygwin_dir)s\\setup_env.bat" && '
  232. cmd += 'set CYGWIN=nontsec&& '
  233. if direct_cmd.find('NUMBER_OF_PROCESSORS') >= 0:
  234. cmd += 'set /a NUMBER_OF_PROCESSORS_PLUS_1=%%NUMBER_OF_PROCESSORS%%+1&& '
  235. if direct_cmd.find('INTDIR') >= 0:
  236. cmd += 'set INTDIR=$(IntDir)&& '
  237. if direct_cmd.find('OUTDIR') >= 0:
  238. cmd += 'set OUTDIR=$(OutDir)&& '
  239. if has_input_path and direct_cmd.find('INPUTPATH') >= 0:
  240. cmd += 'set INPUTPATH=$(InputPath) && '
  241. cmd += 'bash -c "%(cmd)s"'
  242. cmd = cmd % {'cygwin_dir': cygwin_dir,
  243. 'cmd': direct_cmd}
  244. return input_dir_preamble + cmd
  245. else:
  246. # Convert cat --> type to mimic unix.
  247. if cmd[0] == 'cat':
  248. command = ['type']
  249. else:
  250. command = [cmd[0].replace('/', '\\')]
  251. # Add call before command to ensure that commands can be tied together one
  252. # after the other without aborting in Incredibuild, since IB makes a bat
  253. # file out of the raw command string, and some commands (like python) are
  254. # actually batch files themselves.
  255. command.insert(0, 'call')
  256. # Fix the paths
  257. # TODO(quote): This is a really ugly heuristic, and will miss path fixing
  258. # for arguments like "--arg=path" or "/opt:path".
  259. # If the argument starts with a slash or dash, it's probably a command line
  260. # switch
  261. arguments = [i if (i[:1] in "/-") else _FixPath(i) for i in cmd[1:]]
  262. arguments = [i.replace('$(InputDir)','%INPUTDIR%') for i in arguments]
  263. arguments = [MSVSSettings.FixVCMacroSlashes(i) for i in arguments]
  264. if quote_cmd:
  265. # Support a mode for using cmd directly.
  266. # Convert any paths to native form (first element is used directly).
  267. # TODO(quote): regularize quoting path names throughout the module
  268. arguments = ['"%s"' % i for i in arguments]
  269. # Collapse into a single command.
  270. return input_dir_preamble + ' '.join(command + arguments)
  271. def _BuildCommandLineForRule(spec, rule, has_input_path, do_setup_env):
  272. # Currently this weird argument munging is used to duplicate the way a
  273. # python script would need to be run as part of the chrome tree.
  274. # Eventually we should add some sort of rule_default option to set this
  275. # per project. For now the behavior chrome needs is the default.
  276. mcs = rule.get('msvs_cygwin_shell')
  277. if mcs is None:
  278. mcs = int(spec.get('msvs_cygwin_shell', 1))
  279. elif isinstance(mcs, str):
  280. mcs = int(mcs)
  281. quote_cmd = int(rule.get('msvs_quote_cmd', 1))
  282. return _BuildCommandLineForRuleRaw(spec, rule['action'], mcs, has_input_path,
  283. quote_cmd, do_setup_env=do_setup_env)
  284. def _AddActionStep(actions_dict, inputs, outputs, description, command):
  285. """Merge action into an existing list of actions.
  286. Care must be taken so that actions which have overlapping inputs either don't
  287. get assigned to the same input, or get collapsed into one.
  288. Arguments:
  289. actions_dict: dictionary keyed on input name, which maps to a list of
  290. dicts describing the actions attached to that input file.
  291. inputs: list of inputs
  292. outputs: list of outputs
  293. description: description of the action
  294. command: command line to execute
  295. """
  296. # Require there to be at least one input (call sites will ensure this).
  297. assert inputs
  298. action = {
  299. 'inputs': inputs,
  300. 'outputs': outputs,
  301. 'description': description,
  302. 'command': command,
  303. }
  304. # Pick where to stick this action.
  305. # While less than optimal in terms of build time, attach them to the first
  306. # input for now.
  307. chosen_input = inputs[0]
  308. # Add it there.
  309. if chosen_input not in actions_dict:
  310. actions_dict[chosen_input] = []
  311. actions_dict[chosen_input].append(action)
  312. def _AddCustomBuildToolForMSVS(p, spec, primary_input,
  313. inputs, outputs, description, cmd):
  314. """Add a custom build tool to execute something.
  315. Arguments:
  316. p: the target project
  317. spec: the target project dict
  318. primary_input: input file to attach the build tool to
  319. inputs: list of inputs
  320. outputs: list of outputs
  321. description: description of the action
  322. cmd: command line to execute
  323. """
  324. inputs = _FixPaths(inputs)
  325. outputs = _FixPaths(outputs)
  326. tool = MSVSProject.Tool(
  327. 'VCCustomBuildTool',
  328. {'Description': description,
  329. 'AdditionalDependencies': ';'.join(inputs),
  330. 'Outputs': ';'.join(outputs),
  331. 'CommandLine': cmd,
  332. })
  333. # Add to the properties of primary input for each config.
  334. for config_name, c_data in spec['configurations'].iteritems():
  335. p.AddFileConfig(_FixPath(primary_input),
  336. _ConfigFullName(config_name, c_data), tools=[tool])
  337. def _AddAccumulatedActionsToMSVS(p, spec, actions_dict):
  338. """Add actions accumulated into an actions_dict, merging as needed.
  339. Arguments:
  340. p: the target project
  341. spec: the target project dict
  342. actions_dict: dictionary keyed on input name, which maps to a list of
  343. dicts describing the actions attached to that input file.
  344. """
  345. for primary_input in actions_dict:
  346. inputs = set()
  347. outputs = set()
  348. descriptions = []
  349. commands = []
  350. for action in actions_dict[primary_input]:
  351. inputs.update(set(action['inputs']))
  352. outputs.update(set(action['outputs']))
  353. descriptions.append(action['description'])
  354. commands.append(action['command'])
  355. # Add the custom build step for one input file.
  356. description = ', and also '.join(descriptions)
  357. command = '\r\n'.join(commands)
  358. _AddCustomBuildToolForMSVS(p, spec,
  359. primary_input=primary_input,
  360. inputs=inputs,
  361. outputs=outputs,
  362. description=description,
  363. cmd=command)
  364. def _RuleExpandPath(path, input_file):
  365. """Given the input file to which a rule applied, string substitute a path.
  366. Arguments:
  367. path: a path to string expand
  368. input_file: the file to which the rule applied.
  369. Returns:
  370. The string substituted path.
  371. """
  372. path = path.replace('$(InputName)',
  373. os.path.splitext(os.path.split(input_file)[1])[0])
  374. path = path.replace('$(InputDir)', os.path.dirname(input_file))
  375. path = path.replace('$(InputExt)',
  376. os.path.splitext(os.path.split(input_file)[1])[1])
  377. path = path.replace('$(InputFileName)', os.path.split(input_file)[1])
  378. path = path.replace('$(InputPath)', input_file)
  379. return path
  380. def _FindRuleTriggerFiles(rule, sources):
  381. """Find the list of files which a particular rule applies to.
  382. Arguments:
  383. rule: the rule in question
  384. sources: the set of all known source files for this project
  385. Returns:
  386. The list of sources that trigger a particular rule.
  387. """
  388. rule_ext = rule['extension']
  389. return [s for s in sources if s.endswith('.' + rule_ext)]
  390. def _RuleInputsAndOutputs(rule, trigger_file):
  391. """Find the inputs and outputs generated by a rule.
  392. Arguments:
  393. rule: the rule in question.
  394. trigger_file: the main trigger for this rule.
  395. Returns:
  396. The pair of (inputs, outputs) involved in this rule.
  397. """
  398. raw_inputs = _FixPaths(rule.get('inputs', []))
  399. raw_outputs = _FixPaths(rule.get('outputs', []))
  400. inputs = set()
  401. outputs = set()
  402. inputs.add(trigger_file)
  403. for i in raw_inputs:
  404. inputs.add(_RuleExpandPath(i, trigger_file))
  405. for o in raw_outputs:
  406. outputs.add(_RuleExpandPath(o, trigger_file))
  407. return (inputs, outputs)
  408. def _GenerateNativeRulesForMSVS(p, rules, output_dir, spec, options):
  409. """Generate a native rules file.
  410. Arguments:
  411. p: the target project
  412. rules: the set of rules to include
  413. output_dir: the directory in which the project/gyp resides
  414. spec: the project dict
  415. options: global generator options
  416. """
  417. rules_filename = '%s%s.rules' % (spec['target_name'],
  418. options.suffix)
  419. rules_file = MSVSToolFile.Writer(os.path.join(output_dir, rules_filename),
  420. spec['target_name'])
  421. # Add each rule.
  422. for r in rules:
  423. rule_name = r['rule_name']
  424. rule_ext = r['extension']
  425. inputs = _FixPaths(r.get('inputs', []))
  426. outputs = _FixPaths(r.get('outputs', []))
  427. # Skip a rule with no action and no inputs.
  428. if 'action' not in r and not r.get('rule_sources', []):
  429. continue
  430. cmd = _BuildCommandLineForRule(spec, r, has_input_path=True,
  431. do_setup_env=True)
  432. rules_file.AddCustomBuildRule(name=rule_name,
  433. description=r.get('message', rule_name),
  434. extensions=[rule_ext],
  435. additional_dependencies=inputs,
  436. outputs=outputs,
  437. cmd=cmd)
  438. # Write out rules file.
  439. rules_file.WriteIfChanged()
  440. # Add rules file to project.
  441. p.AddToolFile(rules_filename)
  442. def _Cygwinify(path):
  443. path = path.replace('$(OutDir)', '$(OutDirCygwin)')
  444. path = path.replace('$(IntDir)', '$(IntDirCygwin)')
  445. return path
  446. def _GenerateExternalRules(rules, output_dir, spec,
  447. sources, options, actions_to_add):
  448. """Generate an external makefile to do a set of rules.
  449. Arguments:
  450. rules: the list of rules to include
  451. output_dir: path containing project and gyp files
  452. spec: project specification data
  453. sources: set of sources known
  454. options: global generator options
  455. actions_to_add: The list of actions we will add to.
  456. """
  457. filename = '%s_rules%s.mk' % (spec['target_name'], options.suffix)
  458. mk_file = gyp.common.WriteOnDiff(os.path.join(output_dir, filename))
  459. # Find cygwin style versions of some paths.
  460. mk_file.write('OutDirCygwin:=$(shell cygpath -u "$(OutDir)")\n')
  461. mk_file.write('IntDirCygwin:=$(shell cygpath -u "$(IntDir)")\n')
  462. # Gather stuff needed to emit all: target.
  463. all_inputs = set()
  464. all_outputs = set()
  465. all_output_dirs = set()
  466. first_outputs = []
  467. for rule in rules:
  468. trigger_files = _FindRuleTriggerFiles(rule, sources)
  469. for tf in trigger_files:
  470. inputs, outputs = _RuleInputsAndOutputs(rule, tf)
  471. all_inputs.update(set(inputs))
  472. all_outputs.update(set(outputs))
  473. # Only use one target from each rule as the dependency for
  474. # 'all' so we don't try to build each rule multiple times.
  475. first_outputs.append(list(outputs)[0])
  476. # Get the unique output directories for this rule.
  477. output_dirs = [os.path.split(i)[0] for i in outputs]
  478. for od in output_dirs:
  479. all_output_dirs.add(od)
  480. first_outputs_cyg = [_Cygwinify(i) for i in first_outputs]
  481. # Write out all: target, including mkdir for each output directory.
  482. mk_file.write('all: %s\n' % ' '.join(first_outputs_cyg))
  483. for od in all_output_dirs:
  484. if od:
  485. mk_file.write('\tmkdir -p `cygpath -u "%s"`\n' % od)
  486. mk_file.write('\n')
  487. # Define how each output is generated.
  488. for rule in rules:
  489. trigger_files = _FindRuleTriggerFiles(rule, sources)
  490. for tf in trigger_files:
  491. # Get all the inputs and outputs for this rule for this trigger file.
  492. inputs, outputs = _RuleInputsAndOutputs(rule, tf)
  493. inputs = [_Cygwinify(i) for i in inputs]
  494. outputs = [_Cygwinify(i) for i in outputs]
  495. # Prepare the command line for this rule.
  496. cmd = [_RuleExpandPath(c, tf) for c in rule['action']]
  497. cmd = ['"%s"' % i for i in cmd]
  498. cmd = ' '.join(cmd)
  499. # Add it to the makefile.
  500. mk_file.write('%s: %s\n' % (' '.join(outputs), ' '.join(inputs)))
  501. mk_file.write('\t%s\n\n' % cmd)
  502. # Close up the file.
  503. mk_file.close()
  504. # Add makefile to list of sources.
  505. sources.add(filename)
  506. # Add a build action to call makefile.
  507. cmd = ['make',
  508. 'OutDir=$(OutDir)',
  509. 'IntDir=$(IntDir)',
  510. '-j', '${NUMBER_OF_PROCESSORS_PLUS_1}',
  511. '-f', filename]
  512. cmd = _BuildCommandLineForRuleRaw(spec, cmd, True, False, True, True)
  513. # Insert makefile as 0'th input, so it gets the action attached there,
  514. # as this is easier to understand from in the IDE.
  515. all_inputs = list(all_inputs)
  516. all_inputs.insert(0, filename)
  517. _AddActionStep(actions_to_add,
  518. inputs=_FixPaths(all_inputs),
  519. outputs=_FixPaths(all_outputs),
  520. description='Running external rules for %s' %
  521. spec['target_name'],
  522. command=cmd)
  523. def _EscapeEnvironmentVariableExpansion(s):
  524. """Escapes % characters.
  525. Escapes any % characters so that Windows-style environment variable
  526. expansions will leave them alone.
  527. See http://connect.microsoft.com/VisualStudio/feedback/details/106127/cl-d-name-text-containing-percentage-characters-doesnt-compile
  528. to understand why we have to do this.
  529. Args:
  530. s: The string to be escaped.
  531. Returns:
  532. The escaped string.
  533. """
  534. s = s.replace('%', '%%')
  535. return s
  536. quote_replacer_regex = re.compile(r'(\\*)"')
  537. def _EscapeCommandLineArgumentForMSVS(s):
  538. """Escapes a Windows command-line argument.
  539. So that the Win32 CommandLineToArgv function will turn the escaped result back
  540. into the original string.
  541. See http://msdn.microsoft.com/en-us/library/17w5ykft.aspx
  542. ("Parsing C++ Command-Line Arguments") to understand why we have to do
  543. this.
  544. Args:
  545. s: the string to be escaped.
  546. Returns:
  547. the escaped string.
  548. """
  549. def _Replace(match):
  550. # For a literal quote, CommandLineToArgv requires an odd number of
  551. # backslashes preceding it, and it produces half as many literal backslashes
  552. # (rounded down). So we need to produce 2n+1 backslashes.
  553. return 2 * match.group(1) + '\\"'
  554. # Escape all quotes so that they are interpreted literally.
  555. s = quote_replacer_regex.sub(_Replace, s)
  556. # Now add unescaped quotes so that any whitespace is interpreted literally.
  557. s = '"' + s + '"'
  558. return s
  559. delimiters_replacer_regex = re.compile(r'(\\*)([,;]+)')
  560. def _EscapeVCProjCommandLineArgListItem(s):
  561. """Escapes command line arguments for MSVS.
  562. The VCProj format stores string lists in a single string using commas and
  563. semi-colons as separators, which must be quoted if they are to be
  564. interpreted literally. However, command-line arguments may already have
  565. quotes, and the VCProj parser is ignorant of the backslash escaping
  566. convention used by CommandLineToArgv, so the command-line quotes and the
  567. VCProj quotes may not be the same quotes. So to store a general
  568. command-line argument in a VCProj list, we need to parse the existing
  569. quoting according to VCProj's convention and quote any delimiters that are
  570. not already quoted by that convention. The quotes that we add will also be
  571. seen by CommandLineToArgv, so if backslashes precede them then we also have
  572. to escape those backslashes according to the CommandLineToArgv
  573. convention.
  574. Args:
  575. s: the string to be escaped.
  576. Returns:
  577. the escaped string.
  578. """
  579. def _Replace(match):
  580. # For a non-literal quote, CommandLineToArgv requires an even number of
  581. # backslashes preceding it, and it produces half as many literal
  582. # backslashes. So we need to produce 2n backslashes.
  583. return 2 * match.group(1) + '"' + match.group(2) + '"'
  584. segments = s.split('"')
  585. # The unquoted segments are at the even-numbered indices.
  586. for i in range(0, len(segments), 2):
  587. segments[i] = delimiters_replacer_regex.sub(_Replace, segments[i])
  588. # Concatenate back into a single string
  589. s = '"'.join(segments)
  590. if len(segments) % 2 == 0:
  591. # String ends while still quoted according to VCProj's convention. This
  592. # means the delimiter and the next list item that follow this one in the
  593. # .vcproj file will be misinterpreted as part of this item. There is nothing
  594. # we can do about this. Adding an extra quote would correct the problem in
  595. # the VCProj but cause the same problem on the final command-line. Moving
  596. # the item to the end of the list does works, but that's only possible if
  597. # there's only one such item. Let's just warn the user.
  598. print >> sys.stderr, ('Warning: MSVS may misinterpret the odd number of ' +
  599. 'quotes in ' + s)
  600. return s
  601. def _EscapeCppDefineForMSVS(s):
  602. """Escapes a CPP define so that it will reach the compiler unaltered."""
  603. s = _EscapeEnvironmentVariableExpansion(s)
  604. s = _EscapeCommandLineArgumentForMSVS(s)
  605. s = _EscapeVCProjCommandLineArgListItem(s)
  606. # cl.exe replaces literal # characters with = in preprocesor definitions for
  607. # some reason. Octal-encode to work around that.
  608. s = s.replace('#', '\\%03o' % ord('#'))
  609. return s
  610. quote_replacer_regex2 = re.compile(r'(\\+)"')
  611. def _EscapeCommandLineArgumentForMSBuild(s):
  612. """Escapes a Windows command-line argument for use by MSBuild."""
  613. def _Replace(match):
  614. return (len(match.group(1))/2*4)*'\\' + '\\"'
  615. # Escape all quotes so that they are interpreted literally.
  616. s = quote_replacer_regex2.sub(_Replace, s)
  617. return s
  618. def _EscapeMSBuildSpecialCharacters(s):
  619. escape_dictionary = {
  620. '%': '%25',
  621. '$': '%24',
  622. '@': '%40',
  623. "'": '%27',
  624. ';': '%3B',
  625. '?': '%3F',
  626. '*': '%2A'
  627. }
  628. result = ''.join([escape_dictionary.get(c, c) for c in s])
  629. return result
  630. def _EscapeCppDefineForMSBuild(s):
  631. """Escapes a CPP define so that it will reach the compiler unaltered."""
  632. s = _EscapeEnvironmentVariableExpansion(s)
  633. s = _EscapeCommandLineArgumentForMSBuild(s)
  634. s = _EscapeMSBuildSpecialCharacters(s)
  635. # cl.exe replaces literal # characters with = in preprocesor definitions for
  636. # some reason. Octal-encode to work around that.
  637. s = s.replace('#', '\\%03o' % ord('#'))
  638. return s
  639. def _GenerateRulesForMSVS(p, output_dir, options, spec,
  640. sources, excluded_sources,
  641. actions_to_add):
  642. """Generate all the rules for a particular project.
  643. Arguments:
  644. p: the project
  645. output_dir: directory to emit rules to
  646. options: global options passed to the generator
  647. spec: the specification for this project
  648. sources: the set of all known source files in this project
  649. excluded_sources: the set of sources excluded from normal processing
  650. actions_to_add: deferred list of actions to add in
  651. """
  652. rules = spec.get('rules', [])
  653. rules_native = [r for r in rules if not int(r.get('msvs_external_rule', 0))]
  654. rules_external = [r for r in rules if int(r.get('msvs_external_rule', 0))]
  655. # Handle rules that use a native rules file.
  656. if rules_native:
  657. _GenerateNativeRulesForMSVS(p, rules_native, output_dir, spec, options)
  658. # Handle external rules (non-native rules).
  659. if rules_external:
  660. _GenerateExternalRules(rules_external, output_dir, spec,
  661. sources, options, actions_to_add)
  662. _AdjustSourcesForRules(rules, sources, excluded_sources)
  663. def _AdjustSourcesForRules(rules, sources, excluded_sources):
  664. # Add outputs generated by each rule (if applicable).
  665. for rule in rules:
  666. # Done if not processing outputs as sources.
  667. if int(rule.get('process_outputs_as_sources', False)):
  668. # Add in the outputs from this rule.
  669. trigger_files = _FindRuleTriggerFiles(rule, sources)
  670. for trigger_file in trigger_files:
  671. inputs, outputs = _RuleInputsAndOutputs(rule, trigger_file)
  672. inputs = set(_FixPaths(inputs))
  673. outputs = set(_FixPaths(outputs))
  674. inputs.remove(_FixPath(trigger_file))
  675. sources.update(inputs)
  676. excluded_sources.update(inputs)
  677. sources.update(outputs)
  678. def _FilterActionsFromExcluded(excluded_sources, actions_to_add):
  679. """Take inputs with actions attached out of the list of exclusions.
  680. Arguments:
  681. excluded_sources: list of source files not to be built.
  682. actions_to_add: dict of actions keyed on source file they're attached to.
  683. Returns:
  684. excluded_sources with files that have actions attached removed.
  685. """
  686. must_keep = set(_FixPaths(actions_to_add.keys()))
  687. return [s for s in excluded_sources if s not in must_keep]
  688. def _GetDefaultConfiguration(spec):
  689. return spec['configurations'][spec['default_configuration']]
  690. def _GetGuidOfProject(proj_path, spec):
  691. """Get the guid for the project.
  692. Arguments:
  693. proj_path: Path of the vcproj or vcxproj file to generate.
  694. spec: The target dictionary containing the properties of the target.
  695. Returns:
  696. the guid.
  697. Raises:
  698. ValueError: if the specified GUID is invalid.
  699. """
  700. # Pluck out the default configuration.
  701. default_config = _GetDefaultConfiguration(spec)
  702. # Decide the guid of the project.
  703. guid = default_config.get('msvs_guid')
  704. if guid:
  705. if VALID_MSVS_GUID_CHARS.match(guid) is None:
  706. raise ValueError('Invalid MSVS guid: "%s". Must match regex: "%s".' %
  707. (guid, VALID_MSVS_GUID_CHARS.pattern))
  708. guid = '{%s}' % guid
  709. guid = guid or MSVSNew.MakeGuid(proj_path)
  710. return guid
  711. def _GetMsbuildToolsetOfProject(proj_path, spec, version):
  712. """Get the platform toolset for the project.
  713. Arguments:
  714. proj_path: Path of the vcproj or vcxproj file to generate.
  715. spec: The target dictionary containing the properties of the target.
  716. version: The MSVSVersion object.
  717. Returns:
  718. the platform toolset string or None.
  719. """
  720. # Pluck out the default configuration.
  721. default_config = _GetDefaultConfiguration(spec)
  722. toolset = default_config.get('msbuild_toolset')
  723. if not toolset and version.DefaultToolset():
  724. toolset = version.DefaultToolset()
  725. return toolset
  726. def _GenerateProject(project, options, version, generator_flags):
  727. """Generates a vcproj file.
  728. Arguments:
  729. project: the MSVSProject object.
  730. options: global generator options.
  731. version: the MSVSVersion object.
  732. generator_flags: dict of generator-specific flags.
  733. Returns:
  734. A list of source files that cannot be found on disk.
  735. """
  736. default_config = _GetDefaultConfiguration(project.spec)
  737. # Skip emitting anything if told to with msvs_existing_vcproj option.
  738. if default_config.get('msvs_existing_vcproj'):
  739. return []
  740. if version.UsesVcxproj():
  741. return _GenerateMSBuildProject(project, options, version, generator_flags)
  742. else:
  743. return _GenerateMSVSProject(project, options, version, generator_flags)
  744. def _GenerateMSVSProject(project, options, version, generator_flags):
  745. """Generates a .vcproj file. It may create .rules and .user files too.
  746. Arguments:
  747. project: The project object we will generate the file for.
  748. options: Global options passed to the generator.
  749. version: The VisualStudioVersion object.
  750. generator_flags: dict of generator-specific flags.
  751. """
  752. spec = project.spec
  753. vcproj_dir = os.path.dirname(project.path)
  754. if vcproj_dir and not os.path.exists(vcproj_dir):
  755. os.makedirs(vcproj_dir)
  756. platforms = _GetUniquePlatforms(spec)
  757. p = MSVSProject.Writer(project.path, version, spec['target_name'],
  758. project.guid, platforms)
  759. # Get directory project file is in.
  760. project_dir = os.path.split(project.path)[0]
  761. gyp_path = _NormalizedSource(project.build_file)
  762. relative_path_of_gyp_file = gyp.common.RelativePath(gyp_path, project_dir)
  763. config_type = _GetMSVSConfigurationType(spec, project.build_file)
  764. for config_name, config in spec['configurations'].iteritems():
  765. _AddConfigurationToMSVSProject(p, spec, config_type, config_name, config)
  766. # Prepare list of sources and excluded sources.
  767. gyp_file = os.path.split(project.build_file)[1]
  768. sources, excluded_sources = _PrepareListOfSources(spec, generator_flags,
  769. gyp_file)
  770. # Add rules.
  771. actions_to_add = {}
  772. _GenerateRulesForMSVS(p, project_dir, options, spec,
  773. sources, excluded_sources,
  774. actions_to_add)
  775. list_excluded = generator_flags.get('msvs_list_excluded_files', True)
  776. sources, excluded_sources, excluded_idl = (
  777. _AdjustSourcesAndConvertToFilterHierarchy(
  778. spec, options, project_dir, sources, excluded_sources, list_excluded))
  779. # Add in files.
  780. missing_sources = _VerifySourcesExist(sources, project_dir)
  781. p.AddFiles(sources)
  782. _AddToolFilesToMSVS(p, spec)
  783. _HandlePreCompiledHeaders(p, sources, spec)
  784. _AddActions(actions_to_add, spec, relative_path_of_gyp_file)
  785. _AddCopies(actions_to_add, spec)
  786. _WriteMSVSUserFile(project.path, version, spec)
  787. # NOTE: this stanza must appear after all actions have been decided.
  788. # Don't excluded sources with actions attached, or they won't run.
  789. excluded_sources = _FilterActionsFromExcluded(
  790. excluded_sources, actions_to_add)
  791. _ExcludeFilesFromBeingBuilt(p, spec, excluded_sources, excluded_idl,
  792. list_excluded)
  793. _AddAccumulatedActionsToMSVS(p, spec, actions_to_add)
  794. # Write it out.
  795. p.WriteIfChanged()
  796. return missing_sources
  797. def _GetUniquePlatforms(spec):
  798. """Returns the list of unique platforms for this spec, e.g ['win32', ...].
  799. Arguments:
  800. spec: The target dictionary containing the properties of the target.
  801. Returns:
  802. The MSVSUserFile object created.
  803. """
  804. # Gather list of unique platforms.
  805. platforms = set()
  806. for configuration in spec['configurations']:
  807. platforms.add(_ConfigPlatform(spec['configurations'][configuration]))
  808. platforms = list(platforms)
  809. return platforms
  810. def _CreateMSVSUserFile(proj_path, version, spec):
  811. """Generates a .user file for the user running this Gyp program.
  812. Arguments:
  813. proj_path: The path of the project file being created. The .user file
  814. shares the same path (with an appropriate suffix).
  815. version: The VisualStudioVersion object.
  816. spec: The target dictionary containing the properties of the target.
  817. Returns:
  818. The MSVSUserFile object created.
  819. """
  820. (domain, username) = _GetDomainAndUserName()
  821. vcuser_filename = '.'.join([proj_path, domain, username, 'user'])
  822. user_file = MSVSUserFile.Writer(vcuser_filename, version,
  823. spec['target_name'])
  824. return user_file
  825. def _GetMSVSConfigurationType(spec, build_file):
  826. """Returns the configuration type for this project.
  827. It's a number defined by Microsoft. May raise an exception.
  828. Args:
  829. spec: The target dictionary containing the properties of the target.
  830. build_file: The path of the gyp file.
  831. Returns:
  832. An integer, the configuration type.
  833. """
  834. try:
  835. config_type = {
  836. 'executable': '1', # .exe
  837. 'shared_library': '2', # .dll
  838. 'loadable_module': '2', # .dll
  839. 'static_library': '4', # .lib
  840. 'none': '10', # Utility type
  841. }[spec['type']]
  842. except KeyError:
  843. if spec.get('type'):
  844. raise Exception('Target type %s is not a valid target type for '
  845. 'target %s in %s.' %
  846. (spec['type'], spec['target_name'], build_file))
  847. else:
  848. raise Exception('Missing type field for target %s in %s.' %
  849. (spec['target_name'], build_file))
  850. return config_type
  851. def _AddConfigurationToMSVSProject(p, spec, config_type, config_name, config):
  852. """Adds a configuration to the MSVS project.
  853. Many settings in a vcproj file are specific to a configuration. This
  854. function the main part of the vcproj file that's configuration specific.
  855. Arguments:
  856. p: The target project being generated.
  857. spec: The target dictionary containing the properties of the target.
  858. config_type: The configuration type, a number as defined by Microsoft.
  859. config_name: The name of the configuration.
  860. config: The dictionnary that defines the special processing to be done
  861. for this configuration.
  862. """
  863. # Get the information for this configuration
  864. include_dirs, resource_include_dirs = _GetIncludeDirs(config)
  865. libraries = _GetLibraries(spec)
  866. out_file, vc_tool, _ = _GetOutputFilePathAndTool(spec, msbuild=False)
  867. defines = _GetDefines(config)
  868. defines = [_EscapeCppDefineForMSVS(d) for d in defines]
  869. disabled_warnings = _GetDisabledWarnings(config)
  870. prebuild = config.get('msvs_prebuild')
  871. postbuild = config.get('msvs_postbuild')
  872. def_file = _GetModuleDefinition(spec)
  873. precompiled_header = config.get('msvs_precompiled_header')
  874. # Prepare the list of tools as a dictionary.
  875. tools = dict()
  876. # Add in user specified msvs_settings.
  877. msvs_settings = config.get('msvs_settings', {})
  878. MSVSSettings.ValidateMSVSSettings(msvs_settings)
  879. for tool in msvs_settings:
  880. settings = config['msvs_settings'][tool]
  881. for setting in settings:
  882. _ToolAppend(tools, tool, setting, settings[setting])
  883. # Add the information to the appropriate tool
  884. _ToolAppend(tools, 'VCCLCompilerTool',
  885. 'AdditionalIncludeDirectories', include_dirs)
  886. _ToolAppend(tools, 'VCResourceCompilerTool',
  887. 'AdditionalIncludeDirectories', resource_include_dirs)
  888. # Add in libraries.
  889. _ToolAppend(tools, 'VCLinkerTool', 'AdditionalDependencies', libraries)
  890. if out_file:
  891. _ToolAppend(tools, vc_tool, 'OutputFile', out_file, only_if_unset=True)
  892. # Add defines.
  893. _ToolAppend(tools, 'VCCLCompilerTool', 'PreprocessorDefinitions', defines)
  894. _ToolAppend(tools, 'VCResourceCompilerTool', 'PreprocessorDefinitions',
  895. defines)
  896. # Change program database directory to prevent collisions.
  897. _ToolAppend(tools, 'VCCLCompilerTool', 'ProgramDataBaseFileName',
  898. '$(IntDir)$(ProjectName)\\vc80.pdb', only_if_unset=True)
  899. # Add disabled warnings.
  900. _ToolAppend(tools, 'VCCLCompilerTool',
  901. 'DisableSpecificWarnings', disabled_warnings)
  902. # Add Pre-build.
  903. _ToolAppend(tools, 'VCPreBuildEventTool', 'CommandLine', prebuild)
  904. # Add Post-build.
  905. _ToolAppend(tools, 'VCPostBuildEventTool', 'CommandLine', postbuild)
  906. # Turn on precompiled headers if appropriate.
  907. if precompiled_header:
  908. precompiled_header = os.path.split(precompiled_header)[1]
  909. _ToolAppend(tools, 'VCCLCompilerTool', 'UsePrecompiledHeader', '2')
  910. _ToolAppend(tools, 'VCCLCompilerTool',
  911. 'PrecompiledHeaderThrough', precompiled_header)
  912. _ToolAppend(tools, 'VCCLCompilerTool',
  913. 'ForcedIncludeFiles', precompiled_header)
  914. # Loadable modules don't generate import libraries;
  915. # tell dependent projects to not expect one.
  916. if spec['type'] == 'loadable_module':
  917. _ToolAppend(tools, 'VCLinkerTool', 'IgnoreImportLibrary', 'true')
  918. # Set the module definition file if any.
  919. if def_file:
  920. _ToolAppend(tools, 'VCLinkerTool', 'ModuleDefinitionFile', def_file)
  921. _AddConfigurationToMSVS(p, spec, tools, config, config_type, config_name)
  922. def _GetIncludeDirs(config):
  923. """Returns the list of directories to be used for #include directives.
  924. Arguments:
  925. config: The dictionnary that defines the special processing to be done
  926. for this configuration.
  927. Returns:
  928. The list of directory paths.
  929. """
  930. # TODO(bradnelson): include_dirs should really be flexible enough not to
  931. # require this sort of thing.
  932. include_dirs = (
  933. config.get('include_dirs', []) +
  934. config.get('msvs_system_include_dirs', []))
  935. resource_include_dirs = config.get('resource_include_dirs', include_dirs)
  936. include_dirs = _FixPaths(include_dirs)
  937. resource_include_dirs = _FixPaths(resource_include_dirs)
  938. return include_dirs, resource_include_dirs
  939. def _GetLibraries(spec):
  940. """Returns the list of libraries for this configuration.
  941. Arguments:
  942. spec: The target dictionary containing the properties of the target.
  943. Returns:
  944. The list of directory paths.
  945. """
  946. libraries = spec.get('libraries', [])
  947. # Strip out -l, as it is not used on windows (but is needed so we can pass
  948. # in libraries that are assumed to be in the default library path).
  949. # Also remove duplicate entries, leaving only the last duplicate, while
  950. # preserving order.
  951. found = set()
  952. unique_libraries_list = []
  953. for entry in reversed(libraries):
  954. library = re.sub('^\-l', '', entry)
  955. if library not in found:
  956. found.add(library)
  957. unique_libraries_list.append(library)
  958. unique_libraries_list.reverse()
  959. return unique_libraries_list
  960. def _GetOutputFilePathAndTool(spec, msbuild):
  961. """Returns the path and tool to use for this target.
  962. Figures out the path of the file this spec will create and the name of
  963. the VC tool that will create it.
  964. Arguments:
  965. spec: The target dictionary containing the properties of the target.
  966. Returns:
  967. A triple of (file path, name of the vc tool, name of the msbuild tool)
  968. """
  969. # Select a name for the output file.
  970. out_file = ''
  971. vc_tool = ''
  972. msbuild_tool = ''
  973. output_file_map = {
  974. 'executable': ('VCLinkerTool', 'Link', '$(OutDir)', '.exe'),
  975. 'shared_library': ('VCLinkerTool', 'Link', '$(OutDir)', '.dll'),
  976. 'loadable_module': ('VCLinkerTool', 'Link', '$(OutDir)', '.dll'),
  977. 'static_library': ('VCLibrarianTool', 'Lib', '$(OutDir)lib\\', '.lib'),
  978. }
  979. output_file_props = output_file_map.get(spec['type'])
  980. if output_file_props and int(spec.get('msvs_auto_output_file', 1)):
  981. vc_tool, msbuild_tool, out_dir, suffix = output_file_props
  982. out_dir = spec.get('product_dir', out_dir)
  983. product_extension = spec.get('product_extension')
  984. if product_extension:
  985. suffix = '.' + product_extension
  986. elif msbuild:
  987. suffix = '$(TargetExt)'
  988. prefix = spec.get('product_prefix', '')
  989. product_name = spec.get('product_name', '$(ProjectName)')
  990. out_file = ntpath.join(out_dir, prefix + product_name + suffix)
  991. return out_file, vc_tool, msbuild_tool
  992. def _GetDefines(config):
  993. """Returns the list of preprocessor definitions for this configuation.
  994. Arguments:
  995. config: The dictionnary that defines the special processing to be done
  996. for this configuration.
  997. Returns:
  998. The list of preprocessor definitions.
  999. """
  1000. defines = []
  1001. for d in config.get('defines', []):
  1002. if type(d) == list:
  1003. fd = '='.join([str(dpart) for dpart in d])
  1004. else:
  1005. fd = str(d)
  1006. defines.append(fd)
  1007. return defines
  1008. def _GetDisabledWarnings(config):
  1009. return [str(i) for i in config.get('msvs_disabled_warnings', [])]
  1010. def _GetModuleDefinition(spec):
  1011. def_file = ''
  1012. if spec['type'] in ['shared_library', 'loadable_module', 'executable']:
  1013. def_files = [s for s in spec.get('sources', []) if s.endswith('.def')]
  1014. if len(def_files) == 1:
  1015. def_file = _FixPath(def_files[0])
  1016. elif def_files:
  1017. raise ValueError(
  1018. 'Multiple module definition files in one target, target %s lists '
  1019. 'multiple .def files: %s' % (
  1020. spec['target_name'], ' '.join(def_files)))
  1021. return def_file
  1022. def _ConvertToolsToExpectedForm(tools):
  1023. """Convert tools to a form expected by Visual Studio.
  1024. Arguments:
  1025. tools: A dictionnary of settings; the tool name is the key.
  1026. Returns:
  1027. A list of Tool objects.
  1028. """
  1029. tool_list = []
  1030. for tool, settings in tools.iteritems():
  1031. # Collapse settings with lists.
  1032. settings_fixed = {}
  1033. for setting, value in settings.iteritems():
  1034. if type(value) == list:
  1035. if ((tool == 'VCLinkerTool' and
  1036. setting == 'AdditionalDependencies') or
  1037. setting == 'AdditionalOptions'):
  1038. settings_fixed[setting] = ' '.join(value)
  1039. else:
  1040. settings_fixed[setting] = ';'.join(value)
  1041. else:
  1042. settings_fixed[setting] = value
  1043. # Add in this tool.
  1044. tool_list.append(MSVSProject.Tool(tool, settings_fixed))
  1045. return tool_list
  1046. def _AddConfigurationToMSVS(p, spec, tools, config, config_type, config_name):
  1047. """Add to the project file the configuration specified by config.
  1048. Arguments:
  1049. p: The target project being generated.
  1050. spec: the target project dict.
  1051. tools: A dictionnary of settings; the tool name is the key.
  1052. config: The dictionnary that defines the special processing to be done
  1053. for this configuration.
  1054. config_type: The configuration type, a number as defined by Microsoft.
  1055. config_name: The name of the configuration.
  1056. """
  1057. attributes = _GetMSVSAttributes(spec, config, config_type)
  1058. # Add in this configuration.
  1059. tool_list = _ConvertToolsToExpectedForm(tools)
  1060. p.AddConfig(_ConfigFullName(config_name, config),
  1061. attrs=attributes, tools=tool_list)
  1062. def _GetMSVSAttributes(spec, config, config_type):
  1063. # Prepare configuration attributes.
  1064. prepared_attrs = {}
  1065. source_attrs = config.get('msvs_configuration_attributes', {})
  1066. for a in source_attrs:
  1067. prepared_attrs[a] = source_attrs[a]
  1068. # Add props files.
  1069. vsprops_dirs = config.get('msvs_props', [])
  1070. vsprops_dirs = _FixPaths(vsprops_dirs)
  1071. if vsprops_dirs:
  1072. prepared_attrs['InheritedPropertySheets'] = ';'.join(vsprops_dirs)
  1073. # Set configuration type.
  1074. prepared_attrs['ConfigurationType'] = config_type
  1075. output_dir = prepared_attrs.get('OutputDirectory',
  1076. '$(SolutionDir)$(ConfigurationName)')
  1077. prepared_attrs['OutputDirectory'] = _FixPath(output_dir) + '\\'
  1078. if 'IntermediateDirectory' not in prepared_attrs:
  1079. intermediate = '$(ConfigurationName)\\obj\\$(ProjectName)'
  1080. prepared_attrs['IntermediateDirectory'] = _FixPath(intermediate) + '\\'
  1081. else:
  1082. intermediate = _FixPath(prepared_attrs['IntermediateDirectory']) + '\\'
  1083. intermediate = MSVSSettings.FixVCMacroSlashes(intermediate)
  1084. prepared_attrs['IntermediateDirectory'] = intermediate
  1085. return prepared_attrs
  1086. def _AddNormalizedSources(sources_set, sources_array):
  1087. sources = [_NormalizedSource(s) for s in sources_array]
  1088. sources_set.update(set(sources))
  1089. def _PrepareListOfSources(spec, generator_flags, gyp_file):
  1090. """Prepare list of sources and excluded sources.
  1091. Besides the sources specified directly in the spec, adds the gyp file so
  1092. that a change to it will cause a re-compile. Also adds appropriate sources
  1093. for actions and copies. Assumes later stage will un-exclude files which
  1094. have custom build steps attached.
  1095. Arguments:
  1096. spec: The target dictionary containing the properties of the target.
  1097. gyp_file: The name of the gyp file.
  1098. Returns:
  1099. A pair of (list of sources, list of excluded sources).
  1100. The sources will be relative to the gyp file.
  1101. """
  1102. sources = set()
  1103. _AddNormalizedSources(sources, spec.get('sources', []))
  1104. excluded_sources = set()
  1105. # Add in the gyp file.
  1106. if not generator_flags.get('standalone'):
  1107. sources.add(gyp_file)
  1108. # Add in 'action' inputs and outputs.
  1109. for a in spec.get('actions', []):
  1110. inputs = a['inputs']
  1111. inputs = [_NormalizedSource(i) for i in inputs]
  1112. # Add all inputs to sources and excluded sources.
  1113. inputs = set(inputs)
  1114. sources.update(inputs)
  1115. excluded_sources.update(inputs)
  1116. if int(a.get('process_outputs_as_sources', False)):
  1117. _AddNormalizedSources(sources, a.get('outputs', []))
  1118. # Add in 'copies' inputs and outputs.
  1119. for cpy in spec.get('copies', []):
  1120. _AddNormalizedSources(sources, cpy.get('files', []))
  1121. return (sources, excluded_sources)
  1122. def _AdjustSourcesAndConvertToFilterHierarchy(
  1123. spec, options, gyp_dir, sources, excluded_sources, list_excluded):
  1124. """Adjusts the list of sources and excluded sources.
  1125. Also converts the sets to lists.
  1126. Arguments:
  1127. spec: The target dictionary containing the properties of the target.
  1128. options: Global generator options.
  1129. gyp_dir: The path to the gyp file being processed.
  1130. sources: A set of sources to be included for this project.
  1131. excluded_sources: A set of sources to be excluded for this project.
  1132. Returns:
  1133. A trio of (list of sources, list of excluded sources,
  1134. path of excluded IDL file)
  1135. """
  1136. # Exclude excluded sources coming into the generator.
  1137. excluded_sources.update(set(spec.get('sources_excluded', [])))
  1138. # Add excluded sources into sources for good measure.
  1139. sources.update(excluded_sources)
  1140. # Convert to proper windows form.
  1141. # NOTE: sources goes from being a set to a list here.
  1142. # NOTE: excluded_sources goes from being a set to a list here.
  1143. sources = _FixPaths(sources)
  1144. # Convert to proper windows form.
  1145. excluded_sources = _FixPaths(excluded_sources)
  1146. excluded_idl = _IdlFilesHandledNonNatively(spec, sources)
  1147. precompiled_related = _GetPrecompileRelatedFiles(spec)
  1148. # Find the excluded ones, minus the precompiled header related ones.
  1149. fully_excluded = [i for i in excluded_sources if i not in precompiled_related]
  1150. # Convert to folders and the right slashes.
  1151. sources = [i.split('\\') for i in sources]
  1152. sources = _ConvertSourcesToFilterHierarchy(sources, excluded=fully_excluded,
  1153. list_excluded=list_excluded)
  1154. return sources, excluded_sources, excluded_idl
  1155. def _IdlFilesHandledNonNatively(spec, sources):
  1156. # If any non-native rules use 'idl' as an extension exclude idl files.
  1157. # Gather a list here to use later.
  1158. using_idl = False
  1159. for rule in spec.get('rules', []):
  1160. if rule['extension'] == 'idl' and int(rule.get('msvs_external_rule', 0)):
  1161. using_idl = True
  1162. break
  1163. if using_idl:
  1164. excluded_idl = [i for i in sources if i.endswith('.idl')]
  1165. else:
  1166. excluded_idl = []
  1167. return excluded_idl
  1168. def _GetPrecompileRelatedFiles(spec):
  1169. # Gather a list of precompiled header related sources.
  1170. precompiled_related = []
  1171. for _, config in spec['configurations'].iteritems():
  1172. for k in precomp_keys:
  1173. f = config.get(k)
  1174. if f:
  1175. precompiled_related.append(_FixPath(f))
  1176. return precompiled_related
  1177. def _ExcludeFilesFromBeingBuilt(p, spec, excluded_sources, excluded_idl,
  1178. list_excluded):
  1179. exclusions = _GetExcludedFilesFromBuild(spec, excluded_sources, excluded_idl)
  1180. for file_name, excluded_configs in exclusions.iteritems():
  1181. if (not list_excluded and
  1182. len(excluded_configs) == len(spec['configurations'])):
  1183. # If we're not listing excluded files, then they won't appear in the
  1184. # project, so don't try to configure them to be excluded.
  1185. pass
  1186. else:
  1187. for config_name, config in excluded_configs:
  1188. p.AddFileConfig(file_name, _ConfigFullName(config_name, config),
  1189. {'ExcludedFromBuild': 'true'})
  1190. def _GetExcludedFilesFromBuild(spec, excluded_sources, excluded_idl):
  1191. exclusions = {}
  1192. # Exclude excluded sources from being built.
  1193. for f in excluded_sources:
  1194. excluded_configs = []
  1195. for config_name, config in spec['configurations'].iteritems():
  1196. precomped = [_FixPath(config.get(i, '')) for i in precomp_keys]
  1197. # Don't do this for ones that are precompiled header related.
  1198. if f not in precomped:
  1199. excluded_configs.append((config_name, config))
  1200. exclusions[f] = excluded_configs
  1201. # If any non-native rules use 'idl' as an extension exclude idl files.
  1202. # Exclude them now.
  1203. for f in excluded_idl:
  1204. excluded_configs = []
  1205. for config_name, config in spec['configurations'].iteritems():
  1206. excluded_configs.append((config_name, config))
  1207. exclusions[f] = excluded_configs
  1208. return exclusions
  1209. def _AddToolFilesToMSVS(p, spec):
  1210. # Add in tool files (rules).
  1211. tool_files = set()
  1212. for _, config in spec['configurations'].iteritems():
  1213. for f in config.get('msvs_tool_files', []):
  1214. tool_files.add(f)
  1215. for f in tool_files:
  1216. p.AddToolFile(f)
  1217. def _HandlePreCompiledHeaders(p, sources, spec):
  1218. # Pre-compiled header source stubs need a different compiler flag
  1219. # (generate precompiled header) and any source file not of the same
  1220. # kind (i.e. C vs. C++) as the precompiled header source stub needs
  1221. # to have use of precompiled headers disabled.
  1222. extensions_excluded_from_precompile = []
  1223. for config_name, config in spec['configurations'].iteritems():
  1224. source = config.get('msvs_precompiled_source')
  1225. if source:
  1226. source = _FixPath(source)
  1227. # UsePrecompiledHeader=1 for if using precompiled headers.
  1228. tool = MSVSProject.Tool('VCCLCompilerTool',
  1229. {'UsePrecompiledHeader': '1'})
  1230. p.AddFileConfig(source, _ConfigFullName(config_name, config),
  1231. {}, tools=[tool])
  1232. basename, extension = os.path.splitext(source)
  1233. if extension == '.c':
  1234. extensions_excluded_from_precompile = ['.cc', '.cpp', '.cxx']
  1235. else:
  1236. extensions_excluded_from_precompile = ['.c']
  1237. def DisableForSourceTree(source_tree):
  1238. for source in source_tree:
  1239. if isinstance(source, MSVSProject.Filter):
  1240. DisableForSourceTree(source.contents)
  1241. else:
  1242. basename, extension = os.path.splitext(source)
  1243. if extension in extensions_excluded_from_precompile:
  1244. for config_name, config in spec['configurations'].iteritems():
  1245. tool = MSVSProject.Tool('VCCLCompilerTool',
  1246. {'UsePrecompiledHeader': '0',
  1247. 'ForcedIncludeFiles': '$(NOINHERIT)'})
  1248. p.AddFileConfig(_FixPath(source),
  1249. _ConfigFullName(config_name, config),
  1250. {}, tools=[tool])
  1251. # Do nothing if there was no precompiled source.
  1252. if extensions_excluded_from_precompile:
  1253. DisableForSourceTree(sources)
  1254. def _AddActions(actions_to_add, spec, relative_path_of_gyp_file):
  1255. # Add actions.
  1256. actions = spec.get('actions', [])
  1257. # Don't setup_env every time. When all the actions are run together in one
  1258. # batch file in VS, the PATH will grow too long.
  1259. # Membership in this set means that the cygwin environment has been set up,
  1260. # and does not need to be set up again.
  1261. have_setup_env = set()
  1262. for a in actions:
  1263. # Attach actions to the gyp file if nothing else is there.
  1264. inputs = a.get('inputs') or [relative_path_of_gyp_file]
  1265. attached_to = inputs[0]
  1266. need_setup_env = attached_to not in have_setup_env
  1267. cmd = _BuildCommandLineForRule(spec, a, has_input_path=False,
  1268. do_setup_env=need_setup_env)
  1269. have_setup_env.add(attached_to)
  1270. # Add the action.
  1271. _AddActionStep(actions_to_add,
  1272. inputs=inputs,
  1273. outputs=a.get('outputs', []),
  1274. description=a.get('message', a['action_name']),
  1275. command=cmd)
  1276. def _WriteMSVSUserFile(project_path, version, spec):
  1277. # Add run_as and test targets.
  1278. if 'run_as' in spec:
  1279. run_as = spec['run_as']
  1280. action = run_as.get('action', [])
  1281. environment = run_as.get('environment', [])
  1282. working_directory = run_as.get('working_directory', '.')
  1283. elif int(spec.get('test', 0)):
  1284. action = ['$(TargetPath)', '--gtest_print_time']
  1285. environment = []
  1286. working_directory = '.'
  1287. else:
  1288. return # Nothing to add
  1289. # Write out the user file.
  1290. user_file = _CreateMSVSUserFile(project_path, version, spec)
  1291. for config_name, c_data in spec['configurations'].iteritems():
  1292. user_file.AddDebugSettings(_ConfigFullName(config_name, c_data),
  1293. action, environment, working_directory)
  1294. user_file.WriteIfChanged()
  1295. def _AddCopies(actions_to_add, spec):
  1296. copies = _GetCopies(spec)
  1297. for inputs, outputs, cmd, description in copies:
  1298. _AddActionStep(actions_to_add, inputs=inputs, outputs=outputs,
  1299. description=description, command=cmd)
  1300. def _GetCopies(spec):
  1301. copies = []
  1302. # Add copies.
  1303. for cpy in spec.get('copies', []):
  1304. for src in cpy.get('files', []):
  1305. dst = os.path.join(cpy['destination'], os.path.basename(src))
  1306. # _AddCustomBuildToolForMSVS() will call _FixPath() on the inputs and
  1307. # outputs, so do the same for our generated command line.
  1308. if src.endswith('/'):
  1309. src_bare = src[:-1]
  1310. base_dir = posixpath.split(src_bare)[0]
  1311. outer_dir = posixpath.split(src_bare)[1]
  1312. cmd = 'cd "%s" && xcopy /e /f /y "%s" "%s\\%s\\"' % (
  1313. _FixPath(base_dir), outer_dir, _FixPath(dst), outer_dir)
  1314. copies.append(([src], ['dummy_copies', dst], cmd,
  1315. 'Copying %s to %s' % (src, dst)))
  1316. else:
  1317. cmd = 'mkdir "%s" 2>nul & set ERRORLEVEL=0 & copy /Y "%s" "%s"' % (
  1318. _FixPath(cpy['destination']), _FixPath(src), _FixPath(dst))
  1319. copies.append(([src], [dst], cmd, 'Copying %s to %s' % (src, dst)))
  1320. return copies
  1321. def _GetPathDict(root, path):
  1322. # |path| will eventually be empty (in the recursive calls) if it was initially
  1323. # relative; otherwise it will eventually end up as '\', 'D:\', etc.
  1324. if not path or path.endswith(os.sep):
  1325. return root
  1326. parent, folder = os.path.split(path)
  1327. parent_dict = _GetPathDict(root, parent)
  1328. if folder not in parent_dict:
  1329. parent_dict[folder] = dict()
  1330. return parent_dict[folder]
  1331. def _DictsToFolders(base_path, bucket, flat):
  1332. # Convert to folders recursively.
  1333. children = []
  1334. for folder, contents in bucket.iteritems():
  1335. if type(contents) == dict:
  1336. folder_children = _DictsToFolders(os.path.join(base_path, folder),
  1337. contents, flat)
  1338. if flat:
  1339. children += folder_children
  1340. else:
  1341. folder_children = MSVSNew.MSVSFolder(os.path.join(base_path, folder),
  1342. name='(' + folder + ')',
  1343. entries=folder_children)
  1344. children.append(folder_children)
  1345. else:
  1346. children.append(contents)
  1347. return children
  1348. def _CollapseSingles(parent, node):
  1349. # Recursively explorer the tree of dicts looking for projects which are
  1350. # the sole item in a folder which has the same name as the project. Bring
  1351. # such projects up one level.
  1352. if (type(node) == dict and
  1353. len(node) == 1 and
  1354. node.keys()[0] == parent + '.vcproj'):
  1355. return node[node.keys()[0]]
  1356. if type(node) != dict:
  1357. return node
  1358. for child in node:
  1359. node[child] = _CollapseSingles(child, node[child])
  1360. return node
  1361. def _GatherSolutionFolders(sln_projects, project_objects, flat):
  1362. root = {}
  1363. # Convert into a tree of dicts on path.
  1364. for p in sln_projects:
  1365. gyp_file, target = gyp.common.ParseQualifiedTarget(p)[0:2]
  1366. gyp_dir = os.path.dirname(gyp_file)
  1367. path_dict = _GetPathDict(root, gyp_dir)
  1368. path_dict[target + '.vcproj'] = project_objects[p]
  1369. # Walk down from the top until we hit a folder that has more than one entry.
  1370. # In practice, this strips the top-level "src/" dir from the hierarchy in
  1371. # the solution.
  1372. while len(root) == 1 and type(root[root.keys()[0]]) == dict:
  1373. root = root[root.keys()[0]]
  1374. # Collapse singles.
  1375. root = _CollapseSingles('', root)
  1376. # Merge buckets until everything is a root entry.
  1377. return _DictsToFolders('', root, flat)
  1378. def _GetPathOfProject(qualified_target, spec, options, msvs_version):
  1379. default_config = _GetDefaultConfiguration(spec)
  1380. proj_filename = default_config.get('msvs_existing_vcproj')
  1381. if not proj_filename:
  1382. proj_filename = (spec['target_name'] + options.suffix +
  1383. msvs_version.ProjectExtension())
  1384. build_file = gyp.common.BuildFile(qualified_target)
  1385. proj_path = os.path.join(os.path.dirname(build_file), proj_filename)
  1386. fix_prefix = None
  1387. if options.generator_output:
  1388. project_dir_path = os.path.dirname(os.path.abspath(proj_path))
  1389. proj_path = os.path.join(options.generator_output, proj_path)
  1390. fix_prefix = gyp.common.RelativePath(project_dir_path,
  1391. os.path.dirname(proj_path))
  1392. return proj_path, fix_prefix
  1393. def _GetPlatformOverridesOfProject(spec):
  1394. # Prepare a dict indicating which project configurations are used for which
  1395. # solution configurations for this target.
  1396. config_platform_overrides = {}
  1397. for config_name, c in spec['configurations'].iteritems():
  1398. config_fullname = _ConfigFullName(config_name, c)
  1399. platform = c.get('msvs_target_platform', _ConfigPlatform(c))
  1400. fixed_config_fullname = '%s|%s' % (
  1401. _ConfigBaseName(config_name, _ConfigPlatform(c)), platform)
  1402. config_platform_overrides[config_fullname] = fixed_config_fullname
  1403. return config_platform_overrides
  1404. def _CreateProjectObjects(target_list, target_dicts, options, msvs_version):
  1405. """Create a MSVSProject object for the targets found in target list.
  1406. Arguments:
  1407. target_list: the list of targets to generate project objects for.
  1408. target_dicts: the dictionary of specifications.
  1409. options: global generator options.
  1410. msvs_version: the MSVSVersion object.
  1411. Returns:
  1412. A set of created projects, keyed by target.
  1413. """
  1414. global fixpath_prefix
  1415. # Generate each project.
  1416. projects = {}
  1417. for qualified_target in target_list:
  1418. spec = target_dicts[qualified_target]
  1419. if spec['toolset'] != 'target':
  1420. raise Exception(
  1421. 'Multiple toolsets not supported in msvs build (target %s)' %
  1422. qualified_target)
  1423. proj_path, fixpath_prefix = _GetPathOfProject(qualified_target, spec,
  1424. options, msvs_version)
  1425. guid = _GetGuidOfProject(proj_path, spec)
  1426. overrides = _GetPlatformOverridesOfProject(spec)
  1427. build_file = gyp.common.BuildFile(qualified_target)
  1428. # Create object for this project.
  1429. obj = MSVSNew.MSVSProject(
  1430. _FixPath(proj_path),
  1431. name=spec['target_name'],
  1432. guid=guid,
  1433. spec=spec,
  1434. build_file=build_file,
  1435. config_platform_overrides=overrides,
  1436. fixpath_prefix=fixpath_prefix)
  1437. # Set project toolset if any (MS build only)
  1438. if msvs_version.UsesVcxproj():
  1439. obj.set_msbuild_toolset(
  1440. _GetMsbuildToolsetOfProject(proj_path, spec, msvs_version))
  1441. projects[qualified_target] = obj
  1442. # Set all the dependencies
  1443. for project in projects.values():
  1444. deps = project.spec.get('dependencies', [])
  1445. deps = [projects[d] for d in deps]
  1446. project.set_dependencies(deps)
  1447. return projects
  1448. def CalculateVariables(default_variables, params):
  1449. """Generated variables that require params to be known."""
  1450. generator_flags = params.get('generator_flags', {})
  1451. # Select project file format version (if unset, default to auto detecting).
  1452. msvs_version = MSVSVersion.SelectVisualStudioVersion(
  1453. generator_flags.get('msvs_version', 'auto'))
  1454. # Stash msvs_version for later (so we don't have to probe the system twice).
  1455. params['msvs_version'] = msvs_version
  1456. # Set a variable so conditions can be based on msvs_version.
  1457. default_variables['MSVS_VERSION'] = msvs_version.ShortName()
  1458. # To determine processor word size on Windows, in addition to checking
  1459. # PROCESSOR_ARCHITECTURE (which reflects the word size of the current
  1460. # process), it is also necessary to check PROCESSOR_ARCITEW6432 (which
  1461. # contains the actual word size of the system when running thru WOW64).
  1462. if (os.environ.get('PROCESSOR_ARCHITECTURE', '').find('64') >= 0 or
  1463. os.environ.get('PROCESSOR_ARCHITEW6432', '').find('64') >= 0):
  1464. default_variables['MSVS_OS_BITS'] = 64
  1465. else:
  1466. default_variables['MSVS_OS_BITS'] = 32
  1467. def _ShardName(name, number):
  1468. """Add a shard number to the end of a target.
  1469. Arguments:
  1470. name: name of the target (foo#target)
  1471. number: shard number
  1472. Returns:
  1473. Target name with shard added (foo_1#target)
  1474. """
  1475. parts = name.rsplit('#', 1)
  1476. parts[0] = '%s_%d' % (parts[0], number)
  1477. return '#'.join(parts)
  1478. def _ShardTargets(target_list, target_dicts):
  1479. """Shard some targets apart to work around the linkers limits.
  1480. Arguments:
  1481. target_list: List of target pairs: 'base/base.gyp:base'.
  1482. target_dicts: Dict of target properties keyed on target pair.
  1483. Returns:
  1484. Tuple of the new sharded versions of the inputs.
  1485. """
  1486. # Gather the targets to shard, and how many pieces.
  1487. targets_to_shard = {}
  1488. for t in target_dicts:
  1489. shards = int(target_dicts[t].get('msvs_shard', 0))
  1490. if shards:
  1491. targets_to_shard[t] = shards
  1492. # Shard target_list.
  1493. new_target_list = []
  1494. for t in target_list:
  1495. if t in targets_to_shard:
  1496. for i in range(targets_to_shard[t]):
  1497. new_target_list.append(_ShardName(t, i))
  1498. else:
  1499. new_target_list.append(t)
  1500. # Shard target_dict.
  1501. new_target_dicts = {}
  1502. for t in target_dicts:
  1503. if t in targets_to_shard:
  1504. for i in range(targets_to_shard[t]):
  1505. name = _ShardName(t, i)
  1506. new_target_dicts[name] = copy.copy(target_dicts[t])
  1507. new_target_dicts[name]['target_name'] = _ShardName(
  1508. new_target_dicts[name]['target_name'], i)
  1509. sources = new_target_dicts[name].get('sources', [])
  1510. new_sources = []
  1511. for pos in range(i, len(sources), targets_to_shard[t]):
  1512. new_sources.append(sources[pos])
  1513. new_target_dicts[name]['sources'] = new_sources
  1514. else:
  1515. new_target_dicts[t] = target_dicts[t]
  1516. # Shard dependencies.
  1517. for t in new_target_dicts:
  1518. dependencies = copy.copy(new_target_dicts[t].get('dependencies', []))
  1519. new_dependencies = []
  1520. for d in dependencies:
  1521. if d in targets_to_shard:
  1522. for i in range(targets_to_shard[d]):
  1523. new_dependencies.append(_ShardName(d, i))
  1524. else:
  1525. new_dependencies.append(d)
  1526. new_target_dicts[t]['dependencies'] = new_dependencies
  1527. return (new_target_list, new_target_dicts)
  1528. def GenerateOutput(target_list, target_dicts, data, params):
  1529. """Generate .sln and .vcproj files.
  1530. This is the entry point for this generator.
  1531. Arguments:
  1532. target_list: List of target pairs: 'base/base.gyp:base'.
  1533. target_dicts: Dict of target properties keyed on target pair.
  1534. data: Dictionary containing per .gyp data.
  1535. """
  1536. global fixpath_prefix
  1537. options = params['options']
  1538. # Get the project file format version back out of where we stashed it in
  1539. # GeneratorCalculatedVariables.
  1540. msvs_version = params['msvs_version']
  1541. generator_flags = params.get('generator_flags', {})
  1542. # Optionally shard targets marked with 'msvs_shard': SHARD_COUNT.
  1543. (target_list, target_dicts) = _ShardTargets(target_list, target_dicts)
  1544. # Prepare the set of configurations.
  1545. configs = set()
  1546. for qualified_target in target_list:
  1547. spec = target_dicts[qualified_target]
  1548. for config_name, config in spec['configurations'].iteritems():
  1549. configs.add(_ConfigFullName(config_name, config))
  1550. configs = list(configs)
  1551. # Figure out all the projects that will be generated and their guids
  1552. project_objects = _CreateProjectObjects(target_list, target_dicts, options,
  1553. msvs_version)
  1554. # Generate each project.
  1555. missing_sources = []
  1556. for project in project_objects.values():
  1557. fixpath_prefix = project.fixpath_prefix
  1558. missing_sources.extend(_GenerateProject(project, options, msvs_version,
  1559. generator_flags))
  1560. fixpath_prefix = None
  1561. for build_file in data:
  1562. # Validate build_file extension
  1563. if not build_file.endswith('.gyp'):
  1564. continue
  1565. sln_path = os.path.splitext(build_file)[0] + options.suffix + '.sln'
  1566. if options.generator_output:
  1567. sln_path = os.path.join(options.generator_output, sln_path)
  1568. # Get projects in the solution, and their dependents.
  1569. sln_projects = gyp.common.BuildFileTargets(target_list, build_file)
  1570. sln_projects += gyp.common.DeepDependencyTargets(target_dicts, sln_projects)
  1571. # Create folder hierarchy.
  1572. root_entries = _GatherSolutionFolders(
  1573. sln_projects, project_objects, flat=msvs_version.FlatSolution())
  1574. # Create solution.
  1575. sln = MSVSNew.MSVSSolution(sln_path,
  1576. entries=root_entries,
  1577. variants=configs,
  1578. websiteProperties=False,
  1579. version=msvs_version)
  1580. sln.Write()
  1581. if missing_sources:
  1582. error_message = "Missing input files:\n" + \
  1583. '\n'.join(set(missing_sources))
  1584. if generator_flags.get('msvs_error_on_missing_sources', False):
  1585. raise Exception(error_message)
  1586. else:
  1587. print >>sys.stdout, "Warning: " + error_message
  1588. def _GenerateMSBuildFiltersFile(filters_path, source_files,
  1589. extension_to_rule_name):
  1590. """Generate the filters file.
  1591. This file is used by Visual Studio to organize the presentation of source
  1592. files into folders.
  1593. Arguments:
  1594. filters_path: The path of the file to be created.
  1595. source_files: The hierarchical structure of all the sources.
  1596. extension_to_rule_name: A dictionary mapping file extensions to rules.
  1597. """
  1598. filter_group = []
  1599. source_group = []
  1600. _AppendFiltersForMSBuild('', source_files, extension_to_rule_name,
  1601. filter_group, source_group)
  1602. if filter_group:
  1603. content = ['Project',
  1604. {'ToolsVersion': '4.0',
  1605. 'xmlns': 'http://schemas.microsoft.com/developer/msbuild/2003'
  1606. },
  1607. ['ItemGroup'] + filter_group,
  1608. ['ItemGroup'] + source_group
  1609. ]
  1610. easy_xml.WriteXmlIfChanged(content, filters_path, pretty=True, win32=True)
  1611. elif os.path.exists(filters_path):
  1612. # We don't need this filter anymore. Delete the old filter file.
  1613. os.unlink(filters_path)
  1614. def _AppendFiltersForMSBuild(parent_filter_name, sources,
  1615. extension_to_rule_name,
  1616. filter_group, source_group):
  1617. """Creates the list of filters and sources to be added in the filter file.
  1618. Args:
  1619. parent_filter_name: The name of the filter under which the sources are
  1620. found.
  1621. sources: The hierarchy of filters and sources to process.
  1622. extension_to_rule_name: A dictionary mapping file extensions to rules.
  1623. filter_group: The list to which filter entries will be appended.
  1624. source_group: The list to which source entries will be appeneded.
  1625. """
  1626. for source in sources:
  1627. if isinstance(source, MSVSProject.Filter):
  1628. # We have a sub-filter. Create the name of that sub-filter.
  1629. if not parent_filter_name:
  1630. filter_name = source.name
  1631. else:
  1632. filter_name = '%s\\%s' % (parent_filter_name, source.name)
  1633. # Add the filter to the group.
  1634. filter_group.append(
  1635. ['Filter', {'Include': filter_name},
  1636. ['UniqueIdentifier', MSVSNew.MakeGuid(source.name)]])
  1637. # Recurse and add its dependents.
  1638. _AppendFiltersForMSBuild(filter_name, source.contents,
  1639. extension_to_rule_name,
  1640. filter_group, source_group)
  1641. else:
  1642. # It's a source. Create a source entry.
  1643. _, element = _MapFileToMsBuildSourceType(source, extension_to_rule_name)
  1644. source_entry = [element, {'Include': source}]
  1645. # Specify the filter it is part of, if any.
  1646. if parent_filter_name:
  1647. source_entry.append(['Filter', parent_filter_name])
  1648. source_group.append(source_entry)
  1649. def _MapFileToMsBuildSourceType(source, extension_to_rule_name):
  1650. """Returns the group and element type of the source file.
  1651. Arguments:
  1652. source: The source file name.
  1653. extension_to_rule_name: A dictionary mapping file extensions to rules.
  1654. Returns:
  1655. A pair of (group this file should be part of, the label of element)
  1656. """
  1657. _, ext = os.path.splitext(source)
  1658. if ext in extension_to_rule_name:
  1659. group = 'rule'
  1660. element = extension_to_rule_name[ext]
  1661. elif ext in ['.cc', '.cpp', '.c', '.cxx']:
  1662. group = 'compile'
  1663. element = 'ClCompile'
  1664. elif ext in ['.h', '.hxx']:
  1665. group = 'include'
  1666. element = 'ClInclude'
  1667. elif ext == '.rc':
  1668. group = 'resource'
  1669. element = 'ResourceCompile'
  1670. elif ext == '.idl':
  1671. group = 'midl'
  1672. element = 'Midl'
  1673. else:
  1674. group = 'none'
  1675. element = 'None'
  1676. return (group, element)
  1677. def _GenerateRulesForMSBuild(output_dir, options, spec,
  1678. sources, excluded_sources,
  1679. props_files_of_rules, targets_files_of_rules,
  1680. actions_to_add, extension_to_rule_name):
  1681. # MSBuild rules are implemented using three files: an XML file, a .targets
  1682. # file and a .props file.
  1683. # See http://blogs.msdn.com/b/vcblog/archive/2010/04/21/quick-help-on-vs2010-custom-build-rule.aspx
  1684. # for more details.
  1685. rules = spec.get('rules', [])
  1686. rules_native = [r for r in rules if not int(r.get('msvs_external_rule', 0))]
  1687. rules_external = [r for r in rules if int(r.get('msvs_external_rule', 0))]
  1688. msbuild_rules = []
  1689. for rule in rules_native:
  1690. # Skip a rule with no action and no inputs.
  1691. if 'action' not in rule and not rule.get('rule_sources', []):
  1692. continue
  1693. msbuild_rule = MSBuildRule(rule, spec)
  1694. msbuild_rules.append(msbuild_rule)
  1695. extension_to_rule_name[msbuild_rule.extension] = msbuild_rule.rule_name
  1696. if msbuild_rules:
  1697. base = spec['target_name'] + options.suffix
  1698. props_name = base + '.props'
  1699. targets_name = base + '.targets'
  1700. xml_name = base + '.xml'
  1701. props_files_of_rules.add(props_name)
  1702. targets_files_of_rules.add(targets_name)
  1703. props_path = os.path.join(output_dir, props_name)
  1704. targets_path = os.path.join(output_dir, targets_name)
  1705. xml_path = os.path.join(output_dir, xml_name)
  1706. _GenerateMSBuildRulePropsFile(props_path, msbuild_rules)
  1707. _GenerateMSBuildRuleTargetsFile(targets_path, msbuild_rules)
  1708. _GenerateMSBuildRuleXmlFile(xml_path, msbuild_rules)
  1709. if rules_external:
  1710. _GenerateExternalRules(rules_external, output_dir, spec,
  1711. sources, options, actions_to_add)
  1712. _AdjustSourcesForRules(rules, sources, excluded_sources)
  1713. class MSBuildRule(object):
  1714. """Used to store information used to generate an MSBuild rule.
  1715. Attributes:
  1716. rule_name: The rule name, sanitized to use in XML.
  1717. target_name: The name of the target.
  1718. after_targets: The name of the AfterTargets element.
  1719. before_targets: The name of the BeforeTargets element.
  1720. depends_on: The name of the DependsOn element.
  1721. compute_output: The name of the ComputeOutput element.
  1722. dirs_to_make: The name of the DirsToMake element.
  1723. inputs: The name of the _inputs element.
  1724. tlog: The name of the _tlog element.
  1725. extension: The extension this rule applies to.
  1726. description: The message displayed when this rule is invoked.
  1727. additional_dependencies: A string listing additional dependencies.
  1728. outputs: The outputs of this rule.
  1729. command: The command used to run the rule.
  1730. """
  1731. def __init__(self, rule, spec):
  1732. self.display_name = rule['rule_name']
  1733. # Assure that the rule name is only characters and numbers
  1734. self.rule_name = re.sub(r'\W', '_', self.display_name)
  1735. # Create the various element names, following the example set by the
  1736. # Visual Studio 2008 to 2010 conversion. I don't know if VS2010
  1737. # is sensitive to the exact names.
  1738. self.target_name = '_' + self.rule_name
  1739. self.after_targets = self.rule_name + 'AfterTargets'
  1740. self.before_targets = self.rule_name + 'BeforeTargets'
  1741. self.depends_on = self.rule_name + 'DependsOn'
  1742. self.compute_output = 'Compute%sOutput' % self.rule_name
  1743. self.dirs_to_make = self.rule_name + 'DirsToMake'
  1744. self.inputs = self.rule_name + '_inputs'
  1745. self.tlog = self.rule_name + '_tlog'
  1746. self.extension = rule['extension']
  1747. if not self.extension.startswith('.'):
  1748. self.extension = '.' + self.extension
  1749. self.description = MSVSSettings.ConvertVCMacrosToMSBuild(
  1750. rule.get('message', self.rule_name))
  1751. old_additional_dependencies = _FixPaths(rule.get('inputs', []))
  1752. self.additional_dependencies = (
  1753. ';'.join([MSVSSettings.ConvertVCMacrosToMSBuild(i)
  1754. for i in old_additional_dependencies]))
  1755. old_outputs = _FixPaths(rule.get('outputs', []))
  1756. self.outputs = ';'.join([MSVSSettings.ConvertVCMacrosToMSBuild(i)
  1757. for i in old_outputs])
  1758. old_command = _BuildCommandLineForRule(spec, rule, has_input_path=True,
  1759. do_setup_env=True)
  1760. self.command = MSVSSettings.ConvertVCMacrosToMSBuild(old_command)
  1761. def _GenerateMSBuildRulePropsFile(props_path, msbuild_rules):
  1762. """Generate the .props file."""
  1763. content = ['Project',
  1764. {'xmlns': 'http://schemas.microsoft.com/developer/msbuild/2003'}]
  1765. for rule in msbuild_rules:
  1766. content.extend([
  1767. ['PropertyGroup',
  1768. {'Condition': "'$(%s)' == '' and '$(%s)' == '' and "
  1769. "'$(ConfigurationType)' != 'Makefile'" % (rule.before_targets,
  1770. rule.after_targets)
  1771. },
  1772. [rule.before_targets, 'Midl'],
  1773. [rule.after_targets, 'CustomBuild'],
  1774. ],
  1775. ['PropertyGroup',
  1776. [rule.depends_on,
  1777. {'Condition': "'$(ConfigurationType)' != 'Makefile'"},
  1778. '_SelectedFiles;$(%s)' % rule.depends_on
  1779. ],
  1780. ],
  1781. ['ItemDefinitionGroup',
  1782. [rule.rule_name,
  1783. ['CommandLineTemplate', rule.command],
  1784. ['Outputs', rule.outputs],
  1785. ['ExecutionDescription', rule.description],
  1786. ['AdditionalDependencies', rule.additional_dependencies],
  1787. ],
  1788. ]
  1789. ])
  1790. easy_xml.WriteXmlIfChanged(content, props_path, pretty=True, win32=True)
  1791. def _GenerateMSBuildRuleTargetsFile(targets_path, msbuild_rules):
  1792. """Generate the .targets file."""
  1793. content = ['Project',
  1794. {'xmlns': 'http://schemas.microsoft.com/developer/msbuild/2003'
  1795. }
  1796. ]
  1797. item_group = [
  1798. 'ItemGroup',
  1799. ['PropertyPageSchema',
  1800. {'Include': '$(MSBuildThisFileDirectory)$(MSBuildThisFileName).xml'}
  1801. ]
  1802. ]
  1803. for rule in msbuild_rules:
  1804. item_group.append(
  1805. ['AvailableItemName',
  1806. {'Include': rule.rule_name},
  1807. ['Targets', rule.target_name],
  1808. ])
  1809. content.append(item_group)
  1810. for rule in msbuild_rules:
  1811. content.append(
  1812. ['UsingTask',
  1813. {'TaskName': rule.rule_name,
  1814. 'TaskFactory': 'XamlTaskFactory',
  1815. 'AssemblyName': 'Microsoft.Build.Tasks.v4.0'
  1816. },
  1817. ['Task', '$(MSBuildThisFileDirectory)$(MSBuildThisFileName).xml'],
  1818. ])
  1819. for rule in msbuild_rules:
  1820. rule_name = rule.rule_name
  1821. target_outputs = '%%(%s.Outputs)' % rule_name
  1822. target_inputs = ('%%(%s.Identity);%%(%s.AdditionalDependencies);'
  1823. '$(MSBuildProjectFile)') % (rule_name, rule_name)
  1824. rule_inputs = '%%(%s.Identity)' % rule_name
  1825. extension_condition = ("'%(Extension)'=='.obj' or "
  1826. "'%(Extension)'=='.res' or "
  1827. "'%(Extension)'=='.rsc' or "
  1828. "'%(Extension)'=='.lib'")
  1829. remove_section = [
  1830. 'ItemGroup',
  1831. {'Condition': "'@(SelectedFiles)' != ''"},
  1832. [rule_name,
  1833. {'Remove': '@(%s)' % rule_name,
  1834. 'Condition': "'%(Identity)' != '@(SelectedFiles)'"
  1835. }
  1836. ]
  1837. ]
  1838. inputs_section = [
  1839. 'ItemGroup',
  1840. [rule.inputs, {'Include': '%%(%s.AdditionalDependencies)' % rule_name}]
  1841. ]
  1842. logging_section = [
  1843. 'ItemGroup',
  1844. [rule.tlog,
  1845. {'Include': '%%(%s.Outputs)' % rule_name,
  1846. 'Condition': ("'%%(%s.Outputs)' != '' and "
  1847. "'%%(%s.ExcludedFromBuild)' != 'true'" %
  1848. (rule_name, rule_name))
  1849. },
  1850. ['Source', "@(%s, '|')" % rule_name],
  1851. ['Inputs', "@(%s -> '%%(Fullpath)', ';')" % rule.inputs],
  1852. ],
  1853. ]
  1854. message_section = [
  1855. 'Message',
  1856. {'Importance': 'High',
  1857. 'Text': '%%(%s.ExecutionDescription)' % rule_name
  1858. }
  1859. ]
  1860. write_tlog_section = [
  1861. 'WriteLinesToFile',
  1862. {'Condition': "'@(%s)' != '' and '%%(%s.ExcludedFromBuild)' != "
  1863. "'true'" % (rule.tlog, rule.tlog),
  1864. 'File': '$(IntDir)$(ProjectName).write.1.tlog',
  1865. 'Lines': "^%%(%s.Source);@(%s->'%%(Fullpath)')" % (rule.tlog,
  1866. rule.tlog)
  1867. }
  1868. ]
  1869. read_tlog_section = [
  1870. 'WriteLinesToFile',
  1871. {'Condition': "'@(%s)' != '' and '%%(%s.ExcludedFromBuild)' != "
  1872. "'true'" % (rule.tlog, rule.tlog),
  1873. 'File': '$(IntDir)$(ProjectName).read.1.tlog',
  1874. 'Lines': "^%%(%s.Source);%%(%s.Inputs)" % (rule.tlog, rule.tlog)
  1875. }
  1876. ]
  1877. command_and_input_section = [
  1878. rule_name,
  1879. {'Condition': "'@(%s)' != '' and '%%(%s.ExcludedFromBuild)' != "
  1880. "'true'" % (rule_name, rule_name),
  1881. 'CommandLineTemplate': '%%(%s.CommandLineTemplate)' % rule_name,
  1882. 'AdditionalOptions': '%%(%s.AdditionalOptions)' % rule_name,
  1883. 'Inputs': rule_inputs
  1884. }
  1885. ]
  1886. content.extend([
  1887. ['Target',
  1888. {'Name': rule.target_name,
  1889. 'BeforeTargets': '$(%s)' % rule.before_targets,
  1890. 'AfterTargets': '$(%s)' % rule.after_targets,
  1891. 'Condition': "'@(%s)' != ''" % rule_name,
  1892. 'DependsOnTargets': '$(%s);%s' % (rule.depends_on,
  1893. rule.compute_output),
  1894. 'Outputs': target_outputs,
  1895. 'Inputs': target_inputs
  1896. },
  1897. remove_section,
  1898. inputs_section,
  1899. logging_section,
  1900. message_section,
  1901. write_tlog_section,
  1902. read_tlog_section,
  1903. command_and_input_section,
  1904. ],
  1905. ['PropertyGroup',
  1906. ['ComputeLinkInputsTargets',
  1907. '$(ComputeLinkInputsTargets);',
  1908. '%s;' % rule.compute_output
  1909. ],
  1910. ['ComputeLibInputsTargets',
  1911. '$(ComputeLibInputsTargets);',
  1912. '%s;' % rule.compute_output
  1913. ],
  1914. ],
  1915. ['Target',
  1916. {'Name': rule.compute_output,
  1917. 'Condition': "'@(%s)' != ''" % rule_name
  1918. },
  1919. ['ItemGroup',
  1920. [rule.dirs_to_make,
  1921. {'Condition': "'@(%s)' != '' and "
  1922. "'%%(%s.ExcludedFromBuild)' != 'true'" % (rule_name, rule_name),
  1923. 'Include': '%%(%s.Outputs)' % rule_name
  1924. }
  1925. ],
  1926. ['Link',
  1927. {'Include': '%%(%s.Identity)' % rule.dirs_to_make,
  1928. 'Condition': extension_condition
  1929. }
  1930. ],
  1931. ['Lib',
  1932. {'Include': '%%(%s.Identity)' % rule.dirs_to_make,
  1933. 'Condition': extension_condition
  1934. }
  1935. ],
  1936. ['ImpLib',
  1937. {'Include': '%%(%s.Identity)' % rule.dirs_to_make,
  1938. 'Condition': extension_condition
  1939. }
  1940. ],
  1941. ],
  1942. ['MakeDir',
  1943. {'Directories': ("@(%s->'%%(RootDir)%%(Directory)')" %
  1944. rule.dirs_to_make)
  1945. }
  1946. ]
  1947. ],
  1948. ])
  1949. easy_xml.WriteXmlIfChanged(content, targets_path, pretty=True, win32=True)
  1950. def _GenerateMSBuildRuleXmlFile(xml_path, msbuild_rules):
  1951. # Generate the .xml file
  1952. content = [
  1953. 'ProjectSchemaDefinitions',
  1954. {'xmlns': ('clr-namespace:Microsoft.Build.Framework.XamlTypes;'
  1955. 'assembly=Microsoft.Build.Framework'),
  1956. 'xmlns:x': 'http://schemas.microsoft.com/winfx/2006/xaml',
  1957. 'xmlns:sys': 'clr-namespace:System;assembly=mscorlib',
  1958. 'xmlns:transformCallback':
  1959. 'Microsoft.Cpp.Dev10.ConvertPropertyCallback'
  1960. }
  1961. ]
  1962. for rule in msbuild_rules:
  1963. content.extend([
  1964. ['Rule',
  1965. {'Name': rule.rule_name,
  1966. 'PageTemplate': 'tool',
  1967. 'DisplayName': rule.display_name,
  1968. 'Order': '200'
  1969. },
  1970. ['Rule.DataSource',
  1971. ['DataSource',
  1972. {'Persistence': 'ProjectFile',
  1973. 'ItemType': rule.rule_name
  1974. }
  1975. ]
  1976. ],
  1977. ['Rule.Categories',
  1978. ['Category',
  1979. {'Name': 'General'},
  1980. ['Category.DisplayName',
  1981. ['sys:String', 'General'],
  1982. ],
  1983. ],
  1984. ['Category',
  1985. {'Name': 'Command Line',
  1986. 'Subtype': 'CommandLine'
  1987. },
  1988. ['Category.DisplayName',
  1989. ['sys:String', 'Command Line'],
  1990. ],
  1991. ],
  1992. ],
  1993. ['StringListProperty',
  1994. {'Name': 'Inputs',
  1995. 'Category': 'Command Line',
  1996. 'IsRequired': 'true',
  1997. 'Switch': ' '
  1998. },
  1999. ['StringListProperty.DataSource',
  2000. ['DataSource',
  2001. {'Persistence': 'ProjectFile',
  2002. 'ItemType': rule.rule_name,
  2003. 'SourceType': 'Item'
  2004. }
  2005. ]
  2006. ],
  2007. ],
  2008. ['StringProperty',
  2009. {'Name': 'CommandLineTemplate',
  2010. 'DisplayName': 'Command Line',
  2011. 'Visible': 'False',
  2012. 'IncludeInCommandLine': 'False'
  2013. }
  2014. ],
  2015. ['DynamicEnumProperty',
  2016. {'Name': rule.before_targets,
  2017. 'Category': 'General',
  2018. 'EnumProvider': 'Targets',
  2019. 'IncludeInCommandLine': 'False'
  2020. },
  2021. ['DynamicEnumProperty.DisplayName',
  2022. ['sys:String', 'Execute Before'],
  2023. ],
  2024. ['DynamicEnumProperty.Description',
  2025. ['sys:String', 'Specifies the targets for the build customization'
  2026. ' to run before.'
  2027. ],
  2028. ],
  2029. ['DynamicEnumProperty.ProviderSettings',
  2030. ['NameValuePair',
  2031. {'Name': 'Exclude',
  2032. 'Value': '^%s|^Compute' % rule.before_targets
  2033. }
  2034. ]
  2035. ],
  2036. ['DynamicEnumProperty.DataSource',
  2037. ['DataSource',
  2038. {'Persistence': 'ProjectFile',
  2039. 'HasConfigurationCondition': 'true'
  2040. }
  2041. ]
  2042. ],
  2043. ],
  2044. ['DynamicEnumProperty',
  2045. {'Name': rule.after_targets,
  2046. 'Category': 'General',
  2047. 'EnumProvider': 'Targets',
  2048. 'IncludeInCommandLine': 'False'
  2049. },
  2050. ['DynamicEnumProperty.DisplayName',
  2051. ['sys:String', 'Execute After'],
  2052. ],
  2053. ['DynamicEnumProperty.Description',
  2054. ['sys:String', ('Specifies the targets for the build customization'
  2055. ' to run after.')
  2056. ],
  2057. ],
  2058. ['DynamicEnumProperty.ProviderSettings',
  2059. ['NameValuePair',
  2060. {'Name': 'Exclude',
  2061. 'Value': '^%s|^Compute' % rule.after_targets
  2062. }
  2063. ]
  2064. ],
  2065. ['DynamicEnumProperty.DataSource',
  2066. ['DataSource',
  2067. {'Persistence': 'ProjectFile',
  2068. 'ItemType': '',
  2069. 'HasConfigurationCondition': 'true'
  2070. }
  2071. ]
  2072. ],
  2073. ],
  2074. ['StringListProperty',
  2075. {'Name': 'Outputs',
  2076. 'DisplayName': 'Outputs',
  2077. 'Visible': 'False',
  2078. 'IncludeInCommandLine': 'False'
  2079. }
  2080. ],
  2081. ['StringProperty',
  2082. {'Name': 'ExecutionDescription',
  2083. 'DisplayName': 'Execution Description',
  2084. 'Visible': 'False',
  2085. 'IncludeInCommandLine': 'False'
  2086. }
  2087. ],
  2088. ['StringListProperty',
  2089. {'Name': 'AdditionalDependencies',
  2090. 'DisplayName': 'Additional Dependencies',
  2091. 'IncludeInCommandLine': 'False',
  2092. 'Visible': 'false'
  2093. }
  2094. ],
  2095. ['StringProperty',
  2096. {'Subtype': 'AdditionalOptions',
  2097. 'Name': 'AdditionalOptions',
  2098. 'Category': 'Command Line'
  2099. },
  2100. ['StringProperty.DisplayName',
  2101. ['sys:String', 'Additional Options'],
  2102. ],
  2103. ['StringProperty.Description',
  2104. ['sys:String', 'Additional Options'],
  2105. ],
  2106. ],
  2107. ],
  2108. ['ItemType',
  2109. {'Name': rule.rule_name,
  2110. 'DisplayName': rule.display_name
  2111. }
  2112. ],
  2113. ['FileExtension',
  2114. {'Name': '*' + rule.extension,
  2115. 'ContentType': rule.rule_name
  2116. }
  2117. ],
  2118. ['ContentType',
  2119. {'Name': rule.rule_name,
  2120. 'DisplayName': '',
  2121. 'ItemType': rule.rule_name
  2122. }
  2123. ]
  2124. ])
  2125. easy_xml.WriteXmlIfChanged(content, xml_path, pretty=True, win32=True)
  2126. def _GetConfigurationAndPlatform(name, settings):
  2127. configuration = name.rsplit('_', 1)[0]
  2128. platform = settings.get('msvs_configuration_platform', 'Win32')
  2129. return (configuration, platform)
  2130. def _GetConfigurationCondition(name, settings):
  2131. return (r"'$(Configuration)|$(Platform)'=='%s|%s'" %
  2132. _GetConfigurationAndPlatform(name, settings))
  2133. def _GetMSBuildProjectConfigurations(configurations):
  2134. group = ['ItemGroup', {'Label': 'ProjectConfigurations'}]
  2135. for (name, settings) in sorted(configurations.iteritems()):
  2136. configuration, platform = _GetConfigurationAndPlatform(name, settings)
  2137. designation = '%s|%s' % (configuration, platform)
  2138. group.append(
  2139. ['ProjectConfiguration', {'Include': designation},
  2140. ['Configuration', configuration],
  2141. ['Platform', platform]])
  2142. return [group]
  2143. def _GetMSBuildGlobalProperties(spec, guid, gyp_file_name):
  2144. namespace = os.path.splitext(gyp_file_name)[0]
  2145. return [
  2146. ['PropertyGroup', {'Label': 'Globals'},
  2147. ['ProjectGuid', guid],
  2148. ['Keyword', 'Win32Proj'],
  2149. ['RootNamespace', namespace],
  2150. ]
  2151. ]
  2152. def _GetMSBuildConfigurationDetails(spec, build_file):
  2153. properties = {}
  2154. for name, settings in spec['configurations'].iteritems():
  2155. msbuild_attributes = _GetMSBuildAttributes(spec, settings, build_file)
  2156. condition = _GetConfigurationCondition(name, settings)
  2157. character_set = msbuild_attributes.get('CharacterSet')
  2158. _AddConditionalProperty(properties, condition, 'ConfigurationType',
  2159. msbuild_attributes['ConfigurationType'])
  2160. if character_set:
  2161. _AddConditionalProperty(properties, condition, 'CharacterSet',
  2162. character_set)
  2163. return _GetMSBuildPropertyGroup(spec, 'Configuration', properties)
  2164. def _GetMSBuildLocalProperties(msbuild_toolset):
  2165. # Currently the only local property we support is PlatformToolset
  2166. properties = {}
  2167. if msbuild_toolset:
  2168. properties = [
  2169. ['PropertyGroup', {'Label': 'Locals'},
  2170. ['PlatformToolset', msbuild_toolset],
  2171. ]
  2172. ]
  2173. return properties
  2174. def _GetMSBuildPropertySheets(configurations):
  2175. user_props = r'$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props'
  2176. additional_props = {}
  2177. props_specified = False
  2178. for name, settings in sorted(configurations.iteritems()):
  2179. configuration = _GetConfigurationCondition(name, settings)
  2180. if settings.has_key('msbuild_props'):
  2181. additional_props[configuration] = _FixPaths(settings['msbuild_props'])
  2182. props_specified = True
  2183. else:
  2184. additional_props[configuration] = ''
  2185. if not props_specified:
  2186. return [
  2187. ['ImportGroup',
  2188. {'Label': 'PropertySheets'},
  2189. ['Import',
  2190. {'Project': user_props,
  2191. 'Condition': "exists('%s')" % user_props,
  2192. 'Label': 'LocalAppDataPlatform'
  2193. }
  2194. ]
  2195. ]
  2196. ]
  2197. else:
  2198. sheets = []
  2199. for condition, props in additional_props.iteritems():
  2200. import_group = [
  2201. 'ImportGroup',
  2202. {'Label': 'PropertySheets',
  2203. 'Condition': condition
  2204. },
  2205. ['Import',
  2206. {'Project': user_props,
  2207. 'Condition': "exists('%s')" % user_props,
  2208. 'Label': 'LocalAppDataPlatform'
  2209. }
  2210. ]
  2211. ]
  2212. for props_file in props:
  2213. import_group.append(['Import', {'Project':props_file}])
  2214. sheets.append(import_group)
  2215. return sheets
  2216. def _ConvertMSVSBuildAttributes(spec, config, build_file):
  2217. config_type = _GetMSVSConfigurationType(spec, build_file)
  2218. msvs_attributes = _GetMSVSAttributes(spec, config, config_type)
  2219. msbuild_attributes = {}
  2220. for a in msvs_attributes:
  2221. if a in ['IntermediateDirectory', 'OutputDirectory']:
  2222. directory = MSVSSettings.ConvertVCMacrosToMSBuild(msvs_attributes[a])
  2223. if not directory.endswith('\\'):
  2224. directory += '\\'
  2225. msbuild_attributes[a] = directory
  2226. elif a == 'CharacterSet':
  2227. msbuild_attributes[a] = _ConvertMSVSCharacterSet(msvs_attributes[a])
  2228. elif a == 'ConfigurationType':
  2229. msbuild_attributes[a] = _ConvertMSVSConfigurationType(msvs_attributes[a])
  2230. else:
  2231. print 'Warning: Do not know how to convert MSVS attribute ' + a
  2232. return msbuild_attributes
  2233. def _ConvertMSVSCharacterSet(char_set):
  2234. if char_set.isdigit():
  2235. char_set = {
  2236. '0': 'MultiByte',
  2237. '1': 'Unicode',
  2238. '2': 'MultiByte',
  2239. }[char_set]
  2240. return char_set
  2241. def _ConvertMSVSConfigurationType(config_type):
  2242. if config_type.isdigit():
  2243. config_type = {
  2244. '1': 'Application',
  2245. '2': 'DynamicLibrary',
  2246. '4': 'StaticLibrary',
  2247. '10': 'Utility'
  2248. }[config_type]
  2249. return config_type
  2250. def _GetMSBuildAttributes(spec, config, build_file):
  2251. if 'msbuild_configuration_attributes' not in config:
  2252. msbuild_attributes = _ConvertMSVSBuildAttributes(spec, config, build_file)
  2253. else:
  2254. config_type = _GetMSVSConfigurationType(spec, build_file)
  2255. config_type = _ConvertMSVSConfigurationType(config_type)
  2256. msbuild_attributes = config.get('msbuild_configuration_attributes', {})
  2257. msbuild_attributes.setdefault('ConfigurationType', config_type)
  2258. output_dir = msbuild_attributes.get('OutputDirectory',
  2259. '$(SolutionDir)$(Configuration)')
  2260. msbuild_attributes['OutputDirectory'] = _FixPath(output_dir) + '\\'
  2261. if 'IntermediateDirectory' not in msbuild_attributes:
  2262. intermediate = _FixPath('$(Configuration)') + '\\'
  2263. msbuild_attributes['IntermediateDirectory'] = intermediate
  2264. if 'CharacterSet' in msbuild_attributes:
  2265. msbuild_attributes['CharacterSet'] = _ConvertMSVSCharacterSet(
  2266. msbuild_attributes['CharacterSet'])
  2267. if 'TargetName' not in msbuild_attributes:
  2268. prefix = spec.get('product_prefix', '')
  2269. product_name = spec.get('product_name', '$(ProjectName)')
  2270. target_name = prefix + product_name
  2271. msbuild_attributes['TargetName'] = target_name
  2272. # Make sure that 'TargetPath' matches 'Lib.OutputFile' or 'Link.OutputFile'
  2273. # (depending on the tool used) to avoid MSB8012 warning.
  2274. msbuild_tool_map = {
  2275. 'executable': 'Link',
  2276. 'shared_library': 'Link',
  2277. 'loadable_module': 'Link',
  2278. 'static_library': 'Lib',
  2279. }
  2280. msbuild_tool = msbuild_tool_map.get(spec['type'])
  2281. if msbuild_tool:
  2282. msbuild_settings = config['finalized_msbuild_settings']
  2283. out_file = msbuild_settings[msbuild_tool].get('OutputFile')
  2284. if out_file:
  2285. msbuild_attributes['TargetPath'] = _FixPath(out_file)
  2286. return msbuild_attributes
  2287. def _GetMSBuildConfigurationGlobalProperties(spec, configurations, build_file):
  2288. # TODO(jeanluc) We could optimize out the following and do it only if
  2289. # there are actions.
  2290. # TODO(jeanluc) Handle the equivalent of setting 'CYGWIN=nontsec'.
  2291. new_paths = []
  2292. cygwin_dirs = spec.get('msvs_cygwin_dirs', ['.'])[0]
  2293. if cygwin_dirs:
  2294. cyg_path = '$(MSBuildProjectDirectory)\\%s\\bin\\' % _FixPath(cygwin_dirs)
  2295. new_paths.append(cyg_path)
  2296. # TODO(jeanluc) Change the convention to have both a cygwin_dir and a
  2297. # python_dir.
  2298. python_path = cyg_path.replace('cygwin\\bin', 'python_26')
  2299. new_paths.append(python_path)
  2300. if new_paths:
  2301. new_paths = '$(ExecutablePath);' + ';'.join(new_paths)
  2302. properties = {}
  2303. for (name, configuration) in sorted(configurations.iteritems()):
  2304. condition = _GetConfigurationCondition(name, configuration)
  2305. attributes = _GetMSBuildAttributes(spec, configuration, build_file)
  2306. msbuild_settings = configuration['finalized_msbuild_settings']
  2307. _AddConditionalProperty(properties, condition, 'IntDir',
  2308. attributes['IntermediateDirectory'])
  2309. _AddConditionalProperty(properties, condition, 'OutDir',
  2310. attributes['OutputDirectory'])
  2311. _AddConditionalProperty(properties, condition, 'TargetName',
  2312. attributes['TargetName'])
  2313. if attributes.get('TargetPath'):
  2314. _AddConditionalProperty(properties, condition, 'TargetPath',
  2315. attributes['TargetPath'])
  2316. if new_paths:
  2317. _AddConditionalProperty(properties, condition, 'ExecutablePath',
  2318. new_paths)
  2319. tool_settings = msbuild_settings.get('', {})
  2320. for name, value in sorted(tool_settings.iteritems()):
  2321. formatted_value = _GetValueFormattedForMSBuild('', name, value)
  2322. _AddConditionalProperty(properties, condition, name, formatted_value)
  2323. return _GetMSBuildPropertyGroup(spec, None, properties)
  2324. def _AddConditionalProperty(properties, condition, name, value):
  2325. """Adds a property / conditional value pair to a dictionary.
  2326. Arguments:
  2327. properties: The dictionary to be modified. The key is the name of the
  2328. property. The value is itself a dictionary; its key is the value and
  2329. the value a list of condition for which this value is true.
  2330. condition: The condition under which the named property has the value.
  2331. name: The name of the property.
  2332. value: The value of the property.
  2333. """
  2334. if name not in properties:
  2335. properties[name] = {}
  2336. values = properties[name]
  2337. if value not in values:
  2338. values[value] = []
  2339. conditions = values[value]
  2340. conditions.append(condition)
  2341. # Regex for msvs variable references ( i.e. $(FOO) ).
  2342. MSVS_VARIABLE_REFERENCE = re.compile('\$\(([a-zA-Z_][a-zA-Z0-9_]*)\)')
  2343. def _GetMSBuildPropertyGroup(spec, label, properties):
  2344. """Returns a PropertyGroup definition for the specified properties.
  2345. Arguments:
  2346. spec: The target project dict.
  2347. label: An optional label for the PropertyGroup.
  2348. properties: The dictionary to be converted. The key is the name of the
  2349. property. The value is itself a dictionary; its key is the value and
  2350. the value a list of condition for which this value is true.
  2351. """
  2352. group = ['PropertyGroup']
  2353. if label:
  2354. group.append({'Label': label})
  2355. num_configurations = len(spec['configurations'])
  2356. def GetEdges(node):
  2357. # Use a definition of edges such that user_of_variable -> used_varible.
  2358. # This happens to be easier in this case, since a variable's
  2359. # definition contains all variables it references in a single string.
  2360. edges = set()
  2361. for value in sorted(properties[node].keys()):
  2362. # Add to edges all $(...) references to variables.
  2363. #
  2364. # Variable references that refer to names not in properties are excluded
  2365. # These can exist for instance to refer built in definitions like
  2366. # $(SolutionDir).
  2367. #
  2368. # Self references are ignored. Self reference is used in a few places to
  2369. # append to the default value. I.e. PATH=$(PATH);other_path
  2370. edges.update(set([v for v in MSVS_VARIABLE_REFERENCE.findall(value)
  2371. if v in properties and v != node]))
  2372. return edges
  2373. properties_ordered = gyp.common.TopologicallySorted(
  2374. properties.keys(), GetEdges)
  2375. # Walk properties in the reverse of a topological sort on
  2376. # user_of_variable -> used_variable as this ensures variables are
  2377. # defined before they are used.
  2378. # NOTE: reverse(topsort(DAG)) = topsort(reverse_edges(DAG))
  2379. for name in reversed(properties_ordered):
  2380. values = properties[name]
  2381. for value, conditions in sorted(values.iteritems()):
  2382. if len(conditions) == num_configurations:
  2383. # If the value is the same all configurations,
  2384. # just add one unconditional entry.
  2385. group.append([name, value])
  2386. else:
  2387. for condition in conditions:
  2388. group.append([name, {'Condition': condition}, value])
  2389. return [group]
  2390. def _GetMSBuildToolSettingsSections(spec, configurations):
  2391. groups = []
  2392. for (name, configuration) in sorted(configurations.iteritems()):
  2393. msbuild_settings = configuration['finalized_msbuild_settings']
  2394. group = ['ItemDefinitionGroup',
  2395. {'Condition': _GetConfigurationCondition(name, configuration)}
  2396. ]
  2397. for tool_name, tool_settings in sorted(msbuild_settings.iteritems()):
  2398. # Skip the tool named '' which is a holder of global settings handled
  2399. # by _GetMSBuildConfigurationGlobalProperties.
  2400. if tool_name:
  2401. if tool_settings:
  2402. tool = [tool_name]
  2403. for name, value in sorted(tool_settings.iteritems()):
  2404. formatted_value = _GetValueFormattedForMSBuild(tool_name, name,
  2405. value)
  2406. tool.append([name, formatted_value])
  2407. group.append(tool)
  2408. groups.append(group)
  2409. return groups
  2410. def _FinalizeMSBuildSettings(spec, configuration):
  2411. if 'msbuild_settings' in configuration:
  2412. converted = False
  2413. msbuild_settings = configuration['msbuild_settings']
  2414. MSVSSettings.ValidateMSBuildSettings(msbuild_settings)
  2415. else:
  2416. converted = True
  2417. msvs_settings = configuration.get('msvs_settings', {})
  2418. msbuild_settings = MSVSSettings.ConvertToMSBuildSettings(msvs_settings)
  2419. include_dirs, resource_include_dirs = _GetIncludeDirs(configuration)
  2420. libraries = _GetLibraries(spec)
  2421. out_file, _, msbuild_tool = _GetOutputFilePathAndTool(spec, msbuild=True)
  2422. defines = _GetDefines(configuration)
  2423. if converted:
  2424. # Visual Studio 2010 has TR1
  2425. defines = [d for d in defines if d != '_HAS_TR1=0']
  2426. # Warn of ignored settings
  2427. ignored_settings = ['msvs_prebuild', 'msvs_postbuild', 'msvs_tool_files']
  2428. for ignored_setting in ignored_settings:
  2429. value = configuration.get(ignored_setting)
  2430. if value:
  2431. print ('Warning: The automatic conversion to MSBuild does not handle '
  2432. '%s. Ignoring setting of %s' % (ignored_setting, str(value)))
  2433. defines = [_EscapeCppDefineForMSBuild(d) for d in defines]
  2434. disabled_warnings = _GetDisabledWarnings(configuration)
  2435. # TODO(jeanluc) Validate & warn that we don't translate
  2436. # prebuild = configuration.get('msvs_prebuild')
  2437. # postbuild = configuration.get('msvs_postbuild')
  2438. def_file = _GetModuleDefinition(spec)
  2439. precompiled_header = configuration.get('msvs_precompiled_header')
  2440. # Add the information to the appropriate tool
  2441. # TODO(jeanluc) We could optimize and generate these settings only if
  2442. # the corresponding files are found, e.g. don't generate ResourceCompile
  2443. # if you don't have any resources.
  2444. _ToolAppend(msbuild_settings, 'ClCompile',
  2445. 'AdditionalIncludeDirectories', include_dirs)
  2446. _ToolAppend(msbuild_settings, 'ResourceCompile',
  2447. 'AdditionalIncludeDirectories', resource_include_dirs)
  2448. # Add in libraries.
  2449. _ToolAppend(msbuild_settings, 'Link', 'AdditionalDependencies', libraries)
  2450. if out_file:
  2451. _ToolAppend(msbuild_settings, msbuild_tool, 'OutputFile', out_file,
  2452. only_if_unset=True)
  2453. # Add defines.
  2454. _ToolAppend(msbuild_settings, 'ClCompile',
  2455. 'PreprocessorDefinitions', defines)
  2456. _ToolAppend(msbuild_settings, 'ResourceCompile',
  2457. 'PreprocessorDefinitions', defines)
  2458. # Add disabled warnings.
  2459. _ToolAppend(msbuild_settings, 'ClCompile',
  2460. 'DisableSpecificWarnings', disabled_warnings)
  2461. # Turn on precompiled headers if appropriate.
  2462. if precompiled_header:
  2463. precompiled_header = os.path.split(precompiled_header)[1]
  2464. _ToolAppend(msbuild_settings, 'ClCompile', 'PrecompiledHeader', 'Use')
  2465. _ToolAppend(msbuild_settings, 'ClCompile',
  2466. 'PrecompiledHeaderFile', precompiled_header)
  2467. _ToolAppend(msbuild_settings, 'ClCompile',
  2468. 'ForcedIncludeFiles', precompiled_header)
  2469. # Loadable modules don't generate import libraries;
  2470. # tell dependent projects to not expect one.
  2471. if spec['type'] == 'loadable_module':
  2472. _ToolAppend(msbuild_settings, '', 'IgnoreImportLibrary', 'true')
  2473. # Set the module definition file if any.
  2474. if def_file:
  2475. _ToolAppend(msbuild_settings, 'Link', 'ModuleDefinitionFile', def_file)
  2476. configuration['finalized_msbuild_settings'] = msbuild_settings
  2477. def _GetValueFormattedForMSBuild(tool_name, name, value):
  2478. if type(value) == list:
  2479. # For some settings, VS2010 does not automatically extends the settings
  2480. # TODO(jeanluc) Is this what we want?
  2481. if name in ['AdditionalDependencies',
  2482. 'AdditionalIncludeDirectories',
  2483. 'AdditionalLibraryDirectories',
  2484. 'AdditionalOptions',
  2485. 'DelayLoadDLLs',
  2486. 'DisableSpecificWarnings',
  2487. 'PreprocessorDefinitions']:
  2488. value.append('%%(%s)' % name)
  2489. # For most tools, entries in a list should be separated with ';' but some
  2490. # settings use a space. Check for those first.
  2491. exceptions = {
  2492. 'ClCompile': ['AdditionalOptions'],
  2493. 'Link': ['AdditionalOptions'],
  2494. 'Lib': ['AdditionalOptions']}
  2495. if tool_name in exceptions and name in exceptions[tool_name]:
  2496. char = ' '
  2497. else:
  2498. char = ';'
  2499. formatted_value = char.join(
  2500. [MSVSSettings.ConvertVCMacrosToMSBuild(i) for i in value])
  2501. else:
  2502. formatted_value = MSVSSettings.ConvertVCMacrosToMSBuild(value)
  2503. return formatted_value
  2504. def _VerifySourcesExist(sources, root_dir):
  2505. """Verifies that all source files exist on disk.
  2506. Checks that all regular source files, i.e. not created at run time,
  2507. exist on disk. Missing files cause needless recompilation but no otherwise
  2508. visible errors.
  2509. Arguments:
  2510. sources: A recursive list of Filter/file names.
  2511. root_dir: The root directory for the relative path names.
  2512. Returns:
  2513. A list of source files that cannot be found on disk.
  2514. """
  2515. missing_sources = []
  2516. for source in sources:
  2517. if isinstance(source, MSVSProject.Filter):
  2518. missing_sources.extend(_VerifySourcesExist(source.contents, root_dir))
  2519. else:
  2520. if '$' not in source:
  2521. full_path = os.path.join(root_dir, source)
  2522. if not os.path.exists(full_path):
  2523. missing_sources.append(full_path)
  2524. return missing_sources
  2525. def _GetMSBuildSources(spec, sources, exclusions, extension_to_rule_name,
  2526. actions_spec, sources_handled_by_action, list_excluded):
  2527. groups = ['none', 'midl', 'include', 'compile', 'resource', 'rule']
  2528. grouped_sources = {}
  2529. for g in groups:
  2530. grouped_sources[g] = []
  2531. _AddSources2(spec, sources, exclusions, grouped_sources,
  2532. extension_to_rule_name, sources_handled_by_action, list_excluded)
  2533. sources = []
  2534. for g in groups:
  2535. if grouped_sources[g]:
  2536. sources.append(['ItemGroup'] + grouped_sources[g])
  2537. if actions_spec:
  2538. sources.append(['ItemGroup'] + actions_spec)
  2539. return sources
  2540. def _AddSources2(spec, sources, exclusions, grouped_sources,
  2541. extension_to_rule_name, sources_handled_by_action,
  2542. list_excluded):
  2543. extensions_excluded_from_precompile = []
  2544. for source in sources:
  2545. if isinstance(source, MSVSProject.Filter):
  2546. _AddSources2(spec, source.contents, exclusions, grouped_sources,
  2547. extension_to_rule_name, sources_handled_by_action,
  2548. list_excluded)
  2549. else:
  2550. if not source in sources_handled_by_action:
  2551. detail = []
  2552. excluded_configurations = exclusions.get(source, [])
  2553. if len(excluded_configurations) == len(spec['configurations']):
  2554. detail.append(['ExcludedFromBuild', 'true'])
  2555. else:
  2556. for config_name, configuration in sorted(excluded_configurations):
  2557. condition = _GetConfigurationCondition(config_name, configuration)
  2558. detail.append(['ExcludedFromBuild',
  2559. {'Condition': condition},
  2560. 'true'])
  2561. # Add precompile if needed
  2562. for config_name, configuration in spec['configurations'].iteritems():
  2563. precompiled_source = configuration.get('msvs_precompiled_source', '')
  2564. if precompiled_source != '':
  2565. precompiled_source = _FixPath(precompiled_source)
  2566. if not extensions_excluded_from_precompile:
  2567. # If the precompiled header is generated by a C source, we must
  2568. # not try to use it for C++ sources, and vice versa.
  2569. basename, extension = os.path.splitext(precompiled_source)
  2570. if extension == '.c':
  2571. extensions_excluded_from_precompile = ['.cc', '.cpp', '.cxx']
  2572. else:
  2573. extensions_excluded_from_precompile = ['.c']
  2574. if precompiled_source == source:
  2575. condition = _GetConfigurationCondition(config_name, configuration)
  2576. detail.append(['PrecompiledHeader',
  2577. {'Condition': condition},
  2578. 'Create'
  2579. ])
  2580. else:
  2581. # Turn off precompiled header usage for source files of a
  2582. # different type than the file that generated the
  2583. # precompiled header.
  2584. for extension in extensions_excluded_from_precompile:
  2585. if source.endswith(extension):
  2586. detail.append(['PrecompiledHeader', ''])
  2587. detail.append(['ForcedIncludeFiles', ''])
  2588. group, element = _MapFileToMsBuildSourceType(source,
  2589. extension_to_rule_name)
  2590. grouped_sources[group].append([element, {'Include': source}] + detail)
  2591. def _GetMSBuildProjectReferences(project):
  2592. references = []
  2593. if project.dependencies:
  2594. group = ['ItemGroup']
  2595. for dependency in project.dependencies:
  2596. guid = dependency.guid
  2597. project_dir = os.path.split(project.path)[0]
  2598. relative_path = gyp.common.RelativePath(dependency.path, project_dir)
  2599. project_ref = ['ProjectReference',
  2600. {'Include': relative_path},
  2601. ['Project', guid],
  2602. ['ReferenceOutputAssembly', 'false']
  2603. ]
  2604. for config in dependency.spec.get('configurations', {}).itervalues():
  2605. # If it's disabled in any config, turn it off in the reference.
  2606. if config.get('msvs_2010_disable_uldi_when_referenced', 0):
  2607. project_ref.append(['UseLibraryDependencyInputs', 'false'])
  2608. break
  2609. group.append(project_ref)
  2610. references.append(group)
  2611. return references
  2612. def _GenerateMSBuildProject(project, options, version, generator_flags):
  2613. spec = project.spec
  2614. configurations = spec['configurations']
  2615. project_dir, project_file_name = os.path.split(project.path)
  2616. msbuildproj_dir = os.path.dirname(project.path)
  2617. if msbuildproj_dir and not os.path.exists(msbuildproj_dir):
  2618. os.makedirs(msbuildproj_dir)
  2619. # Prepare list of sources and excluded sources.
  2620. gyp_path = _NormalizedSource(project.build_file)
  2621. relative_path_of_gyp_file = gyp.common.RelativePath(gyp_path, project_dir)
  2622. gyp_file = os.path.split(project.build_file)[1]
  2623. sources, excluded_sources = _PrepareListOfSources(spec, generator_flags,
  2624. gyp_file)
  2625. # Add rules.
  2626. actions_to_add = {}
  2627. props_files_of_rules = set()
  2628. targets_files_of_rules = set()
  2629. extension_to_rule_name = {}
  2630. list_excluded = generator_flags.get('msvs_list_excluded_files', True)
  2631. _GenerateRulesForMSBuild(project_dir, options, spec,
  2632. sources, excluded_sources,
  2633. props_files_of_rules, targets_files_of_rules,
  2634. actions_to_add, extension_to_rule_name)
  2635. sources, excluded_sources, excluded_idl = (
  2636. _AdjustSourcesAndConvertToFilterHierarchy(spec, options,
  2637. project_dir, sources,
  2638. excluded_sources,
  2639. list_excluded))
  2640. _AddActions(actions_to_add, spec, project.build_file)
  2641. _AddCopies(actions_to_add, spec)
  2642. # NOTE: this stanza must appear after all actions have been decided.
  2643. # Don't excluded sources with actions attached, or they won't run.
  2644. excluded_sources = _FilterActionsFromExcluded(
  2645. excluded_sources, actions_to_add)
  2646. exclusions = _GetExcludedFilesFromBuild(spec, excluded_sources, excluded_idl)
  2647. actions_spec, sources_handled_by_action = _GenerateActionsForMSBuild(
  2648. spec, actions_to_add)
  2649. _GenerateMSBuildFiltersFile(project.path + '.filters', sources,
  2650. extension_to_rule_name)
  2651. missing_sources = _VerifySourcesExist(sources, project_dir)
  2652. for configuration in configurations.itervalues():
  2653. _FinalizeMSBuildSettings(spec, configuration)
  2654. # Add attributes to root element
  2655. import_default_section = [
  2656. ['Import', {'Project': r'$(VCTargetsPath)\Microsoft.Cpp.Default.props'}]]
  2657. import_cpp_props_section = [
  2658. ['Import', {'Project': r'$(VCTargetsPath)\Microsoft.Cpp.props'}]]
  2659. import_cpp_targets_section = [
  2660. ['Import', {'Project': r'$(VCTargetsPath)\Microsoft.Cpp.targets'}]]
  2661. macro_section = [['PropertyGroup', {'Label': 'UserMacros'}]]
  2662. content = [
  2663. 'Project',
  2664. {'xmlns': 'http://schemas.microsoft.com/developer/msbuild/2003',
  2665. 'ToolsVersion': version.ProjectVersion(),
  2666. 'DefaultTargets': 'Build'
  2667. }]
  2668. content += _GetMSBuildProjectConfigurations(configurations)
  2669. content += _GetMSBuildGlobalProperties(spec, project.guid, project_file_name)
  2670. content += import_default_section
  2671. content += _GetMSBuildConfigurationDetails(spec, project.build_file)
  2672. content += _GetMSBuildLocalProperties(project.msbuild_toolset)
  2673. content += import_cpp_props_section
  2674. content += _GetMSBuildExtensions(props_files_of_rules)
  2675. content += _GetMSBuildPropertySheets(configurations)
  2676. content += macro_section
  2677. content += _GetMSBuildConfigurationGlobalProperties(spec, configurations,
  2678. project.build_file)
  2679. content += _GetMSBuildToolSettingsSections(spec, configurations)
  2680. content += _GetMSBuildSources(
  2681. spec, sources, exclusions, extension_to_rule_name, actions_spec,
  2682. sources_handled_by_action, list_excluded)
  2683. content += _GetMSBuildProjectReferences(project)
  2684. content += import_cpp_targets_section
  2685. content += _GetMSBuildExtensionTargets(targets_files_of_rules)
  2686. # TODO(jeanluc) File a bug to get rid of runas. We had in MSVS:
  2687. # has_run_as = _WriteMSVSUserFile(project.path, version, spec)
  2688. easy_xml.WriteXmlIfChanged(content, project.path, pretty=True, win32=True)
  2689. return missing_sources
  2690. def _GetMSBuildExtensions(props_files_of_rules):
  2691. extensions = ['ImportGroup', {'Label': 'ExtensionSettings'}]
  2692. for props_file in props_files_of_rules:
  2693. extensions.append(['Import', {'Project': props_file}])
  2694. return [extensions]
  2695. def _GetMSBuildExtensionTargets(targets_files_of_rules):
  2696. targets_node = ['ImportGroup', {'Label': 'ExtensionTargets'}]
  2697. for targets_file in sorted(targets_files_of_rules):
  2698. targets_node.append(['Import', {'Project': targets_file}])
  2699. return [targets_node]
  2700. def _GenerateActionsForMSBuild(spec, actions_to_add):
  2701. """Add actions accumulated into an actions_to_add, merging as needed.
  2702. Arguments:
  2703. spec: the target project dict
  2704. actions_to_add: dictionary keyed on input name, which maps to a list of
  2705. dicts describing the actions attached to that input file.
  2706. Returns:
  2707. A pair of (action specification, the sources handled by this action).
  2708. """
  2709. sources_handled_by_action = set()
  2710. actions_spec = []
  2711. for primary_input, actions in actions_to_add.iteritems():
  2712. inputs = set()
  2713. outputs = set()
  2714. descriptions = []
  2715. commands = []
  2716. for action in actions:
  2717. inputs.update(set(action['inputs']))
  2718. outputs.update(set(action['outputs']))
  2719. descriptions.append(action['description'])
  2720. cmd = action['command']
  2721. # For most actions, add 'call' so that actions that invoke batch files
  2722. # return and continue executing. msbuild_use_call provides a way to
  2723. # disable this but I have not seen any adverse effect from doing that
  2724. # for everything.
  2725. if action.get('msbuild_use_call', True):
  2726. cmd = 'call ' + cmd
  2727. commands.append(cmd)
  2728. # Add the custom build action for one input file.
  2729. description = ', and also '.join(descriptions)
  2730. # We can't join the commands simply with && because the command line will
  2731. # get too long. See also _AddActions: cygwin's setup_env mustn't be called
  2732. # for every invocation or the command that sets the PATH will grow too
  2733. # long.
  2734. command = (
  2735. '\r\nif %errorlevel% neq 0 exit /b %errorlevel%\r\n'.join(commands))
  2736. _AddMSBuildAction(spec,
  2737. primary_input,
  2738. inputs,
  2739. outputs,
  2740. command,
  2741. description,
  2742. sources_handled_by_action,
  2743. actions_spec)
  2744. return actions_spec, sources_handled_by_action
  2745. def _AddMSBuildAction(spec, primary_input, inputs, outputs, cmd, description,
  2746. sources_handled_by_action, actions_spec):
  2747. command = MSVSSettings.ConvertVCMacrosToMSBuild(cmd)
  2748. primary_input = _FixPath(primary_input)
  2749. inputs_array = _FixPaths(inputs)
  2750. outputs_array = _FixPaths(outputs)
  2751. additional_inputs = ';'.join([i for i in inputs_array
  2752. if i != primary_input])
  2753. outputs = ';'.join(outputs_array)
  2754. sources_handled_by_action.add(primary_input)
  2755. action_spec = ['CustomBuild', {'Include': primary_input}]
  2756. action_spec.extend(
  2757. # TODO(jeanluc) 'Document' for all or just if as_sources?
  2758. [['FileType', 'Document'],
  2759. ['Command', command],
  2760. ['Message', description],
  2761. ['Outputs', outputs]
  2762. ])
  2763. if additional_inputs:
  2764. action_spec.append(['AdditionalInputs', additional_inputs])
  2765. actions_spec.append(action_spec)