wsba-hockey 1.0.3__py3-none-any.whl → 1.0.5__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (131) hide show
  1. wsba_hockey/__init__.py +1 -1
  2. wsba_hockey/data_pipelines.py +183 -0
  3. wsba_hockey/evidence/weakside-breakout/node_modules/duckdb/vendor.py +146 -0
  4. wsba_hockey/evidence/weakside-breakout/node_modules/flatted/python/flatted.py +149 -0
  5. wsba_hockey/evidence/weakside-breakout/node_modules/flatted/python/test.py +63 -0
  6. wsba_hockey/evidence/weakside-breakout/node_modules/node-gyp/gyp/gyp_main.py +45 -0
  7. wsba_hockey/evidence/weakside-breakout/node_modules/node-gyp/gyp/pylib/gyp/MSVSNew.py +367 -0
  8. wsba_hockey/evidence/weakside-breakout/node_modules/node-gyp/gyp/pylib/gyp/MSVSProject.py +206 -0
  9. wsba_hockey/evidence/weakside-breakout/node_modules/node-gyp/gyp/pylib/gyp/MSVSSettings.py +1270 -0
  10. wsba_hockey/evidence/weakside-breakout/node_modules/node-gyp/gyp/pylib/gyp/MSVSSettings_test.py +1547 -0
  11. wsba_hockey/evidence/weakside-breakout/node_modules/node-gyp/gyp/pylib/gyp/MSVSToolFile.py +59 -0
  12. wsba_hockey/evidence/weakside-breakout/node_modules/node-gyp/gyp/pylib/gyp/MSVSUserFile.py +153 -0
  13. wsba_hockey/evidence/weakside-breakout/node_modules/node-gyp/gyp/pylib/gyp/MSVSUtil.py +271 -0
  14. wsba_hockey/evidence/weakside-breakout/node_modules/node-gyp/gyp/pylib/gyp/MSVSVersion.py +574 -0
  15. wsba_hockey/evidence/weakside-breakout/node_modules/node-gyp/gyp/pylib/gyp/__init__.py +690 -0
  16. wsba_hockey/evidence/weakside-breakout/node_modules/node-gyp/gyp/pylib/gyp/common.py +661 -0
  17. wsba_hockey/evidence/weakside-breakout/node_modules/node-gyp/gyp/pylib/gyp/common_test.py +78 -0
  18. wsba_hockey/evidence/weakside-breakout/node_modules/node-gyp/gyp/pylib/gyp/easy_xml.py +165 -0
  19. wsba_hockey/evidence/weakside-breakout/node_modules/node-gyp/gyp/pylib/gyp/easy_xml_test.py +109 -0
  20. wsba_hockey/evidence/weakside-breakout/node_modules/node-gyp/gyp/pylib/gyp/flock_tool.py +55 -0
  21. wsba_hockey/evidence/weakside-breakout/node_modules/node-gyp/gyp/pylib/gyp/generator/__init__.py +0 -0
  22. wsba_hockey/evidence/weakside-breakout/node_modules/node-gyp/gyp/pylib/gyp/generator/analyzer.py +808 -0
  23. wsba_hockey/evidence/weakside-breakout/node_modules/node-gyp/gyp/pylib/gyp/generator/android.py +1173 -0
  24. wsba_hockey/evidence/weakside-breakout/node_modules/node-gyp/gyp/pylib/gyp/generator/cmake.py +1321 -0
  25. wsba_hockey/evidence/weakside-breakout/node_modules/node-gyp/gyp/pylib/gyp/generator/compile_commands_json.py +120 -0
  26. wsba_hockey/evidence/weakside-breakout/node_modules/node-gyp/gyp/pylib/gyp/generator/dump_dependency_json.py +103 -0
  27. wsba_hockey/evidence/weakside-breakout/node_modules/node-gyp/gyp/pylib/gyp/generator/eclipse.py +464 -0
  28. wsba_hockey/evidence/weakside-breakout/node_modules/node-gyp/gyp/pylib/gyp/generator/gypd.py +89 -0
  29. wsba_hockey/evidence/weakside-breakout/node_modules/node-gyp/gyp/pylib/gyp/generator/gypsh.py +58 -0
  30. wsba_hockey/evidence/weakside-breakout/node_modules/node-gyp/gyp/pylib/gyp/generator/make.py +2714 -0
  31. wsba_hockey/evidence/weakside-breakout/node_modules/node-gyp/gyp/pylib/gyp/generator/msvs.py +3981 -0
  32. wsba_hockey/evidence/weakside-breakout/node_modules/node-gyp/gyp/pylib/gyp/generator/msvs_test.py +44 -0
  33. wsba_hockey/evidence/weakside-breakout/node_modules/node-gyp/gyp/pylib/gyp/generator/ninja.py +2936 -0
  34. wsba_hockey/evidence/weakside-breakout/node_modules/node-gyp/gyp/pylib/gyp/generator/ninja_test.py +55 -0
  35. wsba_hockey/evidence/weakside-breakout/node_modules/node-gyp/gyp/pylib/gyp/generator/xcode.py +1394 -0
  36. wsba_hockey/evidence/weakside-breakout/node_modules/node-gyp/gyp/pylib/gyp/generator/xcode_test.py +25 -0
  37. wsba_hockey/evidence/weakside-breakout/node_modules/node-gyp/gyp/pylib/gyp/input.py +3130 -0
  38. wsba_hockey/evidence/weakside-breakout/node_modules/node-gyp/gyp/pylib/gyp/input_test.py +98 -0
  39. wsba_hockey/evidence/weakside-breakout/node_modules/node-gyp/gyp/pylib/gyp/mac_tool.py +771 -0
  40. wsba_hockey/evidence/weakside-breakout/node_modules/node-gyp/gyp/pylib/gyp/msvs_emulation.py +1271 -0
  41. wsba_hockey/evidence/weakside-breakout/node_modules/node-gyp/gyp/pylib/gyp/ninja_syntax.py +174 -0
  42. wsba_hockey/evidence/weakside-breakout/node_modules/node-gyp/gyp/pylib/gyp/simple_copy.py +61 -0
  43. wsba_hockey/evidence/weakside-breakout/node_modules/node-gyp/gyp/pylib/gyp/win_tool.py +374 -0
  44. wsba_hockey/evidence/weakside-breakout/node_modules/node-gyp/gyp/pylib/gyp/xcode_emulation.py +1939 -0
  45. wsba_hockey/evidence/weakside-breakout/node_modules/node-gyp/gyp/pylib/gyp/xcode_ninja.py +302 -0
  46. wsba_hockey/evidence/weakside-breakout/node_modules/node-gyp/gyp/pylib/gyp/xcodeproj_file.py +3197 -0
  47. wsba_hockey/evidence/weakside-breakout/node_modules/node-gyp/gyp/pylib/gyp/xml_fix.py +65 -0
  48. wsba_hockey/evidence/weakside-breakout/node_modules/node-gyp/gyp/test_gyp.py +261 -0
  49. wsba_hockey/evidence/weakside-breakout/node_modules/node-gyp/gyp/tools/graphviz.py +102 -0
  50. wsba_hockey/evidence/weakside-breakout/node_modules/node-gyp/gyp/tools/pretty_gyp.py +156 -0
  51. wsba_hockey/evidence/weakside-breakout/node_modules/node-gyp/gyp/tools/pretty_sln.py +181 -0
  52. wsba_hockey/evidence/weakside-breakout/node_modules/node-gyp/gyp/tools/pretty_vcproj.py +339 -0
  53. wsba_hockey/evidence/weakside-breakout/node_modules/node-gyp/test/fixtures/test-charmap.py +31 -0
  54. wsba_hockey/evidence/weakside-breakout/node_modules/node-gyp/update-gyp.py +64 -0
  55. wsba_hockey/evidence/weakside-breakout/node_modules/sqlite3/node_modules/node-gyp/gyp/gyp_main.py +45 -0
  56. wsba_hockey/evidence/weakside-breakout/node_modules/sqlite3/node_modules/node-gyp/gyp/pylib/gyp/MSVSNew.py +367 -0
  57. wsba_hockey/evidence/weakside-breakout/node_modules/sqlite3/node_modules/node-gyp/gyp/pylib/gyp/MSVSProject.py +206 -0
  58. wsba_hockey/evidence/weakside-breakout/node_modules/sqlite3/node_modules/node-gyp/gyp/pylib/gyp/MSVSSettings.py +1270 -0
  59. wsba_hockey/evidence/weakside-breakout/node_modules/sqlite3/node_modules/node-gyp/gyp/pylib/gyp/MSVSSettings_test.py +1547 -0
  60. wsba_hockey/evidence/weakside-breakout/node_modules/sqlite3/node_modules/node-gyp/gyp/pylib/gyp/MSVSToolFile.py +59 -0
  61. wsba_hockey/evidence/weakside-breakout/node_modules/sqlite3/node_modules/node-gyp/gyp/pylib/gyp/MSVSUserFile.py +153 -0
  62. wsba_hockey/evidence/weakside-breakout/node_modules/sqlite3/node_modules/node-gyp/gyp/pylib/gyp/MSVSUtil.py +271 -0
  63. wsba_hockey/evidence/weakside-breakout/node_modules/sqlite3/node_modules/node-gyp/gyp/pylib/gyp/MSVSVersion.py +574 -0
  64. wsba_hockey/evidence/weakside-breakout/node_modules/sqlite3/node_modules/node-gyp/gyp/pylib/gyp/__init__.py +666 -0
  65. wsba_hockey/evidence/weakside-breakout/node_modules/sqlite3/node_modules/node-gyp/gyp/pylib/gyp/common.py +654 -0
  66. wsba_hockey/evidence/weakside-breakout/node_modules/sqlite3/node_modules/node-gyp/gyp/pylib/gyp/common_test.py +78 -0
  67. wsba_hockey/evidence/weakside-breakout/node_modules/sqlite3/node_modules/node-gyp/gyp/pylib/gyp/easy_xml.py +165 -0
  68. wsba_hockey/evidence/weakside-breakout/node_modules/sqlite3/node_modules/node-gyp/gyp/pylib/gyp/easy_xml_test.py +109 -0
  69. wsba_hockey/evidence/weakside-breakout/node_modules/sqlite3/node_modules/node-gyp/gyp/pylib/gyp/flock_tool.py +55 -0
  70. wsba_hockey/evidence/weakside-breakout/node_modules/sqlite3/node_modules/node-gyp/gyp/pylib/gyp/generator/__init__.py +0 -0
  71. wsba_hockey/evidence/weakside-breakout/node_modules/sqlite3/node_modules/node-gyp/gyp/pylib/gyp/generator/analyzer.py +808 -0
  72. wsba_hockey/evidence/weakside-breakout/node_modules/sqlite3/node_modules/node-gyp/gyp/pylib/gyp/generator/android.py +1173 -0
  73. wsba_hockey/evidence/weakside-breakout/node_modules/sqlite3/node_modules/node-gyp/gyp/pylib/gyp/generator/cmake.py +1321 -0
  74. wsba_hockey/evidence/weakside-breakout/node_modules/sqlite3/node_modules/node-gyp/gyp/pylib/gyp/generator/compile_commands_json.py +120 -0
  75. wsba_hockey/evidence/weakside-breakout/node_modules/sqlite3/node_modules/node-gyp/gyp/pylib/gyp/generator/dump_dependency_json.py +103 -0
  76. wsba_hockey/evidence/weakside-breakout/node_modules/sqlite3/node_modules/node-gyp/gyp/pylib/gyp/generator/eclipse.py +464 -0
  77. wsba_hockey/evidence/weakside-breakout/node_modules/sqlite3/node_modules/node-gyp/gyp/pylib/gyp/generator/gypd.py +89 -0
  78. wsba_hockey/evidence/weakside-breakout/node_modules/sqlite3/node_modules/node-gyp/gyp/pylib/gyp/generator/gypsh.py +58 -0
  79. wsba_hockey/evidence/weakside-breakout/node_modules/sqlite3/node_modules/node-gyp/gyp/pylib/gyp/generator/make.py +2518 -0
  80. wsba_hockey/evidence/weakside-breakout/node_modules/sqlite3/node_modules/node-gyp/gyp/pylib/gyp/generator/msvs.py +3978 -0
  81. wsba_hockey/evidence/weakside-breakout/node_modules/sqlite3/node_modules/node-gyp/gyp/pylib/gyp/generator/msvs_test.py +44 -0
  82. wsba_hockey/evidence/weakside-breakout/node_modules/sqlite3/node_modules/node-gyp/gyp/pylib/gyp/generator/ninja.py +2936 -0
  83. wsba_hockey/evidence/weakside-breakout/node_modules/sqlite3/node_modules/node-gyp/gyp/pylib/gyp/generator/ninja_test.py +55 -0
  84. wsba_hockey/evidence/weakside-breakout/node_modules/sqlite3/node_modules/node-gyp/gyp/pylib/gyp/generator/xcode.py +1394 -0
  85. wsba_hockey/evidence/weakside-breakout/node_modules/sqlite3/node_modules/node-gyp/gyp/pylib/gyp/generator/xcode_test.py +25 -0
  86. wsba_hockey/evidence/weakside-breakout/node_modules/sqlite3/node_modules/node-gyp/gyp/pylib/gyp/input.py +3137 -0
  87. wsba_hockey/evidence/weakside-breakout/node_modules/sqlite3/node_modules/node-gyp/gyp/pylib/gyp/input_test.py +98 -0
  88. wsba_hockey/evidence/weakside-breakout/node_modules/sqlite3/node_modules/node-gyp/gyp/pylib/gyp/mac_tool.py +771 -0
  89. wsba_hockey/evidence/weakside-breakout/node_modules/sqlite3/node_modules/node-gyp/gyp/pylib/gyp/msvs_emulation.py +1271 -0
  90. wsba_hockey/evidence/weakside-breakout/node_modules/sqlite3/node_modules/node-gyp/gyp/pylib/gyp/ninja_syntax.py +174 -0
  91. wsba_hockey/evidence/weakside-breakout/node_modules/sqlite3/node_modules/node-gyp/gyp/pylib/gyp/simple_copy.py +61 -0
  92. wsba_hockey/evidence/weakside-breakout/node_modules/sqlite3/node_modules/node-gyp/gyp/pylib/gyp/win_tool.py +374 -0
  93. wsba_hockey/evidence/weakside-breakout/node_modules/sqlite3/node_modules/node-gyp/gyp/pylib/gyp/xcode_emulation.py +1939 -0
  94. wsba_hockey/evidence/weakside-breakout/node_modules/sqlite3/node_modules/node-gyp/gyp/pylib/gyp/xcode_ninja.py +302 -0
  95. wsba_hockey/evidence/weakside-breakout/node_modules/sqlite3/node_modules/node-gyp/gyp/pylib/gyp/xcodeproj_file.py +3197 -0
  96. wsba_hockey/evidence/weakside-breakout/node_modules/sqlite3/node_modules/node-gyp/gyp/pylib/gyp/xml_fix.py +65 -0
  97. wsba_hockey/evidence/weakside-breakout/node_modules/sqlite3/node_modules/node-gyp/gyp/setup.py +42 -0
  98. wsba_hockey/evidence/weakside-breakout/node_modules/sqlite3/node_modules/node-gyp/gyp/test_gyp.py +260 -0
  99. wsba_hockey/evidence/weakside-breakout/node_modules/sqlite3/node_modules/node-gyp/gyp/tools/graphviz.py +102 -0
  100. wsba_hockey/evidence/weakside-breakout/node_modules/sqlite3/node_modules/node-gyp/gyp/tools/pretty_gyp.py +156 -0
  101. wsba_hockey/evidence/weakside-breakout/node_modules/sqlite3/node_modules/node-gyp/gyp/tools/pretty_sln.py +181 -0
  102. wsba_hockey/evidence/weakside-breakout/node_modules/sqlite3/node_modules/node-gyp/gyp/tools/pretty_vcproj.py +339 -0
  103. wsba_hockey/evidence/weakside-breakout/node_modules/sqlite3/node_modules/node-gyp/test/fixtures/test-charmap.py +31 -0
  104. wsba_hockey/evidence/weakside-breakout/node_modules/sqlite3/node_modules/node-gyp/update-gyp.py +46 -0
  105. wsba_hockey/evidence/weakside-breakout/wsba_nhl_apps/wsba_nhl_apps/game_stats/app.py +400 -0
  106. wsba_hockey/evidence/weakside-breakout/wsba_nhl_apps/wsba_nhl_apps/game_stats/name_fix.py +47 -0
  107. wsba_hockey/evidence/weakside-breakout/wsba_nhl_apps/wsba_nhl_apps/heatmaps/app.py +108 -0
  108. wsba_hockey/evidence/weakside-breakout/wsba_nhl_apps/wsba_nhl_apps/heatmaps/plot.py +93 -0
  109. wsba_hockey/evidence/weakside-breakout/wsba_nhl_apps/wsba_nhl_apps/heatmaps/rink_plot.py +245 -0
  110. wsba_hockey/evidence/weakside-breakout/wsba_nhl_apps/wsba_nhl_apps/matchups/app.py +145 -0
  111. wsba_hockey/evidence/weakside-breakout/wsba_nhl_apps/wsba_nhl_apps/matchups/plot.py +77 -0
  112. wsba_hockey/evidence/weakside-breakout/wsba_nhl_apps/wsba_nhl_apps/matchups/rink_plot.py +245 -0
  113. wsba_hockey/evidence/weakside-breakout/wsba_nhl_apps/wsba_nhl_apps/pbp/app.py +389 -0
  114. wsba_hockey/evidence/weakside-breakout/wsba_nhl_apps/wsba_nhl_apps/pbp/plot.py +70 -0
  115. wsba_hockey/evidence/weakside-breakout/wsba_nhl_apps/wsba_nhl_apps/pbp/rink_plot.py +245 -0
  116. wsba_hockey/evidence/weakside-breakout/wsba_nhl_apps/wsba_nhl_apps/skater/app.py +110 -0
  117. wsba_hockey/evidence/weakside-breakout/wsba_nhl_apps/wsba_nhl_apps/skater/plot.py +58 -0
  118. wsba_hockey/evidence/weakside-breakout/wsba_nhl_apps/wsba_nhl_apps/skater/rink_plot.py +245 -0
  119. wsba_hockey/tools/agg.py +243 -54
  120. wsba_hockey/tools/plotting.py +25 -25
  121. wsba_hockey/tools/scraping.py +154 -263
  122. wsba_hockey/tools/xg_model.py +369 -315
  123. wsba_hockey/workspace.py +22 -117
  124. wsba_hockey/wsba_main.py +499 -167
  125. {wsba_hockey-1.0.3.dist-info → wsba_hockey-1.0.5.dist-info}/METADATA +1 -1
  126. wsba_hockey-1.0.5.dist-info/RECORD +135 -0
  127. {wsba_hockey-1.0.3.dist-info → wsba_hockey-1.0.5.dist-info}/WHEEL +1 -1
  128. wsba_hockey/stats/calculate_viz/shot_impact.py +0 -2
  129. wsba_hockey-1.0.3.dist-info/RECORD +0 -19
  130. {wsba_hockey-1.0.3.dist-info → wsba_hockey-1.0.5.dist-info}/licenses/LICENSE +0 -0
  131. {wsba_hockey-1.0.3.dist-info → wsba_hockey-1.0.5.dist-info}/top_level.txt +0 -0
@@ -0,0 +1,3978 @@
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
+
5
+
6
+ import ntpath
7
+ import os
8
+ import posixpath
9
+ import re
10
+ import subprocess
11
+ import sys
12
+
13
+ from collections import OrderedDict
14
+
15
+ import gyp.common
16
+ import gyp.easy_xml as easy_xml
17
+ import gyp.generator.ninja as ninja_generator
18
+ import gyp.MSVSNew as MSVSNew
19
+ import gyp.MSVSProject as MSVSProject
20
+ import gyp.MSVSSettings as MSVSSettings
21
+ import gyp.MSVSToolFile as MSVSToolFile
22
+ import gyp.MSVSUserFile as MSVSUserFile
23
+ import gyp.MSVSUtil as MSVSUtil
24
+ import gyp.MSVSVersion as MSVSVersion
25
+ from gyp.common import GypError
26
+ from gyp.common import OrderedSet
27
+
28
+
29
+ # Regular expression for validating Visual Studio GUIDs. If the GUID
30
+ # contains lowercase hex letters, MSVS will be fine. However,
31
+ # IncrediBuild BuildConsole will parse the solution file, but then
32
+ # silently skip building the target causing hard to track down errors.
33
+ # Note that this only happens with the BuildConsole, and does not occur
34
+ # if IncrediBuild is executed from inside Visual Studio. This regex
35
+ # validates that the string looks like a GUID with all uppercase hex
36
+ # letters.
37
+ VALID_MSVS_GUID_CHARS = re.compile(r"^[A-F0-9\-]+$")
38
+
39
+ generator_supports_multiple_toolsets = gyp.common.CrossCompileRequested()
40
+
41
+ generator_default_variables = {
42
+ "DRIVER_PREFIX": "",
43
+ "DRIVER_SUFFIX": ".sys",
44
+ "EXECUTABLE_PREFIX": "",
45
+ "EXECUTABLE_SUFFIX": ".exe",
46
+ "STATIC_LIB_PREFIX": "",
47
+ "SHARED_LIB_PREFIX": "",
48
+ "STATIC_LIB_SUFFIX": ".lib",
49
+ "SHARED_LIB_SUFFIX": ".dll",
50
+ "INTERMEDIATE_DIR": "$(IntDir)",
51
+ "SHARED_INTERMEDIATE_DIR": "$(OutDir)/obj/global_intermediate",
52
+ "OS": "win",
53
+ "PRODUCT_DIR": "$(OutDir)",
54
+ "LIB_DIR": "$(OutDir)lib",
55
+ "RULE_INPUT_ROOT": "$(InputName)",
56
+ "RULE_INPUT_DIRNAME": "$(InputDir)",
57
+ "RULE_INPUT_EXT": "$(InputExt)",
58
+ "RULE_INPUT_NAME": "$(InputFileName)",
59
+ "RULE_INPUT_PATH": "$(InputPath)",
60
+ "CONFIGURATION_NAME": "$(ConfigurationName)",
61
+ }
62
+
63
+
64
+ # The msvs specific sections that hold paths
65
+ generator_additional_path_sections = [
66
+ "msvs_cygwin_dirs",
67
+ "msvs_props",
68
+ ]
69
+
70
+
71
+ generator_additional_non_configuration_keys = [
72
+ "msvs_cygwin_dirs",
73
+ "msvs_cygwin_shell",
74
+ "msvs_large_pdb",
75
+ "msvs_shard",
76
+ "msvs_external_builder",
77
+ "msvs_external_builder_out_dir",
78
+ "msvs_external_builder_build_cmd",
79
+ "msvs_external_builder_clean_cmd",
80
+ "msvs_external_builder_clcompile_cmd",
81
+ "msvs_enable_winrt",
82
+ "msvs_requires_importlibrary",
83
+ "msvs_enable_winphone",
84
+ "msvs_application_type_revision",
85
+ "msvs_target_platform_version",
86
+ "msvs_target_platform_minversion",
87
+ ]
88
+
89
+ generator_filelist_paths = None
90
+
91
+ # List of precompiled header related keys.
92
+ precomp_keys = [
93
+ "msvs_precompiled_header",
94
+ "msvs_precompiled_source",
95
+ ]
96
+
97
+
98
+ cached_username = None
99
+
100
+
101
+ cached_domain = None
102
+
103
+
104
+ # TODO(gspencer): Switch the os.environ calls to be
105
+ # win32api.GetDomainName() and win32api.GetUserName() once the
106
+ # python version in depot_tools has been updated to work on Vista
107
+ # 64-bit.
108
+ def _GetDomainAndUserName():
109
+ if sys.platform not in ("win32", "cygwin"):
110
+ return ("DOMAIN", "USERNAME")
111
+ global cached_username
112
+ global cached_domain
113
+ if not cached_domain or not cached_username:
114
+ domain = os.environ.get("USERDOMAIN")
115
+ username = os.environ.get("USERNAME")
116
+ if not domain or not username:
117
+ call = subprocess.Popen(
118
+ ["net", "config", "Workstation"], stdout=subprocess.PIPE
119
+ )
120
+ config = call.communicate()[0].decode("utf-8")
121
+ username_re = re.compile(r"^User name\s+(\S+)", re.MULTILINE)
122
+ username_match = username_re.search(config)
123
+ if username_match:
124
+ username = username_match.group(1)
125
+ domain_re = re.compile(r"^Logon domain\s+(\S+)", re.MULTILINE)
126
+ domain_match = domain_re.search(config)
127
+ if domain_match:
128
+ domain = domain_match.group(1)
129
+ cached_domain = domain
130
+ cached_username = username
131
+ return (cached_domain, cached_username)
132
+
133
+
134
+ fixpath_prefix = None
135
+
136
+
137
+ def _NormalizedSource(source):
138
+ """Normalize the path.
139
+
140
+ But not if that gets rid of a variable, as this may expand to something
141
+ larger than one directory.
142
+
143
+ Arguments:
144
+ source: The path to be normalize.d
145
+
146
+ Returns:
147
+ The normalized path.
148
+ """
149
+ normalized = os.path.normpath(source)
150
+ if source.count("$") == normalized.count("$"):
151
+ source = normalized
152
+ return source
153
+
154
+
155
+ def _FixPath(path, separator="\\"):
156
+ """Convert paths to a form that will make sense in a vcproj file.
157
+
158
+ Arguments:
159
+ path: The path to convert, may contain / etc.
160
+ Returns:
161
+ The path with all slashes made into backslashes.
162
+ """
163
+ if (
164
+ fixpath_prefix
165
+ and path
166
+ and not os.path.isabs(path)
167
+ and not path[0] == "$"
168
+ and not _IsWindowsAbsPath(path)
169
+ ):
170
+ path = os.path.join(fixpath_prefix, path)
171
+ if separator == "\\":
172
+ path = path.replace("/", "\\")
173
+ path = _NormalizedSource(path)
174
+ if separator == "/":
175
+ path = path.replace("\\", "/")
176
+ if path and path[-1] == separator:
177
+ path = path[:-1]
178
+ return path
179
+
180
+
181
+ def _IsWindowsAbsPath(path):
182
+ """
183
+ On Cygwin systems Python needs a little help determining if a path
184
+ is an absolute Windows path or not, so that
185
+ it does not treat those as relative, which results in bad paths like:
186
+ '..\\C:\\<some path>\\some_source_code_file.cc'
187
+ """
188
+ return path.startswith("c:") or path.startswith("C:")
189
+
190
+
191
+ def _FixPaths(paths, separator="\\"):
192
+ """Fix each of the paths of the list."""
193
+ return [_FixPath(i, separator) for i in paths]
194
+
195
+
196
+ def _ConvertSourcesToFilterHierarchy(
197
+ sources, prefix=None, excluded=None, list_excluded=True, msvs_version=None
198
+ ):
199
+ """Converts a list split source file paths into a vcproj folder hierarchy.
200
+
201
+ Arguments:
202
+ sources: A list of source file paths split.
203
+ prefix: A list of source file path layers meant to apply to each of sources.
204
+ excluded: A set of excluded files.
205
+ msvs_version: A MSVSVersion object.
206
+
207
+ Returns:
208
+ A hierarchy of filenames and MSVSProject.Filter objects that matches the
209
+ layout of the source tree.
210
+ For example:
211
+ _ConvertSourcesToFilterHierarchy([['a', 'bob1.c'], ['b', 'bob2.c']],
212
+ prefix=['joe'])
213
+ -->
214
+ [MSVSProject.Filter('a', contents=['joe\\a\\bob1.c']),
215
+ MSVSProject.Filter('b', contents=['joe\\b\\bob2.c'])]
216
+ """
217
+ if not prefix:
218
+ prefix = []
219
+ result = []
220
+ excluded_result = []
221
+ folders = OrderedDict()
222
+ # Gather files into the final result, excluded, or folders.
223
+ for s in sources:
224
+ if len(s) == 1:
225
+ filename = _NormalizedSource("\\".join(prefix + s))
226
+ if filename in excluded:
227
+ excluded_result.append(filename)
228
+ else:
229
+ result.append(filename)
230
+ elif msvs_version and not msvs_version.UsesVcxproj():
231
+ # For MSVS 2008 and earlier, we need to process all files before walking
232
+ # the sub folders.
233
+ if not folders.get(s[0]):
234
+ folders[s[0]] = []
235
+ folders[s[0]].append(s[1:])
236
+ else:
237
+ contents = _ConvertSourcesToFilterHierarchy(
238
+ [s[1:]],
239
+ prefix + [s[0]],
240
+ excluded=excluded,
241
+ list_excluded=list_excluded,
242
+ msvs_version=msvs_version,
243
+ )
244
+ contents = MSVSProject.Filter(s[0], contents=contents)
245
+ result.append(contents)
246
+ # Add a folder for excluded files.
247
+ if excluded_result and list_excluded:
248
+ excluded_folder = MSVSProject.Filter(
249
+ "_excluded_files", contents=excluded_result
250
+ )
251
+ result.append(excluded_folder)
252
+
253
+ if msvs_version and msvs_version.UsesVcxproj():
254
+ return result
255
+
256
+ # Populate all the folders.
257
+ for f in folders:
258
+ contents = _ConvertSourcesToFilterHierarchy(
259
+ folders[f],
260
+ prefix=prefix + [f],
261
+ excluded=excluded,
262
+ list_excluded=list_excluded,
263
+ msvs_version=msvs_version,
264
+ )
265
+ contents = MSVSProject.Filter(f, contents=contents)
266
+ result.append(contents)
267
+ return result
268
+
269
+
270
+ def _ToolAppend(tools, tool_name, setting, value, only_if_unset=False):
271
+ if not value:
272
+ return
273
+ _ToolSetOrAppend(tools, tool_name, setting, value, only_if_unset)
274
+
275
+
276
+ def _ToolSetOrAppend(tools, tool_name, setting, value, only_if_unset=False):
277
+ # TODO(bradnelson): ugly hack, fix this more generally!!!
278
+ if "Directories" in setting or "Dependencies" in setting:
279
+ if type(value) == str:
280
+ value = value.replace("/", "\\")
281
+ else:
282
+ value = [i.replace("/", "\\") for i in value]
283
+ if not tools.get(tool_name):
284
+ tools[tool_name] = dict()
285
+ tool = tools[tool_name]
286
+ if "CompileAsWinRT" == setting:
287
+ return
288
+ if tool.get(setting):
289
+ if only_if_unset:
290
+ return
291
+ if type(tool[setting]) == list and type(value) == list:
292
+ tool[setting] += value
293
+ else:
294
+ raise TypeError(
295
+ 'Appending "%s" to a non-list setting "%s" for tool "%s" is '
296
+ "not allowed, previous value: %s"
297
+ % (value, setting, tool_name, str(tool[setting]))
298
+ )
299
+ else:
300
+ tool[setting] = value
301
+
302
+
303
+ def _ConfigTargetVersion(config_data):
304
+ return config_data.get("msvs_target_version", "Windows7")
305
+
306
+
307
+ def _ConfigPlatform(config_data):
308
+ return config_data.get("msvs_configuration_platform", "Win32")
309
+
310
+
311
+ def _ConfigBaseName(config_name, platform_name):
312
+ if config_name.endswith("_" + platform_name):
313
+ return config_name[0 : -len(platform_name) - 1]
314
+ else:
315
+ return config_name
316
+
317
+
318
+ def _ConfigFullName(config_name, config_data):
319
+ platform_name = _ConfigPlatform(config_data)
320
+ return f"{_ConfigBaseName(config_name, platform_name)}|{platform_name}"
321
+
322
+
323
+ def _ConfigWindowsTargetPlatformVersion(config_data, version):
324
+ target_ver = config_data.get("msvs_windows_target_platform_version")
325
+ if target_ver and re.match(r"^\d+", target_ver):
326
+ return target_ver
327
+ config_ver = config_data.get("msvs_windows_sdk_version")
328
+ vers = [config_ver] if config_ver else version.compatible_sdks
329
+ for ver in vers:
330
+ for key in [
331
+ r"HKLM\Software\Microsoft\Microsoft SDKs\Windows\%s",
332
+ r"HKLM\Software\Wow6432Node\Microsoft\Microsoft SDKs\Windows\%s",
333
+ ]:
334
+ sdk_dir = MSVSVersion._RegistryGetValue(key % ver, "InstallationFolder")
335
+ if not sdk_dir:
336
+ continue
337
+ version = MSVSVersion._RegistryGetValue(key % ver, "ProductVersion") or ""
338
+ # Find a matching entry in sdk_dir\include.
339
+ expected_sdk_dir = r"%s\include" % sdk_dir
340
+ names = sorted(
341
+ (
342
+ x
343
+ for x in (
344
+ os.listdir(expected_sdk_dir)
345
+ if os.path.isdir(expected_sdk_dir)
346
+ else []
347
+ )
348
+ if x.startswith(version)
349
+ ),
350
+ reverse=True,
351
+ )
352
+ if names:
353
+ return names[0]
354
+ else:
355
+ print(
356
+ "Warning: No include files found for detected "
357
+ "Windows SDK version %s" % (version),
358
+ file=sys.stdout,
359
+ )
360
+
361
+
362
+ def _BuildCommandLineForRuleRaw(
363
+ spec, cmd, cygwin_shell, has_input_path, quote_cmd, do_setup_env
364
+ ):
365
+
366
+ if [x for x in cmd if "$(InputDir)" in x]:
367
+ input_dir_preamble = (
368
+ "set INPUTDIR=$(InputDir)\n"
369
+ "if NOT DEFINED INPUTDIR set INPUTDIR=.\\\n"
370
+ "set INPUTDIR=%INPUTDIR:~0,-1%\n"
371
+ )
372
+ else:
373
+ input_dir_preamble = ""
374
+
375
+ if cygwin_shell:
376
+ # Find path to cygwin.
377
+ cygwin_dir = _FixPath(spec.get("msvs_cygwin_dirs", ["."])[0])
378
+ # Prepare command.
379
+ direct_cmd = cmd
380
+ direct_cmd = [
381
+ i.replace("$(IntDir)", '`cygpath -m "${INTDIR}"`') for i in direct_cmd
382
+ ]
383
+ direct_cmd = [
384
+ i.replace("$(OutDir)", '`cygpath -m "${OUTDIR}"`') for i in direct_cmd
385
+ ]
386
+ direct_cmd = [
387
+ i.replace("$(InputDir)", '`cygpath -m "${INPUTDIR}"`') for i in direct_cmd
388
+ ]
389
+ if has_input_path:
390
+ direct_cmd = [
391
+ i.replace("$(InputPath)", '`cygpath -m "${INPUTPATH}"`')
392
+ for i in direct_cmd
393
+ ]
394
+ direct_cmd = ['\\"%s\\"' % i.replace('"', '\\\\\\"') for i in direct_cmd]
395
+ # direct_cmd = gyp.common.EncodePOSIXShellList(direct_cmd)
396
+ direct_cmd = " ".join(direct_cmd)
397
+ # TODO(quote): regularize quoting path names throughout the module
398
+ cmd = ""
399
+ if do_setup_env:
400
+ cmd += 'call "$(ProjectDir)%(cygwin_dir)s\\setup_env.bat" && '
401
+ cmd += "set CYGWIN=nontsec&& "
402
+ if direct_cmd.find("NUMBER_OF_PROCESSORS") >= 0:
403
+ cmd += "set /a NUMBER_OF_PROCESSORS_PLUS_1=%%NUMBER_OF_PROCESSORS%%+1&& "
404
+ if direct_cmd.find("INTDIR") >= 0:
405
+ cmd += "set INTDIR=$(IntDir)&& "
406
+ if direct_cmd.find("OUTDIR") >= 0:
407
+ cmd += "set OUTDIR=$(OutDir)&& "
408
+ if has_input_path and direct_cmd.find("INPUTPATH") >= 0:
409
+ cmd += "set INPUTPATH=$(InputPath) && "
410
+ cmd += 'bash -c "%(cmd)s"'
411
+ cmd = cmd % {"cygwin_dir": cygwin_dir, "cmd": direct_cmd}
412
+ return input_dir_preamble + cmd
413
+ else:
414
+ # Convert cat --> type to mimic unix.
415
+ if cmd[0] == "cat":
416
+ command = ["type"]
417
+ else:
418
+ command = [cmd[0].replace("/", "\\")]
419
+ # Add call before command to ensure that commands can be tied together one
420
+ # after the other without aborting in Incredibuild, since IB makes a bat
421
+ # file out of the raw command string, and some commands (like python) are
422
+ # actually batch files themselves.
423
+ command.insert(0, "call")
424
+ # Fix the paths
425
+ # TODO(quote): This is a really ugly heuristic, and will miss path fixing
426
+ # for arguments like "--arg=path" or "/opt:path".
427
+ # If the argument starts with a slash or dash, it's probably a command line
428
+ # switch
429
+ # Return the path with forward slashes because the command using it might
430
+ # not support backslashes.
431
+ arguments = [i if (i[:1] in "/-") else _FixPath(i, "/") for i in cmd[1:]]
432
+ arguments = [i.replace("$(InputDir)", "%INPUTDIR%") for i in arguments]
433
+ arguments = [MSVSSettings.FixVCMacroSlashes(i) for i in arguments]
434
+ if quote_cmd:
435
+ # Support a mode for using cmd directly.
436
+ # Convert any paths to native form (first element is used directly).
437
+ # TODO(quote): regularize quoting path names throughout the module
438
+ arguments = ['"%s"' % i for i in arguments]
439
+ # Collapse into a single command.
440
+ return input_dir_preamble + " ".join(command + arguments)
441
+
442
+
443
+ def _BuildCommandLineForRule(spec, rule, has_input_path, do_setup_env):
444
+ # Currently this weird argument munging is used to duplicate the way a
445
+ # python script would need to be run as part of the chrome tree.
446
+ # Eventually we should add some sort of rule_default option to set this
447
+ # per project. For now the behavior chrome needs is the default.
448
+ mcs = rule.get("msvs_cygwin_shell")
449
+ if mcs is None:
450
+ mcs = int(spec.get("msvs_cygwin_shell", 1))
451
+ elif isinstance(mcs, str):
452
+ mcs = int(mcs)
453
+ quote_cmd = int(rule.get("msvs_quote_cmd", 1))
454
+ return _BuildCommandLineForRuleRaw(
455
+ spec, rule["action"], mcs, has_input_path, quote_cmd, do_setup_env=do_setup_env
456
+ )
457
+
458
+
459
+ def _AddActionStep(actions_dict, inputs, outputs, description, command):
460
+ """Merge action into an existing list of actions.
461
+
462
+ Care must be taken so that actions which have overlapping inputs either don't
463
+ get assigned to the same input, or get collapsed into one.
464
+
465
+ Arguments:
466
+ actions_dict: dictionary keyed on input name, which maps to a list of
467
+ dicts describing the actions attached to that input file.
468
+ inputs: list of inputs
469
+ outputs: list of outputs
470
+ description: description of the action
471
+ command: command line to execute
472
+ """
473
+ # Require there to be at least one input (call sites will ensure this).
474
+ assert inputs
475
+
476
+ action = {
477
+ "inputs": inputs,
478
+ "outputs": outputs,
479
+ "description": description,
480
+ "command": command,
481
+ }
482
+
483
+ # Pick where to stick this action.
484
+ # While less than optimal in terms of build time, attach them to the first
485
+ # input for now.
486
+ chosen_input = inputs[0]
487
+
488
+ # Add it there.
489
+ if chosen_input not in actions_dict:
490
+ actions_dict[chosen_input] = []
491
+ actions_dict[chosen_input].append(action)
492
+
493
+
494
+ def _AddCustomBuildToolForMSVS(
495
+ p, spec, primary_input, inputs, outputs, description, cmd
496
+ ):
497
+ """Add a custom build tool to execute something.
498
+
499
+ Arguments:
500
+ p: the target project
501
+ spec: the target project dict
502
+ primary_input: input file to attach the build tool to
503
+ inputs: list of inputs
504
+ outputs: list of outputs
505
+ description: description of the action
506
+ cmd: command line to execute
507
+ """
508
+ inputs = _FixPaths(inputs)
509
+ outputs = _FixPaths(outputs)
510
+ tool = MSVSProject.Tool(
511
+ "VCCustomBuildTool",
512
+ {
513
+ "Description": description,
514
+ "AdditionalDependencies": ";".join(inputs),
515
+ "Outputs": ";".join(outputs),
516
+ "CommandLine": cmd,
517
+ },
518
+ )
519
+ # Add to the properties of primary input for each config.
520
+ for config_name, c_data in spec["configurations"].items():
521
+ p.AddFileConfig(
522
+ _FixPath(primary_input), _ConfigFullName(config_name, c_data), tools=[tool]
523
+ )
524
+
525
+
526
+ def _AddAccumulatedActionsToMSVS(p, spec, actions_dict):
527
+ """Add actions accumulated into an actions_dict, merging as needed.
528
+
529
+ Arguments:
530
+ p: the target project
531
+ spec: the target project dict
532
+ actions_dict: dictionary keyed on input name, which maps to a list of
533
+ dicts describing the actions attached to that input file.
534
+ """
535
+ for primary_input in actions_dict:
536
+ inputs = OrderedSet()
537
+ outputs = OrderedSet()
538
+ descriptions = []
539
+ commands = []
540
+ for action in actions_dict[primary_input]:
541
+ inputs.update(OrderedSet(action["inputs"]))
542
+ outputs.update(OrderedSet(action["outputs"]))
543
+ descriptions.append(action["description"])
544
+ commands.append(action["command"])
545
+ # Add the custom build step for one input file.
546
+ description = ", and also ".join(descriptions)
547
+ command = "\r\n".join(commands)
548
+ _AddCustomBuildToolForMSVS(
549
+ p,
550
+ spec,
551
+ primary_input=primary_input,
552
+ inputs=inputs,
553
+ outputs=outputs,
554
+ description=description,
555
+ cmd=command,
556
+ )
557
+
558
+
559
+ def _RuleExpandPath(path, input_file):
560
+ """Given the input file to which a rule applied, string substitute a path.
561
+
562
+ Arguments:
563
+ path: a path to string expand
564
+ input_file: the file to which the rule applied.
565
+ Returns:
566
+ The string substituted path.
567
+ """
568
+ path = path.replace(
569
+ "$(InputName)", os.path.splitext(os.path.split(input_file)[1])[0]
570
+ )
571
+ path = path.replace("$(InputDir)", os.path.dirname(input_file))
572
+ path = path.replace(
573
+ "$(InputExt)", os.path.splitext(os.path.split(input_file)[1])[1]
574
+ )
575
+ path = path.replace("$(InputFileName)", os.path.split(input_file)[1])
576
+ path = path.replace("$(InputPath)", input_file)
577
+ return path
578
+
579
+
580
+ def _FindRuleTriggerFiles(rule, sources):
581
+ """Find the list of files which a particular rule applies to.
582
+
583
+ Arguments:
584
+ rule: the rule in question
585
+ sources: the set of all known source files for this project
586
+ Returns:
587
+ The list of sources that trigger a particular rule.
588
+ """
589
+ return rule.get("rule_sources", [])
590
+
591
+
592
+ def _RuleInputsAndOutputs(rule, trigger_file):
593
+ """Find the inputs and outputs generated by a rule.
594
+
595
+ Arguments:
596
+ rule: the rule in question.
597
+ trigger_file: the main trigger for this rule.
598
+ Returns:
599
+ The pair of (inputs, outputs) involved in this rule.
600
+ """
601
+ raw_inputs = _FixPaths(rule.get("inputs", []))
602
+ raw_outputs = _FixPaths(rule.get("outputs", []))
603
+ inputs = OrderedSet()
604
+ outputs = OrderedSet()
605
+ inputs.add(trigger_file)
606
+ for i in raw_inputs:
607
+ inputs.add(_RuleExpandPath(i, trigger_file))
608
+ for o in raw_outputs:
609
+ outputs.add(_RuleExpandPath(o, trigger_file))
610
+ return (inputs, outputs)
611
+
612
+
613
+ def _GenerateNativeRulesForMSVS(p, rules, output_dir, spec, options):
614
+ """Generate a native rules file.
615
+
616
+ Arguments:
617
+ p: the target project
618
+ rules: the set of rules to include
619
+ output_dir: the directory in which the project/gyp resides
620
+ spec: the project dict
621
+ options: global generator options
622
+ """
623
+ rules_filename = "{}{}.rules".format(spec["target_name"], options.suffix)
624
+ rules_file = MSVSToolFile.Writer(
625
+ os.path.join(output_dir, rules_filename), spec["target_name"]
626
+ )
627
+ # Add each rule.
628
+ for r in rules:
629
+ rule_name = r["rule_name"]
630
+ rule_ext = r["extension"]
631
+ inputs = _FixPaths(r.get("inputs", []))
632
+ outputs = _FixPaths(r.get("outputs", []))
633
+ # Skip a rule with no action and no inputs.
634
+ if "action" not in r and not r.get("rule_sources", []):
635
+ continue
636
+ cmd = _BuildCommandLineForRule(spec, r, has_input_path=True, do_setup_env=True)
637
+ rules_file.AddCustomBuildRule(
638
+ name=rule_name,
639
+ description=r.get("message", rule_name),
640
+ extensions=[rule_ext],
641
+ additional_dependencies=inputs,
642
+ outputs=outputs,
643
+ cmd=cmd,
644
+ )
645
+ # Write out rules file.
646
+ rules_file.WriteIfChanged()
647
+
648
+ # Add rules file to project.
649
+ p.AddToolFile(rules_filename)
650
+
651
+
652
+ def _Cygwinify(path):
653
+ path = path.replace("$(OutDir)", "$(OutDirCygwin)")
654
+ path = path.replace("$(IntDir)", "$(IntDirCygwin)")
655
+ return path
656
+
657
+
658
+ def _GenerateExternalRules(rules, output_dir, spec, sources, options, actions_to_add):
659
+ """Generate an external makefile to do a set of rules.
660
+
661
+ Arguments:
662
+ rules: the list of rules to include
663
+ output_dir: path containing project and gyp files
664
+ spec: project specification data
665
+ sources: set of sources known
666
+ options: global generator options
667
+ actions_to_add: The list of actions we will add to.
668
+ """
669
+ filename = "{}_rules{}.mk".format(spec["target_name"], options.suffix)
670
+ mk_file = gyp.common.WriteOnDiff(os.path.join(output_dir, filename))
671
+ # Find cygwin style versions of some paths.
672
+ mk_file.write('OutDirCygwin:=$(shell cygpath -u "$(OutDir)")\n')
673
+ mk_file.write('IntDirCygwin:=$(shell cygpath -u "$(IntDir)")\n')
674
+ # Gather stuff needed to emit all: target.
675
+ all_inputs = OrderedSet()
676
+ all_outputs = OrderedSet()
677
+ all_output_dirs = OrderedSet()
678
+ first_outputs = []
679
+ for rule in rules:
680
+ trigger_files = _FindRuleTriggerFiles(rule, sources)
681
+ for tf in trigger_files:
682
+ inputs, outputs = _RuleInputsAndOutputs(rule, tf)
683
+ all_inputs.update(OrderedSet(inputs))
684
+ all_outputs.update(OrderedSet(outputs))
685
+ # Only use one target from each rule as the dependency for
686
+ # 'all' so we don't try to build each rule multiple times.
687
+ first_outputs.append(list(outputs)[0])
688
+ # Get the unique output directories for this rule.
689
+ output_dirs = [os.path.split(i)[0] for i in outputs]
690
+ for od in output_dirs:
691
+ all_output_dirs.add(od)
692
+ first_outputs_cyg = [_Cygwinify(i) for i in first_outputs]
693
+ # Write out all: target, including mkdir for each output directory.
694
+ mk_file.write("all: %s\n" % " ".join(first_outputs_cyg))
695
+ for od in all_output_dirs:
696
+ if od:
697
+ mk_file.write('\tmkdir -p `cygpath -u "%s"`\n' % od)
698
+ mk_file.write("\n")
699
+ # Define how each output is generated.
700
+ for rule in rules:
701
+ trigger_files = _FindRuleTriggerFiles(rule, sources)
702
+ for tf in trigger_files:
703
+ # Get all the inputs and outputs for this rule for this trigger file.
704
+ inputs, outputs = _RuleInputsAndOutputs(rule, tf)
705
+ inputs = [_Cygwinify(i) for i in inputs]
706
+ outputs = [_Cygwinify(i) for i in outputs]
707
+ # Prepare the command line for this rule.
708
+ cmd = [_RuleExpandPath(c, tf) for c in rule["action"]]
709
+ cmd = ['"%s"' % i for i in cmd]
710
+ cmd = " ".join(cmd)
711
+ # Add it to the makefile.
712
+ mk_file.write("{}: {}\n".format(" ".join(outputs), " ".join(inputs)))
713
+ mk_file.write("\t%s\n\n" % cmd)
714
+ # Close up the file.
715
+ mk_file.close()
716
+
717
+ # Add makefile to list of sources.
718
+ sources.add(filename)
719
+ # Add a build action to call makefile.
720
+ cmd = [
721
+ "make",
722
+ "OutDir=$(OutDir)",
723
+ "IntDir=$(IntDir)",
724
+ "-j",
725
+ "${NUMBER_OF_PROCESSORS_PLUS_1}",
726
+ "-f",
727
+ filename,
728
+ ]
729
+ cmd = _BuildCommandLineForRuleRaw(spec, cmd, True, False, True, True)
730
+ # Insert makefile as 0'th input, so it gets the action attached there,
731
+ # as this is easier to understand from in the IDE.
732
+ all_inputs = list(all_inputs)
733
+ all_inputs.insert(0, filename)
734
+ _AddActionStep(
735
+ actions_to_add,
736
+ inputs=_FixPaths(all_inputs),
737
+ outputs=_FixPaths(all_outputs),
738
+ description="Running external rules for %s" % spec["target_name"],
739
+ command=cmd,
740
+ )
741
+
742
+
743
+ def _EscapeEnvironmentVariableExpansion(s):
744
+ """Escapes % characters.
745
+
746
+ Escapes any % characters so that Windows-style environment variable
747
+ expansions will leave them alone.
748
+ See http://connect.microsoft.com/VisualStudio/feedback/details/106127/cl-d-name-text-containing-percentage-characters-doesnt-compile
749
+ to understand why we have to do this.
750
+
751
+ Args:
752
+ s: The string to be escaped.
753
+
754
+ Returns:
755
+ The escaped string.
756
+ """ # noqa: E731,E123,E501
757
+ s = s.replace("%", "%%")
758
+ return s
759
+
760
+
761
+ quote_replacer_regex = re.compile(r'(\\*)"')
762
+
763
+
764
+ def _EscapeCommandLineArgumentForMSVS(s):
765
+ """Escapes a Windows command-line argument.
766
+
767
+ So that the Win32 CommandLineToArgv function will turn the escaped result back
768
+ into the original string.
769
+ See http://msdn.microsoft.com/en-us/library/17w5ykft.aspx
770
+ ("Parsing C++ Command-Line Arguments") to understand why we have to do
771
+ this.
772
+
773
+ Args:
774
+ s: the string to be escaped.
775
+ Returns:
776
+ the escaped string.
777
+ """
778
+
779
+ def _Replace(match):
780
+ # For a literal quote, CommandLineToArgv requires an odd number of
781
+ # backslashes preceding it, and it produces half as many literal backslashes
782
+ # (rounded down). So we need to produce 2n+1 backslashes.
783
+ return 2 * match.group(1) + '\\"'
784
+
785
+ # Escape all quotes so that they are interpreted literally.
786
+ s = quote_replacer_regex.sub(_Replace, s)
787
+ # Now add unescaped quotes so that any whitespace is interpreted literally.
788
+ s = '"' + s + '"'
789
+ return s
790
+
791
+
792
+ delimiters_replacer_regex = re.compile(r"(\\*)([,;]+)")
793
+
794
+
795
+ def _EscapeVCProjCommandLineArgListItem(s):
796
+ """Escapes command line arguments for MSVS.
797
+
798
+ The VCProj format stores string lists in a single string using commas and
799
+ semi-colons as separators, which must be quoted if they are to be
800
+ interpreted literally. However, command-line arguments may already have
801
+ quotes, and the VCProj parser is ignorant of the backslash escaping
802
+ convention used by CommandLineToArgv, so the command-line quotes and the
803
+ VCProj quotes may not be the same quotes. So to store a general
804
+ command-line argument in a VCProj list, we need to parse the existing
805
+ quoting according to VCProj's convention and quote any delimiters that are
806
+ not already quoted by that convention. The quotes that we add will also be
807
+ seen by CommandLineToArgv, so if backslashes precede them then we also have
808
+ to escape those backslashes according to the CommandLineToArgv
809
+ convention.
810
+
811
+ Args:
812
+ s: the string to be escaped.
813
+ Returns:
814
+ the escaped string.
815
+ """
816
+
817
+ def _Replace(match):
818
+ # For a non-literal quote, CommandLineToArgv requires an even number of
819
+ # backslashes preceding it, and it produces half as many literal
820
+ # backslashes. So we need to produce 2n backslashes.
821
+ return 2 * match.group(1) + '"' + match.group(2) + '"'
822
+
823
+ segments = s.split('"')
824
+ # The unquoted segments are at the even-numbered indices.
825
+ for i in range(0, len(segments), 2):
826
+ segments[i] = delimiters_replacer_regex.sub(_Replace, segments[i])
827
+ # Concatenate back into a single string
828
+ s = '"'.join(segments)
829
+ if len(segments) % 2 == 0:
830
+ # String ends while still quoted according to VCProj's convention. This
831
+ # means the delimiter and the next list item that follow this one in the
832
+ # .vcproj file will be misinterpreted as part of this item. There is nothing
833
+ # we can do about this. Adding an extra quote would correct the problem in
834
+ # the VCProj but cause the same problem on the final command-line. Moving
835
+ # the item to the end of the list does works, but that's only possible if
836
+ # there's only one such item. Let's just warn the user.
837
+ print(
838
+ "Warning: MSVS may misinterpret the odd number of " + "quotes in " + s,
839
+ file=sys.stderr,
840
+ )
841
+ return s
842
+
843
+
844
+ def _EscapeCppDefineForMSVS(s):
845
+ """Escapes a CPP define so that it will reach the compiler unaltered."""
846
+ s = _EscapeEnvironmentVariableExpansion(s)
847
+ s = _EscapeCommandLineArgumentForMSVS(s)
848
+ s = _EscapeVCProjCommandLineArgListItem(s)
849
+ # cl.exe replaces literal # characters with = in preprocessor definitions for
850
+ # some reason. Octal-encode to work around that.
851
+ s = s.replace("#", "\\%03o" % ord("#"))
852
+ return s
853
+
854
+
855
+ quote_replacer_regex2 = re.compile(r'(\\+)"')
856
+
857
+
858
+ def _EscapeCommandLineArgumentForMSBuild(s):
859
+ """Escapes a Windows command-line argument for use by MSBuild."""
860
+
861
+ def _Replace(match):
862
+ return (len(match.group(1)) / 2 * 4) * "\\" + '\\"'
863
+
864
+ # Escape all quotes so that they are interpreted literally.
865
+ s = quote_replacer_regex2.sub(_Replace, s)
866
+ return s
867
+
868
+
869
+ def _EscapeMSBuildSpecialCharacters(s):
870
+ escape_dictionary = {
871
+ "%": "%25",
872
+ "$": "%24",
873
+ "@": "%40",
874
+ "'": "%27",
875
+ ";": "%3B",
876
+ "?": "%3F",
877
+ "*": "%2A",
878
+ }
879
+ result = "".join([escape_dictionary.get(c, c) for c in s])
880
+ return result
881
+
882
+
883
+ def _EscapeCppDefineForMSBuild(s):
884
+ """Escapes a CPP define so that it will reach the compiler unaltered."""
885
+ s = _EscapeEnvironmentVariableExpansion(s)
886
+ s = _EscapeCommandLineArgumentForMSBuild(s)
887
+ s = _EscapeMSBuildSpecialCharacters(s)
888
+ # cl.exe replaces literal # characters with = in preprocessor definitions for
889
+ # some reason. Octal-encode to work around that.
890
+ s = s.replace("#", "\\%03o" % ord("#"))
891
+ return s
892
+
893
+
894
+ def _GenerateRulesForMSVS(
895
+ p, output_dir, options, spec, sources, excluded_sources, actions_to_add
896
+ ):
897
+ """Generate all the rules for a particular project.
898
+
899
+ Arguments:
900
+ p: the project
901
+ output_dir: directory to emit rules to
902
+ options: global options passed to the generator
903
+ spec: the specification for this project
904
+ sources: the set of all known source files in this project
905
+ excluded_sources: the set of sources excluded from normal processing
906
+ actions_to_add: deferred list of actions to add in
907
+ """
908
+ rules = spec.get("rules", [])
909
+ rules_native = [r for r in rules if not int(r.get("msvs_external_rule", 0))]
910
+ rules_external = [r for r in rules if int(r.get("msvs_external_rule", 0))]
911
+
912
+ # Handle rules that use a native rules file.
913
+ if rules_native:
914
+ _GenerateNativeRulesForMSVS(p, rules_native, output_dir, spec, options)
915
+
916
+ # Handle external rules (non-native rules).
917
+ if rules_external:
918
+ _GenerateExternalRules(
919
+ rules_external, output_dir, spec, sources, options, actions_to_add
920
+ )
921
+ _AdjustSourcesForRules(rules, sources, excluded_sources, False)
922
+
923
+
924
+ def _AdjustSourcesForRules(rules, sources, excluded_sources, is_msbuild):
925
+ # Add outputs generated by each rule (if applicable).
926
+ for rule in rules:
927
+ # Add in the outputs from this rule.
928
+ trigger_files = _FindRuleTriggerFiles(rule, sources)
929
+ for trigger_file in trigger_files:
930
+ # Remove trigger_file from excluded_sources to let the rule be triggered
931
+ # (e.g. rule trigger ax_enums.idl is added to excluded_sources
932
+ # because it's also in an action's inputs in the same project)
933
+ excluded_sources.discard(_FixPath(trigger_file))
934
+ # Done if not processing outputs as sources.
935
+ if int(rule.get("process_outputs_as_sources", False)):
936
+ inputs, outputs = _RuleInputsAndOutputs(rule, trigger_file)
937
+ inputs = OrderedSet(_FixPaths(inputs))
938
+ outputs = OrderedSet(_FixPaths(outputs))
939
+ inputs.remove(_FixPath(trigger_file))
940
+ sources.update(inputs)
941
+ if not is_msbuild:
942
+ excluded_sources.update(inputs)
943
+ sources.update(outputs)
944
+
945
+
946
+ def _FilterActionsFromExcluded(excluded_sources, actions_to_add):
947
+ """Take inputs with actions attached out of the list of exclusions.
948
+
949
+ Arguments:
950
+ excluded_sources: list of source files not to be built.
951
+ actions_to_add: dict of actions keyed on source file they're attached to.
952
+ Returns:
953
+ excluded_sources with files that have actions attached removed.
954
+ """
955
+ must_keep = OrderedSet(_FixPaths(actions_to_add.keys()))
956
+ return [s for s in excluded_sources if s not in must_keep]
957
+
958
+
959
+ def _GetDefaultConfiguration(spec):
960
+ return spec["configurations"][spec["default_configuration"]]
961
+
962
+
963
+ def _GetGuidOfProject(proj_path, spec):
964
+ """Get the guid for the project.
965
+
966
+ Arguments:
967
+ proj_path: Path of the vcproj or vcxproj file to generate.
968
+ spec: The target dictionary containing the properties of the target.
969
+ Returns:
970
+ the guid.
971
+ Raises:
972
+ ValueError: if the specified GUID is invalid.
973
+ """
974
+ # Pluck out the default configuration.
975
+ default_config = _GetDefaultConfiguration(spec)
976
+ # Decide the guid of the project.
977
+ guid = default_config.get("msvs_guid")
978
+ if guid:
979
+ if VALID_MSVS_GUID_CHARS.match(guid) is None:
980
+ raise ValueError(
981
+ 'Invalid MSVS guid: "%s". Must match regex: "%s".'
982
+ % (guid, VALID_MSVS_GUID_CHARS.pattern)
983
+ )
984
+ guid = "{%s}" % guid
985
+ guid = guid or MSVSNew.MakeGuid(proj_path)
986
+ return guid
987
+
988
+
989
+ def _GetMsbuildToolsetOfProject(proj_path, spec, version):
990
+ """Get the platform toolset for the project.
991
+
992
+ Arguments:
993
+ proj_path: Path of the vcproj or vcxproj file to generate.
994
+ spec: The target dictionary containing the properties of the target.
995
+ version: The MSVSVersion object.
996
+ Returns:
997
+ the platform toolset string or None.
998
+ """
999
+ # Pluck out the default configuration.
1000
+ default_config = _GetDefaultConfiguration(spec)
1001
+ toolset = default_config.get("msbuild_toolset")
1002
+ if not toolset and version.DefaultToolset():
1003
+ toolset = version.DefaultToolset()
1004
+ if spec["type"] == "windows_driver":
1005
+ toolset = "WindowsKernelModeDriver10.0"
1006
+ return toolset
1007
+
1008
+
1009
+ def _GenerateProject(project, options, version, generator_flags, spec):
1010
+ """Generates a vcproj file.
1011
+
1012
+ Arguments:
1013
+ project: the MSVSProject object.
1014
+ options: global generator options.
1015
+ version: the MSVSVersion object.
1016
+ generator_flags: dict of generator-specific flags.
1017
+ Returns:
1018
+ A list of source files that cannot be found on disk.
1019
+ """
1020
+ default_config = _GetDefaultConfiguration(project.spec)
1021
+
1022
+ # Skip emitting anything if told to with msvs_existing_vcproj option.
1023
+ if default_config.get("msvs_existing_vcproj"):
1024
+ return []
1025
+
1026
+ if version.UsesVcxproj():
1027
+ return _GenerateMSBuildProject(project, options, version, generator_flags, spec)
1028
+ else:
1029
+ return _GenerateMSVSProject(project, options, version, generator_flags)
1030
+
1031
+
1032
+ def _GenerateMSVSProject(project, options, version, generator_flags):
1033
+ """Generates a .vcproj file. It may create .rules and .user files too.
1034
+
1035
+ Arguments:
1036
+ project: The project object we will generate the file for.
1037
+ options: Global options passed to the generator.
1038
+ version: The VisualStudioVersion object.
1039
+ generator_flags: dict of generator-specific flags.
1040
+ """
1041
+ spec = project.spec
1042
+ gyp.common.EnsureDirExists(project.path)
1043
+
1044
+ platforms = _GetUniquePlatforms(spec)
1045
+ p = MSVSProject.Writer(
1046
+ project.path, version, spec["target_name"], project.guid, platforms
1047
+ )
1048
+
1049
+ # Get directory project file is in.
1050
+ project_dir = os.path.split(project.path)[0]
1051
+ gyp_path = _NormalizedSource(project.build_file)
1052
+ relative_path_of_gyp_file = gyp.common.RelativePath(gyp_path, project_dir)
1053
+
1054
+ config_type = _GetMSVSConfigurationType(spec, project.build_file)
1055
+ for config_name, config in spec["configurations"].items():
1056
+ _AddConfigurationToMSVSProject(p, spec, config_type, config_name, config)
1057
+
1058
+ # Prepare list of sources and excluded sources.
1059
+ gyp_file = os.path.split(project.build_file)[1]
1060
+ sources, excluded_sources = _PrepareListOfSources(spec, generator_flags, gyp_file)
1061
+
1062
+ # Add rules.
1063
+ actions_to_add = {}
1064
+ _GenerateRulesForMSVS(
1065
+ p, project_dir, options, spec, sources, excluded_sources, actions_to_add
1066
+ )
1067
+ list_excluded = generator_flags.get("msvs_list_excluded_files", True)
1068
+ sources, excluded_sources, excluded_idl = _AdjustSourcesAndConvertToFilterHierarchy(
1069
+ spec, options, project_dir, sources, excluded_sources, list_excluded, version
1070
+ )
1071
+
1072
+ # Add in files.
1073
+ missing_sources = _VerifySourcesExist(sources, project_dir)
1074
+ p.AddFiles(sources)
1075
+
1076
+ _AddToolFilesToMSVS(p, spec)
1077
+ _HandlePreCompiledHeaders(p, sources, spec)
1078
+ _AddActions(actions_to_add, spec, relative_path_of_gyp_file)
1079
+ _AddCopies(actions_to_add, spec)
1080
+ _WriteMSVSUserFile(project.path, version, spec)
1081
+
1082
+ # NOTE: this stanza must appear after all actions have been decided.
1083
+ # Don't excluded sources with actions attached, or they won't run.
1084
+ excluded_sources = _FilterActionsFromExcluded(excluded_sources, actions_to_add)
1085
+ _ExcludeFilesFromBeingBuilt(p, spec, excluded_sources, excluded_idl, list_excluded)
1086
+ _AddAccumulatedActionsToMSVS(p, spec, actions_to_add)
1087
+
1088
+ # Write it out.
1089
+ p.WriteIfChanged()
1090
+
1091
+ return missing_sources
1092
+
1093
+
1094
+ def _GetUniquePlatforms(spec):
1095
+ """Returns the list of unique platforms for this spec, e.g ['win32', ...].
1096
+
1097
+ Arguments:
1098
+ spec: The target dictionary containing the properties of the target.
1099
+ Returns:
1100
+ The MSVSUserFile object created.
1101
+ """
1102
+ # Gather list of unique platforms.
1103
+ platforms = OrderedSet()
1104
+ for configuration in spec["configurations"]:
1105
+ platforms.add(_ConfigPlatform(spec["configurations"][configuration]))
1106
+ platforms = list(platforms)
1107
+ return platforms
1108
+
1109
+
1110
+ def _CreateMSVSUserFile(proj_path, version, spec):
1111
+ """Generates a .user file for the user running this Gyp program.
1112
+
1113
+ Arguments:
1114
+ proj_path: The path of the project file being created. The .user file
1115
+ shares the same path (with an appropriate suffix).
1116
+ version: The VisualStudioVersion object.
1117
+ spec: The target dictionary containing the properties of the target.
1118
+ Returns:
1119
+ The MSVSUserFile object created.
1120
+ """
1121
+ (domain, username) = _GetDomainAndUserName()
1122
+ vcuser_filename = ".".join([proj_path, domain, username, "user"])
1123
+ user_file = MSVSUserFile.Writer(vcuser_filename, version, spec["target_name"])
1124
+ return user_file
1125
+
1126
+
1127
+ def _GetMSVSConfigurationType(spec, build_file):
1128
+ """Returns the configuration type for this project.
1129
+
1130
+ It's a number defined by Microsoft. May raise an exception.
1131
+
1132
+ Args:
1133
+ spec: The target dictionary containing the properties of the target.
1134
+ build_file: The path of the gyp file.
1135
+ Returns:
1136
+ An integer, the configuration type.
1137
+ """
1138
+ try:
1139
+ config_type = {
1140
+ "executable": "1", # .exe
1141
+ "shared_library": "2", # .dll
1142
+ "loadable_module": "2", # .dll
1143
+ "static_library": "4", # .lib
1144
+ "windows_driver": "5", # .sys
1145
+ "none": "10", # Utility type
1146
+ }[spec["type"]]
1147
+ except KeyError:
1148
+ if spec.get("type"):
1149
+ raise GypError(
1150
+ "Target type %s is not a valid target type for "
1151
+ "target %s in %s." % (spec["type"], spec["target_name"], build_file)
1152
+ )
1153
+ else:
1154
+ raise GypError(
1155
+ "Missing type field for target %s in %s."
1156
+ % (spec["target_name"], build_file)
1157
+ )
1158
+ return config_type
1159
+
1160
+
1161
+ def _AddConfigurationToMSVSProject(p, spec, config_type, config_name, config):
1162
+ """Adds a configuration to the MSVS project.
1163
+
1164
+ Many settings in a vcproj file are specific to a configuration. This
1165
+ function the main part of the vcproj file that's configuration specific.
1166
+
1167
+ Arguments:
1168
+ p: The target project being generated.
1169
+ spec: The target dictionary containing the properties of the target.
1170
+ config_type: The configuration type, a number as defined by Microsoft.
1171
+ config_name: The name of the configuration.
1172
+ config: The dictionary that defines the special processing to be done
1173
+ for this configuration.
1174
+ """
1175
+ # Get the information for this configuration
1176
+ include_dirs, midl_include_dirs, resource_include_dirs = _GetIncludeDirs(config)
1177
+ libraries = _GetLibraries(spec)
1178
+ library_dirs = _GetLibraryDirs(config)
1179
+ out_file, vc_tool, _ = _GetOutputFilePathAndTool(spec, msbuild=False)
1180
+ defines = _GetDefines(config)
1181
+ defines = [_EscapeCppDefineForMSVS(d) for d in defines]
1182
+ disabled_warnings = _GetDisabledWarnings(config)
1183
+ prebuild = config.get("msvs_prebuild")
1184
+ postbuild = config.get("msvs_postbuild")
1185
+ def_file = _GetModuleDefinition(spec)
1186
+ precompiled_header = config.get("msvs_precompiled_header")
1187
+
1188
+ # Prepare the list of tools as a dictionary.
1189
+ tools = dict()
1190
+ # Add in user specified msvs_settings.
1191
+ msvs_settings = config.get("msvs_settings", {})
1192
+ MSVSSettings.ValidateMSVSSettings(msvs_settings)
1193
+
1194
+ # Prevent default library inheritance from the environment.
1195
+ _ToolAppend(tools, "VCLinkerTool", "AdditionalDependencies", ["$(NOINHERIT)"])
1196
+
1197
+ for tool in msvs_settings:
1198
+ settings = config["msvs_settings"][tool]
1199
+ for setting in settings:
1200
+ _ToolAppend(tools, tool, setting, settings[setting])
1201
+ # Add the information to the appropriate tool
1202
+ _ToolAppend(tools, "VCCLCompilerTool", "AdditionalIncludeDirectories", include_dirs)
1203
+ _ToolAppend(tools, "VCMIDLTool", "AdditionalIncludeDirectories", midl_include_dirs)
1204
+ _ToolAppend(
1205
+ tools,
1206
+ "VCResourceCompilerTool",
1207
+ "AdditionalIncludeDirectories",
1208
+ resource_include_dirs,
1209
+ )
1210
+ # Add in libraries.
1211
+ _ToolAppend(tools, "VCLinkerTool", "AdditionalDependencies", libraries)
1212
+ _ToolAppend(tools, "VCLinkerTool", "AdditionalLibraryDirectories", library_dirs)
1213
+ if out_file:
1214
+ _ToolAppend(tools, vc_tool, "OutputFile", out_file, only_if_unset=True)
1215
+ # Add defines.
1216
+ _ToolAppend(tools, "VCCLCompilerTool", "PreprocessorDefinitions", defines)
1217
+ _ToolAppend(tools, "VCResourceCompilerTool", "PreprocessorDefinitions", defines)
1218
+ # Change program database directory to prevent collisions.
1219
+ _ToolAppend(
1220
+ tools,
1221
+ "VCCLCompilerTool",
1222
+ "ProgramDataBaseFileName",
1223
+ "$(IntDir)$(ProjectName)\\vc80.pdb",
1224
+ only_if_unset=True,
1225
+ )
1226
+ # Add disabled warnings.
1227
+ _ToolAppend(tools, "VCCLCompilerTool", "DisableSpecificWarnings", disabled_warnings)
1228
+ # Add Pre-build.
1229
+ _ToolAppend(tools, "VCPreBuildEventTool", "CommandLine", prebuild)
1230
+ # Add Post-build.
1231
+ _ToolAppend(tools, "VCPostBuildEventTool", "CommandLine", postbuild)
1232
+ # Turn on precompiled headers if appropriate.
1233
+ if precompiled_header:
1234
+ precompiled_header = os.path.split(precompiled_header)[1]
1235
+ _ToolAppend(tools, "VCCLCompilerTool", "UsePrecompiledHeader", "2")
1236
+ _ToolAppend(
1237
+ tools, "VCCLCompilerTool", "PrecompiledHeaderThrough", precompiled_header
1238
+ )
1239
+ _ToolAppend(tools, "VCCLCompilerTool", "ForcedIncludeFiles", precompiled_header)
1240
+ # Loadable modules don't generate import libraries;
1241
+ # tell dependent projects to not expect one.
1242
+ if spec["type"] == "loadable_module":
1243
+ _ToolAppend(tools, "VCLinkerTool", "IgnoreImportLibrary", "true")
1244
+ # Set the module definition file if any.
1245
+ if def_file:
1246
+ _ToolAppend(tools, "VCLinkerTool", "ModuleDefinitionFile", def_file)
1247
+
1248
+ _AddConfigurationToMSVS(p, spec, tools, config, config_type, config_name)
1249
+
1250
+
1251
+ def _GetIncludeDirs(config):
1252
+ """Returns the list of directories to be used for #include directives.
1253
+
1254
+ Arguments:
1255
+ config: The dictionary that defines the special processing to be done
1256
+ for this configuration.
1257
+ Returns:
1258
+ The list of directory paths.
1259
+ """
1260
+ # TODO(bradnelson): include_dirs should really be flexible enough not to
1261
+ # require this sort of thing.
1262
+ include_dirs = config.get("include_dirs", []) + config.get(
1263
+ "msvs_system_include_dirs", []
1264
+ )
1265
+ midl_include_dirs = config.get("midl_include_dirs", []) + config.get(
1266
+ "msvs_system_include_dirs", []
1267
+ )
1268
+ resource_include_dirs = config.get("resource_include_dirs", include_dirs)
1269
+ include_dirs = _FixPaths(include_dirs)
1270
+ midl_include_dirs = _FixPaths(midl_include_dirs)
1271
+ resource_include_dirs = _FixPaths(resource_include_dirs)
1272
+ return include_dirs, midl_include_dirs, resource_include_dirs
1273
+
1274
+
1275
+ def _GetLibraryDirs(config):
1276
+ """Returns the list of directories to be used for library search paths.
1277
+
1278
+ Arguments:
1279
+ config: The dictionary that defines the special processing to be done
1280
+ for this configuration.
1281
+ Returns:
1282
+ The list of directory paths.
1283
+ """
1284
+
1285
+ library_dirs = config.get("library_dirs", [])
1286
+ library_dirs = _FixPaths(library_dirs)
1287
+ return library_dirs
1288
+
1289
+
1290
+ def _GetLibraries(spec):
1291
+ """Returns the list of libraries for this configuration.
1292
+
1293
+ Arguments:
1294
+ spec: The target dictionary containing the properties of the target.
1295
+ Returns:
1296
+ The list of directory paths.
1297
+ """
1298
+ libraries = spec.get("libraries", [])
1299
+ # Strip out -l, as it is not used on windows (but is needed so we can pass
1300
+ # in libraries that are assumed to be in the default library path).
1301
+ # Also remove duplicate entries, leaving only the last duplicate, while
1302
+ # preserving order.
1303
+ found = OrderedSet()
1304
+ unique_libraries_list = []
1305
+ for entry in reversed(libraries):
1306
+ library = re.sub(r"^\-l", "", entry)
1307
+ if not os.path.splitext(library)[1]:
1308
+ library += ".lib"
1309
+ if library not in found:
1310
+ found.add(library)
1311
+ unique_libraries_list.append(library)
1312
+ unique_libraries_list.reverse()
1313
+ return unique_libraries_list
1314
+
1315
+
1316
+ def _GetOutputFilePathAndTool(spec, msbuild):
1317
+ """Returns the path and tool to use for this target.
1318
+
1319
+ Figures out the path of the file this spec will create and the name of
1320
+ the VC tool that will create it.
1321
+
1322
+ Arguments:
1323
+ spec: The target dictionary containing the properties of the target.
1324
+ Returns:
1325
+ A triple of (file path, name of the vc tool, name of the msbuild tool)
1326
+ """
1327
+ # Select a name for the output file.
1328
+ out_file = ""
1329
+ vc_tool = ""
1330
+ msbuild_tool = ""
1331
+ output_file_map = {
1332
+ "executable": ("VCLinkerTool", "Link", "$(OutDir)", ".exe"),
1333
+ "shared_library": ("VCLinkerTool", "Link", "$(OutDir)", ".dll"),
1334
+ "loadable_module": ("VCLinkerTool", "Link", "$(OutDir)", ".dll"),
1335
+ "windows_driver": ("VCLinkerTool", "Link", "$(OutDir)", ".sys"),
1336
+ "static_library": ("VCLibrarianTool", "Lib", "$(OutDir)lib\\", ".lib"),
1337
+ }
1338
+ output_file_props = output_file_map.get(spec["type"])
1339
+ if output_file_props and int(spec.get("msvs_auto_output_file", 1)):
1340
+ vc_tool, msbuild_tool, out_dir, suffix = output_file_props
1341
+ if spec.get("standalone_static_library", 0):
1342
+ out_dir = "$(OutDir)"
1343
+ out_dir = spec.get("product_dir", out_dir)
1344
+ product_extension = spec.get("product_extension")
1345
+ if product_extension:
1346
+ suffix = "." + product_extension
1347
+ elif msbuild:
1348
+ suffix = "$(TargetExt)"
1349
+ prefix = spec.get("product_prefix", "")
1350
+ product_name = spec.get("product_name", "$(ProjectName)")
1351
+ out_file = ntpath.join(out_dir, prefix + product_name + suffix)
1352
+ return out_file, vc_tool, msbuild_tool
1353
+
1354
+
1355
+ def _GetOutputTargetExt(spec):
1356
+ """Returns the extension for this target, including the dot
1357
+
1358
+ If product_extension is specified, set target_extension to this to avoid
1359
+ MSB8012, returns None otherwise. Ignores any target_extension settings in
1360
+ the input files.
1361
+
1362
+ Arguments:
1363
+ spec: The target dictionary containing the properties of the target.
1364
+ Returns:
1365
+ A string with the extension, or None
1366
+ """
1367
+ target_extension = spec.get("product_extension")
1368
+ if target_extension:
1369
+ return "." + target_extension
1370
+ return None
1371
+
1372
+
1373
+ def _GetDefines(config):
1374
+ """Returns the list of preprocessor definitions for this configuration.
1375
+
1376
+ Arguments:
1377
+ config: The dictionary that defines the special processing to be done
1378
+ for this configuration.
1379
+ Returns:
1380
+ The list of preprocessor definitions.
1381
+ """
1382
+ defines = []
1383
+ for d in config.get("defines", []):
1384
+ if type(d) == list:
1385
+ fd = "=".join([str(dpart) for dpart in d])
1386
+ else:
1387
+ fd = str(d)
1388
+ defines.append(fd)
1389
+ return defines
1390
+
1391
+
1392
+ def _GetDisabledWarnings(config):
1393
+ return [str(i) for i in config.get("msvs_disabled_warnings", [])]
1394
+
1395
+
1396
+ def _GetModuleDefinition(spec):
1397
+ def_file = ""
1398
+ if spec["type"] in [
1399
+ "shared_library",
1400
+ "loadable_module",
1401
+ "executable",
1402
+ "windows_driver",
1403
+ ]:
1404
+ def_files = [s for s in spec.get("sources", []) if s.endswith(".def")]
1405
+ if len(def_files) == 1:
1406
+ def_file = _FixPath(def_files[0])
1407
+ elif def_files:
1408
+ raise ValueError(
1409
+ "Multiple module definition files in one target, target %s lists "
1410
+ "multiple .def files: %s" % (spec["target_name"], " ".join(def_files))
1411
+ )
1412
+ return def_file
1413
+
1414
+
1415
+ def _ConvertToolsToExpectedForm(tools):
1416
+ """Convert tools to a form expected by Visual Studio.
1417
+
1418
+ Arguments:
1419
+ tools: A dictionary of settings; the tool name is the key.
1420
+ Returns:
1421
+ A list of Tool objects.
1422
+ """
1423
+ tool_list = []
1424
+ for tool, settings in tools.items():
1425
+ # Collapse settings with lists.
1426
+ settings_fixed = {}
1427
+ for setting, value in settings.items():
1428
+ if type(value) == list:
1429
+ if (
1430
+ tool == "VCLinkerTool" and setting == "AdditionalDependencies"
1431
+ ) or setting == "AdditionalOptions":
1432
+ settings_fixed[setting] = " ".join(value)
1433
+ else:
1434
+ settings_fixed[setting] = ";".join(value)
1435
+ else:
1436
+ settings_fixed[setting] = value
1437
+ # Add in this tool.
1438
+ tool_list.append(MSVSProject.Tool(tool, settings_fixed))
1439
+ return tool_list
1440
+
1441
+
1442
+ def _AddConfigurationToMSVS(p, spec, tools, config, config_type, config_name):
1443
+ """Add to the project file the configuration specified by config.
1444
+
1445
+ Arguments:
1446
+ p: The target project being generated.
1447
+ spec: the target project dict.
1448
+ tools: A dictionary of settings; the tool name is the key.
1449
+ config: The dictionary that defines the special processing to be done
1450
+ for this configuration.
1451
+ config_type: The configuration type, a number as defined by Microsoft.
1452
+ config_name: The name of the configuration.
1453
+ """
1454
+ attributes = _GetMSVSAttributes(spec, config, config_type)
1455
+ # Add in this configuration.
1456
+ tool_list = _ConvertToolsToExpectedForm(tools)
1457
+ p.AddConfig(_ConfigFullName(config_name, config), attrs=attributes, tools=tool_list)
1458
+
1459
+
1460
+ def _GetMSVSAttributes(spec, config, config_type):
1461
+ # Prepare configuration attributes.
1462
+ prepared_attrs = {}
1463
+ source_attrs = config.get("msvs_configuration_attributes", {})
1464
+ for a in source_attrs:
1465
+ prepared_attrs[a] = source_attrs[a]
1466
+ # Add props files.
1467
+ vsprops_dirs = config.get("msvs_props", [])
1468
+ vsprops_dirs = _FixPaths(vsprops_dirs)
1469
+ if vsprops_dirs:
1470
+ prepared_attrs["InheritedPropertySheets"] = ";".join(vsprops_dirs)
1471
+ # Set configuration type.
1472
+ prepared_attrs["ConfigurationType"] = config_type
1473
+ output_dir = prepared_attrs.get(
1474
+ "OutputDirectory", "$(SolutionDir)$(ConfigurationName)"
1475
+ )
1476
+ prepared_attrs["OutputDirectory"] = _FixPath(output_dir) + "\\"
1477
+ if "IntermediateDirectory" not in prepared_attrs:
1478
+ intermediate = "$(ConfigurationName)\\obj\\$(ProjectName)"
1479
+ prepared_attrs["IntermediateDirectory"] = _FixPath(intermediate) + "\\"
1480
+ else:
1481
+ intermediate = _FixPath(prepared_attrs["IntermediateDirectory"]) + "\\"
1482
+ intermediate = MSVSSettings.FixVCMacroSlashes(intermediate)
1483
+ prepared_attrs["IntermediateDirectory"] = intermediate
1484
+ return prepared_attrs
1485
+
1486
+
1487
+ def _AddNormalizedSources(sources_set, sources_array):
1488
+ sources_set.update(_NormalizedSource(s) for s in sources_array)
1489
+
1490
+
1491
+ def _PrepareListOfSources(spec, generator_flags, gyp_file):
1492
+ """Prepare list of sources and excluded sources.
1493
+
1494
+ Besides the sources specified directly in the spec, adds the gyp file so
1495
+ that a change to it will cause a re-compile. Also adds appropriate sources
1496
+ for actions and copies. Assumes later stage will un-exclude files which
1497
+ have custom build steps attached.
1498
+
1499
+ Arguments:
1500
+ spec: The target dictionary containing the properties of the target.
1501
+ gyp_file: The name of the gyp file.
1502
+ Returns:
1503
+ A pair of (list of sources, list of excluded sources).
1504
+ The sources will be relative to the gyp file.
1505
+ """
1506
+ sources = OrderedSet()
1507
+ _AddNormalizedSources(sources, spec.get("sources", []))
1508
+ excluded_sources = OrderedSet()
1509
+ # Add in the gyp file.
1510
+ if not generator_flags.get("standalone"):
1511
+ sources.add(gyp_file)
1512
+
1513
+ # Add in 'action' inputs and outputs.
1514
+ for a in spec.get("actions", []):
1515
+ inputs = a["inputs"]
1516
+ inputs = [_NormalizedSource(i) for i in inputs]
1517
+ # Add all inputs to sources and excluded sources.
1518
+ inputs = OrderedSet(inputs)
1519
+ sources.update(inputs)
1520
+ if not spec.get("msvs_external_builder"):
1521
+ excluded_sources.update(inputs)
1522
+ if int(a.get("process_outputs_as_sources", False)):
1523
+ _AddNormalizedSources(sources, a.get("outputs", []))
1524
+ # Add in 'copies' inputs and outputs.
1525
+ for cpy in spec.get("copies", []):
1526
+ _AddNormalizedSources(sources, cpy.get("files", []))
1527
+ return (sources, excluded_sources)
1528
+
1529
+
1530
+ def _AdjustSourcesAndConvertToFilterHierarchy(
1531
+ spec, options, gyp_dir, sources, excluded_sources, list_excluded, version
1532
+ ):
1533
+ """Adjusts the list of sources and excluded sources.
1534
+
1535
+ Also converts the sets to lists.
1536
+
1537
+ Arguments:
1538
+ spec: The target dictionary containing the properties of the target.
1539
+ options: Global generator options.
1540
+ gyp_dir: The path to the gyp file being processed.
1541
+ sources: A set of sources to be included for this project.
1542
+ excluded_sources: A set of sources to be excluded for this project.
1543
+ version: A MSVSVersion object.
1544
+ Returns:
1545
+ A trio of (list of sources, list of excluded sources,
1546
+ path of excluded IDL file)
1547
+ """
1548
+ # Exclude excluded sources coming into the generator.
1549
+ excluded_sources.update(OrderedSet(spec.get("sources_excluded", [])))
1550
+ # Add excluded sources into sources for good measure.
1551
+ sources.update(excluded_sources)
1552
+ # Convert to proper windows form.
1553
+ # NOTE: sources goes from being a set to a list here.
1554
+ # NOTE: excluded_sources goes from being a set to a list here.
1555
+ sources = _FixPaths(sources)
1556
+ # Convert to proper windows form.
1557
+ excluded_sources = _FixPaths(excluded_sources)
1558
+
1559
+ excluded_idl = _IdlFilesHandledNonNatively(spec, sources)
1560
+
1561
+ precompiled_related = _GetPrecompileRelatedFiles(spec)
1562
+ # Find the excluded ones, minus the precompiled header related ones.
1563
+ fully_excluded = [i for i in excluded_sources if i not in precompiled_related]
1564
+
1565
+ # Convert to folders and the right slashes.
1566
+ sources = [i.split("\\") for i in sources]
1567
+ sources = _ConvertSourcesToFilterHierarchy(
1568
+ sources,
1569
+ excluded=fully_excluded,
1570
+ list_excluded=list_excluded,
1571
+ msvs_version=version,
1572
+ )
1573
+
1574
+ # Prune filters with a single child to flatten ugly directory structures
1575
+ # such as ../../src/modules/module1 etc.
1576
+ if version.UsesVcxproj():
1577
+ while (
1578
+ all([isinstance(s, MSVSProject.Filter) for s in sources])
1579
+ and len({s.name for s in sources}) == 1
1580
+ ):
1581
+ assert all([len(s.contents) == 1 for s in sources])
1582
+ sources = [s.contents[0] for s in sources]
1583
+ else:
1584
+ while len(sources) == 1 and isinstance(sources[0], MSVSProject.Filter):
1585
+ sources = sources[0].contents
1586
+
1587
+ return sources, excluded_sources, excluded_idl
1588
+
1589
+
1590
+ def _IdlFilesHandledNonNatively(spec, sources):
1591
+ # If any non-native rules use 'idl' as an extension exclude idl files.
1592
+ # Gather a list here to use later.
1593
+ using_idl = False
1594
+ for rule in spec.get("rules", []):
1595
+ if rule["extension"] == "idl" and int(rule.get("msvs_external_rule", 0)):
1596
+ using_idl = True
1597
+ break
1598
+ if using_idl:
1599
+ excluded_idl = [i for i in sources if i.endswith(".idl")]
1600
+ else:
1601
+ excluded_idl = []
1602
+ return excluded_idl
1603
+
1604
+
1605
+ def _GetPrecompileRelatedFiles(spec):
1606
+ # Gather a list of precompiled header related sources.
1607
+ precompiled_related = []
1608
+ for _, config in spec["configurations"].items():
1609
+ for k in precomp_keys:
1610
+ f = config.get(k)
1611
+ if f:
1612
+ precompiled_related.append(_FixPath(f))
1613
+ return precompiled_related
1614
+
1615
+
1616
+ def _ExcludeFilesFromBeingBuilt(p, spec, excluded_sources, excluded_idl, list_excluded):
1617
+ exclusions = _GetExcludedFilesFromBuild(spec, excluded_sources, excluded_idl)
1618
+ for file_name, excluded_configs in exclusions.items():
1619
+ if not list_excluded and len(excluded_configs) == len(spec["configurations"]):
1620
+ # If we're not listing excluded files, then they won't appear in the
1621
+ # project, so don't try to configure them to be excluded.
1622
+ pass
1623
+ else:
1624
+ for config_name, config in excluded_configs:
1625
+ p.AddFileConfig(
1626
+ file_name,
1627
+ _ConfigFullName(config_name, config),
1628
+ {"ExcludedFromBuild": "true"},
1629
+ )
1630
+
1631
+
1632
+ def _GetExcludedFilesFromBuild(spec, excluded_sources, excluded_idl):
1633
+ exclusions = {}
1634
+ # Exclude excluded sources from being built.
1635
+ for f in excluded_sources:
1636
+ excluded_configs = []
1637
+ for config_name, config in spec["configurations"].items():
1638
+ precomped = [_FixPath(config.get(i, "")) for i in precomp_keys]
1639
+ # Don't do this for ones that are precompiled header related.
1640
+ if f not in precomped:
1641
+ excluded_configs.append((config_name, config))
1642
+ exclusions[f] = excluded_configs
1643
+ # If any non-native rules use 'idl' as an extension exclude idl files.
1644
+ # Exclude them now.
1645
+ for f in excluded_idl:
1646
+ excluded_configs = []
1647
+ for config_name, config in spec["configurations"].items():
1648
+ excluded_configs.append((config_name, config))
1649
+ exclusions[f] = excluded_configs
1650
+ return exclusions
1651
+
1652
+
1653
+ def _AddToolFilesToMSVS(p, spec):
1654
+ # Add in tool files (rules).
1655
+ tool_files = OrderedSet()
1656
+ for _, config in spec["configurations"].items():
1657
+ for f in config.get("msvs_tool_files", []):
1658
+ tool_files.add(f)
1659
+ for f in tool_files:
1660
+ p.AddToolFile(f)
1661
+
1662
+
1663
+ def _HandlePreCompiledHeaders(p, sources, spec):
1664
+ # Pre-compiled header source stubs need a different compiler flag
1665
+ # (generate precompiled header) and any source file not of the same
1666
+ # kind (i.e. C vs. C++) as the precompiled header source stub needs
1667
+ # to have use of precompiled headers disabled.
1668
+ extensions_excluded_from_precompile = []
1669
+ for config_name, config in spec["configurations"].items():
1670
+ source = config.get("msvs_precompiled_source")
1671
+ if source:
1672
+ source = _FixPath(source)
1673
+ # UsePrecompiledHeader=1 for if using precompiled headers.
1674
+ tool = MSVSProject.Tool("VCCLCompilerTool", {"UsePrecompiledHeader": "1"})
1675
+ p.AddFileConfig(
1676
+ source, _ConfigFullName(config_name, config), {}, tools=[tool]
1677
+ )
1678
+ basename, extension = os.path.splitext(source)
1679
+ if extension == ".c":
1680
+ extensions_excluded_from_precompile = [".cc", ".cpp", ".cxx"]
1681
+ else:
1682
+ extensions_excluded_from_precompile = [".c"]
1683
+
1684
+ def DisableForSourceTree(source_tree):
1685
+ for source in source_tree:
1686
+ if isinstance(source, MSVSProject.Filter):
1687
+ DisableForSourceTree(source.contents)
1688
+ else:
1689
+ basename, extension = os.path.splitext(source)
1690
+ if extension in extensions_excluded_from_precompile:
1691
+ for config_name, config in spec["configurations"].items():
1692
+ tool = MSVSProject.Tool(
1693
+ "VCCLCompilerTool",
1694
+ {
1695
+ "UsePrecompiledHeader": "0",
1696
+ "ForcedIncludeFiles": "$(NOINHERIT)",
1697
+ },
1698
+ )
1699
+ p.AddFileConfig(
1700
+ _FixPath(source),
1701
+ _ConfigFullName(config_name, config),
1702
+ {},
1703
+ tools=[tool],
1704
+ )
1705
+
1706
+ # Do nothing if there was no precompiled source.
1707
+ if extensions_excluded_from_precompile:
1708
+ DisableForSourceTree(sources)
1709
+
1710
+
1711
+ def _AddActions(actions_to_add, spec, relative_path_of_gyp_file):
1712
+ # Add actions.
1713
+ actions = spec.get("actions", [])
1714
+ # Don't setup_env every time. When all the actions are run together in one
1715
+ # batch file in VS, the PATH will grow too long.
1716
+ # Membership in this set means that the cygwin environment has been set up,
1717
+ # and does not need to be set up again.
1718
+ have_setup_env = set()
1719
+ for a in actions:
1720
+ # Attach actions to the gyp file if nothing else is there.
1721
+ inputs = a.get("inputs") or [relative_path_of_gyp_file]
1722
+ attached_to = inputs[0]
1723
+ need_setup_env = attached_to not in have_setup_env
1724
+ cmd = _BuildCommandLineForRule(
1725
+ spec, a, has_input_path=False, do_setup_env=need_setup_env
1726
+ )
1727
+ have_setup_env.add(attached_to)
1728
+ # Add the action.
1729
+ _AddActionStep(
1730
+ actions_to_add,
1731
+ inputs=inputs,
1732
+ outputs=a.get("outputs", []),
1733
+ description=a.get("message", a["action_name"]),
1734
+ command=cmd,
1735
+ )
1736
+
1737
+
1738
+ def _WriteMSVSUserFile(project_path, version, spec):
1739
+ # Add run_as and test targets.
1740
+ if "run_as" in spec:
1741
+ run_as = spec["run_as"]
1742
+ action = run_as.get("action", [])
1743
+ environment = run_as.get("environment", [])
1744
+ working_directory = run_as.get("working_directory", ".")
1745
+ elif int(spec.get("test", 0)):
1746
+ action = ["$(TargetPath)", "--gtest_print_time"]
1747
+ environment = []
1748
+ working_directory = "."
1749
+ else:
1750
+ return # Nothing to add
1751
+ # Write out the user file.
1752
+ user_file = _CreateMSVSUserFile(project_path, version, spec)
1753
+ for config_name, c_data in spec["configurations"].items():
1754
+ user_file.AddDebugSettings(
1755
+ _ConfigFullName(config_name, c_data), action, environment, working_directory
1756
+ )
1757
+ user_file.WriteIfChanged()
1758
+
1759
+
1760
+ def _AddCopies(actions_to_add, spec):
1761
+ copies = _GetCopies(spec)
1762
+ for inputs, outputs, cmd, description in copies:
1763
+ _AddActionStep(
1764
+ actions_to_add,
1765
+ inputs=inputs,
1766
+ outputs=outputs,
1767
+ description=description,
1768
+ command=cmd,
1769
+ )
1770
+
1771
+
1772
+ def _GetCopies(spec):
1773
+ copies = []
1774
+ # Add copies.
1775
+ for cpy in spec.get("copies", []):
1776
+ for src in cpy.get("files", []):
1777
+ dst = os.path.join(cpy["destination"], os.path.basename(src))
1778
+ # _AddCustomBuildToolForMSVS() will call _FixPath() on the inputs and
1779
+ # outputs, so do the same for our generated command line.
1780
+ if src.endswith("/"):
1781
+ src_bare = src[:-1]
1782
+ base_dir = posixpath.split(src_bare)[0]
1783
+ outer_dir = posixpath.split(src_bare)[1]
1784
+ fixed_dst = _FixPath(dst)
1785
+ full_dst = f'"{fixed_dst}\\{outer_dir}\\"'
1786
+ cmd = 'mkdir {} 2>nul & cd "{}" && xcopy /e /f /y "{}" {}'.format(
1787
+ full_dst,
1788
+ _FixPath(base_dir),
1789
+ outer_dir,
1790
+ full_dst,
1791
+ )
1792
+ copies.append(
1793
+ (
1794
+ [src],
1795
+ ["dummy_copies", dst],
1796
+ cmd,
1797
+ f"Copying {src} to {fixed_dst}",
1798
+ )
1799
+ )
1800
+ else:
1801
+ fix_dst = _FixPath(cpy["destination"])
1802
+ cmd = 'mkdir "{}" 2>nul & set ERRORLEVEL=0 & copy /Y "{}" "{}"'.format(
1803
+ fix_dst,
1804
+ _FixPath(src),
1805
+ _FixPath(dst),
1806
+ )
1807
+ copies.append(([src], [dst], cmd, f"Copying {src} to {fix_dst}"))
1808
+ return copies
1809
+
1810
+
1811
+ def _GetPathDict(root, path):
1812
+ # |path| will eventually be empty (in the recursive calls) if it was initially
1813
+ # relative; otherwise it will eventually end up as '\', 'D:\', etc.
1814
+ if not path or path.endswith(os.sep):
1815
+ return root
1816
+ parent, folder = os.path.split(path)
1817
+ parent_dict = _GetPathDict(root, parent)
1818
+ if folder not in parent_dict:
1819
+ parent_dict[folder] = dict()
1820
+ return parent_dict[folder]
1821
+
1822
+
1823
+ def _DictsToFolders(base_path, bucket, flat):
1824
+ # Convert to folders recursively.
1825
+ children = []
1826
+ for folder, contents in bucket.items():
1827
+ if type(contents) == dict:
1828
+ folder_children = _DictsToFolders(
1829
+ os.path.join(base_path, folder), contents, flat
1830
+ )
1831
+ if flat:
1832
+ children += folder_children
1833
+ else:
1834
+ folder_children = MSVSNew.MSVSFolder(
1835
+ os.path.join(base_path, folder),
1836
+ name="(" + folder + ")",
1837
+ entries=folder_children,
1838
+ )
1839
+ children.append(folder_children)
1840
+ else:
1841
+ children.append(contents)
1842
+ return children
1843
+
1844
+
1845
+ def _CollapseSingles(parent, node):
1846
+ # Recursively explorer the tree of dicts looking for projects which are
1847
+ # the sole item in a folder which has the same name as the project. Bring
1848
+ # such projects up one level.
1849
+ if type(node) == dict and len(node) == 1 and next(iter(node)) == parent + ".vcproj":
1850
+ return node[next(iter(node))]
1851
+ if type(node) != dict:
1852
+ return node
1853
+ for child in node:
1854
+ node[child] = _CollapseSingles(child, node[child])
1855
+ return node
1856
+
1857
+
1858
+ def _GatherSolutionFolders(sln_projects, project_objects, flat):
1859
+ root = {}
1860
+ # Convert into a tree of dicts on path.
1861
+ for p in sln_projects:
1862
+ gyp_file, target = gyp.common.ParseQualifiedTarget(p)[0:2]
1863
+ if p.endswith("#host"):
1864
+ target += "_host"
1865
+ gyp_dir = os.path.dirname(gyp_file)
1866
+ path_dict = _GetPathDict(root, gyp_dir)
1867
+ path_dict[target + ".vcproj"] = project_objects[p]
1868
+ # Walk down from the top until we hit a folder that has more than one entry.
1869
+ # In practice, this strips the top-level "src/" dir from the hierarchy in
1870
+ # the solution.
1871
+ while len(root) == 1 and type(root[next(iter(root))]) == dict:
1872
+ root = root[next(iter(root))]
1873
+ # Collapse singles.
1874
+ root = _CollapseSingles("", root)
1875
+ # Merge buckets until everything is a root entry.
1876
+ return _DictsToFolders("", root, flat)
1877
+
1878
+
1879
+ def _GetPathOfProject(qualified_target, spec, options, msvs_version):
1880
+ default_config = _GetDefaultConfiguration(spec)
1881
+ proj_filename = default_config.get("msvs_existing_vcproj")
1882
+ if not proj_filename:
1883
+ proj_filename = spec["target_name"]
1884
+ if spec["toolset"] == "host":
1885
+ proj_filename += "_host"
1886
+ proj_filename = proj_filename + options.suffix + msvs_version.ProjectExtension()
1887
+
1888
+ build_file = gyp.common.BuildFile(qualified_target)
1889
+ proj_path = os.path.join(os.path.dirname(build_file), proj_filename)
1890
+ fix_prefix = None
1891
+ if options.generator_output:
1892
+ project_dir_path = os.path.dirname(os.path.abspath(proj_path))
1893
+ proj_path = os.path.join(options.generator_output, proj_path)
1894
+ fix_prefix = gyp.common.RelativePath(
1895
+ project_dir_path, os.path.dirname(proj_path)
1896
+ )
1897
+ return proj_path, fix_prefix
1898
+
1899
+
1900
+ def _GetPlatformOverridesOfProject(spec):
1901
+ # Prepare a dict indicating which project configurations are used for which
1902
+ # solution configurations for this target.
1903
+ config_platform_overrides = {}
1904
+ for config_name, c in spec["configurations"].items():
1905
+ config_fullname = _ConfigFullName(config_name, c)
1906
+ platform = c.get("msvs_target_platform", _ConfigPlatform(c))
1907
+ fixed_config_fullname = "{}|{}".format(
1908
+ _ConfigBaseName(config_name, _ConfigPlatform(c)),
1909
+ platform,
1910
+ )
1911
+ if spec["toolset"] == "host" and generator_supports_multiple_toolsets:
1912
+ fixed_config_fullname = f"{config_name}|x64"
1913
+ config_platform_overrides[config_fullname] = fixed_config_fullname
1914
+ return config_platform_overrides
1915
+
1916
+
1917
+ def _CreateProjectObjects(target_list, target_dicts, options, msvs_version):
1918
+ """Create a MSVSProject object for the targets found in target list.
1919
+
1920
+ Arguments:
1921
+ target_list: the list of targets to generate project objects for.
1922
+ target_dicts: the dictionary of specifications.
1923
+ options: global generator options.
1924
+ msvs_version: the MSVSVersion object.
1925
+ Returns:
1926
+ A set of created projects, keyed by target.
1927
+ """
1928
+ global fixpath_prefix
1929
+ # Generate each project.
1930
+ projects = {}
1931
+ for qualified_target in target_list:
1932
+ spec = target_dicts[qualified_target]
1933
+ proj_path, fixpath_prefix = _GetPathOfProject(
1934
+ qualified_target, spec, options, msvs_version
1935
+ )
1936
+ guid = _GetGuidOfProject(proj_path, spec)
1937
+ overrides = _GetPlatformOverridesOfProject(spec)
1938
+ build_file = gyp.common.BuildFile(qualified_target)
1939
+ # Create object for this project.
1940
+ target_name = spec["target_name"]
1941
+ if spec["toolset"] == "host":
1942
+ target_name += "_host"
1943
+ obj = MSVSNew.MSVSProject(
1944
+ proj_path,
1945
+ name=target_name,
1946
+ guid=guid,
1947
+ spec=spec,
1948
+ build_file=build_file,
1949
+ config_platform_overrides=overrides,
1950
+ fixpath_prefix=fixpath_prefix,
1951
+ )
1952
+ # Set project toolset if any (MS build only)
1953
+ if msvs_version.UsesVcxproj():
1954
+ obj.set_msbuild_toolset(
1955
+ _GetMsbuildToolsetOfProject(proj_path, spec, msvs_version)
1956
+ )
1957
+ projects[qualified_target] = obj
1958
+ # Set all the dependencies, but not if we are using an external builder like
1959
+ # ninja
1960
+ for project in projects.values():
1961
+ if not project.spec.get("msvs_external_builder"):
1962
+ deps = project.spec.get("dependencies", [])
1963
+ deps = [projects[d] for d in deps]
1964
+ project.set_dependencies(deps)
1965
+ return projects
1966
+
1967
+
1968
+ def _InitNinjaFlavor(params, target_list, target_dicts):
1969
+ """Initialize targets for the ninja flavor.
1970
+
1971
+ This sets up the necessary variables in the targets to generate msvs projects
1972
+ that use ninja as an external builder. The variables in the spec are only set
1973
+ if they have not been set. This allows individual specs to override the
1974
+ default values initialized here.
1975
+ Arguments:
1976
+ params: Params provided to the generator.
1977
+ target_list: List of target pairs: 'base/base.gyp:base'.
1978
+ target_dicts: Dict of target properties keyed on target pair.
1979
+ """
1980
+ for qualified_target in target_list:
1981
+ spec = target_dicts[qualified_target]
1982
+ if spec.get("msvs_external_builder"):
1983
+ # The spec explicitly defined an external builder, so don't change it.
1984
+ continue
1985
+
1986
+ path_to_ninja = spec.get("msvs_path_to_ninja", "ninja.exe")
1987
+
1988
+ spec["msvs_external_builder"] = "ninja"
1989
+ if not spec.get("msvs_external_builder_out_dir"):
1990
+ gyp_file, _, _ = gyp.common.ParseQualifiedTarget(qualified_target)
1991
+ gyp_dir = os.path.dirname(gyp_file)
1992
+ configuration = "$(Configuration)"
1993
+ if params.get("target_arch") == "x64":
1994
+ configuration += "_x64"
1995
+ if params.get("target_arch") == "arm64":
1996
+ configuration += "_arm64"
1997
+ spec["msvs_external_builder_out_dir"] = os.path.join(
1998
+ gyp.common.RelativePath(params["options"].toplevel_dir, gyp_dir),
1999
+ ninja_generator.ComputeOutputDir(params),
2000
+ configuration,
2001
+ )
2002
+ if not spec.get("msvs_external_builder_build_cmd"):
2003
+ spec["msvs_external_builder_build_cmd"] = [
2004
+ path_to_ninja,
2005
+ "-C",
2006
+ "$(OutDir)",
2007
+ "$(ProjectName)",
2008
+ ]
2009
+ if not spec.get("msvs_external_builder_clean_cmd"):
2010
+ spec["msvs_external_builder_clean_cmd"] = [
2011
+ path_to_ninja,
2012
+ "-C",
2013
+ "$(OutDir)",
2014
+ "-tclean",
2015
+ "$(ProjectName)",
2016
+ ]
2017
+
2018
+
2019
+ def CalculateVariables(default_variables, params):
2020
+ """Generated variables that require params to be known."""
2021
+
2022
+ generator_flags = params.get("generator_flags", {})
2023
+
2024
+ # Select project file format version (if unset, default to auto detecting).
2025
+ msvs_version = MSVSVersion.SelectVisualStudioVersion(
2026
+ generator_flags.get("msvs_version", "auto")
2027
+ )
2028
+ # Stash msvs_version for later (so we don't have to probe the system twice).
2029
+ params["msvs_version"] = msvs_version
2030
+
2031
+ # Set a variable so conditions can be based on msvs_version.
2032
+ default_variables["MSVS_VERSION"] = msvs_version.ShortName()
2033
+
2034
+ # To determine processor word size on Windows, in addition to checking
2035
+ # PROCESSOR_ARCHITECTURE (which reflects the word size of the current
2036
+ # process), it is also necessary to check PROCESSOR_ARCITEW6432 (which
2037
+ # contains the actual word size of the system when running thru WOW64).
2038
+ if (
2039
+ os.environ.get("PROCESSOR_ARCHITECTURE", "").find("64") >= 0
2040
+ or os.environ.get("PROCESSOR_ARCHITEW6432", "").find("64") >= 0
2041
+ ):
2042
+ default_variables["MSVS_OS_BITS"] = 64
2043
+ else:
2044
+ default_variables["MSVS_OS_BITS"] = 32
2045
+
2046
+ if gyp.common.GetFlavor(params) == "ninja":
2047
+ default_variables["SHARED_INTERMEDIATE_DIR"] = "$(OutDir)gen"
2048
+
2049
+
2050
+ def PerformBuild(data, configurations, params):
2051
+ options = params["options"]
2052
+ msvs_version = params["msvs_version"]
2053
+ devenv = os.path.join(msvs_version.path, "Common7", "IDE", "devenv.com")
2054
+
2055
+ for build_file, build_file_dict in data.items():
2056
+ (build_file_root, build_file_ext) = os.path.splitext(build_file)
2057
+ if build_file_ext != ".gyp":
2058
+ continue
2059
+ sln_path = build_file_root + options.suffix + ".sln"
2060
+ if options.generator_output:
2061
+ sln_path = os.path.join(options.generator_output, sln_path)
2062
+
2063
+ for config in configurations:
2064
+ arguments = [devenv, sln_path, "/Build", config]
2065
+ print(f"Building [{config}]: {arguments}")
2066
+ subprocess.check_call(arguments)
2067
+
2068
+
2069
+ def CalculateGeneratorInputInfo(params):
2070
+ if params.get("flavor") == "ninja":
2071
+ toplevel = params["options"].toplevel_dir
2072
+ qualified_out_dir = os.path.normpath(
2073
+ os.path.join(
2074
+ toplevel,
2075
+ ninja_generator.ComputeOutputDir(params),
2076
+ "gypfiles-msvs-ninja",
2077
+ )
2078
+ )
2079
+
2080
+ global generator_filelist_paths
2081
+ generator_filelist_paths = {
2082
+ "toplevel": toplevel,
2083
+ "qualified_out_dir": qualified_out_dir,
2084
+ }
2085
+
2086
+
2087
+ def GenerateOutput(target_list, target_dicts, data, params):
2088
+ """Generate .sln and .vcproj files.
2089
+
2090
+ This is the entry point for this generator.
2091
+ Arguments:
2092
+ target_list: List of target pairs: 'base/base.gyp:base'.
2093
+ target_dicts: Dict of target properties keyed on target pair.
2094
+ data: Dictionary containing per .gyp data.
2095
+ """
2096
+ global fixpath_prefix
2097
+
2098
+ options = params["options"]
2099
+
2100
+ # Get the project file format version back out of where we stashed it in
2101
+ # GeneratorCalculatedVariables.
2102
+ msvs_version = params["msvs_version"]
2103
+
2104
+ generator_flags = params.get("generator_flags", {})
2105
+
2106
+ # Optionally shard targets marked with 'msvs_shard': SHARD_COUNT.
2107
+ (target_list, target_dicts) = MSVSUtil.ShardTargets(target_list, target_dicts)
2108
+
2109
+ # Optionally use the large PDB workaround for targets marked with
2110
+ # 'msvs_large_pdb': 1.
2111
+ (target_list, target_dicts) = MSVSUtil.InsertLargePdbShims(
2112
+ target_list, target_dicts, generator_default_variables
2113
+ )
2114
+
2115
+ # Optionally configure each spec to use ninja as the external builder.
2116
+ if params.get("flavor") == "ninja":
2117
+ _InitNinjaFlavor(params, target_list, target_dicts)
2118
+
2119
+ # Prepare the set of configurations.
2120
+ configs = set()
2121
+ for qualified_target in target_list:
2122
+ spec = target_dicts[qualified_target]
2123
+ for config_name, config in spec["configurations"].items():
2124
+ config_name = _ConfigFullName(config_name, config)
2125
+ configs.add(config_name)
2126
+ if config_name == "Release|arm64":
2127
+ configs.add("Release|x64")
2128
+ configs = list(configs)
2129
+
2130
+ # Figure out all the projects that will be generated and their guids
2131
+ project_objects = _CreateProjectObjects(
2132
+ target_list, target_dicts, options, msvs_version
2133
+ )
2134
+
2135
+ # Generate each project.
2136
+ missing_sources = []
2137
+ for project in project_objects.values():
2138
+ fixpath_prefix = project.fixpath_prefix
2139
+ missing_sources.extend(
2140
+ _GenerateProject(project, options, msvs_version, generator_flags, spec)
2141
+ )
2142
+ fixpath_prefix = None
2143
+
2144
+ for build_file in data:
2145
+ # Validate build_file extension
2146
+ target_only_configs = configs
2147
+ if generator_supports_multiple_toolsets:
2148
+ target_only_configs = [i for i in configs if i.endswith("arm64")]
2149
+ if not build_file.endswith(".gyp"):
2150
+ continue
2151
+ sln_path = os.path.splitext(build_file)[0] + options.suffix + ".sln"
2152
+ if options.generator_output:
2153
+ sln_path = os.path.join(options.generator_output, sln_path)
2154
+ # Get projects in the solution, and their dependents.
2155
+ sln_projects = gyp.common.BuildFileTargets(target_list, build_file)
2156
+ sln_projects += gyp.common.DeepDependencyTargets(target_dicts, sln_projects)
2157
+ # Create folder hierarchy.
2158
+ root_entries = _GatherSolutionFolders(
2159
+ sln_projects, project_objects, flat=msvs_version.FlatSolution()
2160
+ )
2161
+ # Create solution.
2162
+ sln = MSVSNew.MSVSSolution(
2163
+ sln_path,
2164
+ entries=root_entries,
2165
+ variants=target_only_configs,
2166
+ websiteProperties=False,
2167
+ version=msvs_version,
2168
+ )
2169
+ sln.Write()
2170
+
2171
+ if missing_sources:
2172
+ error_message = "Missing input files:\n" + "\n".join(set(missing_sources))
2173
+ if generator_flags.get("msvs_error_on_missing_sources", False):
2174
+ raise GypError(error_message)
2175
+ else:
2176
+ print("Warning: " + error_message, file=sys.stdout)
2177
+
2178
+
2179
+ def _GenerateMSBuildFiltersFile(
2180
+ filters_path,
2181
+ source_files,
2182
+ rule_dependencies,
2183
+ extension_to_rule_name,
2184
+ platforms,
2185
+ toolset,
2186
+ ):
2187
+ """Generate the filters file.
2188
+
2189
+ This file is used by Visual Studio to organize the presentation of source
2190
+ files into folders.
2191
+
2192
+ Arguments:
2193
+ filters_path: The path of the file to be created.
2194
+ source_files: The hierarchical structure of all the sources.
2195
+ extension_to_rule_name: A dictionary mapping file extensions to rules.
2196
+ """
2197
+ filter_group = []
2198
+ source_group = []
2199
+ _AppendFiltersForMSBuild(
2200
+ "",
2201
+ source_files,
2202
+ rule_dependencies,
2203
+ extension_to_rule_name,
2204
+ platforms,
2205
+ toolset,
2206
+ filter_group,
2207
+ source_group,
2208
+ )
2209
+ if filter_group:
2210
+ content = [
2211
+ "Project",
2212
+ {
2213
+ "ToolsVersion": "4.0",
2214
+ "xmlns": "http://schemas.microsoft.com/developer/msbuild/2003",
2215
+ },
2216
+ ["ItemGroup"] + filter_group,
2217
+ ["ItemGroup"] + source_group,
2218
+ ]
2219
+ easy_xml.WriteXmlIfChanged(content, filters_path, pretty=True, win32=True)
2220
+ elif os.path.exists(filters_path):
2221
+ # We don't need this filter anymore. Delete the old filter file.
2222
+ os.unlink(filters_path)
2223
+
2224
+
2225
+ def _AppendFiltersForMSBuild(
2226
+ parent_filter_name,
2227
+ sources,
2228
+ rule_dependencies,
2229
+ extension_to_rule_name,
2230
+ platforms,
2231
+ toolset,
2232
+ filter_group,
2233
+ source_group,
2234
+ ):
2235
+ """Creates the list of filters and sources to be added in the filter file.
2236
+
2237
+ Args:
2238
+ parent_filter_name: The name of the filter under which the sources are
2239
+ found.
2240
+ sources: The hierarchy of filters and sources to process.
2241
+ extension_to_rule_name: A dictionary mapping file extensions to rules.
2242
+ filter_group: The list to which filter entries will be appended.
2243
+ source_group: The list to which source entries will be appended.
2244
+ """
2245
+ for source in sources:
2246
+ if isinstance(source, MSVSProject.Filter):
2247
+ # We have a sub-filter. Create the name of that sub-filter.
2248
+ if not parent_filter_name:
2249
+ filter_name = source.name
2250
+ else:
2251
+ filter_name = f"{parent_filter_name}\\{source.name}"
2252
+ # Add the filter to the group.
2253
+ filter_group.append(
2254
+ [
2255
+ "Filter",
2256
+ {"Include": filter_name},
2257
+ ["UniqueIdentifier", MSVSNew.MakeGuid(source.name)],
2258
+ ]
2259
+ )
2260
+ # Recurse and add its dependents.
2261
+ _AppendFiltersForMSBuild(
2262
+ filter_name,
2263
+ source.contents,
2264
+ rule_dependencies,
2265
+ extension_to_rule_name,
2266
+ platforms,
2267
+ toolset,
2268
+ filter_group,
2269
+ source_group,
2270
+ )
2271
+ else:
2272
+ # It's a source. Create a source entry.
2273
+ _, element = _MapFileToMsBuildSourceType(
2274
+ source, rule_dependencies, extension_to_rule_name, platforms, toolset
2275
+ )
2276
+ source_entry = [element, {"Include": source}]
2277
+ # Specify the filter it is part of, if any.
2278
+ if parent_filter_name:
2279
+ source_entry.append(["Filter", parent_filter_name])
2280
+ source_group.append(source_entry)
2281
+
2282
+
2283
+ def _MapFileToMsBuildSourceType(
2284
+ source, rule_dependencies, extension_to_rule_name, platforms, toolset
2285
+ ):
2286
+ """Returns the group and element type of the source file.
2287
+
2288
+ Arguments:
2289
+ source: The source file name.
2290
+ extension_to_rule_name: A dictionary mapping file extensions to rules.
2291
+
2292
+ Returns:
2293
+ A pair of (group this file should be part of, the label of element)
2294
+ """
2295
+ _, ext = os.path.splitext(source)
2296
+ ext = ext.lower()
2297
+ if ext in extension_to_rule_name:
2298
+ group = "rule"
2299
+ element = extension_to_rule_name[ext]
2300
+ elif ext in [".cc", ".cpp", ".c", ".cxx", ".mm"]:
2301
+ group = "compile"
2302
+ element = "ClCompile"
2303
+ elif ext in [".h", ".hxx"]:
2304
+ group = "include"
2305
+ element = "ClInclude"
2306
+ elif ext == ".rc":
2307
+ group = "resource"
2308
+ element = "ResourceCompile"
2309
+ elif ext in [".s", ".asm"]:
2310
+ group = "masm"
2311
+ element = "MASM"
2312
+ if "arm64" in platforms and toolset == "target":
2313
+ element = "MARMASM"
2314
+ elif ext == ".idl":
2315
+ group = "midl"
2316
+ element = "Midl"
2317
+ elif source in rule_dependencies:
2318
+ group = "rule_dependency"
2319
+ element = "CustomBuild"
2320
+ else:
2321
+ group = "none"
2322
+ element = "None"
2323
+ return (group, element)
2324
+
2325
+
2326
+ def _GenerateRulesForMSBuild(
2327
+ output_dir,
2328
+ options,
2329
+ spec,
2330
+ sources,
2331
+ excluded_sources,
2332
+ props_files_of_rules,
2333
+ targets_files_of_rules,
2334
+ actions_to_add,
2335
+ rule_dependencies,
2336
+ extension_to_rule_name,
2337
+ ):
2338
+ # MSBuild rules are implemented using three files: an XML file, a .targets
2339
+ # file and a .props file.
2340
+ # For more details see:
2341
+ # https://devblogs.microsoft.com/cppblog/quick-help-on-vs2010-custom-build-rule/
2342
+ rules = spec.get("rules", [])
2343
+ rules_native = [r for r in rules if not int(r.get("msvs_external_rule", 0))]
2344
+ rules_external = [r for r in rules if int(r.get("msvs_external_rule", 0))]
2345
+
2346
+ msbuild_rules = []
2347
+ for rule in rules_native:
2348
+ # Skip a rule with no action and no inputs.
2349
+ if "action" not in rule and not rule.get("rule_sources", []):
2350
+ continue
2351
+ msbuild_rule = MSBuildRule(rule, spec)
2352
+ msbuild_rules.append(msbuild_rule)
2353
+ rule_dependencies.update(msbuild_rule.additional_dependencies.split(";"))
2354
+ extension_to_rule_name[msbuild_rule.extension] = msbuild_rule.rule_name
2355
+ if msbuild_rules:
2356
+ base = spec["target_name"] + options.suffix
2357
+ props_name = base + ".props"
2358
+ targets_name = base + ".targets"
2359
+ xml_name = base + ".xml"
2360
+
2361
+ props_files_of_rules.add(props_name)
2362
+ targets_files_of_rules.add(targets_name)
2363
+
2364
+ props_path = os.path.join(output_dir, props_name)
2365
+ targets_path = os.path.join(output_dir, targets_name)
2366
+ xml_path = os.path.join(output_dir, xml_name)
2367
+
2368
+ _GenerateMSBuildRulePropsFile(props_path, msbuild_rules)
2369
+ _GenerateMSBuildRuleTargetsFile(targets_path, msbuild_rules)
2370
+ _GenerateMSBuildRuleXmlFile(xml_path, msbuild_rules)
2371
+
2372
+ if rules_external:
2373
+ _GenerateExternalRules(
2374
+ rules_external, output_dir, spec, sources, options, actions_to_add
2375
+ )
2376
+ _AdjustSourcesForRules(rules, sources, excluded_sources, True)
2377
+
2378
+
2379
+ class MSBuildRule:
2380
+ """Used to store information used to generate an MSBuild rule.
2381
+
2382
+ Attributes:
2383
+ rule_name: The rule name, sanitized to use in XML.
2384
+ target_name: The name of the target.
2385
+ after_targets: The name of the AfterTargets element.
2386
+ before_targets: The name of the BeforeTargets element.
2387
+ depends_on: The name of the DependsOn element.
2388
+ compute_output: The name of the ComputeOutput element.
2389
+ dirs_to_make: The name of the DirsToMake element.
2390
+ inputs: The name of the _inputs element.
2391
+ tlog: The name of the _tlog element.
2392
+ extension: The extension this rule applies to.
2393
+ description: The message displayed when this rule is invoked.
2394
+ additional_dependencies: A string listing additional dependencies.
2395
+ outputs: The outputs of this rule.
2396
+ command: The command used to run the rule.
2397
+ """
2398
+
2399
+ def __init__(self, rule, spec):
2400
+ self.display_name = rule["rule_name"]
2401
+ # Assure that the rule name is only characters and numbers
2402
+ self.rule_name = re.sub(r"\W", "_", self.display_name)
2403
+ # Create the various element names, following the example set by the
2404
+ # Visual Studio 2008 to 2010 conversion. I don't know if VS2010
2405
+ # is sensitive to the exact names.
2406
+ self.target_name = "_" + self.rule_name
2407
+ self.after_targets = self.rule_name + "AfterTargets"
2408
+ self.before_targets = self.rule_name + "BeforeTargets"
2409
+ self.depends_on = self.rule_name + "DependsOn"
2410
+ self.compute_output = "Compute%sOutput" % self.rule_name
2411
+ self.dirs_to_make = self.rule_name + "DirsToMake"
2412
+ self.inputs = self.rule_name + "_inputs"
2413
+ self.tlog = self.rule_name + "_tlog"
2414
+ self.extension = rule["extension"]
2415
+ if not self.extension.startswith("."):
2416
+ self.extension = "." + self.extension
2417
+
2418
+ self.description = MSVSSettings.ConvertVCMacrosToMSBuild(
2419
+ rule.get("message", self.rule_name)
2420
+ )
2421
+ old_additional_dependencies = _FixPaths(rule.get("inputs", []))
2422
+ self.additional_dependencies = ";".join(
2423
+ [
2424
+ MSVSSettings.ConvertVCMacrosToMSBuild(i)
2425
+ for i in old_additional_dependencies
2426
+ ]
2427
+ )
2428
+ old_outputs = _FixPaths(rule.get("outputs", []))
2429
+ self.outputs = ";".join(
2430
+ [MSVSSettings.ConvertVCMacrosToMSBuild(i) for i in old_outputs]
2431
+ )
2432
+ old_command = _BuildCommandLineForRule(
2433
+ spec, rule, has_input_path=True, do_setup_env=True
2434
+ )
2435
+ self.command = MSVSSettings.ConvertVCMacrosToMSBuild(old_command)
2436
+
2437
+
2438
+ def _GenerateMSBuildRulePropsFile(props_path, msbuild_rules):
2439
+ """Generate the .props file."""
2440
+ content = [
2441
+ "Project",
2442
+ {"xmlns": "http://schemas.microsoft.com/developer/msbuild/2003"},
2443
+ ]
2444
+ for rule in msbuild_rules:
2445
+ content.extend(
2446
+ [
2447
+ [
2448
+ "PropertyGroup",
2449
+ {
2450
+ "Condition": "'$(%s)' == '' and '$(%s)' == '' and "
2451
+ "'$(ConfigurationType)' != 'Makefile'"
2452
+ % (rule.before_targets, rule.after_targets)
2453
+ },
2454
+ [rule.before_targets, "Midl"],
2455
+ [rule.after_targets, "CustomBuild"],
2456
+ ],
2457
+ [
2458
+ "PropertyGroup",
2459
+ [
2460
+ rule.depends_on,
2461
+ {"Condition": "'$(ConfigurationType)' != 'Makefile'"},
2462
+ "_SelectedFiles;$(%s)" % rule.depends_on,
2463
+ ],
2464
+ ],
2465
+ [
2466
+ "ItemDefinitionGroup",
2467
+ [
2468
+ rule.rule_name,
2469
+ ["CommandLineTemplate", rule.command],
2470
+ ["Outputs", rule.outputs],
2471
+ ["ExecutionDescription", rule.description],
2472
+ ["AdditionalDependencies", rule.additional_dependencies],
2473
+ ],
2474
+ ],
2475
+ ]
2476
+ )
2477
+ easy_xml.WriteXmlIfChanged(content, props_path, pretty=True, win32=True)
2478
+
2479
+
2480
+ def _GenerateMSBuildRuleTargetsFile(targets_path, msbuild_rules):
2481
+ """Generate the .targets file."""
2482
+ content = [
2483
+ "Project",
2484
+ {"xmlns": "http://schemas.microsoft.com/developer/msbuild/2003"},
2485
+ ]
2486
+ item_group = [
2487
+ "ItemGroup",
2488
+ [
2489
+ "PropertyPageSchema",
2490
+ {"Include": "$(MSBuildThisFileDirectory)$(MSBuildThisFileName).xml"},
2491
+ ],
2492
+ ]
2493
+ for rule in msbuild_rules:
2494
+ item_group.append(
2495
+ [
2496
+ "AvailableItemName",
2497
+ {"Include": rule.rule_name},
2498
+ ["Targets", rule.target_name],
2499
+ ]
2500
+ )
2501
+ content.append(item_group)
2502
+
2503
+ for rule in msbuild_rules:
2504
+ content.append(
2505
+ [
2506
+ "UsingTask",
2507
+ {
2508
+ "TaskName": rule.rule_name,
2509
+ "TaskFactory": "XamlTaskFactory",
2510
+ "AssemblyName": "Microsoft.Build.Tasks.v4.0",
2511
+ },
2512
+ ["Task", "$(MSBuildThisFileDirectory)$(MSBuildThisFileName).xml"],
2513
+ ]
2514
+ )
2515
+ for rule in msbuild_rules:
2516
+ rule_name = rule.rule_name
2517
+ target_outputs = "%%(%s.Outputs)" % rule_name
2518
+ target_inputs = (
2519
+ "%%(%s.Identity);%%(%s.AdditionalDependencies);" "$(MSBuildProjectFile)"
2520
+ ) % (rule_name, rule_name)
2521
+ rule_inputs = "%%(%s.Identity)" % rule_name
2522
+ extension_condition = (
2523
+ "'%(Extension)'=='.obj' or "
2524
+ "'%(Extension)'=='.res' or "
2525
+ "'%(Extension)'=='.rsc' or "
2526
+ "'%(Extension)'=='.lib'"
2527
+ )
2528
+ remove_section = [
2529
+ "ItemGroup",
2530
+ {"Condition": "'@(SelectedFiles)' != ''"},
2531
+ [
2532
+ rule_name,
2533
+ {
2534
+ "Remove": "@(%s)" % rule_name,
2535
+ "Condition": "'%(Identity)' != '@(SelectedFiles)'",
2536
+ },
2537
+ ],
2538
+ ]
2539
+ inputs_section = [
2540
+ "ItemGroup",
2541
+ [rule.inputs, {"Include": "%%(%s.AdditionalDependencies)" % rule_name}],
2542
+ ]
2543
+ logging_section = [
2544
+ "ItemGroup",
2545
+ [
2546
+ rule.tlog,
2547
+ {
2548
+ "Include": "%%(%s.Outputs)" % rule_name,
2549
+ "Condition": (
2550
+ "'%%(%s.Outputs)' != '' and "
2551
+ "'%%(%s.ExcludedFromBuild)' != 'true'" % (rule_name, rule_name)
2552
+ ),
2553
+ },
2554
+ ["Source", "@(%s, '|')" % rule_name],
2555
+ ["Inputs", "@(%s -> '%%(Fullpath)', ';')" % rule.inputs],
2556
+ ],
2557
+ ]
2558
+ message_section = [
2559
+ "Message",
2560
+ {"Importance": "High", "Text": "%%(%s.ExecutionDescription)" % rule_name},
2561
+ ]
2562
+ write_tlog_section = [
2563
+ "WriteLinesToFile",
2564
+ {
2565
+ "Condition": "'@(%s)' != '' and '%%(%s.ExcludedFromBuild)' != "
2566
+ "'true'" % (rule.tlog, rule.tlog),
2567
+ "File": "$(IntDir)$(ProjectName).write.1.tlog",
2568
+ "Lines": "^%%(%s.Source);@(%s->'%%(Fullpath)')"
2569
+ % (rule.tlog, rule.tlog),
2570
+ },
2571
+ ]
2572
+ read_tlog_section = [
2573
+ "WriteLinesToFile",
2574
+ {
2575
+ "Condition": "'@(%s)' != '' and '%%(%s.ExcludedFromBuild)' != "
2576
+ "'true'" % (rule.tlog, rule.tlog),
2577
+ "File": "$(IntDir)$(ProjectName).read.1.tlog",
2578
+ "Lines": f"^%({rule.tlog}.Source);%({rule.tlog}.Inputs)",
2579
+ },
2580
+ ]
2581
+ command_and_input_section = [
2582
+ rule_name,
2583
+ {
2584
+ "Condition": "'@(%s)' != '' and '%%(%s.ExcludedFromBuild)' != "
2585
+ "'true'" % (rule_name, rule_name),
2586
+ "EchoOff": "true",
2587
+ "StandardOutputImportance": "High",
2588
+ "StandardErrorImportance": "High",
2589
+ "CommandLineTemplate": "%%(%s.CommandLineTemplate)" % rule_name,
2590
+ "AdditionalOptions": "%%(%s.AdditionalOptions)" % rule_name,
2591
+ "Inputs": rule_inputs,
2592
+ },
2593
+ ]
2594
+ content.extend(
2595
+ [
2596
+ [
2597
+ "Target",
2598
+ {
2599
+ "Name": rule.target_name,
2600
+ "BeforeTargets": "$(%s)" % rule.before_targets,
2601
+ "AfterTargets": "$(%s)" % rule.after_targets,
2602
+ "Condition": "'@(%s)' != ''" % rule_name,
2603
+ "DependsOnTargets": "$(%s);%s"
2604
+ % (rule.depends_on, rule.compute_output),
2605
+ "Outputs": target_outputs,
2606
+ "Inputs": target_inputs,
2607
+ },
2608
+ remove_section,
2609
+ inputs_section,
2610
+ logging_section,
2611
+ message_section,
2612
+ write_tlog_section,
2613
+ read_tlog_section,
2614
+ command_and_input_section,
2615
+ ],
2616
+ [
2617
+ "PropertyGroup",
2618
+ [
2619
+ "ComputeLinkInputsTargets",
2620
+ "$(ComputeLinkInputsTargets);",
2621
+ "%s;" % rule.compute_output,
2622
+ ],
2623
+ [
2624
+ "ComputeLibInputsTargets",
2625
+ "$(ComputeLibInputsTargets);",
2626
+ "%s;" % rule.compute_output,
2627
+ ],
2628
+ ],
2629
+ [
2630
+ "Target",
2631
+ {
2632
+ "Name": rule.compute_output,
2633
+ "Condition": "'@(%s)' != ''" % rule_name,
2634
+ },
2635
+ [
2636
+ "ItemGroup",
2637
+ [
2638
+ rule.dirs_to_make,
2639
+ {
2640
+ "Condition": "'@(%s)' != '' and "
2641
+ "'%%(%s.ExcludedFromBuild)' != 'true'"
2642
+ % (rule_name, rule_name),
2643
+ "Include": "%%(%s.Outputs)" % rule_name,
2644
+ },
2645
+ ],
2646
+ [
2647
+ "Link",
2648
+ {
2649
+ "Include": "%%(%s.Identity)" % rule.dirs_to_make,
2650
+ "Condition": extension_condition,
2651
+ },
2652
+ ],
2653
+ [
2654
+ "Lib",
2655
+ {
2656
+ "Include": "%%(%s.Identity)" % rule.dirs_to_make,
2657
+ "Condition": extension_condition,
2658
+ },
2659
+ ],
2660
+ [
2661
+ "ImpLib",
2662
+ {
2663
+ "Include": "%%(%s.Identity)" % rule.dirs_to_make,
2664
+ "Condition": extension_condition,
2665
+ },
2666
+ ],
2667
+ ],
2668
+ [
2669
+ "MakeDir",
2670
+ {
2671
+ "Directories": (
2672
+ "@(%s->'%%(RootDir)%%(Directory)')" % rule.dirs_to_make
2673
+ )
2674
+ },
2675
+ ],
2676
+ ],
2677
+ ]
2678
+ )
2679
+ easy_xml.WriteXmlIfChanged(content, targets_path, pretty=True, win32=True)
2680
+
2681
+
2682
+ def _GenerateMSBuildRuleXmlFile(xml_path, msbuild_rules):
2683
+ # Generate the .xml file
2684
+ content = [
2685
+ "ProjectSchemaDefinitions",
2686
+ {
2687
+ "xmlns": (
2688
+ "clr-namespace:Microsoft.Build.Framework.XamlTypes;"
2689
+ "assembly=Microsoft.Build.Framework"
2690
+ ),
2691
+ "xmlns:x": "http://schemas.microsoft.com/winfx/2006/xaml",
2692
+ "xmlns:sys": "clr-namespace:System;assembly=mscorlib",
2693
+ "xmlns:transformCallback": "Microsoft.Cpp.Dev10.ConvertPropertyCallback",
2694
+ },
2695
+ ]
2696
+ for rule in msbuild_rules:
2697
+ content.extend(
2698
+ [
2699
+ [
2700
+ "Rule",
2701
+ {
2702
+ "Name": rule.rule_name,
2703
+ "PageTemplate": "tool",
2704
+ "DisplayName": rule.display_name,
2705
+ "Order": "200",
2706
+ },
2707
+ [
2708
+ "Rule.DataSource",
2709
+ [
2710
+ "DataSource",
2711
+ {"Persistence": "ProjectFile", "ItemType": rule.rule_name},
2712
+ ],
2713
+ ],
2714
+ [
2715
+ "Rule.Categories",
2716
+ [
2717
+ "Category",
2718
+ {"Name": "General"},
2719
+ ["Category.DisplayName", ["sys:String", "General"]],
2720
+ ],
2721
+ [
2722
+ "Category",
2723
+ {"Name": "Command Line", "Subtype": "CommandLine"},
2724
+ ["Category.DisplayName", ["sys:String", "Command Line"]],
2725
+ ],
2726
+ ],
2727
+ [
2728
+ "StringListProperty",
2729
+ {
2730
+ "Name": "Inputs",
2731
+ "Category": "Command Line",
2732
+ "IsRequired": "true",
2733
+ "Switch": " ",
2734
+ },
2735
+ [
2736
+ "StringListProperty.DataSource",
2737
+ [
2738
+ "DataSource",
2739
+ {
2740
+ "Persistence": "ProjectFile",
2741
+ "ItemType": rule.rule_name,
2742
+ "SourceType": "Item",
2743
+ },
2744
+ ],
2745
+ ],
2746
+ ],
2747
+ [
2748
+ "StringProperty",
2749
+ {
2750
+ "Name": "CommandLineTemplate",
2751
+ "DisplayName": "Command Line",
2752
+ "Visible": "False",
2753
+ "IncludeInCommandLine": "False",
2754
+ },
2755
+ ],
2756
+ [
2757
+ "DynamicEnumProperty",
2758
+ {
2759
+ "Name": rule.before_targets,
2760
+ "Category": "General",
2761
+ "EnumProvider": "Targets",
2762
+ "IncludeInCommandLine": "False",
2763
+ },
2764
+ [
2765
+ "DynamicEnumProperty.DisplayName",
2766
+ ["sys:String", "Execute Before"],
2767
+ ],
2768
+ [
2769
+ "DynamicEnumProperty.Description",
2770
+ [
2771
+ "sys:String",
2772
+ "Specifies the targets for the build customization"
2773
+ " to run before.",
2774
+ ],
2775
+ ],
2776
+ [
2777
+ "DynamicEnumProperty.ProviderSettings",
2778
+ [
2779
+ "NameValuePair",
2780
+ {
2781
+ "Name": "Exclude",
2782
+ "Value": "^%s|^Compute" % rule.before_targets,
2783
+ },
2784
+ ],
2785
+ ],
2786
+ [
2787
+ "DynamicEnumProperty.DataSource",
2788
+ [
2789
+ "DataSource",
2790
+ {
2791
+ "Persistence": "ProjectFile",
2792
+ "HasConfigurationCondition": "true",
2793
+ },
2794
+ ],
2795
+ ],
2796
+ ],
2797
+ [
2798
+ "DynamicEnumProperty",
2799
+ {
2800
+ "Name": rule.after_targets,
2801
+ "Category": "General",
2802
+ "EnumProvider": "Targets",
2803
+ "IncludeInCommandLine": "False",
2804
+ },
2805
+ [
2806
+ "DynamicEnumProperty.DisplayName",
2807
+ ["sys:String", "Execute After"],
2808
+ ],
2809
+ [
2810
+ "DynamicEnumProperty.Description",
2811
+ [
2812
+ "sys:String",
2813
+ (
2814
+ "Specifies the targets for the build customization"
2815
+ " to run after."
2816
+ ),
2817
+ ],
2818
+ ],
2819
+ [
2820
+ "DynamicEnumProperty.ProviderSettings",
2821
+ [
2822
+ "NameValuePair",
2823
+ {
2824
+ "Name": "Exclude",
2825
+ "Value": "^%s|^Compute" % rule.after_targets,
2826
+ },
2827
+ ],
2828
+ ],
2829
+ [
2830
+ "DynamicEnumProperty.DataSource",
2831
+ [
2832
+ "DataSource",
2833
+ {
2834
+ "Persistence": "ProjectFile",
2835
+ "ItemType": "",
2836
+ "HasConfigurationCondition": "true",
2837
+ },
2838
+ ],
2839
+ ],
2840
+ ],
2841
+ [
2842
+ "StringListProperty",
2843
+ {
2844
+ "Name": "Outputs",
2845
+ "DisplayName": "Outputs",
2846
+ "Visible": "False",
2847
+ "IncludeInCommandLine": "False",
2848
+ },
2849
+ ],
2850
+ [
2851
+ "StringProperty",
2852
+ {
2853
+ "Name": "ExecutionDescription",
2854
+ "DisplayName": "Execution Description",
2855
+ "Visible": "False",
2856
+ "IncludeInCommandLine": "False",
2857
+ },
2858
+ ],
2859
+ [
2860
+ "StringListProperty",
2861
+ {
2862
+ "Name": "AdditionalDependencies",
2863
+ "DisplayName": "Additional Dependencies",
2864
+ "IncludeInCommandLine": "False",
2865
+ "Visible": "false",
2866
+ },
2867
+ ],
2868
+ [
2869
+ "StringProperty",
2870
+ {
2871
+ "Subtype": "AdditionalOptions",
2872
+ "Name": "AdditionalOptions",
2873
+ "Category": "Command Line",
2874
+ },
2875
+ [
2876
+ "StringProperty.DisplayName",
2877
+ ["sys:String", "Additional Options"],
2878
+ ],
2879
+ [
2880
+ "StringProperty.Description",
2881
+ ["sys:String", "Additional Options"],
2882
+ ],
2883
+ ],
2884
+ ],
2885
+ [
2886
+ "ItemType",
2887
+ {"Name": rule.rule_name, "DisplayName": rule.display_name},
2888
+ ],
2889
+ [
2890
+ "FileExtension",
2891
+ {"Name": "*" + rule.extension, "ContentType": rule.rule_name},
2892
+ ],
2893
+ [
2894
+ "ContentType",
2895
+ {
2896
+ "Name": rule.rule_name,
2897
+ "DisplayName": "",
2898
+ "ItemType": rule.rule_name,
2899
+ },
2900
+ ],
2901
+ ]
2902
+ )
2903
+ easy_xml.WriteXmlIfChanged(content, xml_path, pretty=True, win32=True)
2904
+
2905
+
2906
+ def _GetConfigurationAndPlatform(name, settings, spec):
2907
+ configuration = name.rsplit("_", 1)[0]
2908
+ platform = settings.get("msvs_configuration_platform", "Win32")
2909
+ if spec["toolset"] == "host" and platform == "arm64":
2910
+ platform = "x64" # Host-only tools are always built for x64
2911
+ return (configuration, platform)
2912
+
2913
+
2914
+ def _GetConfigurationCondition(name, settings, spec):
2915
+ return r"'$(Configuration)|$(Platform)'=='%s|%s'" % _GetConfigurationAndPlatform(
2916
+ name, settings, spec
2917
+ )
2918
+
2919
+
2920
+ def _GetMSBuildProjectConfigurations(configurations, spec):
2921
+ group = ["ItemGroup", {"Label": "ProjectConfigurations"}]
2922
+ for (name, settings) in sorted(configurations.items()):
2923
+ configuration, platform = _GetConfigurationAndPlatform(name, settings, spec)
2924
+ designation = f"{configuration}|{platform}"
2925
+ group.append(
2926
+ [
2927
+ "ProjectConfiguration",
2928
+ {"Include": designation},
2929
+ ["Configuration", configuration],
2930
+ ["Platform", platform],
2931
+ ]
2932
+ )
2933
+ return [group]
2934
+
2935
+
2936
+ def _GetMSBuildGlobalProperties(spec, version, guid, gyp_file_name):
2937
+ namespace = os.path.splitext(gyp_file_name)[0]
2938
+ properties = [
2939
+ [
2940
+ "PropertyGroup",
2941
+ {"Label": "Globals"},
2942
+ ["ProjectGuid", guid],
2943
+ ["Keyword", "Win32Proj"],
2944
+ ["RootNamespace", namespace],
2945
+ ["IgnoreWarnCompileDuplicatedFilename", "true"],
2946
+ ]
2947
+ ]
2948
+
2949
+ if (
2950
+ os.environ.get("PROCESSOR_ARCHITECTURE") == "AMD64"
2951
+ or os.environ.get("PROCESSOR_ARCHITEW6432") == "AMD64"
2952
+ ):
2953
+ properties[0].append(["PreferredToolArchitecture", "x64"])
2954
+
2955
+ if spec.get("msvs_target_platform_version"):
2956
+ target_platform_version = spec.get("msvs_target_platform_version")
2957
+ properties[0].append(["WindowsTargetPlatformVersion", target_platform_version])
2958
+ if spec.get("msvs_target_platform_minversion"):
2959
+ target_platform_minversion = spec.get("msvs_target_platform_minversion")
2960
+ properties[0].append(
2961
+ ["WindowsTargetPlatformMinVersion", target_platform_minversion]
2962
+ )
2963
+ else:
2964
+ properties[0].append(
2965
+ ["WindowsTargetPlatformMinVersion", target_platform_version]
2966
+ )
2967
+
2968
+ if spec.get("msvs_enable_winrt"):
2969
+ properties[0].append(["DefaultLanguage", "en-US"])
2970
+ properties[0].append(["AppContainerApplication", "true"])
2971
+ if spec.get("msvs_application_type_revision"):
2972
+ app_type_revision = spec.get("msvs_application_type_revision")
2973
+ properties[0].append(["ApplicationTypeRevision", app_type_revision])
2974
+ else:
2975
+ properties[0].append(["ApplicationTypeRevision", "8.1"])
2976
+ if spec.get("msvs_enable_winphone"):
2977
+ properties[0].append(["ApplicationType", "Windows Phone"])
2978
+ else:
2979
+ properties[0].append(["ApplicationType", "Windows Store"])
2980
+
2981
+ platform_name = None
2982
+ msvs_windows_sdk_version = None
2983
+ for configuration in spec["configurations"].values():
2984
+ platform_name = platform_name or _ConfigPlatform(configuration)
2985
+ msvs_windows_sdk_version = (
2986
+ msvs_windows_sdk_version
2987
+ or _ConfigWindowsTargetPlatformVersion(configuration, version)
2988
+ )
2989
+ if platform_name and msvs_windows_sdk_version:
2990
+ break
2991
+ if msvs_windows_sdk_version:
2992
+ properties[0].append(
2993
+ ["WindowsTargetPlatformVersion", str(msvs_windows_sdk_version)]
2994
+ )
2995
+ elif version.compatible_sdks:
2996
+ raise GypError(
2997
+ "%s requires any SDK of %s version, but none were found"
2998
+ % (version.description, version.compatible_sdks)
2999
+ )
3000
+
3001
+ if platform_name == "ARM":
3002
+ properties[0].append(["WindowsSDKDesktopARMSupport", "true"])
3003
+
3004
+ return properties
3005
+
3006
+
3007
+ def _GetMSBuildConfigurationDetails(spec, build_file):
3008
+ properties = {}
3009
+ for name, settings in spec["configurations"].items():
3010
+ msbuild_attributes = _GetMSBuildAttributes(spec, settings, build_file)
3011
+ condition = _GetConfigurationCondition(name, settings, spec)
3012
+ character_set = msbuild_attributes.get("CharacterSet")
3013
+ config_type = msbuild_attributes.get("ConfigurationType")
3014
+ _AddConditionalProperty(properties, condition, "ConfigurationType", config_type)
3015
+ if config_type == "Driver":
3016
+ _AddConditionalProperty(properties, condition, "DriverType", "WDM")
3017
+ _AddConditionalProperty(
3018
+ properties, condition, "TargetVersion", _ConfigTargetVersion(settings)
3019
+ )
3020
+ if character_set:
3021
+ if "msvs_enable_winrt" not in spec:
3022
+ _AddConditionalProperty(
3023
+ properties, condition, "CharacterSet", character_set
3024
+ )
3025
+ return _GetMSBuildPropertyGroup(spec, "Configuration", properties)
3026
+
3027
+
3028
+ def _GetMSBuildLocalProperties(msbuild_toolset):
3029
+ # Currently the only local property we support is PlatformToolset
3030
+ properties = {}
3031
+ if msbuild_toolset:
3032
+ properties = [
3033
+ [
3034
+ "PropertyGroup",
3035
+ {"Label": "Locals"},
3036
+ ["PlatformToolset", msbuild_toolset],
3037
+ ]
3038
+ ]
3039
+ return properties
3040
+
3041
+
3042
+ def _GetMSBuildPropertySheets(configurations, spec):
3043
+ user_props = r"$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props"
3044
+ additional_props = {}
3045
+ props_specified = False
3046
+ for name, settings in sorted(configurations.items()):
3047
+ configuration = _GetConfigurationCondition(name, settings, spec)
3048
+ if "msbuild_props" in settings:
3049
+ additional_props[configuration] = _FixPaths(settings["msbuild_props"])
3050
+ props_specified = True
3051
+ else:
3052
+ additional_props[configuration] = ""
3053
+
3054
+ if not props_specified:
3055
+ return [
3056
+ [
3057
+ "ImportGroup",
3058
+ {"Label": "PropertySheets"},
3059
+ [
3060
+ "Import",
3061
+ {
3062
+ "Project": user_props,
3063
+ "Condition": "exists('%s')" % user_props,
3064
+ "Label": "LocalAppDataPlatform",
3065
+ },
3066
+ ],
3067
+ ]
3068
+ ]
3069
+ else:
3070
+ sheets = []
3071
+ for condition, props in additional_props.items():
3072
+ import_group = [
3073
+ "ImportGroup",
3074
+ {"Label": "PropertySheets", "Condition": condition},
3075
+ [
3076
+ "Import",
3077
+ {
3078
+ "Project": user_props,
3079
+ "Condition": "exists('%s')" % user_props,
3080
+ "Label": "LocalAppDataPlatform",
3081
+ },
3082
+ ],
3083
+ ]
3084
+ for props_file in props:
3085
+ import_group.append(["Import", {"Project": props_file}])
3086
+ sheets.append(import_group)
3087
+ return sheets
3088
+
3089
+
3090
+ def _ConvertMSVSBuildAttributes(spec, config, build_file):
3091
+ config_type = _GetMSVSConfigurationType(spec, build_file)
3092
+ msvs_attributes = _GetMSVSAttributes(spec, config, config_type)
3093
+ msbuild_attributes = {}
3094
+ for a in msvs_attributes:
3095
+ if a in ["IntermediateDirectory", "OutputDirectory"]:
3096
+ directory = MSVSSettings.ConvertVCMacrosToMSBuild(msvs_attributes[a])
3097
+ if not directory.endswith("\\"):
3098
+ directory += "\\"
3099
+ msbuild_attributes[a] = directory
3100
+ elif a == "CharacterSet":
3101
+ msbuild_attributes[a] = _ConvertMSVSCharacterSet(msvs_attributes[a])
3102
+ elif a == "ConfigurationType":
3103
+ msbuild_attributes[a] = _ConvertMSVSConfigurationType(msvs_attributes[a])
3104
+ else:
3105
+ print("Warning: Do not know how to convert MSVS attribute " + a)
3106
+ return msbuild_attributes
3107
+
3108
+
3109
+ def _ConvertMSVSCharacterSet(char_set):
3110
+ if char_set.isdigit():
3111
+ char_set = {"0": "MultiByte", "1": "Unicode", "2": "MultiByte"}[char_set]
3112
+ return char_set
3113
+
3114
+
3115
+ def _ConvertMSVSConfigurationType(config_type):
3116
+ if config_type.isdigit():
3117
+ config_type = {
3118
+ "1": "Application",
3119
+ "2": "DynamicLibrary",
3120
+ "4": "StaticLibrary",
3121
+ "5": "Driver",
3122
+ "10": "Utility",
3123
+ }[config_type]
3124
+ return config_type
3125
+
3126
+
3127
+ def _GetMSBuildAttributes(spec, config, build_file):
3128
+ if "msbuild_configuration_attributes" not in config:
3129
+ msbuild_attributes = _ConvertMSVSBuildAttributes(spec, config, build_file)
3130
+
3131
+ else:
3132
+ config_type = _GetMSVSConfigurationType(spec, build_file)
3133
+ config_type = _ConvertMSVSConfigurationType(config_type)
3134
+ msbuild_attributes = config.get("msbuild_configuration_attributes", {})
3135
+ msbuild_attributes.setdefault("ConfigurationType", config_type)
3136
+ output_dir = msbuild_attributes.get(
3137
+ "OutputDirectory", "$(SolutionDir)$(Configuration)"
3138
+ )
3139
+ msbuild_attributes["OutputDirectory"] = _FixPath(output_dir) + "\\"
3140
+ if "IntermediateDirectory" not in msbuild_attributes:
3141
+ intermediate = _FixPath("$(Configuration)") + "\\"
3142
+ msbuild_attributes["IntermediateDirectory"] = intermediate
3143
+ if "CharacterSet" in msbuild_attributes:
3144
+ msbuild_attributes["CharacterSet"] = _ConvertMSVSCharacterSet(
3145
+ msbuild_attributes["CharacterSet"]
3146
+ )
3147
+ if "TargetName" not in msbuild_attributes:
3148
+ prefix = spec.get("product_prefix", "")
3149
+ product_name = spec.get("product_name", "$(ProjectName)")
3150
+ target_name = prefix + product_name
3151
+ msbuild_attributes["TargetName"] = target_name
3152
+ if "TargetExt" not in msbuild_attributes and "product_extension" in spec:
3153
+ ext = spec.get("product_extension")
3154
+ msbuild_attributes["TargetExt"] = "." + ext
3155
+
3156
+ if spec.get("msvs_external_builder"):
3157
+ external_out_dir = spec.get("msvs_external_builder_out_dir", ".")
3158
+ msbuild_attributes["OutputDirectory"] = _FixPath(external_out_dir) + "\\"
3159
+
3160
+ # Make sure that 'TargetPath' matches 'Lib.OutputFile' or 'Link.OutputFile'
3161
+ # (depending on the tool used) to avoid MSB8012 warning.
3162
+ msbuild_tool_map = {
3163
+ "executable": "Link",
3164
+ "shared_library": "Link",
3165
+ "loadable_module": "Link",
3166
+ "windows_driver": "Link",
3167
+ "static_library": "Lib",
3168
+ }
3169
+ msbuild_tool = msbuild_tool_map.get(spec["type"])
3170
+ if msbuild_tool:
3171
+ msbuild_settings = config["finalized_msbuild_settings"]
3172
+ out_file = msbuild_settings[msbuild_tool].get("OutputFile")
3173
+ if out_file:
3174
+ msbuild_attributes["TargetPath"] = _FixPath(out_file)
3175
+ target_ext = msbuild_settings[msbuild_tool].get("TargetExt")
3176
+ if target_ext:
3177
+ msbuild_attributes["TargetExt"] = target_ext
3178
+
3179
+ return msbuild_attributes
3180
+
3181
+
3182
+ def _GetMSBuildConfigurationGlobalProperties(spec, configurations, build_file):
3183
+ # TODO(jeanluc) We could optimize out the following and do it only if
3184
+ # there are actions.
3185
+ # TODO(jeanluc) Handle the equivalent of setting 'CYGWIN=nontsec'.
3186
+ new_paths = []
3187
+ cygwin_dirs = spec.get("msvs_cygwin_dirs", ["."])[0]
3188
+ if cygwin_dirs:
3189
+ cyg_path = "$(MSBuildProjectDirectory)\\%s\\bin\\" % _FixPath(cygwin_dirs)
3190
+ new_paths.append(cyg_path)
3191
+ # TODO(jeanluc) Change the convention to have both a cygwin_dir and a
3192
+ # python_dir.
3193
+ python_path = cyg_path.replace("cygwin\\bin", "python_26")
3194
+ new_paths.append(python_path)
3195
+ if new_paths:
3196
+ new_paths = "$(ExecutablePath);" + ";".join(new_paths)
3197
+
3198
+ properties = {}
3199
+ for (name, configuration) in sorted(configurations.items()):
3200
+ condition = _GetConfigurationCondition(name, configuration, spec)
3201
+ attributes = _GetMSBuildAttributes(spec, configuration, build_file)
3202
+ msbuild_settings = configuration["finalized_msbuild_settings"]
3203
+ _AddConditionalProperty(
3204
+ properties, condition, "IntDir", attributes["IntermediateDirectory"]
3205
+ )
3206
+ _AddConditionalProperty(
3207
+ properties, condition, "OutDir", attributes["OutputDirectory"]
3208
+ )
3209
+ _AddConditionalProperty(
3210
+ properties, condition, "TargetName", attributes["TargetName"]
3211
+ )
3212
+ if "TargetExt" in attributes:
3213
+ _AddConditionalProperty(
3214
+ properties, condition, "TargetExt", attributes["TargetExt"]
3215
+ )
3216
+
3217
+ if attributes.get("TargetPath"):
3218
+ _AddConditionalProperty(
3219
+ properties, condition, "TargetPath", attributes["TargetPath"]
3220
+ )
3221
+ if attributes.get("TargetExt"):
3222
+ _AddConditionalProperty(
3223
+ properties, condition, "TargetExt", attributes["TargetExt"]
3224
+ )
3225
+
3226
+ if new_paths:
3227
+ _AddConditionalProperty(properties, condition, "ExecutablePath", new_paths)
3228
+ tool_settings = msbuild_settings.get("", {})
3229
+ for name, value in sorted(tool_settings.items()):
3230
+ formatted_value = _GetValueFormattedForMSBuild("", name, value)
3231
+ _AddConditionalProperty(properties, condition, name, formatted_value)
3232
+ return _GetMSBuildPropertyGroup(spec, None, properties)
3233
+
3234
+
3235
+ def _AddConditionalProperty(properties, condition, name, value):
3236
+ """Adds a property / conditional value pair to a dictionary.
3237
+
3238
+ Arguments:
3239
+ properties: The dictionary to be modified. The key is the name of the
3240
+ property. The value is itself a dictionary; its key is the value and
3241
+ the value a list of condition for which this value is true.
3242
+ condition: The condition under which the named property has the value.
3243
+ name: The name of the property.
3244
+ value: The value of the property.
3245
+ """
3246
+ if name not in properties:
3247
+ properties[name] = {}
3248
+ values = properties[name]
3249
+ if value not in values:
3250
+ values[value] = []
3251
+ conditions = values[value]
3252
+ conditions.append(condition)
3253
+
3254
+
3255
+ # Regex for msvs variable references ( i.e. $(FOO) ).
3256
+ MSVS_VARIABLE_REFERENCE = re.compile(r"\$\(([a-zA-Z_][a-zA-Z0-9_]*)\)")
3257
+
3258
+
3259
+ def _GetMSBuildPropertyGroup(spec, label, properties):
3260
+ """Returns a PropertyGroup definition for the specified properties.
3261
+
3262
+ Arguments:
3263
+ spec: The target project dict.
3264
+ label: An optional label for the PropertyGroup.
3265
+ properties: The dictionary to be converted. The key is the name of the
3266
+ property. The value is itself a dictionary; its key is the value and
3267
+ the value a list of condition for which this value is true.
3268
+ """
3269
+ group = ["PropertyGroup"]
3270
+ if label:
3271
+ group.append({"Label": label})
3272
+ num_configurations = len(spec["configurations"])
3273
+
3274
+ def GetEdges(node):
3275
+ # Use a definition of edges such that user_of_variable -> used_varible.
3276
+ # This happens to be easier in this case, since a variable's
3277
+ # definition contains all variables it references in a single string.
3278
+ edges = set()
3279
+ for value in sorted(properties[node].keys()):
3280
+ # Add to edges all $(...) references to variables.
3281
+ #
3282
+ # Variable references that refer to names not in properties are excluded
3283
+ # These can exist for instance to refer built in definitions like
3284
+ # $(SolutionDir).
3285
+ #
3286
+ # Self references are ignored. Self reference is used in a few places to
3287
+ # append to the default value. I.e. PATH=$(PATH);other_path
3288
+ edges.update(
3289
+ {
3290
+ v
3291
+ for v in MSVS_VARIABLE_REFERENCE.findall(value)
3292
+ if v in properties and v != node
3293
+ }
3294
+ )
3295
+ return edges
3296
+
3297
+ properties_ordered = gyp.common.TopologicallySorted(properties.keys(), GetEdges)
3298
+ # Walk properties in the reverse of a topological sort on
3299
+ # user_of_variable -> used_variable as this ensures variables are
3300
+ # defined before they are used.
3301
+ # NOTE: reverse(topsort(DAG)) = topsort(reverse_edges(DAG))
3302
+ for name in reversed(properties_ordered):
3303
+ values = properties[name]
3304
+ for value, conditions in sorted(values.items()):
3305
+ if len(conditions) == num_configurations:
3306
+ # If the value is the same all configurations,
3307
+ # just add one unconditional entry.
3308
+ group.append([name, value])
3309
+ else:
3310
+ for condition in conditions:
3311
+ group.append([name, {"Condition": condition}, value])
3312
+ return [group]
3313
+
3314
+
3315
+ def _GetMSBuildToolSettingsSections(spec, configurations):
3316
+ groups = []
3317
+ for (name, configuration) in sorted(configurations.items()):
3318
+ msbuild_settings = configuration["finalized_msbuild_settings"]
3319
+ group = [
3320
+ "ItemDefinitionGroup",
3321
+ {"Condition": _GetConfigurationCondition(name, configuration, spec)},
3322
+ ]
3323
+ for tool_name, tool_settings in sorted(msbuild_settings.items()):
3324
+ # Skip the tool named '' which is a holder of global settings handled
3325
+ # by _GetMSBuildConfigurationGlobalProperties.
3326
+ if tool_name:
3327
+ if tool_settings:
3328
+ tool = [tool_name]
3329
+ for name, value in sorted(tool_settings.items()):
3330
+ formatted_value = _GetValueFormattedForMSBuild(
3331
+ tool_name, name, value
3332
+ )
3333
+ tool.append([name, formatted_value])
3334
+ group.append(tool)
3335
+ groups.append(group)
3336
+ return groups
3337
+
3338
+
3339
+ def _FinalizeMSBuildSettings(spec, configuration):
3340
+ if "msbuild_settings" in configuration:
3341
+ converted = False
3342
+ msbuild_settings = configuration["msbuild_settings"]
3343
+ MSVSSettings.ValidateMSBuildSettings(msbuild_settings)
3344
+ else:
3345
+ converted = True
3346
+ msvs_settings = configuration.get("msvs_settings", {})
3347
+ msbuild_settings = MSVSSettings.ConvertToMSBuildSettings(msvs_settings)
3348
+ include_dirs, midl_include_dirs, resource_include_dirs = _GetIncludeDirs(
3349
+ configuration
3350
+ )
3351
+ libraries = _GetLibraries(spec)
3352
+ library_dirs = _GetLibraryDirs(configuration)
3353
+ out_file, _, msbuild_tool = _GetOutputFilePathAndTool(spec, msbuild=True)
3354
+ target_ext = _GetOutputTargetExt(spec)
3355
+ defines = _GetDefines(configuration)
3356
+ if converted:
3357
+ # Visual Studio 2010 has TR1
3358
+ defines = [d for d in defines if d != "_HAS_TR1=0"]
3359
+ # Warn of ignored settings
3360
+ ignored_settings = ["msvs_tool_files"]
3361
+ for ignored_setting in ignored_settings:
3362
+ value = configuration.get(ignored_setting)
3363
+ if value:
3364
+ print(
3365
+ "Warning: The automatic conversion to MSBuild does not handle "
3366
+ "%s. Ignoring setting of %s" % (ignored_setting, str(value))
3367
+ )
3368
+
3369
+ defines = [_EscapeCppDefineForMSBuild(d) for d in defines]
3370
+ disabled_warnings = _GetDisabledWarnings(configuration)
3371
+ prebuild = configuration.get("msvs_prebuild")
3372
+ postbuild = configuration.get("msvs_postbuild")
3373
+ def_file = _GetModuleDefinition(spec)
3374
+ precompiled_header = configuration.get("msvs_precompiled_header")
3375
+
3376
+ # Add the information to the appropriate tool
3377
+ # TODO(jeanluc) We could optimize and generate these settings only if
3378
+ # the corresponding files are found, e.g. don't generate ResourceCompile
3379
+ # if you don't have any resources.
3380
+ _ToolAppend(
3381
+ msbuild_settings, "ClCompile", "AdditionalIncludeDirectories", include_dirs
3382
+ )
3383
+ _ToolAppend(
3384
+ msbuild_settings, "Midl", "AdditionalIncludeDirectories", midl_include_dirs
3385
+ )
3386
+ _ToolAppend(
3387
+ msbuild_settings,
3388
+ "ResourceCompile",
3389
+ "AdditionalIncludeDirectories",
3390
+ resource_include_dirs,
3391
+ )
3392
+ # Add in libraries, note that even for empty libraries, we want this
3393
+ # set, to prevent inheriting default libraries from the environment.
3394
+ _ToolSetOrAppend(msbuild_settings, "Link", "AdditionalDependencies", libraries)
3395
+ _ToolAppend(msbuild_settings, "Link", "AdditionalLibraryDirectories", library_dirs)
3396
+ if out_file:
3397
+ _ToolAppend(
3398
+ msbuild_settings, msbuild_tool, "OutputFile", out_file, only_if_unset=True
3399
+ )
3400
+ if target_ext:
3401
+ _ToolAppend(
3402
+ msbuild_settings, msbuild_tool, "TargetExt", target_ext, only_if_unset=True
3403
+ )
3404
+ # Add defines.
3405
+ _ToolAppend(msbuild_settings, "ClCompile", "PreprocessorDefinitions", defines)
3406
+ _ToolAppend(msbuild_settings, "ResourceCompile", "PreprocessorDefinitions", defines)
3407
+ # Add disabled warnings.
3408
+ _ToolAppend(
3409
+ msbuild_settings, "ClCompile", "DisableSpecificWarnings", disabled_warnings
3410
+ )
3411
+ # Turn on precompiled headers if appropriate.
3412
+ if precompiled_header:
3413
+ precompiled_header = os.path.split(precompiled_header)[1]
3414
+ _ToolAppend(msbuild_settings, "ClCompile", "PrecompiledHeader", "Use")
3415
+ _ToolAppend(
3416
+ msbuild_settings, "ClCompile", "PrecompiledHeaderFile", precompiled_header
3417
+ )
3418
+ _ToolAppend(
3419
+ msbuild_settings, "ClCompile", "ForcedIncludeFiles", [precompiled_header]
3420
+ )
3421
+ else:
3422
+ _ToolAppend(msbuild_settings, "ClCompile", "PrecompiledHeader", "NotUsing")
3423
+ # Turn off WinRT compilation
3424
+ _ToolAppend(msbuild_settings, "ClCompile", "CompileAsWinRT", "false")
3425
+ # Turn on import libraries if appropriate
3426
+ if spec.get("msvs_requires_importlibrary"):
3427
+ _ToolAppend(msbuild_settings, "", "IgnoreImportLibrary", "false")
3428
+ # Loadable modules don't generate import libraries;
3429
+ # tell dependent projects to not expect one.
3430
+ if spec["type"] == "loadable_module":
3431
+ _ToolAppend(msbuild_settings, "", "IgnoreImportLibrary", "true")
3432
+ # Set the module definition file if any.
3433
+ if def_file:
3434
+ _ToolAppend(msbuild_settings, "Link", "ModuleDefinitionFile", def_file)
3435
+ configuration["finalized_msbuild_settings"] = msbuild_settings
3436
+ if prebuild:
3437
+ _ToolAppend(msbuild_settings, "PreBuildEvent", "Command", prebuild)
3438
+ if postbuild:
3439
+ _ToolAppend(msbuild_settings, "PostBuildEvent", "Command", postbuild)
3440
+
3441
+
3442
+ def _GetValueFormattedForMSBuild(tool_name, name, value):
3443
+ if type(value) == list:
3444
+ # For some settings, VS2010 does not automatically extends the settings
3445
+ # TODO(jeanluc) Is this what we want?
3446
+ if name in [
3447
+ "AdditionalIncludeDirectories",
3448
+ "AdditionalLibraryDirectories",
3449
+ "AdditionalOptions",
3450
+ "DelayLoadDLLs",
3451
+ "DisableSpecificWarnings",
3452
+ "PreprocessorDefinitions",
3453
+ ]:
3454
+ value.append("%%(%s)" % name)
3455
+ # For most tools, entries in a list should be separated with ';' but some
3456
+ # settings use a space. Check for those first.
3457
+ exceptions = {
3458
+ "ClCompile": ["AdditionalOptions"],
3459
+ "Link": ["AdditionalOptions"],
3460
+ "Lib": ["AdditionalOptions"],
3461
+ }
3462
+ if tool_name in exceptions and name in exceptions[tool_name]:
3463
+ char = " "
3464
+ else:
3465
+ char = ";"
3466
+ formatted_value = char.join(
3467
+ [MSVSSettings.ConvertVCMacrosToMSBuild(i) for i in value]
3468
+ )
3469
+ else:
3470
+ formatted_value = MSVSSettings.ConvertVCMacrosToMSBuild(value)
3471
+ return formatted_value
3472
+
3473
+
3474
+ def _VerifySourcesExist(sources, root_dir):
3475
+ """Verifies that all source files exist on disk.
3476
+
3477
+ Checks that all regular source files, i.e. not created at run time,
3478
+ exist on disk. Missing files cause needless recompilation but no otherwise
3479
+ visible errors.
3480
+
3481
+ Arguments:
3482
+ sources: A recursive list of Filter/file names.
3483
+ root_dir: The root directory for the relative path names.
3484
+ Returns:
3485
+ A list of source files that cannot be found on disk.
3486
+ """
3487
+ missing_sources = []
3488
+ for source in sources:
3489
+ if isinstance(source, MSVSProject.Filter):
3490
+ missing_sources.extend(_VerifySourcesExist(source.contents, root_dir))
3491
+ else:
3492
+ if "$" not in source:
3493
+ full_path = os.path.join(root_dir, source)
3494
+ if not os.path.exists(full_path):
3495
+ missing_sources.append(full_path)
3496
+ return missing_sources
3497
+
3498
+
3499
+ def _GetMSBuildSources(
3500
+ spec,
3501
+ sources,
3502
+ exclusions,
3503
+ rule_dependencies,
3504
+ extension_to_rule_name,
3505
+ actions_spec,
3506
+ sources_handled_by_action,
3507
+ list_excluded,
3508
+ ):
3509
+ groups = [
3510
+ "none",
3511
+ "masm",
3512
+ "midl",
3513
+ "include",
3514
+ "compile",
3515
+ "resource",
3516
+ "rule",
3517
+ "rule_dependency",
3518
+ ]
3519
+ grouped_sources = {}
3520
+ for g in groups:
3521
+ grouped_sources[g] = []
3522
+
3523
+ _AddSources2(
3524
+ spec,
3525
+ sources,
3526
+ exclusions,
3527
+ grouped_sources,
3528
+ rule_dependencies,
3529
+ extension_to_rule_name,
3530
+ sources_handled_by_action,
3531
+ list_excluded,
3532
+ )
3533
+ sources = []
3534
+ for g in groups:
3535
+ if grouped_sources[g]:
3536
+ sources.append(["ItemGroup"] + grouped_sources[g])
3537
+ if actions_spec:
3538
+ sources.append(["ItemGroup"] + actions_spec)
3539
+ return sources
3540
+
3541
+
3542
+ def _AddSources2(
3543
+ spec,
3544
+ sources,
3545
+ exclusions,
3546
+ grouped_sources,
3547
+ rule_dependencies,
3548
+ extension_to_rule_name,
3549
+ sources_handled_by_action,
3550
+ list_excluded,
3551
+ ):
3552
+ extensions_excluded_from_precompile = []
3553
+ for source in sources:
3554
+ if isinstance(source, MSVSProject.Filter):
3555
+ _AddSources2(
3556
+ spec,
3557
+ source.contents,
3558
+ exclusions,
3559
+ grouped_sources,
3560
+ rule_dependencies,
3561
+ extension_to_rule_name,
3562
+ sources_handled_by_action,
3563
+ list_excluded,
3564
+ )
3565
+ else:
3566
+ if source not in sources_handled_by_action:
3567
+ detail = []
3568
+ excluded_configurations = exclusions.get(source, [])
3569
+ if len(excluded_configurations) == len(spec["configurations"]):
3570
+ detail.append(["ExcludedFromBuild", "true"])
3571
+ else:
3572
+ for config_name, configuration in sorted(excluded_configurations):
3573
+ condition = _GetConfigurationCondition(
3574
+ config_name, configuration
3575
+ )
3576
+ detail.append(
3577
+ ["ExcludedFromBuild", {"Condition": condition}, "true"]
3578
+ )
3579
+ # Add precompile if needed
3580
+ for config_name, configuration in spec["configurations"].items():
3581
+ precompiled_source = configuration.get(
3582
+ "msvs_precompiled_source", ""
3583
+ )
3584
+ if precompiled_source != "":
3585
+ precompiled_source = _FixPath(precompiled_source)
3586
+ if not extensions_excluded_from_precompile:
3587
+ # If the precompiled header is generated by a C source,
3588
+ # we must not try to use it for C++ sources,
3589
+ # and vice versa.
3590
+ basename, extension = os.path.splitext(precompiled_source)
3591
+ if extension == ".c":
3592
+ extensions_excluded_from_precompile = [
3593
+ ".cc",
3594
+ ".cpp",
3595
+ ".cxx",
3596
+ ]
3597
+ else:
3598
+ extensions_excluded_from_precompile = [".c"]
3599
+
3600
+ if precompiled_source == source:
3601
+ condition = _GetConfigurationCondition(
3602
+ config_name, configuration, spec
3603
+ )
3604
+ detail.append(
3605
+ ["PrecompiledHeader", {"Condition": condition}, "Create"]
3606
+ )
3607
+ else:
3608
+ # Turn off precompiled header usage for source files of a
3609
+ # different type than the file that generated the
3610
+ # precompiled header.
3611
+ for extension in extensions_excluded_from_precompile:
3612
+ if source.endswith(extension):
3613
+ detail.append(["PrecompiledHeader", ""])
3614
+ detail.append(["ForcedIncludeFiles", ""])
3615
+
3616
+ group, element = _MapFileToMsBuildSourceType(
3617
+ source,
3618
+ rule_dependencies,
3619
+ extension_to_rule_name,
3620
+ _GetUniquePlatforms(spec),
3621
+ spec["toolset"],
3622
+ )
3623
+ if group == "compile" and not os.path.isabs(source):
3624
+ # Add an <ObjectFileName> value to support duplicate source
3625
+ # file basenames, except for absolute paths to avoid paths
3626
+ # with more than 260 characters.
3627
+ file_name = os.path.splitext(source)[0] + ".obj"
3628
+ if file_name.startswith("..\\"):
3629
+ file_name = re.sub(r"^(\.\.\\)+", "", file_name)
3630
+ elif file_name.startswith("$("):
3631
+ file_name = re.sub(r"^\$\([^)]+\)\\", "", file_name)
3632
+ detail.append(["ObjectFileName", "$(IntDir)\\" + file_name])
3633
+ grouped_sources[group].append([element, {"Include": source}] + detail)
3634
+
3635
+
3636
+ def _GetMSBuildProjectReferences(project):
3637
+ references = []
3638
+ if project.dependencies:
3639
+ group = ["ItemGroup"]
3640
+ added_dependency_set = set()
3641
+ for dependency in project.dependencies:
3642
+ dependency_spec = dependency.spec
3643
+ should_skip_dep = False
3644
+ if project.spec["toolset"] == "target":
3645
+ if dependency_spec["toolset"] == "host":
3646
+ if dependency_spec["type"] == "static_library":
3647
+ should_skip_dep = True
3648
+ if dependency.name.startswith("run_"):
3649
+ should_skip_dep = False
3650
+ if should_skip_dep:
3651
+ continue
3652
+
3653
+ canonical_name = dependency.name.replace("_host", "")
3654
+ added_dependency_set.add(canonical_name)
3655
+ guid = dependency.guid
3656
+ project_dir = os.path.split(project.path)[0]
3657
+ relative_path = gyp.common.RelativePath(dependency.path, project_dir)
3658
+ project_ref = [
3659
+ "ProjectReference",
3660
+ {"Include": relative_path},
3661
+ ["Project", guid],
3662
+ ["ReferenceOutputAssembly", "false"],
3663
+ ]
3664
+ for config in dependency.spec.get("configurations", {}).values():
3665
+ if config.get("msvs_use_library_dependency_inputs", 0):
3666
+ project_ref.append(["UseLibraryDependencyInputs", "true"])
3667
+ break
3668
+ # If it's disabled in any config, turn it off in the reference.
3669
+ if config.get("msvs_2010_disable_uldi_when_referenced", 0):
3670
+ project_ref.append(["UseLibraryDependencyInputs", "false"])
3671
+ break
3672
+ group.append(project_ref)
3673
+ references.append(group)
3674
+ return references
3675
+
3676
+
3677
+ def _GenerateMSBuildProject(project, options, version, generator_flags, spec):
3678
+ spec = project.spec
3679
+ configurations = spec["configurations"]
3680
+ toolset = spec["toolset"]
3681
+ project_dir, project_file_name = os.path.split(project.path)
3682
+ gyp.common.EnsureDirExists(project.path)
3683
+ # Prepare list of sources and excluded sources.
3684
+
3685
+ gyp_file = os.path.split(project.build_file)[1]
3686
+ sources, excluded_sources = _PrepareListOfSources(spec, generator_flags, gyp_file)
3687
+ # Add rules.
3688
+ actions_to_add = {}
3689
+ props_files_of_rules = set()
3690
+ targets_files_of_rules = set()
3691
+ rule_dependencies = set()
3692
+ extension_to_rule_name = {}
3693
+ list_excluded = generator_flags.get("msvs_list_excluded_files", True)
3694
+ platforms = _GetUniquePlatforms(spec)
3695
+
3696
+ # Don't generate rules if we are using an external builder like ninja.
3697
+ if not spec.get("msvs_external_builder"):
3698
+ _GenerateRulesForMSBuild(
3699
+ project_dir,
3700
+ options,
3701
+ spec,
3702
+ sources,
3703
+ excluded_sources,
3704
+ props_files_of_rules,
3705
+ targets_files_of_rules,
3706
+ actions_to_add,
3707
+ rule_dependencies,
3708
+ extension_to_rule_name,
3709
+ )
3710
+ else:
3711
+ rules = spec.get("rules", [])
3712
+ _AdjustSourcesForRules(rules, sources, excluded_sources, True)
3713
+
3714
+ sources, excluded_sources, excluded_idl = _AdjustSourcesAndConvertToFilterHierarchy(
3715
+ spec, options, project_dir, sources, excluded_sources, list_excluded, version
3716
+ )
3717
+
3718
+ # Don't add actions if we are using an external builder like ninja.
3719
+ if not spec.get("msvs_external_builder"):
3720
+ _AddActions(actions_to_add, spec, project.build_file)
3721
+ _AddCopies(actions_to_add, spec)
3722
+
3723
+ # NOTE: this stanza must appear after all actions have been decided.
3724
+ # Don't excluded sources with actions attached, or they won't run.
3725
+ excluded_sources = _FilterActionsFromExcluded(excluded_sources, actions_to_add)
3726
+
3727
+ exclusions = _GetExcludedFilesFromBuild(spec, excluded_sources, excluded_idl)
3728
+ actions_spec, sources_handled_by_action = _GenerateActionsForMSBuild(
3729
+ spec, actions_to_add
3730
+ )
3731
+
3732
+ _GenerateMSBuildFiltersFile(
3733
+ project.path + ".filters",
3734
+ sources,
3735
+ rule_dependencies,
3736
+ extension_to_rule_name,
3737
+ platforms,
3738
+ toolset,
3739
+ )
3740
+ missing_sources = _VerifySourcesExist(sources, project_dir)
3741
+
3742
+ for configuration in configurations.values():
3743
+ _FinalizeMSBuildSettings(spec, configuration)
3744
+
3745
+ # Add attributes to root element
3746
+
3747
+ import_default_section = [
3748
+ ["Import", {"Project": r"$(VCTargetsPath)\Microsoft.Cpp.Default.props"}]
3749
+ ]
3750
+ import_cpp_props_section = [
3751
+ ["Import", {"Project": r"$(VCTargetsPath)\Microsoft.Cpp.props"}]
3752
+ ]
3753
+ import_cpp_targets_section = [
3754
+ ["Import", {"Project": r"$(VCTargetsPath)\Microsoft.Cpp.targets"}]
3755
+ ]
3756
+ import_masm_props_section = [
3757
+ ["Import", {"Project": r"$(VCTargetsPath)\BuildCustomizations\masm.props"}]
3758
+ ]
3759
+ import_masm_targets_section = [
3760
+ ["Import", {"Project": r"$(VCTargetsPath)\BuildCustomizations\masm.targets"}]
3761
+ ]
3762
+ import_marmasm_props_section = [
3763
+ ["Import", {"Project": r"$(VCTargetsPath)\BuildCustomizations\marmasm.props"}]
3764
+ ]
3765
+ import_marmasm_targets_section = [
3766
+ ["Import", {"Project": r"$(VCTargetsPath)\BuildCustomizations\marmasm.targets"}]
3767
+ ]
3768
+ macro_section = [["PropertyGroup", {"Label": "UserMacros"}]]
3769
+
3770
+ content = [
3771
+ "Project",
3772
+ {
3773
+ "xmlns": "http://schemas.microsoft.com/developer/msbuild/2003",
3774
+ "ToolsVersion": version.ProjectVersion(),
3775
+ "DefaultTargets": "Build",
3776
+ },
3777
+ ]
3778
+
3779
+ content += _GetMSBuildProjectConfigurations(configurations, spec)
3780
+ content += _GetMSBuildGlobalProperties(
3781
+ spec, version, project.guid, project_file_name
3782
+ )
3783
+ content += import_default_section
3784
+ content += _GetMSBuildConfigurationDetails(spec, project.build_file)
3785
+ if spec.get("msvs_enable_winphone"):
3786
+ content += _GetMSBuildLocalProperties("v120_wp81")
3787
+ else:
3788
+ content += _GetMSBuildLocalProperties(project.msbuild_toolset)
3789
+ content += import_cpp_props_section
3790
+ content += import_masm_props_section
3791
+ if "arm64" in platforms and toolset == "target":
3792
+ content += import_marmasm_props_section
3793
+ content += _GetMSBuildExtensions(props_files_of_rules)
3794
+ content += _GetMSBuildPropertySheets(configurations, spec)
3795
+ content += macro_section
3796
+ content += _GetMSBuildConfigurationGlobalProperties(
3797
+ spec, configurations, project.build_file
3798
+ )
3799
+ content += _GetMSBuildToolSettingsSections(spec, configurations)
3800
+ content += _GetMSBuildSources(
3801
+ spec,
3802
+ sources,
3803
+ exclusions,
3804
+ rule_dependencies,
3805
+ extension_to_rule_name,
3806
+ actions_spec,
3807
+ sources_handled_by_action,
3808
+ list_excluded,
3809
+ )
3810
+ content += _GetMSBuildProjectReferences(project)
3811
+ content += import_cpp_targets_section
3812
+ content += import_masm_targets_section
3813
+ if "arm64" in platforms and toolset == "target":
3814
+ content += import_marmasm_targets_section
3815
+ content += _GetMSBuildExtensionTargets(targets_files_of_rules)
3816
+
3817
+ if spec.get("msvs_external_builder"):
3818
+ content += _GetMSBuildExternalBuilderTargets(spec)
3819
+
3820
+ # TODO(jeanluc) File a bug to get rid of runas. We had in MSVS:
3821
+ # has_run_as = _WriteMSVSUserFile(project.path, version, spec)
3822
+
3823
+ easy_xml.WriteXmlIfChanged(content, project.path, pretty=True, win32=True)
3824
+
3825
+ return missing_sources
3826
+
3827
+
3828
+ def _GetMSBuildExternalBuilderTargets(spec):
3829
+ """Return a list of MSBuild targets for external builders.
3830
+
3831
+ The "Build" and "Clean" targets are always generated. If the spec contains
3832
+ 'msvs_external_builder_clcompile_cmd', then the "ClCompile" target will also
3833
+ be generated, to support building selected C/C++ files.
3834
+
3835
+ Arguments:
3836
+ spec: The gyp target spec.
3837
+ Returns:
3838
+ List of MSBuild 'Target' specs.
3839
+ """
3840
+ build_cmd = _BuildCommandLineForRuleRaw(
3841
+ spec, spec["msvs_external_builder_build_cmd"], False, False, False, False
3842
+ )
3843
+ build_target = ["Target", {"Name": "Build"}]
3844
+ build_target.append(["Exec", {"Command": build_cmd}])
3845
+
3846
+ clean_cmd = _BuildCommandLineForRuleRaw(
3847
+ spec, spec["msvs_external_builder_clean_cmd"], False, False, False, False
3848
+ )
3849
+ clean_target = ["Target", {"Name": "Clean"}]
3850
+ clean_target.append(["Exec", {"Command": clean_cmd}])
3851
+
3852
+ targets = [build_target, clean_target]
3853
+
3854
+ if spec.get("msvs_external_builder_clcompile_cmd"):
3855
+ clcompile_cmd = _BuildCommandLineForRuleRaw(
3856
+ spec,
3857
+ spec["msvs_external_builder_clcompile_cmd"],
3858
+ False,
3859
+ False,
3860
+ False,
3861
+ False,
3862
+ )
3863
+ clcompile_target = ["Target", {"Name": "ClCompile"}]
3864
+ clcompile_target.append(["Exec", {"Command": clcompile_cmd}])
3865
+ targets.append(clcompile_target)
3866
+
3867
+ return targets
3868
+
3869
+
3870
+ def _GetMSBuildExtensions(props_files_of_rules):
3871
+ extensions = ["ImportGroup", {"Label": "ExtensionSettings"}]
3872
+ for props_file in props_files_of_rules:
3873
+ extensions.append(["Import", {"Project": props_file}])
3874
+ return [extensions]
3875
+
3876
+
3877
+ def _GetMSBuildExtensionTargets(targets_files_of_rules):
3878
+ targets_node = ["ImportGroup", {"Label": "ExtensionTargets"}]
3879
+ for targets_file in sorted(targets_files_of_rules):
3880
+ targets_node.append(["Import", {"Project": targets_file}])
3881
+ return [targets_node]
3882
+
3883
+
3884
+ def _GenerateActionsForMSBuild(spec, actions_to_add):
3885
+ """Add actions accumulated into an actions_to_add, merging as needed.
3886
+
3887
+ Arguments:
3888
+ spec: the target project dict
3889
+ actions_to_add: dictionary keyed on input name, which maps to a list of
3890
+ dicts describing the actions attached to that input file.
3891
+
3892
+ Returns:
3893
+ A pair of (action specification, the sources handled by this action).
3894
+ """
3895
+ sources_handled_by_action = OrderedSet()
3896
+ actions_spec = []
3897
+ for primary_input, actions in actions_to_add.items():
3898
+ if generator_supports_multiple_toolsets:
3899
+ primary_input = primary_input.replace(".exe", "_host.exe")
3900
+ inputs = OrderedSet()
3901
+ outputs = OrderedSet()
3902
+ descriptions = []
3903
+ commands = []
3904
+ for action in actions:
3905
+
3906
+ def fixup_host_exe(i):
3907
+ if "$(OutDir)" in i:
3908
+ i = i.replace(".exe", "_host.exe")
3909
+ return i
3910
+
3911
+ if generator_supports_multiple_toolsets:
3912
+ action["inputs"] = [fixup_host_exe(i) for i in action["inputs"]]
3913
+ inputs.update(OrderedSet(action["inputs"]))
3914
+ outputs.update(OrderedSet(action["outputs"]))
3915
+ descriptions.append(action["description"])
3916
+ cmd = action["command"]
3917
+ if generator_supports_multiple_toolsets:
3918
+ cmd = cmd.replace(".exe", "_host.exe")
3919
+ # For most actions, add 'call' so that actions that invoke batch files
3920
+ # return and continue executing. msbuild_use_call provides a way to
3921
+ # disable this but I have not seen any adverse effect from doing that
3922
+ # for everything.
3923
+ if action.get("msbuild_use_call", True):
3924
+ cmd = "call " + cmd
3925
+ commands.append(cmd)
3926
+ # Add the custom build action for one input file.
3927
+ description = ", and also ".join(descriptions)
3928
+
3929
+ # We can't join the commands simply with && because the command line will
3930
+ # get too long. See also _AddActions: cygwin's setup_env mustn't be called
3931
+ # for every invocation or the command that sets the PATH will grow too
3932
+ # long.
3933
+ command = "\r\n".join(
3934
+ [c + "\r\nif %errorlevel% neq 0 exit /b %errorlevel%" for c in commands]
3935
+ )
3936
+ _AddMSBuildAction(
3937
+ spec,
3938
+ primary_input,
3939
+ inputs,
3940
+ outputs,
3941
+ command,
3942
+ description,
3943
+ sources_handled_by_action,
3944
+ actions_spec,
3945
+ )
3946
+ return actions_spec, sources_handled_by_action
3947
+
3948
+
3949
+ def _AddMSBuildAction(
3950
+ spec,
3951
+ primary_input,
3952
+ inputs,
3953
+ outputs,
3954
+ cmd,
3955
+ description,
3956
+ sources_handled_by_action,
3957
+ actions_spec,
3958
+ ):
3959
+ command = MSVSSettings.ConvertVCMacrosToMSBuild(cmd)
3960
+ primary_input = _FixPath(primary_input)
3961
+ inputs_array = _FixPaths(inputs)
3962
+ outputs_array = _FixPaths(outputs)
3963
+ additional_inputs = ";".join([i for i in inputs_array if i != primary_input])
3964
+ outputs = ";".join(outputs_array)
3965
+ sources_handled_by_action.add(primary_input)
3966
+ action_spec = ["CustomBuild", {"Include": primary_input}]
3967
+ action_spec.extend(
3968
+ # TODO(jeanluc) 'Document' for all or just if as_sources?
3969
+ [
3970
+ ["FileType", "Document"],
3971
+ ["Command", command],
3972
+ ["Message", description],
3973
+ ["Outputs", outputs],
3974
+ ]
3975
+ )
3976
+ if additional_inputs:
3977
+ action_spec.append(["AdditionalInputs", additional_inputs])
3978
+ actions_spec.append(action_spec)