Repository navigation
Expand file tree
/
Copy pathGenerateSolutionFile.ps1
More file actions
311 lines (246 loc) · 11.5 KB
/
Copy pathGenerateSolutionFile.ps1
File metadata and controls
311 lines (246 loc) · 11.5 KB
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
<#
.SYNOPSIS
Generates a .slnx solution file for a set of Community Toolkit projects.
.DESCRIPTION
Shared by GenerateAllSolution.ps1 and GenerateSingleSolution.ps1. This is intentionally not a general purpose
solution generator, it only supports what the Toolkit components need:
- Projects are grouped into solution folders mirroring their location under the repository root.
- The solution exposes the 'Any CPU', 'x64', 'x86' and 'ARM64' platforms. Projects that target Windows
(UWP and WinAppSdk) are mapped to the matching platform ('Any CPU' maps to 'x64'). Other projects keep their default platform.
- Deployable projects (the sample app heads) are flagged to be deployed.
- Shared repository files (.editorconfig, settings.xamlstyler, markdown files and the tooling GlobalUsings files)
are added to a 'Solution Items' folder.
.PARAMETER OutputPath
The path of the .slnx file to generate. An existing file is overwritten.
.PARAMETER Projects
The projects to include in the solution (.csproj, .shproj, etc...).
.PARAMETER PlatformSpecificProjects
The subset of Projects that target Windows and need to be mapped to a specific platform (x64, x86 or ARM64).
.PARAMETER DeployableProjects
The subset of Projects that should be deployed when running the solution.
.PARAMETER RootDirectory
The root directory of the repository using the tooling. Used to build the solution folders and to find the solution items.
Defaults to the parent directory of the tooling, as the tooling is expected to live in a 'tooling' folder in the repository root.
.PARAMETER IncludeReferencedProjects
Also adds the projects referenced (directly or indirectly) by the included projects.
This needs to evaluate every project with MSBuild for all of its target frameworks, which is slow (a few seconds per project).
.PARAMETER Launch
Opens the generated solution (using the default application for .slnx files) when running on Windows.
.PARAMETER UseDiagnostics
Prints the contents of the generated solution file.
.OUTPUTS
None. The full path of the generated solution file is written to the host.
#>
[CmdletBinding()]
Param (
[Parameter(Mandatory = $true)]
[string]$OutputPath,
[Parameter(Mandatory = $true)]
[string[]]$Projects,
[string[]]$PlatformSpecificProjects = @(),
[string[]]$DeployableProjects = @(),
[string]$RootDirectory = (Join-Path $PSScriptRoot '..'),
[switch]$IncludeReferencedProjects,
[switch]$Launch,
[switch]$UseDiagnostics
)
$ErrorActionPreference = 'Stop'
# The platforms exposed by the solution, and the platform each one is built as for Windows specific projects.
$solutionPlatforms = [ordered]@{ 'Any CPU' = 'x64'; 'ARM64' = 'ARM64'; 'x64' = 'x64'; 'x86' = 'x86' }
$isWindowsPlatform = [System.IO.Path]::DirectorySeparatorChar -eq '\'
$pathComparison = if ($isWindowsPlatform) { [System.StringComparison]::OrdinalIgnoreCase } else { [System.StringComparison]::Ordinal }
function Resolve-FullPath([string]$Path) {
return $ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath($Path)
}
function Get-PathSegments([string]$Path) {
return @($Path -split '[\\/]' | Where-Object { $_ -ne '' })
}
# Gets the path of $To relative to the directory $From, using forward slashes. Not using Path.GetRelativePath for Windows PowerShell.
function Get-RelativePath([string]$From, [string]$To) {
$fromSegments = Get-PathSegments $From
$toSegments = Get-PathSegments $To
$common = 0
while ($common -lt $fromSegments.Count -and
$common -lt $toSegments.Count -and
[string]::Equals($fromSegments[$common], $toSegments[$common], $pathComparison)) {
$common++
}
# Different drives or network shares can't be expressed as a relative path
if ($common -eq 0 -and $isWindowsPlatform) {
return $To.Replace('\', '/')
}
$segments = @('..') * ($fromSegments.Count - $common)
if ($common -lt $toSegments.Count) {
$segments += $toSegments[$common..($toSegments.Count - 1)]
}
return $segments -join '/'
}
$root = (Resolve-FullPath $RootDirectory).TrimEnd('\', '/')
$outputFullPath = Resolve-FullPath $OutputPath
$outputDirectory = Split-Path $outputFullPath -Parent
# Gets the solution folder for a project: the directory containing the project's own directory, relative to the root
# (for example 'components/MyComponent' for 'components/MyComponent/src/MyComponent.csproj').
function Get-SolutionFolder([string]$ProjectPath) {
$relativeDirectory = Get-RelativePath $root (Split-Path (Split-Path $ProjectPath -Parent) -Parent)
if ($relativeDirectory -eq '' -or $relativeDirectory -eq '..' -or $relativeDirectory.StartsWith('../')) {
return $null
}
return $relativeDirectory
}
function Test-PathInList([string]$Path, [string[]]$List) {
foreach ($item in $List) {
if ([string]::Equals((Resolve-FullPath $item), $Path, $pathComparison)) {
return $true
}
}
return $false
}
# Collect and validate the projects, ignoring duplicates
$entries = [System.Collections.Generic.List[object]]::new()
$seen = [System.Collections.Generic.HashSet[string]]::new([System.StringComparer]::OrdinalIgnoreCase)
foreach ($project in $Projects) {
$projectPath = Resolve-FullPath $project
if (-not (Test-Path -LiteralPath $projectPath -PathType Leaf)) {
throw "Project '$projectPath' does not exist."
}
if (-not $seen.Add($projectPath)) {
continue
}
$entries.Add([pscustomobject]@{
Path = $projectPath
Folder = Get-SolutionFolder $projectPath
PlatformSpecific = Test-PathInList $projectPath $PlatformSpecificProjects
Deployable = Test-PathInList $projectPath $DeployableProjects
})
}
# Gets the full paths of the projects referenced by a project, for all of its target frameworks (a ProjectReference
# can be conditioned on the target framework). This evaluates the project with MSBuild, which takes a few seconds.
function Get-ReferencedProjects([string]$ProjectPath) {
function Invoke-Evaluation([string[]]$Arguments) {
# Windows PowerShell turns any native command stderr output (including MSBuild warnings) into terminating errors otherwise
$previousPreference = $ErrorActionPreference
$ErrorActionPreference = 'Continue'
try {
$output = @(& dotnet msbuild $ProjectPath -nologo -v:q @Arguments 2>$null)
}
finally {
$ErrorActionPreference = $previousPreference
}
$start = [array]::IndexOf($output, '{')
if ($start -lt 0) {
return $null
}
return ($output[$start..($output.Count - 1)] -join "`n") | ConvertFrom-Json
}
$outer = Invoke-Evaluation @('-getProperty:TargetFrameworks', '-getItem:ProjectReference')
if ($null -eq $outer) {
Write-Warning "Could not evaluate '$ProjectPath', its project references won't be added to the solution."
return @()
}
$references = @($outer.Items.ProjectReference)
foreach ($framework in @($outer.Properties.TargetFrameworks -split ';' | Where-Object { $_ -ne '' })) {
$inner = Invoke-Evaluation @("-p:TargetFramework=$framework", '-getItem:ProjectReference')
if ($null -ne $inner) {
$references += @($inner.Items.ProjectReference)
}
}
return @($references | Where-Object { $_.FullPath -and $_.FullPath -notlike '*.shproj' } | ForEach-Object { $_.FullPath })
}
# Add the projects referenced (directly or not) by the included ones, like the solution is expected to have
# them to edit and debug them. Referenced projects of Windows projects are mapped to a specific platform as well.
if ($IncludeReferencedProjects) {
for ($i = 0; $i -lt $entries.Count; $i++) {
$entry = $entries[$i]
if ($entry.Path -notlike '*.csproj') {
continue
}
foreach ($reference in (Get-ReferencedProjects $entry.Path)) {
$referencePath = Resolve-FullPath $reference
if ((Test-Path -LiteralPath $referencePath -PathType Leaf) -and $seen.Add($referencePath)) {
$entries.Add([pscustomobject]@{
Path = $referencePath
Folder = Get-SolutionFolder $referencePath
PlatformSpecific = $entry.PlatformSpecific
Deployable = $false
})
}
}
}
}
# Files shared by all solutions, matching what is available in the repository root (when using the tooling as a 'tooling' submodule) and tooling folders
$solutionItems = @()
if (Test-Path -LiteralPath (Join-Path $root 'tooling') -PathType Container) {
$solutionItems += Get-ChildItem -LiteralPath $root -File -Force |
Where-Object { $_.Name -in @('.editorconfig', 'settings.xamlstyler') -or $_.Name -like '*.md' }
}
$solutionItems += Get-ChildItem -LiteralPath $PSScriptRoot -File -Filter 'GlobalUsings*.cs'
$settings = [System.Xml.XmlWriterSettings]::new()
$settings.Indent = $true
$settings.IndentChars = ' '
$settings.OmitXmlDeclaration = $true
$settings.Encoding = [System.Text.UTF8Encoding]::new($false)
$writer = [System.Xml.XmlWriter]::Create($outputFullPath, $settings)
try {
$writer.WriteStartElement('Solution')
$writer.WriteStartElement('Configurations')
foreach ($platform in $solutionPlatforms.Keys) {
$writer.WriteStartElement('Platform')
$writer.WriteAttributeString('Name', $platform)
$writer.WriteEndElement()
}
$writer.WriteEndElement()
if ($solutionItems.Count -gt 0) {
$writer.WriteStartElement('Folder')
$writer.WriteAttributeString('Name', '/Solution Items/')
foreach ($item in ($solutionItems | Sort-Object FullName)) {
$writer.WriteStartElement('File')
$writer.WriteAttributeString('Path', (Get-RelativePath $outputDirectory $item.FullName))
$writer.WriteEndElement()
}
$writer.WriteEndElement()
}
# Projects outside of any folder first, then each folder in order
$groups = $entries | Group-Object { if ($_.Folder) { $_.Folder } else { '' } } | Sort-Object Name
foreach ($group in $groups) {
if ($group.Name -ne '') {
$writer.WriteStartElement('Folder')
$writer.WriteAttributeString('Name', "/$($group.Name)/")
}
foreach ($entry in ($group.Group | Sort-Object Path)) {
$writer.WriteStartElement('Project')
$writer.WriteAttributeString('Path', (Get-RelativePath $outputDirectory $entry.Path))
if ($entry.PlatformSpecific) {
foreach ($platform in $solutionPlatforms.Keys) {
$writer.WriteStartElement('Platform')
$writer.WriteAttributeString('Solution', "*|$platform")
$writer.WriteAttributeString('Project', $solutionPlatforms[$platform])
$writer.WriteEndElement()
}
}
if ($entry.Deployable) {
$writer.WriteStartElement('Deploy')
$writer.WriteEndElement()
}
$writer.WriteEndElement()
}
if ($group.Name -ne '') {
$writer.WriteEndElement()
}
}
$writer.WriteEndElement()
}
finally {
$writer.Dispose()
}
Write-Host "Generated solution $outputFullPath with $($entries.Count) projects"
if ($UseDiagnostics) {
Get-Content -LiteralPath $outputFullPath | Write-Host
}
if ($Launch -and $isWindowsPlatform) {
try {
Invoke-Item -LiteralPath $outputFullPath
}
catch {
Write-Warning "Could not open $outputFullPath, open it manually. $_"
}
}