PageRenderTime 54ms CodeModel.GetById 18ms 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

Large files files are truncated, but you can click here to view the full file

  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 pr

Large files files are truncated, but you can click here to view the full file