PageRenderTime 57ms CodeModel.GetById 17ms RepoModel.GetById 0ms app.codeStats 0ms

/front/node_modules/node-gyp/gyp/pylib/gyp/generator/msvs.py

https://gitlab.com/boxnia/NFU_MOVIL
Python | 1384 lines | 1321 code | 30 blank | 33 comment | 35 complexity | 722f88ff88862151f6d92f704e0d8992 MD5 | raw 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.generator.ninja as ninja_generator
  14. import gyp.MSVSNew as MSVSNew
  15. import gyp.MSVSProject as MSVSProject
  16. import gyp.MSVSSettings as MSVSSettings
  17. import gyp.MSVSToolFile as MSVSToolFile
  18. import gyp.MSVSUserFile as MSVSUserFile
  19. import gyp.MSVSUtil as MSVSUtil
  20. import gyp.MSVSVersion as MSVSVersion
  21. from gyp.common import GypError
  22. from gyp.common import OrderedSet
  23. # TODO: Remove once bots are on 2.7, http://crbug.com/241769
  24. def _import_OrderedDict():
  25. import collections
  26. try:
  27. return collections.OrderedDict
  28. except AttributeError:
  29. import gyp.ordered_dict
  30. return gyp.ordered_dict.OrderedDict
  31. OrderedDict = _import_OrderedDict()
  32. # Regular expression for validating Visual Studio GUIDs. If the GUID
  33. # contains lowercase hex letters, MSVS will be fine. However,
  34. # IncrediBuild BuildConsole will parse the solution file, but then
  35. # silently skip building the target causing hard to track down errors.
  36. # Note that this only happens with the BuildConsole, and does not occur
  37. # if IncrediBuild is executed from inside Visual Studio. This regex
  38. # validates that the string looks like a GUID with all uppercase hex
  39. # letters.
  40. VALID_MSVS_GUID_CHARS = re.compile(r'^[A-F0-9\-]+$')
  41. generator_default_variables = {
  42. 'EXECUTABLE_PREFIX': '',
  43. 'EXECUTABLE_SUFFIX': '.exe',
  44. 'STATIC_LIB_PREFIX': '',
  45. 'SHARED_LIB_PREFIX': '',
  46. 'STATIC_LIB_SUFFIX': '.lib',
  47. 'SHARED_LIB_SUFFIX': '.dll',
  48. 'INTERMEDIATE_DIR': '$(IntDir)',
  49. 'SHARED_INTERMEDIATE_DIR': '$(OutDir)obj/global_intermediate',
  50. 'OS': 'win',
  51. 'PRODUCT_DIR': '$(OutDir)',
  52. 'LIB_DIR': '$(OutDir)lib',
  53. 'RULE_INPUT_ROOT': '$(InputName)',
  54. 'RULE_INPUT_DIRNAME': '$(InputDir)',
  55. 'RULE_INPUT_EXT': '$(InputExt)',
  56. 'RULE_INPUT_NAME': '$(InputFileName)',
  57. 'RULE_INPUT_PATH': '$(InputPath)',
  58. 'CONFIGURATION_NAME': '$(ConfigurationName)',
  59. }
  60. # The msvs specific sections that hold paths
  61. generator_additional_path_sections = [
  62. 'msvs_cygwin_dirs',
  63. 'msvs_props',
  64. ]
  65. generator_additional_non_configuration_keys = [
  66. 'msvs_cygwin_dirs',
  67. 'msvs_cygwin_shell',
  68. 'msvs_large_pdb',
  69. 'msvs_shard',
  70. 'msvs_external_builder',
  71. 'msvs_external_builder_out_dir',
  72. 'msvs_external_builder_build_cmd',
  73. 'msvs_external_builder_clean_cmd',
  74. 'msvs_external_builder_clcompile_cmd',
  75. 'msvs_enable_winrt',
  76. 'msvs_requires_importlibrary',
  77. 'msvs_enable_winphone',
  78. 'msvs_application_type_revision',
  79. 'msvs_target_platform_version',
  80. 'msvs_target_platform_minversion',
  81. ]
  82. # List of precompiled header related keys.
  83. precomp_keys = [
  84. 'msvs_precompiled_header',
  85. 'msvs_precompiled_source',
  86. ]
  87. cached_username = None
  88. cached_domain = None
  89. # TODO(gspencer): Switch the os.environ calls to be
  90. # win32api.GetDomainName() and win32api.GetUserName() once the
  91. # python version in depot_tools has been updated to work on Vista
  92. # 64-bit.
  93. def _GetDomainAndUserName():
  94. if sys.platform not in ('win32', 'cygwin'):
  95. return ('DOMAIN', 'USERNAME')
  96. global cached_username
  97. global cached_domain
  98. if not cached_domain or not cached_username:
  99. domain = os.environ.get('USERDOMAIN')
  100. username = os.environ.get('USERNAME')
  101. if not domain or not username:
  102. call = subprocess.Popen(['net', 'config', 'Workstation'],
  103. stdout=subprocess.PIPE)
  104. config = call.communicate()[0]
  105. username_re = re.compile(r'^User name\s+(\S+)', re.MULTILINE)
  106. username_match = username_re.search(config)
  107. if username_match:
  108. username = username_match.group(1)
  109. domain_re = re.compile(r'^Logon domain\s+(\S+)', re.MULTILINE)
  110. domain_match = domain_re.search(config)
  111. if domain_match:
  112. domain = domain_match.group(1)
  113. cached_domain = domain
  114. cached_username = username
  115. return (cached_domain, cached_username)
  116. fixpath_prefix = None
  117. def _NormalizedSource(source):
  118. """Normalize the path.
  119. But not if that gets rid of a variable, as this may expand to something
  120. larger than one directory.
  121. Arguments:
  122. source: The path to be normalize.d
  123. Returns:
  124. The normalized path.
  125. """
  126. normalized = os.path.normpath(source)
  127. if source.count('$') == normalized.count('$'):
  128. source = normalized
  129. return source
  130. def _FixPath(path):
  131. """Convert paths to a form that will make sense in a vcproj file.
  132. Arguments:
  133. path: The path to convert, may contain / etc.
  134. Returns:
  135. The path with all slashes made into backslashes.
  136. """
  137. if fixpath_prefix and path and not os.path.isabs(path) and not path[0] == '$':
  138. path = os.path.join(fixpath_prefix, path)
  139. path = path.replace('/', '\\')
  140. path = _NormalizedSource(path)
  141. if path and path[-1] == '\\':
  142. path = path[:-1]
  143. return path
  144. def _FixPaths(paths):
  145. """Fix each of the paths of the list."""
  146. return [_FixPath(i) for i in paths]
  147. def _ConvertSourcesToFilterHierarchy(sources, prefix=None, excluded=None,
  148. list_excluded=True, msvs_version=None):
  149. """Converts a list split source file paths into a vcproj folder hierarchy.
  150. Arguments:
  151. sources: A list of source file paths split.
  152. prefix: A list of source file path layers meant to apply to each of sources.
  153. excluded: A set of excluded files.
  154. msvs_version: A MSVSVersion object.
  155. Returns:
  156. A hierarchy of filenames and MSVSProject.Filter objects that matches the
  157. layout of the source tree.
  158. For example:
  159. _ConvertSourcesToFilterHierarchy([['a', 'bob1.c'], ['b', 'bob2.c']],
  160. prefix=['joe'])
  161. -->
  162. [MSVSProject.Filter('a', contents=['joe\\a\\bob1.c']),
  163. MSVSProject.Filter('b', contents=['joe\\b\\bob2.c'])]
  164. """
  165. if not prefix: prefix = []
  166. result = []
  167. excluded_result = []
  168. folders = OrderedDict()
  169. # Gather files into the final result, excluded, or folders.
  170. for s in sources:
  171. if len(s) == 1:
  172. filename = _NormalizedSource('\\'.join(prefix + s))
  173. if filename in excluded:
  174. excluded_result.append(filename)
  175. else:
  176. result.append(filename)
  177. elif msvs_version and not msvs_version.UsesVcxproj():
  178. # For MSVS 2008 and earlier, we need to process all files before walking
  179. # the sub folders.
  180. if not folders.get(s[0]):
  181. folders[s[0]] = []
  182. folders[s[0]].append(s[1:])
  183. else:
  184. contents = _ConvertSourcesToFilterHierarchy([s[1:]], prefix + [s[0]],
  185. excluded=excluded,
  186. list_excluded=list_excluded,
  187. msvs_version=msvs_version)
  188. contents = MSVSProject.Filter(s[0], contents=contents)
  189. result.append(contents)
  190. # Add a folder for excluded files.
  191. if excluded_result and list_excluded:
  192. excluded_folder = MSVSProject.Filter('_excluded_files',
  193. contents=excluded_result)
  194. result.append(excluded_folder)
  195. if msvs_version and msvs_version.UsesVcxproj():
  196. return result
  197. # Populate all the folders.
  198. for f in folders:
  199. contents = _ConvertSourcesToFilterHierarchy(folders[f], prefix=prefix + [f],
  200. excluded=excluded,
  201. list_excluded=list_excluded,
  202. msvs_version=msvs_version)
  203. contents = MSVSProject.Filter(f, contents=contents)
  204. result.append(contents)
  205. return result
  206. def _ToolAppend(tools, tool_name, setting, value, only_if_unset=False):
  207. if not value: return
  208. _ToolSetOrAppend(tools, tool_name, setting, value, only_if_unset)
  209. def _ToolSetOrAppend(tools, tool_name, setting, value, only_if_unset=False):
  210. # TODO(bradnelson): ugly hack, fix this more generally!!!
  211. if 'Directories' in setting or 'Dependencies' in setting:
  212. if type(value) == str:
  213. value = value.replace('/', '\\')
  214. else:
  215. value = [i.replace('/', '\\') for i in value]
  216. if not tools.get(tool_name):
  217. tools[tool_name] = dict()
  218. tool = tools[tool_name]
  219. if tool.get(setting):
  220. if only_if_unset: return
  221. if type(tool[setting]) == list and type(value) == list:
  222. tool[setting] += value
  223. else:
  224. raise TypeError(
  225. 'Appending "%s" to a non-list setting "%s" for tool "%s" is '
  226. 'not allowed, previous value: %s' % (
  227. value, setting, tool_name, str(tool[setting])))
  228. else:
  229. tool[setting] = value
  230. def _ConfigPlatform(config_data):
  231. return config_data.get('msvs_configuration_platform', 'Win32')
  232. def _ConfigBaseName(config_name, platform_name):
  233. if config_name.endswith('_' + platform_name):
  234. return config_name[0:-len(platform_name) - 1]
  235. else:
  236. return config_name
  237. def _ConfigFullName(config_name, config_data):
  238. platform_name = _ConfigPlatform(config_data)
  239. return '%s|%s' % (_ConfigBaseName(config_name, platform_name), platform_name)
  240. def _BuildCommandLineForRuleRaw(spec, cmd, cygwin_shell, has_input_path,
  241. quote_cmd, do_setup_env):
  242. if [x for x in cmd if '$(InputDir)' in x]:
  243. input_dir_preamble = (
  244. 'set INPUTDIR=$(InputDir)\n'
  245. 'if NOT DEFINED INPUTDIR set INPUTDIR=.\\\n'
  246. 'set INPUTDIR=%INPUTDIR:~0,-1%\n'
  247. )
  248. else:
  249. input_dir_preamble = ''
  250. if cygwin_shell:
  251. # Find path to cygwin.
  252. cygwin_dir = _FixPath(spec.get('msvs_cygwin_dirs', ['.'])[0])
  253. # Prepare command.
  254. direct_cmd = cmd
  255. direct_cmd = [i.replace('$(IntDir)',
  256. '`cygpath -m "${INTDIR}"`') for i in direct_cmd]
  257. direct_cmd = [i.replace('$(OutDir)',
  258. '`cygpath -m "${OUTDIR}"`') for i in direct_cmd]
  259. direct_cmd = [i.replace('$(InputDir)',
  260. '`cygpath -m "${INPUTDIR}"`') for i in direct_cmd]
  261. if has_input_path:
  262. direct_cmd = [i.replace('$(InputPath)',
  263. '`cygpath -m "${INPUTPATH}"`')
  264. for i in direct_cmd]
  265. direct_cmd = ['\\"%s\\"' % i.replace('"', '\\\\\\"') for i in direct_cmd]
  266. # direct_cmd = gyp.common.EncodePOSIXShellList(direct_cmd)
  267. direct_cmd = ' '.join(direct_cmd)
  268. # TODO(quote): regularize quoting path names throughout the module
  269. cmd = ''
  270. if do_setup_env:
  271. cmd += 'call "$(ProjectDir)%(cygwin_dir)s\\setup_env.bat" && '
  272. cmd += 'set CYGWIN=nontsec&& '
  273. if direct_cmd.find('NUMBER_OF_PROCESSORS') >= 0:
  274. cmd += 'set /a NUMBER_OF_PROCESSORS_PLUS_1=%%NUMBER_OF_PROCESSORS%%+1&& '
  275. if direct_cmd.find('INTDIR') >= 0:
  276. cmd += 'set INTDIR=$(IntDir)&& '
  277. if direct_cmd.find('OUTDIR') >= 0:
  278. cmd += 'set OUTDIR=$(OutDir)&& '
  279. if has_input_path and direct_cmd.find('INPUTPATH') >= 0:
  280. cmd += 'set INPUTPATH=$(InputPath) && '
  281. cmd += 'bash -c "%(cmd)s"'
  282. cmd = cmd % {'cygwin_dir': cygwin_dir,
  283. 'cmd': direct_cmd}
  284. return input_dir_preamble + cmd
  285. else:
  286. # Convert cat --> type to mimic unix.
  287. if cmd[0] == 'cat':
  288. command = ['type']
  289. else:
  290. command = [cmd[0].replace('/', '\\')]
  291. # Add call before command to ensure that commands can be tied together one
  292. # after the other without aborting in Incredibuild, since IB makes a bat
  293. # file out of the raw command string, and some commands (like python) are
  294. # actually batch files themselves.
  295. command.insert(0, 'call')
  296. # Fix the paths
  297. # TODO(quote): This is a really ugly heuristic, and will miss path fixing
  298. # for arguments like "--arg=path" or "/opt:path".
  299. # If the argument starts with a slash or dash, it's probably a command line
  300. # switch
  301. arguments = [i if (i[:1] in "/-") else _FixPath(i) for i in cmd[1:]]
  302. arguments = [i.replace('$(InputDir)', '%INPUTDIR%') for i in arguments]
  303. arguments = [MSVSSettings.FixVCMacroSlashes(i) for i in arguments]
  304. if quote_cmd:
  305. # Support a mode for using cmd directly.
  306. # Convert any paths to native form (first element is used directly).
  307. # TODO(quote): regularize quoting path names throughout the module
  308. arguments = ['"%s"' % i for i in arguments]
  309. # Collapse into a single command.
  310. return input_dir_preamble + ' '.join(command + arguments)
  311. def _BuildCommandLineForRule(spec, rule, has_input_path, do_setup_env):
  312. # Currently this weird argument munging is used to duplicate the way a
  313. # python script would need to be run as part of the chrome tree.
  314. # Eventually we should add some sort of rule_default option to set this
  315. # per project. For now the behavior chrome needs is the default.
  316. mcs = rule.get('msvs_cygwin_shell')
  317. if mcs is None:
  318. mcs = int(spec.get('msvs_cygwin_shell', 1))
  319. elif isinstance(mcs, str):
  320. mcs = int(mcs)
  321. quote_cmd = int(rule.get('msvs_quote_cmd', 1))
  322. return _BuildCommandLineForRuleRaw(spec, rule['action'], mcs, has_input_path,
  323. quote_cmd, do_setup_env=do_setup_env)
  324. def _AddActionStep(actions_dict, inputs, outputs, description, command):
  325. """Merge action into an existing list of actions.
  326. Care must be taken so that actions which have overlapping inputs either don't
  327. get assigned to the same input, or get collapsed into one.
  328. Arguments:
  329. actions_dict: dictionary keyed on input name, which maps to a list of
  330. dicts describing the actions attached to that input file.
  331. inputs: list of inputs
  332. outputs: list of outputs
  333. description: description of the action
  334. command: command line to execute
  335. """
  336. # Require there to be at least one input (call sites will ensure this).
  337. assert inputs
  338. action = {
  339. 'inputs': inputs,
  340. 'outputs': outputs,
  341. 'description': description,
  342. 'command': command,
  343. }
  344. # Pick where to stick this action.
  345. # While less than optimal in terms of build time, attach them to the first
  346. # input for now.
  347. chosen_input = inputs[0]
  348. # Add it there.
  349. if chosen_input not in actions_dict:
  350. actions_dict[chosen_input] = []
  351. actions_dict[chosen_input].append(action)
  352. def _AddCustomBuildToolForMSVS(p, spec, primary_input,
  353. inputs, outputs, description, cmd):
  354. """Add a custom build tool to execute something.
  355. Arguments:
  356. p: the target project
  357. spec: the target project dict
  358. primary_input: input file to attach the build tool to
  359. inputs: list of inputs
  360. outputs: list of outputs
  361. description: description of the action
  362. cmd: command line to execute
  363. """
  364. inputs = _FixPaths(inputs)
  365. outputs = _FixPaths(outputs)
  366. tool = MSVSProject.Tool(
  367. 'VCCustomBuildTool',
  368. {'Description': description,
  369. 'AdditionalDependencies': ';'.join(inputs),
  370. 'Outputs': ';'.join(outputs),
  371. 'CommandLine': cmd,
  372. })
  373. # Add to the properties of primary input for each config.
  374. for config_name, c_data in spec['configurations'].iteritems():
  375. p.AddFileConfig(_FixPath(primary_input),
  376. _ConfigFullName(config_name, c_data), tools=[tool])
  377. def _AddAccumulatedActionsToMSVS(p, spec, actions_dict):
  378. """Add actions accumulated into an actions_dict, merging as needed.
  379. Arguments:
  380. p: the target project
  381. spec: the target project dict
  382. actions_dict: dictionary keyed on input name, which maps to a list of
  383. dicts describing the actions attached to that input file.
  384. """
  385. for primary_input in actions_dict:
  386. inputs = OrderedSet()
  387. outputs = OrderedSet()
  388. descriptions = []
  389. commands = []
  390. for action in actions_dict[primary_input]:
  391. inputs.update(OrderedSet(action['inputs']))
  392. outputs.update(OrderedSet(action['outputs']))
  393. descriptions.append(action['description'])
  394. commands.append(action['command'])
  395. # Add the custom build step for one input file.
  396. description = ', and also '.join(descriptions)
  397. command = '\r\n'.join(commands)
  398. _AddCustomBuildToolForMSVS(p, spec,
  399. primary_input=primary_input,
  400. inputs=inputs,
  401. outputs=outputs,
  402. description=description,
  403. cmd=command)
  404. def _RuleExpandPath(path, input_file):
  405. """Given the input file to which a rule applied, string substitute a path.
  406. Arguments:
  407. path: a path to string expand
  408. input_file: the file to which the rule applied.
  409. Returns:
  410. The string substituted path.
  411. """
  412. path = path.replace('$(InputName)',
  413. os.path.splitext(os.path.split(input_file)[1])[0])
  414. path = path.replace('$(InputDir)', os.path.dirname(input_file))
  415. path = path.replace('$(InputExt)',
  416. os.path.splitext(os.path.split(input_file)[1])[1])
  417. path = path.replace('$(InputFileName)', os.path.split(input_file)[1])
  418. path = path.replace('$(InputPath)', input_file)
  419. return path
  420. def _FindRuleTriggerFiles(rule, sources):
  421. """Find the list of files which a particular rule applies to.
  422. Arguments:
  423. rule: the rule in question
  424. sources: the set of all known source files for this project
  425. Returns:
  426. The list of sources that trigger a particular rule.
  427. """
  428. return rule.get('rule_sources', [])
  429. def _RuleInputsAndOutputs(rule, trigger_file):
  430. """Find the inputs and outputs generated by a rule.
  431. Arguments:
  432. rule: the rule in question.
  433. trigger_file: the main trigger for this rule.
  434. Returns:
  435. The pair of (inputs, outputs) involved in this rule.
  436. """
  437. raw_inputs = _FixPaths(rule.get('inputs', []))
  438. raw_outputs = _FixPaths(rule.get('outputs', []))
  439. inputs = OrderedSet()
  440. outputs = OrderedSet()
  441. inputs.add(trigger_file)
  442. for i in raw_inputs:
  443. inputs.add(_RuleExpandPath(i, trigger_file))
  444. for o in raw_outputs:
  445. outputs.add(_RuleExpandPath(o, trigger_file))
  446. return (inputs, outputs)
  447. def _GenerateNativeRulesForMSVS(p, rules, output_dir, spec, options):
  448. """Generate a native rules file.
  449. Arguments:
  450. p: the target project
  451. rules: the set of rules to include
  452. output_dir: the directory in which the project/gyp resides
  453. spec: the project dict
  454. options: global generator options
  455. """
  456. rules_filename = '%s%s.rules' % (spec['target_name'],
  457. options.suffix)
  458. rules_file = MSVSToolFile.Writer(os.path.join(output_dir, rules_filename),
  459. spec['target_name'])
  460. # Add each rule.
  461. for r in rules:
  462. rule_name = r['rule_name']
  463. rule_ext = r['extension']
  464. inputs = _FixPaths(r.get('inputs', []))
  465. outputs = _FixPaths(r.get('outputs', []))
  466. # Skip a rule with no action and no inputs.
  467. if 'action' not in r and not r.get('rule_sources', []):
  468. continue
  469. cmd = _BuildCommandLineForRule(spec, r, has_input_path=True,
  470. do_setup_env=True)
  471. rules_file.AddCustomBuildRule(name=rule_name,
  472. description=r.get('message', rule_name),
  473. extensions=[rule_ext],
  474. additional_dependencies=inputs,
  475. outputs=outputs,
  476. cmd=cmd)
  477. # Write out rules file.
  478. rules_file.WriteIfChanged()
  479. # Add rules file to project.
  480. p.AddToolFile(rules_filename)
  481. def _Cygwinify(path):
  482. path = path.replace('$(OutDir)', '$(OutDirCygwin)')
  483. path = path.replace('$(IntDir)', '$(IntDirCygwin)')
  484. return path
  485. def _GenerateExternalRules(rules, output_dir, spec,
  486. sources, options, actions_to_add):
  487. """Generate an external makefile to do a set of rules.
  488. Arguments:
  489. rules: the list of rules to include
  490. output_dir: path containing project and gyp files
  491. spec: project specification data
  492. sources: set of sources known
  493. options: global generator options
  494. actions_to_add: The list of actions we will add to.
  495. """
  496. filename = '%s_rules%s.mk' % (spec['target_name'], options.suffix)
  497. mk_file = gyp.common.WriteOnDiff(os.path.join(output_dir, filename))
  498. # Find cygwin style versions of some paths.
  499. mk_file.write('OutDirCygwin:=$(shell cygpath -u "$(OutDir)")\n')
  500. mk_file.write('IntDirCygwin:=$(shell cygpath -u "$(IntDir)")\n')
  501. # Gather stuff needed to emit all: target.
  502. all_inputs = OrderedSet()
  503. all_outputs = OrderedSet()
  504. all_output_dirs = OrderedSet()
  505. first_outputs = []
  506. for rule in rules:
  507. trigger_files = _FindRuleTriggerFiles(rule, sources)
  508. for tf in trigger_files:
  509. inputs, outputs = _RuleInputsAndOutputs(rule, tf)
  510. all_inputs.update(OrderedSet(inputs))
  511. all_outputs.update(OrderedSet(outputs))
  512. # Only use one target from each rule as the dependency for
  513. # 'all' so we don't try to build each rule multiple times.
  514. first_outputs.append(list(outputs)[0])
  515. # Get the unique output directories for this rule.
  516. output_dirs = [os.path.split(i)[0] for i in outputs]
  517. for od in output_dirs:
  518. all_output_dirs.add(od)
  519. first_outputs_cyg = [_Cygwinify(i) for i in first_outputs]
  520. # Write out all: target, including mkdir for each output directory.
  521. mk_file.write('all: %s\n' % ' '.join(first_outputs_cyg))
  522. for od in all_output_dirs:
  523. if od:
  524. mk_file.write('\tmkdir -p `cygpath -u "%s"`\n' % od)
  525. mk_file.write('\n')
  526. # Define how each output is generated.
  527. for rule in rules:
  528. trigger_files = _FindRuleTriggerFiles(rule, sources)
  529. for tf in trigger_files:
  530. # Get all the inputs and outputs for this rule for this trigger file.
  531. inputs, outputs = _RuleInputsAndOutputs(rule, tf)
  532. inputs = [_Cygwinify(i) for i in inputs]
  533. outputs = [_Cygwinify(i) for i in outputs]
  534. # Prepare the command line for this rule.
  535. cmd = [_RuleExpandPath(c, tf) for c in rule['action']]
  536. cmd = ['"%s"' % i for i in cmd]
  537. cmd = ' '.join(cmd)
  538. # Add it to the makefile.
  539. mk_file.write('%s: %s\n' % (' '.join(outputs), ' '.join(inputs)))
  540. mk_file.write('\t%s\n\n' % cmd)
  541. # Close up the file.
  542. mk_file.close()
  543. # Add makefile to list of sources.
  544. sources.add(filename)
  545. # Add a build action to call makefile.
  546. cmd = ['make',
  547. 'OutDir=$(OutDir)',
  548. 'IntDir=$(IntDir)',
  549. '-j', '${NUMBER_OF_PROCESSORS_PLUS_1}',
  550. '-f', filename]
  551. cmd = _BuildCommandLineForRuleRaw(spec, cmd, True, False, True, True)
  552. # Insert makefile as 0'th input, so it gets the action attached there,
  553. # as this is easier to understand from in the IDE.
  554. all_inputs = list(all_inputs)
  555. all_inputs.insert(0, filename)
  556. _AddActionStep(actions_to_add,
  557. inputs=_FixPaths(all_inputs),
  558. outputs=_FixPaths(all_outputs),
  559. description='Running external rules for %s' %
  560. spec['target_name'],
  561. command=cmd)
  562. def _EscapeEnvironmentVariableExpansion(s):
  563. """Escapes % characters.
  564. Escapes any % characters so that Windows-style environment variable
  565. expansions will leave them alone.
  566. See http://connect.microsoft.com/VisualStudio/feedback/details/106127/cl-d-name-text-containing-percentage-characters-doesnt-compile
  567. to understand why we have to do this.
  568. Args:
  569. s: The string to be escaped.
  570. Returns:
  571. The escaped string.
  572. """
  573. s = s.replace('%', '%%')
  574. return s
  575. quote_replacer_regex = re.compile(r'(\\*)"')
  576. def _EscapeCommandLineArgumentForMSVS(s):
  577. """Escapes a Windows command-line argument.
  578. So that the Win32 CommandLineToArgv function will turn the escaped result back
  579. into the original string.
  580. See http://msdn.microsoft.com/en-us/library/17w5ykft.aspx
  581. ("Parsing C++ Command-Line Arguments") to understand why we have to do
  582. this.
  583. Args:
  584. s: the string to be escaped.
  585. Returns:
  586. the escaped string.
  587. """
  588. def _Replace(match):
  589. # For a literal quote, CommandLineToArgv requires an odd number of
  590. # backslashes preceding it, and it produces half as many literal backslashes
  591. # (rounded down). So we need to produce 2n+1 backslashes.
  592. return 2 * match.group(1) + '\\"'
  593. # Escape all quotes so that they are interpreted literally.
  594. s = quote_replacer_regex.sub(_Replace, s)
  595. # Now add unescaped quotes so that any whitespace is interpreted literally.
  596. s = '"' + s + '"'
  597. return s
  598. delimiters_replacer_regex = re.compile(r'(\\*)([,;]+)')
  599. def _EscapeVCProjCommandLineArgListItem(s):
  600. """Escapes command line arguments for MSVS.
  601. The VCProj format stores string lists in a single string using commas and
  602. semi-colons as separators, which must be quoted if they are to be
  603. interpreted literally. However, command-line arguments may already have
  604. quotes, and the VCProj parser is ignorant of the backslash escaping
  605. convention used by CommandLineToArgv, so the command-line quotes and the
  606. VCProj quotes may not be the same quotes. So to store a general
  607. command-line argument in a VCProj list, we need to parse the existing
  608. quoting according to VCProj's convention and quote any delimiters that are
  609. not already quoted by that convention. The quotes that we add will also be
  610. seen by CommandLineToArgv, so if backslashes precede them then we also have
  611. to escape those backslashes according to the CommandLineToArgv
  612. convention.
  613. Args:
  614. s: the string to be escaped.
  615. Returns:
  616. the escaped string.
  617. """
  618. def _Replace(match):
  619. # For a non-literal quote, CommandLineToArgv requires an even number of
  620. # backslashes preceding it, and it produces half as many literal
  621. # backslashes. So we need to produce 2n backslashes.
  622. return 2 * match.group(1) + '"' + match.group(2) + '"'
  623. segments = s.split('"')
  624. # The unquoted segments are at the even-numbered indices.
  625. for i in range(0, len(segments), 2):
  626. segments[i] = delimiters_replacer_regex.sub(_Replace, segments[i])
  627. # Concatenate back into a single string
  628. s = '"'.join(segments)
  629. if len(segments) % 2 == 0:
  630. # String ends while still quoted according to VCProj's convention. This
  631. # means the delimiter and the next list item that follow this one in the
  632. # .vcproj file will be misinterpreted as part of this item. There is nothing
  633. # we can do about this. Adding an extra quote would correct the problem in
  634. # the VCProj but cause the same problem on the final command-line. Moving
  635. # the item to the end of the list does works, but that's only possible if
  636. # there's only one such item. Let's just warn the user.
  637. print >> sys.stderr, ('Warning: MSVS may misinterpret the odd number of ' +
  638. 'quotes in ' + s)
  639. return s
  640. def _EscapeCppDefineForMSVS(s):
  641. """Escapes a CPP define so that it will reach the compiler unaltered."""
  642. s = _EscapeEnvironmentVariableExpansion(s)
  643. s = _EscapeCommandLineArgumentForMSVS(s)
  644. s = _EscapeVCProjCommandLineArgListItem(s)
  645. # cl.exe replaces literal # characters with = in preprocesor definitions for
  646. # some reason. Octal-encode to work around that.
  647. s = s.replace('#', '\\%03o' % ord('#'))
  648. return s
  649. quote_replacer_regex2 = re.compile(r'(\\+)"')
  650. def _EscapeCommandLineArgumentForMSBuild(s):
  651. """Escapes a Windows command-line argument for use by MSBuild."""
  652. def _Replace(match):
  653. return (len(match.group(1)) / 2 * 4) * '\\' + '\\"'
  654. # Escape all quotes so that they are interpreted literally.
  655. s = quote_replacer_regex2.sub(_Replace, s)
  656. return s
  657. def _EscapeMSBuildSpecialCharacters(s):
  658. escape_dictionary = {
  659. '%': '%25',
  660. '$': '%24',
  661. '@': '%40',
  662. "'": '%27',
  663. ';': '%3B',
  664. '?': '%3F',
  665. '*': '%2A'
  666. }
  667. result = ''.join([escape_dictionary.get(c, c) for c in s])
  668. return result
  669. def _EscapeCppDefineForMSBuild(s):
  670. """Escapes a CPP define so that it will reach the compiler unaltered."""
  671. s = _EscapeEnvironmentVariableExpansion(s)
  672. s = _EscapeCommandLineArgumentForMSBuild(s)
  673. s = _EscapeMSBuildSpecialCharacters(s)
  674. # cl.exe replaces literal # characters with = in preprocesor definitions for
  675. # some reason. Octal-encode to work around that.
  676. s = s.replace('#', '\\%03o' % ord('#'))
  677. return s
  678. def _GenerateRulesForMSVS(p, output_dir, options, spec,
  679. sources, excluded_sources,
  680. actions_to_add):
  681. """Generate all the rules for a particular project.
  682. Arguments:
  683. p: the project
  684. output_dir: directory to emit rules to
  685. options: global options passed to the generator
  686. spec: the specification for this project
  687. sources: the set of all known source files in this project
  688. excluded_sources: the set of sources excluded from normal processing
  689. actions_to_add: deferred list of actions to add in
  690. """
  691. rules = spec.get('rules', [])
  692. rules_native = [r for r in rules if not int(r.get('msvs_external_rule', 0))]
  693. rules_external = [r for r in rules if int(r.get('msvs_external_rule', 0))]
  694. # Handle rules that use a native rules file.
  695. if rules_native:
  696. _GenerateNativeRulesForMSVS(p, rules_native, output_dir, spec, options)
  697. # Handle external rules (non-native rules).
  698. if rules_external:
  699. _GenerateExternalRules(rules_external, output_dir, spec,
  700. sources, options, actions_to_add)
  701. _AdjustSourcesForRules(rules, sources, excluded_sources, False)
  702. def _AdjustSourcesForRules(rules, sources, excluded_sources, is_msbuild):
  703. # Add outputs generated by each rule (if applicable).
  704. for rule in rules:
  705. # Add in the outputs from this rule.
  706. trigger_files = _FindRuleTriggerFiles(rule, sources)
  707. for trigger_file in trigger_files:
  708. # Remove trigger_file from excluded_sources to let the rule be triggered
  709. # (e.g. rule trigger ax_enums.idl is added to excluded_sources
  710. # because it's also in an action's inputs in the same project)
  711. excluded_sources.discard(_FixPath(trigger_file))
  712. # Done if not processing outputs as sources.
  713. if int(rule.get('process_outputs_as_sources', False)):
  714. inputs, outputs = _RuleInputsAndOutputs(rule, trigger_file)
  715. inputs = OrderedSet(_FixPaths(inputs))
  716. outputs = OrderedSet(_FixPaths(outputs))
  717. inputs.remove(_FixPath(trigger_file))
  718. sources.update(inputs)
  719. if not is_msbuild:
  720. excluded_sources.update(inputs)
  721. sources.update(outputs)
  722. def _FilterActionsFromExcluded(excluded_sources, actions_to_add):
  723. """Take inputs with actions attached out of the list of exclusions.
  724. Arguments:
  725. excluded_sources: list of source files not to be built.
  726. actions_to_add: dict of actions keyed on source file they're attached to.
  727. Returns:
  728. excluded_sources with files that have actions attached removed.
  729. """
  730. must_keep = OrderedSet(_FixPaths(actions_to_add.keys()))
  731. return [s for s in excluded_sources if s not in must_keep]
  732. def _GetDefaultConfiguration(spec):
  733. return spec['configurations'][spec['default_configuration']]
  734. def _GetGuidOfProject(proj_path, spec):
  735. """Get the guid for the project.
  736. Arguments:
  737. proj_path: Path of the vcproj or vcxproj file to generate.
  738. spec: The target dictionary containing the properties of the target.
  739. Returns:
  740. the guid.
  741. Raises:
  742. ValueError: if the specified GUID is invalid.
  743. """
  744. # Pluck out the default configuration.
  745. default_config = _GetDefaultConfiguration(spec)
  746. # Decide the guid of the project.
  747. guid = default_config.get('msvs_guid')
  748. if guid:
  749. if VALID_MSVS_GUID_CHARS.match(guid) is None:
  750. raise ValueError('Invalid MSVS guid: "%s". Must match regex: "%s".' %
  751. (guid, VALID_MSVS_GUID_CHARS.pattern))
  752. guid = '{%s}' % guid
  753. guid = guid or MSVSNew.MakeGuid(proj_path)
  754. return guid
  755. def _GetMsbuildToolsetOfProject(proj_path, spec, version):
  756. """Get the platform toolset for the project.
  757. Arguments:
  758. proj_path: Path of the vcproj or vcxproj file to generate.
  759. spec: The target dictionary containing the properties of the target.
  760. version: The MSVSVersion object.
  761. Returns:
  762. the platform toolset string or None.
  763. """
  764. # Pluck out the default configuration.
  765. default_config = _GetDefaultConfiguration(spec)
  766. toolset = default_config.get('msbuild_toolset')
  767. if not toolset and version.DefaultToolset():
  768. toolset = version.DefaultToolset()
  769. return toolset
  770. def _GenerateProject(project, options, version, generator_flags):
  771. """Generates a vcproj file.
  772. Arguments:
  773. project: the MSVSProject object.
  774. options: global generator options.
  775. version: the MSVSVersion object.
  776. generator_flags: dict of generator-specific flags.
  777. Returns:
  778. A list of source files that cannot be found on disk.
  779. """
  780. default_config = _GetDefaultConfiguration(project.spec)
  781. # Skip emitting anything if told to with msvs_existing_vcproj option.
  782. if default_config.get('msvs_existing_vcproj'):
  783. return []
  784. if version.UsesVcxproj():
  785. return _GenerateMSBuildProject(project, options, version, generator_flags)
  786. else:
  787. return _GenerateMSVSProject(project, options, version, generator_flags)
  788. # TODO: Avoid code duplication with _ValidateSourcesForOSX in make.py.
  789. def _ValidateSourcesForMSVSProject(spec, version):
  790. """Makes sure if duplicate basenames are not specified in the source list.
  791. Arguments:
  792. spec: The target dictionary containing the properties of the target.
  793. version: The VisualStudioVersion object.
  794. """
  795. # This validation should not be applied to MSVC2010 and later.
  796. assert not version.UsesVcxproj()
  797. # TODO: Check if MSVC allows this for loadable_module targets.
  798. if spec.get('type', None) not in ('static_library', 'shared_library'):
  799. return
  800. sources = spec.get('sources', [])
  801. basenames = {}
  802. for source in sources:
  803. name, ext = os.path.splitext(source)
  804. is_compiled_file = ext in [
  805. '.c', '.cc', '.cpp', '.cxx', '.m', '.mm', '.s', '.S']
  806. if not is_compiled_file:
  807. continue
  808. basename = os.path.basename(name) # Don't include extension.
  809. basenames.setdefault(basename, []).append(source)
  810. error = ''
  811. for basename, files in basenames.iteritems():
  812. if len(files) > 1:
  813. error += ' %s: %s\n' % (basename, ' '.join(files))
  814. if error:
  815. print('static library %s has several files with the same basename:\n' %
  816. spec['target_name'] + error + 'MSVC08 cannot handle that.')
  817. raise GypError('Duplicate basenames in sources section, see list above')
  818. def _GenerateMSVSProject(project, options, version, generator_flags):
  819. """Generates a .vcproj file. It may create .rules and .user files too.
  820. Arguments:
  821. project: The project object we will generate the file for.
  822. options: Global options passed to the generator.
  823. version: The VisualStudioVersion object.
  824. generator_flags: dict of generator-specific flags.
  825. """
  826. spec = project.spec
  827. gyp.common.EnsureDirExists(project.path)
  828. platforms = _GetUniquePlatforms(spec)
  829. p = MSVSProject.Writer(project.path, version, spec['target_name'],
  830. project.guid, platforms)
  831. # Get directory project file is in.
  832. project_dir = os.path.split(project.path)[0]
  833. gyp_path = _NormalizedSource(project.build_file)
  834. relative_path_of_gyp_file = gyp.common.RelativePath(gyp_path, project_dir)
  835. config_type = _GetMSVSConfigurationType(spec, project.build_file)
  836. for config_name, config in spec['configurations'].iteritems():
  837. _AddConfigurationToMSVSProject(p, spec, config_type, config_name, config)
  838. # MSVC08 and prior version cannot handle duplicate basenames in the same
  839. # target.
  840. # TODO: Take excluded sources into consideration if possible.
  841. _ValidateSourcesForMSVSProject(spec, version)
  842. # Prepare list of sources and excluded sources.
  843. gyp_file = os.path.split(project.build_file)[1]
  844. sources, excluded_sources = _PrepareListOfSources(spec, generator_flags,
  845. gyp_file)
  846. # Add rules.
  847. actions_to_add = {}
  848. _GenerateRulesForMSVS(p, project_dir, options, spec,
  849. sources, excluded_sources,
  850. actions_to_add)
  851. list_excluded = generator_flags.get('msvs_list_excluded_files', True)
  852. sources, excluded_sources, excluded_idl = (
  853. _AdjustSourcesAndConvertToFilterHierarchy(spec, options, project_dir,
  854. sources, excluded_sources,
  855. list_excluded, version))
  856. # Add in files.
  857. missing_sources = _VerifySourcesExist(sources, project_dir)
  858. p.AddFiles(sources)
  859. _AddToolFilesToMSVS(p, spec)
  860. _HandlePreCompiledHeaders(p, sources, spec)
  861. _AddActions(actions_to_add, spec, relative_path_of_gyp_file)
  862. _AddCopies(actions_to_add, spec)
  863. _WriteMSVSUserFile(project.path, version, spec)
  864. # NOTE: this stanza must appear after all actions have been decided.
  865. # Don't excluded sources with actions attached, or they won't run.
  866. excluded_sources = _FilterActionsFromExcluded(
  867. excluded_sources, actions_to_add)
  868. _ExcludeFilesFromBeingBuilt(p, spec, excluded_sources, excluded_idl,
  869. list_excluded)
  870. _AddAccumulatedActionsToMSVS(p, spec, actions_to_add)
  871. # Write it out.
  872. p.WriteIfChanged()
  873. return missing_sources
  874. def _GetUniquePlatforms(spec):
  875. """Returns the list of unique platforms for this spec, e.g ['win32', ...].
  876. Arguments:
  877. spec: The target dictionary containing the properties of the target.
  878. Returns:
  879. The MSVSUserFile object created.
  880. """
  881. # Gather list of unique platforms.
  882. platforms = OrderedSet()
  883. for configuration in spec['configurations']:
  884. platforms.add(_ConfigPlatform(spec['configurations'][configuration]))
  885. platforms = list(platforms)
  886. return platforms
  887. def _CreateMSVSUserFile(proj_path, version, spec):
  888. """Generates a .user file for the user running this Gyp program.
  889. Arguments:
  890. proj_path: The path of the project file being created. The .user file
  891. shares the same path (with an appropriate suffix).
  892. version: The VisualStudioVersion object.
  893. spec: The target dictionary containing the properties of the target.
  894. Returns:
  895. The MSVSUserFile object created.
  896. """
  897. (domain, username) = _GetDomainAndUserName()
  898. vcuser_filename = '.'.join([proj_path, domain, username, 'user'])
  899. user_file = MSVSUserFile.Writer(vcuser_filename, version,
  900. spec['target_name'])
  901. return user_file
  902. def _GetMSVSConfigurationType(spec, build_file):
  903. """Returns the configuration type for this project.
  904. It's a number defined by Microsoft. May raise an exception.
  905. Args:
  906. spec: The target dictionary containing the properties of the target.
  907. build_file: The path of the gyp file.
  908. Returns:
  909. An integer, the configuration type.
  910. """
  911. try:
  912. config_type = {
  913. 'executable': '1', # .exe
  914. 'shared_library': '2', # .dll
  915. 'loadable_module': '2', # .dll
  916. 'static_library': '4', # .lib
  917. 'none': '10', # Utility type
  918. }[spec['type']]
  919. except KeyError:
  920. if spec.get('type'):
  921. raise GypError('Target type %s is not a valid target type for '
  922. 'target %s in %s.' %
  923. (spec['type'], spec['target_name'], build_file))
  924. else:
  925. raise GypError('Missing type field for target %s in %s.' %
  926. (spec['target_name'], build_file))
  927. return config_type
  928. def _AddConfigurationToMSVSProject(p, spec, config_type, config_name, config):
  929. """Adds a configuration to the MSVS project.
  930. Many settings in a vcproj file are specific to a configuration. This
  931. function the main part of the vcproj file that's configuration specific.
  932. Arguments:
  933. p: The target project being generated.
  934. spec: The target dictionary containing the properties of the target.
  935. config_type: The configuration type, a number as defined by Microsoft.
  936. config_name: The name of the configuration.
  937. config: The dictionary that defines the special processing to be done
  938. for this configuration.
  939. """
  940. # Get the information for this configuration
  941. include_dirs, midl_include_dirs, resource_include_dirs = \
  942. _GetIncludeDirs(config)
  943. libraries = _GetLibraries(spec)
  944. library_dirs = _GetLibraryDirs(config)
  945. out_file, vc_tool, _ = _GetOutputFilePathAndTool(spec, msbuild=False)
  946. defines = _GetDefines(config)
  947. defines = [_EscapeCppDefineForMSVS(d) for d in defines]
  948. disabled_warnings = _GetDisabledWarnings(config)
  949. prebuild = config.get('msvs_prebuild')
  950. postbuild = config.get('msvs_postbuild')
  951. def_file = _GetModuleDefinition(spec)
  952. precompiled_header = config.get('msvs_precompiled_header')
  953. # Prepare the list of tools as a dictionary.
  954. tools = dict()
  955. # Add in user specified msvs_settings.
  956. msvs_settings = config.get('msvs_settings', {})
  957. MSVSSettings.ValidateMSVSSettings(msvs_settings)
  958. # Prevent default library inheritance from the environment.
  959. _ToolAppend(tools, 'VCLinkerTool', 'AdditionalDependencies', ['$(NOINHERIT)'])
  960. for tool in msvs_settings:
  961. settings = config['msvs_settings'][tool]
  962. for setting in settings:
  963. _ToolAppend(tools, tool, setting, settings[setting])
  964. # Add the information to the appropriate tool
  965. _ToolAppend(tools, 'VCCLCompilerTool',
  966. 'AdditionalIncludeDirectories', include_dirs)
  967. _ToolAppend(tools, 'VCMIDLTool',
  968. 'AdditionalIncludeDirectories', midl_include_dirs)
  969. _ToolAppend(tools, 'VCResourceCompilerTool',
  970. 'AdditionalIncludeDirectories', resource_include_dirs)
  971. # Add in libraries.
  972. _ToolAppend(tools, 'VCLinkerTool', 'AdditionalDependencies', libraries)
  973. _ToolAppend(tools, 'VCLinkerTool', 'AdditionalLibraryDirectories',
  974. library_dirs)
  975. if out_file:
  976. _ToolAppend(tools, vc_tool, 'OutputFile', out_file, only_if_unset=True)
  977. # Add defines.
  978. _ToolAppend(tools, 'VCCLCompilerTool', 'PreprocessorDefinitions', defines)
  979. _ToolAppend(tools, 'VCResourceCompilerTool', 'PreprocessorDefinitions',
  980. defines)
  981. # Change program database directory to prevent collisions.
  982. _ToolAppend(tools, 'VCCLCompilerTool', 'ProgramDataBaseFileName',
  983. '$(IntDir)$(ProjectName)\\vc80.pdb', only_if_unset=True)
  984. # Add disabled warnings.
  985. _ToolAppend(tools, 'VCCLCompilerTool',
  986. 'DisableSpecificWarnings', disabled_warnings)
  987. # Add Pre-build.
  988. _ToolAppend(tools, 'VCPreBuildEventTool', 'CommandLine', prebuild)
  989. # Add Post-build.
  990. _ToolAppend(tools, 'VCPostBuildEventTool', 'CommandLine', postbuild)
  991. # Turn on precompiled headers if appropriate.
  992. if precompiled_header:
  993. precompiled_header = os.path.split(precompiled_header)[1]
  994. _ToolAppend(tools, 'VCCLCompilerTool', 'UsePrecompiledHeader', '2')
  995. _ToolAppend(tools, 'VCCLCompilerTool',
  996. 'PrecompiledHeaderThrough', precompiled_header)
  997. _ToolAppend(tools, 'VCCLCompilerTool',
  998. 'ForcedIncludeFiles', precompiled_header)
  999. # Loadable modules don't generate import libraries;
  1000. # tell dependent projects to not expect one.
  1001. if spec['type'] == 'loadable_module':
  1002. _ToolAppend(tools, 'VCLinkerTool', 'IgnoreImportLibrary', 'true')
  1003. # Set the module definition file if any.
  1004. if def_file:
  1005. _ToolAppend(tools, 'VCLinkerTool', 'ModuleDefinitionFile', def_file)
  1006. _AddConfigurationToMSVS(p, spec, tools, config, config_type, config_name)
  1007. def _GetIncludeDirs(config):
  1008. """Returns the list of directories to be used for #include directives.
  1009. Arguments:
  1010. config: The dictionary that defines the special processing to be done
  1011. for this configuration.
  1012. Returns:
  1013. The list of directory paths.
  1014. """
  1015. # TODO(bradnelson): include_dirs should really be flexible enough not to
  1016. # require this sort of thing.
  1017. include_dirs = (
  1018. config.get('include_dirs', []) +
  1019. config.get('msvs_system_include_dirs', []))
  1020. midl_include_dirs = (
  1021. config.get('midl_include_dirs', []) +
  1022. config.get('msvs_system_include_dirs', []))
  1023. resource_include_dirs = config.get('resource_include_dirs', include_dirs)
  1024. include_dirs = _FixPaths(include_dirs)
  1025. midl_include_dirs = _FixPaths(midl_include_dirs)
  1026. resource_include_dirs = _FixPaths(resource_include_dirs)
  1027. return include_dirs, midl_include_dirs, resource_include_dirs
  1028. def _GetLibraryDirs(config):
  1029. """Returns the list of directories to be used for library search paths.
  1030. Arguments:
  1031. config: The dictionary that defines the special processing to be done
  1032. for this configuration.
  1033. Returns:
  1034. The list of directory paths.
  1035. """
  1036. library_dirs = config.get('library_dirs', [])
  1037. library_dirs = _FixPaths(library_dirs)
  1038. return library_dirs
  1039. def _GetLibraries(spec):
  1040. """Returns the list of libraries for this configuration.
  1041. Arguments:
  1042. spec: The target dictionary containing the properties of the target.
  1043. Returns:
  1044. The list of directory paths.
  1045. """
  1046. libraries = spec.get('libraries', [])
  1047. # Strip out -l, as it is not used on windows (but is needed so we can pass
  1048. # in libraries that are assumed to be in the default library path).
  1049. # Also remove duplicate entries, leaving only the last duplicate, while
  1050. # preserving order.
  1051. found = OrderedSet()
  1052. unique_libraries_list = []
  1053. for entry in reversed(libraries):
  1054. library = re.sub(r'^\-l', '', entry)
  1055. if not os.path.splitext(library)[1]:
  1056. library += '.lib'
  1057. if library not in found:
  1058. found.add(library)
  1059. unique_libraries_list.append(library)
  1060. unique_libraries_list.reverse()
  1061. return unique_libraries_list
  1062. def _GetOutputFilePathAndTool(spec, msbuild):
  1063. """Returns the path and tool to use for this target.
  1064. Figures out the path of the file this spec will create and the name of
  1065. the VC tool that will create it.
  1066. Arguments:
  1067. spec: The target dictionary containing the properties of the target.
  1068. Returns:
  1069. A triple of (file path, name of the vc tool, name of the msbuild tool)
  1070. """
  1071. # Select a name for the output file.
  1072. out_file = ''
  1073. vc_tool = ''
  1074. msbuild_tool = ''
  1075. output_file_map = {
  1076. 'executable': ('VCLinkerTool', 'Link', '$(OutDir)', '.exe'),
  1077. 'shared_library': ('VCLinkerTool', 'Link', '$(OutDir)', '.dll'),
  1078. 'loadable_module': ('VCLinkerTool', 'Link', '$(OutDir)', '.dll'),
  1079. 'static_library': ('VCLibrarianTool', 'Lib', '$(OutDir)lib\\', '.lib'),
  1080. }
  1081. output_file_props = output_file_map.get(spec['type'])
  1082. if output_file_props and int(spec.get('msvs_auto_output_file', 1)):
  1083. vc_tool, msbuild_tool, out_dir, suffix = output_file_props
  1084. if spec.get('standalone_static_library', 0):
  1085. out_dir = '$(OutDir)'
  1086. out_dir = spec.get('product_dir', out_dir)
  1087. product_extension = spec.get('product_extension')
  1088. if product_extension:
  1089. suffix = '.' + product_extension
  1090. elif msbuild:
  1091. suffix = '$(TargetExt)'
  1092. prefix = spec.get('product_prefix', '')
  1093. product_name = spec.get('product_name', '$(ProjectName)')
  1094. out_file = ntpath.join(out_dir, prefix + product_name + suffix)
  1095. return out_file, vc_tool, msbuild_tool
  1096. def _GetOutputTargetExt(spec):
  1097. """Returns the extension for this target, including the dot
  1098. If product_extension is specified, set target_extension to this to avoid
  1099. MSB8012, returns None otherwise. Ignores any target_extension settings in
  1100. the input files.
  1101. Arguments:
  1102. spec: The target dictionary containing the properties of the target.
  1103. Returns:
  1104. A string with the extension, or None
  1105. """
  1106. target_extension = spec.get('product_extension')
  1107. if target_extension:
  1108. return '.' + target_extension
  1109. return None
  1110. def _GetDefines(config):
  1111. """Returns the list of preprocessor definitions for this configuation.
  1112. Arguments:
  1113. config: The dictionary that defines the special processing to be done
  1114. for this configuration.
  1115. Returns:
  1116. The list of preprocessor definitions.
  1117. """
  1118. defines = []
  1119. for d in config.get('defines', []):
  1120. if type(d) == list:
  1121. fd = '='.join([str(dpart) for dpart in d])
  1122. else:
  1123. fd = str(d)
  1124. defines.append(fd)
  1125. return defines
  1126. def _GetDisabledWarnings(config):
  1127. return [str(i) for i in config.get('msvs_disabled_warnings', [])]
  1128. def _GetModuleDefinition(spec):
  1129. def_file = ''
  1130. if spec['type'] in ['shared_library', 'loadable_module', 'executable']:
  1131. def_files = [s for s in spec.get('sources', []) if s.endswith('.def')]
  1132. if len(def_files) == 1:
  1133. def_file = _FixPath(def_files[0])
  1134. elif def_files:
  1135. raise ValueError(
  1136. 'Multiple module definition files in one target, target %s lists '
  1137. 'multiple .def files: %s' % (
  1138. spec['target_name'], ' '.join(def_files)))
  1139. return def_file
  1140. def _ConvertToolsToExpectedForm(tools):
  1141. """Convert tools to a form expected by Visual Studio.
  1142. Arguments:
  1143. tools: A dictionary of settings; the tool name is the key.
  1144. Returns:
  1145. A list of Tool objects.
  1146. """
  1147. tool_list = []
  1148. for tool, settings in tools.iteritems():
  1149. # Collapse settings with lists.
  1150. settings_fixed = {}
  1151. for setting, value in settings.iteritems():
  1152. if type(value) == list:
  1153. if ((tool == 'VCLinkerTool' and
  1154. setting == 'AdditionalDependencies') or
  1155. setting == 'AdditionalOptions'):
  1156. settings_fixed[setting] = ' '.join(value)
  1157. else:
  1158. settings_fixed[setting] = ';'.join(value)
  1159. else:
  1160. settings_fixed[setting] = value
  1161. # Add in this tool.
  1162. tool_list.append(MSVSProject.Tool(tool, settings_fixed))
  1163. return tool_list
  1164. def _AddConfigurationToMSVS(p, spec, tools, config, config_type, config_name):
  1165. """Add to the project file the configuration specified by config.
  1166. Arguments:
  1167. p: The target project being generated.
  1168. spec: the target project dict.
  1169. tools: A dictionary of settings; the tool name is the key.
  1170. config: The dictionary that defines the special processing to be done
  1171. for this configuration.
  1172. config_type: The configuration type, a number as defined by Microsoft.
  1173. config_name: The name of the configuration.
  1174. """
  1175. attributes = _Ge