-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathbuild.ps1
More file actions
519 lines (432 loc) · 17.4 KB
/
build.ps1
File metadata and controls
519 lines (432 loc) · 17.4 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
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
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
<#
.SYNOPSIS
Build script for PSScriptBuilder module with automatic dependency resolution.
.DESCRIPTION
This script builds the PSScriptBuilder module by:
1. Analyzing dependencies of all PowerShell files
2. Resolving the correct load order using topological sort
3. Dot-sourcing files in dependency order to make all classes available
4. Loading configuration from PSScriptBuilderConfiguration
5. Creating the compiled module
.PARAMETER ProjectRoot
(Required) The root path of the PSScriptBuilder project.
.PARAMETER Verbose
Show detailed build information.
.EXAMPLE
.\build.ps1 -ProjectRoot 'C:\PSScriptBuilder'
.\build.ps1 -ProjectRoot 'C:\PSScriptBuilder' -Verbose
#>
using namespace System.Collections.Generic
using namespace System.Management.Automation.Language
[CmdletBinding()]
param(
[Parameter(Mandatory=$true)]
[string] $ProjectRoot
)
$ErrorActionPreference = 'Stop'
$InformationPreference = 'Continue'
# Resolve ProjectRoot to absolute path
$ProjectRoot = ($ProjectRoot | Resolve-Path).ProviderPath
# Store in global variable for reference
$Global:PSScriptBuilderProjectRoot = $ProjectRoot
#region Build Configuration
$SrcPath = Join-Path $ProjectRoot 'src'
$EnumPath = Join-Path $SrcPath 'Enums'
$ClassesPath = Join-Path $SrcPath 'Classes'
$PrivatePath = Join-Path $SrcPath 'Private'
$PublicPath = Join-Path $SrcPath 'Public'
Write-Information "=== PSScriptBuilder Build ==="
Write-Information "ProjectRoot: $ProjectRoot"
Write-Information "SrcPath: $SrcPath"
#endregion Build Configuration
#region Dependency Analysis
class FileDependency {
[string] $FilePath
[string] $FileName
[string[]] $DependsOn = @()
[string[]] $UsingStatements = @()
[string] $Type
}
function Analyze-FileDependencies {
param(
[string] $FilePath,
[string] $Type
)
$fileName = Split-Path -Path $FilePath -Leaf
$dependencies = @()
$usingStatements = @()
try {
$ast = [Parser]::ParseFile($FilePath, [ref] $null, [ref] $null)
$content = Get-Content -Path $FilePath -Raw
$usingAsts = $ast.FindAll({ param($node) $node -is [UsingStatementAst] }, $true)
foreach ($using in $usingAsts) {
$usingName = $using.Name.Value
$usingKind = $using.UsingStatementKind
$usingStatement = "using $($usingKind.ToString().ToLower()) $usingName"
if ($usingStatement -notin $usingStatements) {
$usingStatements += $usingStatement
}
}
# Find dependencies via AST
$typeDefinitions = $ast.FindAll({ param($node) $node -is [TypeDefinitionAst] }, $true)
foreach ($typeDef in $typeDefinitions) {
# Base classes
if ($typeDef.BaseTypes.Count -gt 0) {
foreach ($baseType in $typeDef.BaseTypes) {
$baseTypeName = $null
if ($baseType.TypeName) {
$baseTypeName = $baseType.TypeName.Name
}
elseif ($baseType -is [TypeExpressionAst]) {
$baseTypeName = $baseType.Type.Name
}
if ($baseTypeName -and $baseTypeName -match '^PSScriptBuilder' -and $baseTypeName -notin $dependencies) {
$dependencies += $baseTypeName
}
}
}
# Member types (properties and method return types)
foreach ($member in $typeDef.Members) {
if ($member -is [PropertyMemberAst]) {
# Property types - including generics like Dictionary[string, Type]
if ($member.PropertyType -and $member.PropertyType.TypeName) {
# Get the full type string (may include generic parameters)
$typeStr = $member.PropertyType.TypeName.Name
# Extract all PSScriptBuilder types from the string
$typeMatches = [regex]::Matches($typeStr, '\bPSScriptBuilder\w+')
foreach ($match in $typeMatches) {
$typeName = $match.Value
if ($typeName -notin $dependencies) {
$dependencies += $typeName
}
}
}
}
elseif ($member -is [FunctionMemberAst]) {
# Return types
if ($member.ReturnType -and $member.ReturnType.TypeName) {
$typeStr = $member.ReturnType.TypeName.Name
$typeMatches = [regex]::Matches($typeStr, '\bPSScriptBuilder\w+')
foreach ($match in $typeMatches) {
$typeName = $match.Value
if ($typeName -notin $dependencies) {
$dependencies += $typeName
}
}
}
# Parameter types
if ($member.Parameters) {
foreach ($param in $member.Parameters) {
foreach ($attribute in $param.Attributes) {
if ($attribute -is [TypeConstraintAst] -and $attribute.TypeName) {
$typeStr = $attribute.TypeName.Name
$typeMatches = [regex]::Matches($typeStr, '\bPSScriptBuilder\w+')
foreach ($match in $typeMatches) {
$typeName = $match.Value
if ($typeName -notin $dependencies) {
$dependencies += $typeName
}
}
}
}
}
}
}
}
}
# Find static method calls like [PSScriptBuilderFileSystemHelper]::Method()
# Use regex to find [ClassName]:: patterns in the source code
$staticCallMatches = [regex]::Matches($content, '\[PSScriptBuilder\w+\]::', 'IgnoreCase')
foreach ($match in $staticCallMatches) {
# Extract the class name from [ClassName]::
$fullMatch = $match.Value
$typeName = $fullMatch.Substring(1, $fullMatch.Length - 4) # Remove [ and ]::
if ($typeName -notin $dependencies) {
$dependencies += $typeName
}
}
}
catch {
Write-Warning "Error parsing $fileName : $($_.Exception.Message)"
}
# Get the class/enum names defined in this file
$content = Get-Content -Path $FilePath -Raw
$definedNames = @()
$classMatches = [regex]::Matches($content, 'class\s+(\w+)', 'IgnoreCase')
foreach ($match in $classMatches) {
$definedNames += $match.Groups[1].Value
}
$enumMatches = [regex]::Matches($content, 'enum\s+(\w+)', 'IgnoreCase')
foreach ($match in $enumMatches) {
$definedNames += $match.Groups[1].Value
}
# Filter out self-references
$uniqueDependencies = @($dependencies | Where-Object { $_ -notin $definedNames })
return [PSCustomObject] @{
FilePath = $FilePath
FileName = $fileName
DependsOn = @($uniqueDependencies | Select-Object -Unique)
UsingStatements = @($usingStatements | Select-Object -Unique)
Type = $Type
}
}
function Build-ClassNameMap {
param(
[FileDependency[]] $FileDependencies
)
$map = @{}
foreach ($dep in $FileDependencies) {
try {
$ast = [Parser]::ParseFile($dep.FilePath, [ref] $null, [ref] $null)
# Find actual class definitions using AST
$classDefinitions = $ast.FindAll({ param($node) $node -is [TypeDefinitionAst] }, $true)
foreach ($classdef in $classDefinitions) {
$className = $classdef.Name
$map[$className] = $dep.FilePath
}
}
catch {
Write-Warning "Error parsing $($dep.FileName): $($_.Exception.Message)"
}
}
Write-Information " Classes found: $($map.Count)"
return $map
}
function Resolve-FileDependencies {
param(
[object[]] $FileDependencies,
[hashtable] $ClassNameMap
)
foreach ($fileDep in $FileDependencies) {
$resolvedDeps = @()
foreach ($dep in $fileDep.DependsOn) {
if ($ClassNameMap.ContainsKey($dep)) {
$depFilePath = $ClassNameMap[$dep]
if ($depFilePath -ne $fileDep.FilePath -and $depFilePath -notin $resolvedDeps) {
$resolvedDeps += $depFilePath
}
}
}
$fileDep.DependsOn = $resolvedDeps
}
}
function Resolve-LoadOrder {
param(
[FileDependency[]] $FileDependencies
)
# Create lookup map for quick file access by path
$fileMap = @{}
foreach ($file in $FileDependencies) {
$fileMap[$file.FilePath] = $file
}
# Build graph of dependencies: file -> list of files that depend on it
$graph = @{}
$inDegree = @{}
# Initialize all nodes
foreach ($file in $FileDependencies) {
if (-not $graph.ContainsKey($file.FilePath)) {
$graph[$file.FilePath] = @()
}
if (-not $inDegree.ContainsKey($file.FilePath)) {
$inDegree[$file.FilePath] = 0
}
}
# Build edges and calculate in-degrees
# If file A depends on file B, then B -> A (B must be loaded before A)
foreach ($file in $FileDependencies) {
foreach ($depFile in $file.DependsOn) {
# depFile must be loaded before file
# So: graph[depFile] += file (depFile points to file)
# And: inDegree[file]++
if (-not $graph.ContainsKey($depFile)) {
# Dependency resolved to a file that doesn't exist in our list
# This shouldn't happen if Resolve-FileDependencies is working correctly
Write-Verbose "WARNING: Dependency file '$depFile' not found in file list"
continue
}
if ($file.FilePath -notin $graph[$depFile]) {
$graph[$depFile] += $file.FilePath
$inDegree[$file.FilePath]++
}
}
}
if ($Verbose) {
Write-Verbose "Kahn's Algorithm - In-Degrees:"
foreach ($file in $inDegree.GetEnumerator() | Sort-Object Value -Descending) {
$fileName = Split-Path -Leaf $file.Key
Write-Verbose " $fileName : $($file.Value)"
}
}
# Kahn's algorithm
[System.Collections.Queue] $queue = [System.Collections.Queue]::new()
# Start with files that have no dependencies
$noDepFiles = @($inDegree.Keys | Where-Object { $inDegree[$_] -eq 0 })
Write-Verbose "Starting with $($noDepFiles.Count) files with no dependencies"
foreach ($filePath in $noDepFiles) {
$queue.Enqueue($filePath)
}
$sorted = @()
while ($queue.Count -gt 0) {
$current = $queue.Dequeue()
$sorted += $current
# For each file that depends on current
foreach ($dependent in $graph[$current]) {
# Decrement in-degree
$inDegree[$dependent]--
# If all dependencies are satisfied, add to queue
if ($inDegree[$dependent] -eq 0) {
$queue.Enqueue($dependent)
}
}
}
# Check for cycles
if ($sorted.Count -lt $FileDependencies.Count) {
$unprocessed = @()
foreach ($file in $FileDependencies) {
if ($file.FilePath -notin $sorted) {
$unprocessed += $file.FileName
}
}
throw "Circular dependency detected: $($unprocessed -join ', ')"
}
return $sorted
}
#endregion Dependency Analysis
#region Build Process
Write-Information ""
Write-Information "Step 1: Analyzing dependencies..."
$allFiles = @()
if (Test-Path $EnumPath) {
Get-ChildItem -Path $EnumPath -Filter '*.ps1' | ForEach-Object {
$dep = Analyze-FileDependencies -FilePath $_.FullName -Type 'Enum'
$allFiles += $dep
Write-Information " Found enum: $($_.Name)"
}
}
if (Test-Path $ClassesPath) {
Get-ChildItem -Path $ClassesPath -Recurse -Filter '*.ps1' | ForEach-Object {
$dep = Analyze-FileDependencies -FilePath $_.FullName -Type 'Class'
$allFiles += $dep
Write-Information " Found class: $($_.Name)"
}
}
if (Test-Path $PrivatePath) {
Get-ChildItem -Path $PrivatePath -Filter '*.ps1' | ForEach-Object {
$dep = Analyze-FileDependencies -FilePath $_.FullName -Type 'Private'
$allFiles += $dep
Write-Information " Found private: $($_.Name)"
}
}
if (Test-Path $PublicPath) {
Get-ChildItem -Path $PublicPath -Filter '*.ps1' | ForEach-Object {
$dep = Analyze-FileDependencies -FilePath $_.FullName -Type 'Public'
$allFiles += $dep
Write-Information " Found cmdlet: $($_.Name)"
}
}
Write-Information " Total files found: $($allFiles.Count)"
Write-Information ""
Write-Information "Step 2: Building class name map..."
$classNameMap = Build-ClassNameMap -FileDependencies $allFiles
Write-Information " Classes found: $($classNameMap.Count)"
Write-Information ""
Write-Information "Step 3: Resolving load order..."
Resolve-FileDependencies -FileDependencies $allFiles -ClassNameMap $classNameMap
if ($VerbosePreference -eq 'Continue') {
Write-Information " Dependency details:"
foreach ($file in $allFiles) {
if ($file.DependsOn.Count -gt 0) {
Write-Information " DEBUG: $($file.FileName) DependsOn array contains: [$($file.DependsOn -join ' | ')]"
$deps = ($file.DependsOn | ForEach-Object { Split-Path -Path $_ -Leaf }) -join ', '
Write-Information " $($file.FileName) depends on: $deps"
}
}
}
$loadOrder = Resolve-LoadOrder -FileDependencies $allFiles
# Filter out invalid paths (should only contain file paths)
$loadOrder = $loadOrder | Where-Object { Test-Path $_ -PathType Leaf }
Write-Information " Load order:"
$loadOrder | ForEach-Object {
$fileName = Split-Path -Path $_ -Leaf
Write-Information " $([Array]::IndexOf($loadOrder, $_) + 1). $fileName"
}
Write-Information ""
Write-Information "Step 4: Loading classes and functions..."
foreach ($filePath in $loadOrder) {
try {
$fileName = Split-Path -Path $filePath -Leaf
. $filePath
Write-Information " Loaded: $fileName"
}
catch {
Write-Error "Failed to load file: $filePath`n$($_.Exception.Message)"
throw
}
}
Write-Information ""
Write-Information "Step 5: Loading configuration..."
$configuration = [PSScriptBuilderConfiguration]::new()
Write-Information "Configuration:"
$configuration | Format-List
# Resolve output path - if it's relative, resolve it from ProjectRoot; if absolute, use as-is
if ([System.IO.Path]::IsPathRooted($configuration.Build.OutputPath)) {
$OutputPath = $configuration.Build.OutputPath
} else {
$OutputPath = Join-Path $ProjectRoot $configuration.Build.OutputPath
}
$ModuleFile = Join-Path $OutputPath 'PSScriptBuilder.psm1'
Write-Information ""
Write-Information "Output path from configuration: $OutputPath"
Write-Information ""
Write-Information "Step 6: Creating compiled module..."
if (-not (Test-Path $OutputPath)) {
New-Item -ItemType Directory -Path $OutputPath -Force | Out-Null
Write-Information " Created output directory: $OutputPath"
}
$moduleContent = @()
$allUsingStatements = @()
foreach ($filePath in $loadOrder) {
$content = Get-Content -Path $filePath -Raw
$fileName = Split-Path -Path $filePath -Leaf
$fileDep = $allFiles | Where-Object { $_.FilePath -eq $filePath }
if ($fileDep) {
foreach ($using in $fileDep.UsingStatements) {
if ($using -notin $allUsingStatements) {
$allUsingStatements += $using
}
}
}
$cleanContent = $content -replace '(?m)^using\s+(?:namespace|assembly|module)\s+[^\r\n]+[\r\n]*', ''
$regionStart = "#region $fileName`n"
$regionEnd = "`n#endregion $fileName`n`n"
$moduleContent += $regionStart + $cleanContent + $regionEnd
}
Write-Information ""
Write-Information "Step 7: Compiling module..."
$finalContent = @()
if ($allUsingStatements.Count -gt 0) {
Write-Information " Adding $($allUsingStatements.Count) using statements..."
foreach ($using in $allUsingStatements | Sort-Object) {
$finalContent += $using
}
$finalContent += ""
}
$finalContent += $moduleContent
$finalContent -join "`n" | Out-File $ModuleFile -Encoding UTF8 -Force
Write-Information " Module compiled: $ModuleFile"
Write-Information " Module size: $((Get-Item $ModuleFile).Length / 1KB)KB"
Write-Information ""
Write-Information "Step 8: Validating module syntax..."
$syntaxTokens = $null
$syntaxErrors = $null
[Parser]::ParseFile($ModuleFile, [ref] $syntaxTokens, [ref] $syntaxErrors) | Out-Null
if ($syntaxErrors.Count -gt 0) {
Write-Error "Module syntax error: $($syntaxErrors[0].Message)"
throw [System.InvalidOperationException]::new("Module syntax validation failed: $($syntaxErrors[0].Message)")
}
Write-Information " Module syntax is valid"
#endregion Build Process
Write-Information ""
Write-Information "=== Build completed successfully ==="
Write-Information "Module location: $ModuleFile"
Write-Information ""