-
Notifications
You must be signed in to change notification settings - Fork 0
/
generate_vs_sln.py
459 lines (421 loc) · 17.1 KB
/
generate_vs_sln.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
"""This generates a Visual Studio solution file and projects for each module."""
from __future__ import annotations
import os
import re
import uuid
from dataclasses import dataclass, field
from enum import Enum
import sys
import glob
import sysconfig
from collections.abc import Iterable
from hashlib import md5
import importlib.util
ProjectPattern = re.compile(
r'Project\("{(?P<sln_guid>[0-9A-F]{8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12})}"\) = "(?P<project_name>[a-zA-Z0-9_-]+)", "(?P<proj_path>[a-zA-Z0-9\\/_-]+\.vcxproj)", "{(?P<project_guid>[0-9A-F]{8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12})}"'
)
PythonExtensionModuleSuffix = (
f".cp{sys.version_info.major}{sys.version_info.minor}-win_amd64.pyd"
)
PythonIncludeDir = sysconfig.get_paths()["include"]
PythonLibraryDir = os.path.join(os.path.dirname(PythonIncludeDir), "libs")
VCXProjSource = """\
<ClCompile Include="{path}" />"""
VCXProjInclude = """\
<ClInclude Include="{path}" />"""
VCXProj = r"""<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup Label="ProjectConfigurations">
<ProjectConfiguration Include="Debug|x64">
<Configuration>Debug</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|x64">
<Configuration>Release</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
</ItemGroup>
<PropertyGroup Label="Globals">
<VCProjectVersion>17.0</VCProjectVersion>
<ProjectGuid>{{{project_guid}}}</ProjectGuid>
<Keyword>Win32Proj</Keyword>
<WindowsTargetPlatformVersion>10.0</WindowsTargetPlatformVersion>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
<ConfigurationType>{library_type}</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v143</PlatformToolset>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
<ConfigurationType>{library_type}</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v143</PlatformToolset>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
<ImportGroup Label="ExtensionSettings">
</ImportGroup>
<ImportGroup Label="Shared">
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<PropertyGroup Label="UserMacros" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<IntDir>$(SolutionDir)$(Platform)\$(Configuration)\int\{project_name}\</IntDir>
<OutDir>{out_dir}</OutDir>
<TargetExt>{file_extension}</TargetExt>
<LibraryPath>$(VC_LibraryPath_x64);$(WindowsSDK_LibraryPath_x64);$(WindowsSDK_LibraryPath_x64);{library_path}</LibraryPath>
<TargetName>{ext_name}</TargetName>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<IntDir>$(SolutionDir)$(Platform)\$(Configuration)\int\{project_name}\</IntDir>
<OutDir>{out_dir}</OutDir>
<TargetExt>{file_extension}</TargetExt>
<LibraryPath>$(VC_LibraryPath_x64);$(WindowsSDK_LibraryPath_x64);$(WindowsSDK_LibraryPath_x64);{library_path}</LibraryPath>
<TargetName>{ext_name}</TargetName>
</PropertyGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<ClCompile>
<LanguageStandard>stdcpp20</LanguageStandard>
<AdditionalIncludeDirectories>{include_dirs}%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<PreprocessorDefinitions>{preprocessor_definitions}%(PreprocessorDefinitions)</PreprocessorDefinitions>
</ClCompile>
<Link>
<AdditionalDependencies>$(CoreLibraryDependencies);%(AdditionalDependencies);{libraries}</AdditionalDependencies>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<ClCompile>
<LanguageStandard>stdcpp20</LanguageStandard>
<AdditionalIncludeDirectories>{include_dirs}%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<PreprocessorDefinitions>{preprocessor_definitions}%(PreprocessorDefinitions)</PreprocessorDefinitions>
</ClCompile>
<Link>
<AdditionalDependencies>$(CoreLibraryDependencies);%(AdditionalDependencies);{libraries}</AdditionalDependencies>
</Link>
</ItemDefinitionGroup>
<ItemGroup>
{source_files}
</ItemGroup>
<ItemGroup>
{include_files}
</ItemGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<ImportGroup Label="ExtensionTargets">
</ImportGroup>
</Project>"""
VCXProjFiltersSource = """\
<ClCompile Include="{path}">
<Filter>{rel_path}</Filter>
</ClCompile>"""
VCXProjFiltersSourceGroup = """\
<Filter Include="{path}">
<UniqueIdentifier>{{{uuid}}}</UniqueIdentifier>
</Filter>
"""
VCXProjFiltersInclude = """\
<ClInclude Include="{path}">
<Filter>{rel_path}</Filter>
</ClInclude>"""
VCXProjFiltersIncludeGroup = """\
<Filter Include="{path}">
<UniqueIdentifier>{{{uuid}}}</UniqueIdentifier>
</Filter>
"""
VCXProjFilters = r"""<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup>
{filter_groups} </ItemGroup>
<ItemGroup>
{source_files}
</ItemGroup>
<ItemGroup>
{include_files}
</ItemGroup>
</Project>"""
VCXProjUser = r"""<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="Current" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup />
</Project>"""
SolutionHeader = """Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.2.32630.192
MinimumVisualStudioVersion = 10.0.40219.1
"""
SolutionProjectDependency = """\
{{{dependency_guid}}} = {{{dependency_guid}}}
"""
SolutionProjectDependencies = """\
ProjectSection(ProjectDependencies) = postProject
{project_dependencies}\
EndProjectSection
"""
SolutionProject = """Project("{{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}}") = "{project_name}", "{project_name}.vcxproj", "{{{project_guid}}}"
{project_dependencies}EndProject
"""
SolutionGlobalConfigurationPlatforms = """\
{{{project_guid}}}.Debug|x64.ActiveCfg = Debug|x64
{{{project_guid}}}.Debug|x64.Build.0 = Debug|x64
{{{project_guid}}}.Debug|x86.ActiveCfg = Debug|x64
{{{project_guid}}}.Debug|x86.Build.0 = Debug|x64
{{{project_guid}}}.Release|x64.ActiveCfg = Release|x64
{{{project_guid}}}.Release|x64.Build.0 = Release|x64
{{{project_guid}}}.Release|x86.ActiveCfg = Release|x64
{{{project_guid}}}.Release|x86.Build.0 = Release|x64"""
SolutionGlobal = """\
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|x64 = Debug|x64
Debug|x86 = Debug|x86
Release|x64 = Release|x64
Release|x86 = Release|x86
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{configuration_platforms}
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {{6B72B1FC-8248-4021-B089-D05ED8CBCE73}}
EndGlobalSection
EndGlobal
"""
class CompileMode(Enum):
DynamicLibrary = "DynamicLibrary"
StaticLibrary = "StaticLibrary"
PythonExtension = "pyd"
@dataclass(kw_only=True)
class ProjectData:
name: str
compile_mode: CompileMode
source_files: list[tuple[str, str, str]] = field(default_factory=list)
include_files: list[tuple[str, str, str]] = field(default_factory=list)
include_dirs: list[str] = field(default_factory=list)
preprocessor_definitions: list[str] = field(default_factory=list)
library_dirs: list[str] = field(default_factory=list)
dependencies: list[ProjectData | str] = field(default_factory=list)
py_package: str | None = None
package_dir: str | None = None
def project_guid(self) -> str:
encoded_name = self.name.encode()
digest = md5(encoded_name).hexdigest()
return (
digest[0:8].upper()
+ "-"
+ digest[8:12].upper()
+ "-"
+ digest[12:16].upper()
+ "-"
+ digest[16:20].upper()
+ "-"
+ digest[20:32].upper()
)
def write(
src_dir: str, solution_dir: str, solution_name: str, projects: list[ProjectData]
) -> None:
os.makedirs(solution_dir, exist_ok=True)
for project in projects:
project_guid = project.project_guid()
vcxproj_sources = "\n".join(
VCXProjSource.format(path=os.path.join(*path))
for path in project.source_files
)
vcxproj_includes = "\n".join(
VCXProjInclude.format(path=os.path.join(*path))
for path in project.include_files
)
library_type = project.compile_mode
project_name = project.name
if library_type == CompileMode.PythonExtension:
extension = PythonExtensionModuleSuffix
library_type = CompileMode.DynamicLibrary
if project.py_package:
module_path = project.py_package.replace(".", "\\")
out_dir = f"{project.package_dir or src_dir}\\{module_path}\\"
project_name = f"{project.py_package}.{project_name}"
else:
out_dir = f"{project.package_dir or src_dir}\\"
elif library_type == CompileMode.StaticLibrary:
extension = ".lib"
out_dir = (
f"$(SolutionDir)$(Platform)\\$(Configuration)\\out\\{project.name}\\"
)
# elif library_type == CompileMode.DynamicLibrary:
# extension = ".dll"
# out_dir = f"$(SolutionDir)$(Platform)\\$(Configuration)\\out\\{project.name}\\"
else:
raise RuntimeError
with open(
os.path.join(solution_dir, f"{project_name}.vcxproj"), "w", encoding="utf8"
) as f:
f.write(
VCXProj.format(
project_name=project_name,
ext_name=project.name,
source_files=vcxproj_sources,
include_files=vcxproj_includes,
include_dirs="".join(f"{path};" for path in project.include_dirs),
preprocessor_definitions="".join(
f"{ppd};" for ppd in project.preprocessor_definitions
),
library_path="".join(
[f"{path};" for path in project.library_dirs]
+ [
f"$(SolutionDir)$(Platform)\\$(Configuration)\\out\\{dep.name if isinstance(dep, ProjectData) else dep}\\;"
for dep in project.dependencies
if (
dep.compile_mode == CompileMode.StaticLibrary
and dep.source_files
if isinstance(dep, ProjectData)
else True
)
]
),
libraries="".join(
f"{dep.name if isinstance(dep, ProjectData) else dep}.lib;"
for dep in project.dependencies
if (
dep.compile_mode == CompileMode.StaticLibrary
and dep.source_files
if isinstance(dep, ProjectData)
else True
)
),
library_type=library_type.value,
project_guid=project_guid,
file_extension=extension,
out_dir=out_dir,
)
)
filter_sources = []
filter_includes = []
filter_sources_groups = dict[str, str]()
filter_includes_groups = dict[str, str]()
for path in project.source_files:
filter_sources.append(
VCXProjFiltersSource.format(
path=os.path.join(*path), rel_path=path[1] or ""
)
)
rel_path = path[1]
while rel_path:
if rel_path not in filter_sources_groups:
filter_sources_groups[rel_path] = VCXProjFiltersSourceGroup.format(
path=rel_path, uuid=str(uuid.uuid4())
)
rel_path = os.path.dirname(rel_path)
for path in project.include_files:
filter_includes.append(
VCXProjFiltersInclude.format(
path=os.path.join(*path), rel_path=path[1] or ""
)
)
rel_path = path[1]
while rel_path:
if rel_path not in filter_includes_groups:
filter_includes_groups[rel_path] = (
VCXProjFiltersIncludeGroup.format(
path=rel_path, uuid=str(uuid.uuid4())
)
)
rel_path = os.path.dirname(rel_path)
with open(
os.path.join(solution_dir, f"{project_name}.vcxproj.filters"),
"w",
encoding="utf8",
) as f:
f.write(
VCXProjFilters.format(
source_files="\n".join(filter_sources),
include_files="\n".join(filter_includes),
filter_groups="".join(filter_sources_groups.values())
+ "".join(filter_includes_groups.values()),
)
)
with open(
os.path.join(solution_dir, f"{project_name}.vcxproj.user"),
"w",
encoding="utf8",
) as f:
f.write(VCXProjUser)
# write solution file
with open(
os.path.join(solution_dir, f"{solution_name}.sln"), "w", encoding="utf8"
) as f:
f.write(SolutionHeader)
global_configuration_platforms = []
for project in projects:
project_guid = project.project_guid()
project_name = (
f"{project.py_package}.{project.name}"
if project.py_package
else project.name
)
if project.dependencies:
project_dependencies = "".join(
SolutionProjectDependency.format(dependency_guid=dep.project_guid())
for dep in project.dependencies
if isinstance(dep, ProjectData)
)
project_dependencies = SolutionProjectDependencies.format(
project_dependencies=project_dependencies
)
else:
project_dependencies = ""
f.write(
SolutionProject.format(
project_name=project_name,
project_guid=project_guid,
project_dependencies=project_dependencies,
)
)
global_configuration_platforms.append(
SolutionGlobalConfigurationPlatforms.format(project_guid=project_guid)
)
f.write(
SolutionGlobal.format(
configuration_platforms="\n".join(global_configuration_platforms)
)
)
def get_files(
*,
root_dir: str,
ext: str,
root_dir_suffix: str = "",
exclude_dirs: Iterable[str] = (),
exclude_exts: Iterable[str] = (),
) -> list[tuple[str, str, str]]:
"""
Get file paths split into
1) containing folder ("your/path")
2) relative path to parent directory within containing folder ("amulet/io")
3) file name. ("binary_reader.hpp")
get_files("your/path", "hpp")
"""
paths = list[tuple[str, str, str]]()
search_path = root_dir
if root_dir_suffix:
search_path = os.path.join(search_path, root_dir_suffix)
for path in glob.iglob(
os.path.join(glob.escape(search_path), "**", f"*.{ext}"), recursive=True
):
if any(map(path.startswith, exclude_dirs)):
continue
if any(map(path.endswith, exclude_exts)):
continue
rel_path = os.path.relpath(path, root_dir)
paths.append((root_dir, os.path.dirname(rel_path), os.path.basename(rel_path)))
return paths
def get_package_path(name: str) -> str:
spec = importlib.util.find_spec(name)
if spec is None:
raise RuntimeError(f"Could not find {name}")
search_path = spec.submodule_search_locations
if search_path is None:
raise RuntimeError(f"{name} search path is None")
return search_path[0]