-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathbuild.ps1
More file actions
1717 lines (1406 loc) · 58.7 KB
/
build.ps1
File metadata and controls
1717 lines (1406 loc) · 58.7 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
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<#
.SYNOPSIS
Build script for the Convert PowerShell module.
.DESCRIPTION
Parameter-driven build script that compiles Rust libraries, assembles PowerShell modules,
runs tests, performs code analysis, and creates distribution packages.
Supports flexible workflows through language selection (-Rust, -PowerShell) and action
selection (-Build, -Test, -Analyze, -Fix, -Clean, -Package). If no language is specified,
both Rust and PowerShell operations are performed.
.PARAMETER Rust
Target Rust operations. Enables: Build, Test, Analyze, Fix, Clean, Security, Deep.
Automatically installs required Rust tools (cargo-nextest, cargo-audit, miri) if not present.
.PARAMETER PowerShell
Target PowerShell operations. Enables: Build, Test, Analyze, Fix, Clean, Package, Docs.
.PARAMETER Build
Compile Rust library (cargo build --release) or assemble PowerShell module.
.PARAMETER Test
Run Rust cargo tests or PowerShell Pester tests with code coverage.
.PARAMETER Analyze
Run code analysis. Rust: clippy, fmt check, cargo check. PowerShell: PSScriptAnalyzer.
.PARAMETER Fix
Auto-fix code issues. Rust: cargo fmt, clippy --fix. PowerShell: Invoke-Formatter.
.PARAMETER Clean
Remove build artifacts. Rust: cargo clean. PowerShell: remove Artifacts/ directory.
.PARAMETER Package
Create distribution ZIP from assembled PowerShell module. Requires -PowerShell.
.PARAMETER Docs
Generate PowerShell function documentation using PlatyPS. Requires -PowerShell.
.PARAMETER Security
Run Rust security audit (cargo audit). Requires -Rust.
.PARAMETER Deep
Run Rust deep analysis (cargo miri test). Requires -Rust.
.PARAMETER Full
Execute complete build workflow: Clean, Fix, Analyze, Build, Test, Package, Docs.
.PARAMETER CI
Execute CI/CD workflow: Full + S3 upload (CodeBuild only).
.EXAMPLE
.\build.ps1 -Rust -Build
Compile Rust library and copy to module bin directory.
.EXAMPLE
.\build.ps1 -PowerShell -Test
Run PowerShell Pester tests with code coverage validation.
.EXAMPLE
.\build.ps1 -Full
Execute complete build workflow for both Rust and PowerShell components.
.EXAMPLE
.\build.ps1 -CI
Execute CI/CD pipeline with full build and S3 artifact upload.
.EXAMPLE
.\build.ps1 -Rust -Analyze -Security
Run Rust code analysis including security audit with cargo audit.
.EXAMPLE
.\build.ps1 -PowerShell -Docs
Generate PowerShell function documentation from comment-based help.
.NOTES
Action Availability by Language:
Action | Rust | PowerShell
------------|------|------------
Build | Yes | Yes
Test | Yes | Yes
Analyze | Yes | Yes
Fix | Yes | Yes
Clean | Yes | Yes
Package | No | Yes
Docs | No | Yes
Security | Yes | No
Deep | Yes | No
Exit Codes:
0 - Success
1 - General error or validation failure
Requirements:
- PowerShell 5.0 or higher
- Rust toolchain (for Rust operations) - install from https://rustup.rs
- Pester 5.3.0+ (for PowerShell tests)
Rust Dependencies (auto-installed when -Rust is used):
- cargo-nextest - Fast test runner (always installed)
- cargo-audit - Security vulnerability scanner (installed with -Security)
- nightly toolchain + miri - Undefined behavior detector (installed with -Deep)
#>
[CmdletBinding()]
param(
# Language selection
[switch]$Rust,
[switch]$PowerShell,
# Actions
[switch]$Build,
[switch]$Test,
[switch]$Analyze,
[switch]$Fix,
[switch]$Clean,
[switch]$Package,
[switch]$Docs,
# Build modifiers (Rust only)
[switch]$All,
[ValidateSet(
'x86_64-pc-windows-msvc',
'aarch64-pc-windows-msvc',
'x86_64-unknown-linux-gnu',
'aarch64-unknown-linux-gnu',
'armv7-unknown-linux-gnueabihf',
'x86_64-apple-darwin',
'aarch64-apple-darwin'
)]
[string[]]$Targets = @(),
# Test modifiers (PowerShell only)
[switch]$Artifact,
# Analysis modifiers (Rust only)
[switch]$Security,
[switch]$Deep,
# Workflows
[switch]$Full,
[switch]$CI,
[string]$HashFile
)
#region Helper Functions
function Initialize-BuildEnvironment {
<#
.SYNOPSIS
Initializes the build environment and returns configuration object.
.DESCRIPTION
Validates PowerShell version, reads module manifest, detects CodeBuild environment,
and configures build paths and settings.
#>
if ($PSVersionTable.PSVersion.Major -lt 5) {
throw "PowerShell 5.0 or higher is required. Current version: $($PSVersionTable.PSVersion)"
}
$repositoryRoot = [System.IO.Path]::GetFullPath([System.IO.Path]::Combine($PSScriptRoot, '.'))
$manifestPath = [System.IO.Path]::Combine($repositoryRoot, 'src', 'Convert', 'Convert.psd1')
if (-not [System.IO.File]::Exists($manifestPath)) {
throw "Module manifest not found at: $manifestPath"
}
$manifest = Import-PowerShellDataFile -Path $manifestPath
$config = [PSCustomObject]@{
RepositoryRoot = $repositoryRoot
ModuleName = 'Convert'
ModuleVersion = $manifest.ModuleVersion
ModuleDescription = $manifest.Description
FunctionsToExport = $manifest.FunctionsToExport
SourcePath = [System.IO.Path]::Combine($repositoryRoot, 'src', 'Convert')
TestsPath = [System.IO.Path]::Combine($repositoryRoot, 'src', 'Tests')
ArtifactsPath = [System.IO.Path]::Combine($repositoryRoot, 'Artifacts')
ArchivePath = [System.IO.Path]::Combine($repositoryRoot, 'Archive')
DeploymentArtifactsPath = [System.IO.Path]::Combine($repositoryRoot, 'DeploymentArtifacts')
LibPath = [System.IO.Path]::Combine($repositoryRoot, 'lib')
PesterOutputFormat = 'CoverageGutters'
CodeCoverageThreshold = 79
}
return $config
}
function Get-BuildContentHash {
<#
.SYNOPSIS
Calculates a SHA256 hash of all build-relevant files.
#>
param(
[Parameter(Mandatory)]
[string]$RepositoryRoot
)
$searchLocations = @(
@{ Path = @('src', 'Convert'); Pattern = '*.ps1' },
@{ Path = @('src', 'Convert'); Pattern = '*.psd1' },
@{ Path = @('src', 'Convert'); Pattern = '*.psm1' },
@{ Path = @('src', 'Convert', 'Public'); Pattern = '*.ps1' },
@{ Path = @('src', 'Convert', 'Private'); Pattern = '*.ps1' },
@{ Path = @('src', 'Tests', 'Unit'); Pattern = '*.ps1' },
@{ Path = @('.build'); Pattern = '*.ps1' },
@{ Path = @('lib', 'src'); Pattern = '*.rs' },
@{ Path = @('lib'); Pattern = 'Cargo.toml' },
@{ Path = @('lib'); Pattern = 'Cargo.lock' }
)
$rootFiles = @(
'build.ps1',
'install_modules.ps1',
'install_nuget.ps1'
)
$allContent = [System.Text.StringBuilder]::new()
foreach ($file in $rootFiles) {
$filePath = [System.IO.Path]::Combine($RepositoryRoot, $file)
if ([System.IO.File]::Exists($filePath)) {
$content = [System.IO.File]::ReadAllText($filePath, [System.Text.Encoding]::UTF8)
[void]$allContent.AppendLine("### $file ###")
[void]$allContent.AppendLine($content)
}
}
foreach ($location in $searchLocations) {
$pathSegments = @($RepositoryRoot) + $location.Path
$searchPath = [System.IO.Path]::Combine($pathSegments)
$searchPattern = $location.Pattern
if ([System.IO.Directory]::Exists($searchPath)) {
$files = [System.IO.Directory]::GetFiles($searchPath, $searchPattern) | Sort-Object
foreach ($file in $files) {
$relativePath = $file.Substring($RepositoryRoot.Length).TrimStart([System.IO.Path]::DirectorySeparatorChar, [System.IO.Path]::AltDirectorySeparatorChar)
$normalizedPath = $relativePath -replace '\\', '/'
$content = [System.IO.File]::ReadAllText($file, [System.Text.Encoding]::UTF8)
[void]$allContent.AppendLine("### $normalizedPath ###")
[void]$allContent.AppendLine($content)
}
}
}
$bytes = [System.Text.Encoding]::UTF8.GetBytes($allContent.ToString())
$sha256 = [System.Security.Cryptography.SHA256]::Create()
$hashBytes = $sha256.ComputeHash($bytes)
$hash = [System.BitConverter]::ToString($hashBytes) -replace '-', ''
return $hash.ToLower()
}
function Get-PreviousBuildHash {
<#
.SYNOPSIS
Reads the previous build hash from the hash file.
#>
param(
[Parameter(Mandatory)]
[string]$HashFilePath
)
if ([System.IO.File]::Exists($HashFilePath)) {
$content = [System.IO.File]::ReadAllText($HashFilePath, [System.Text.Encoding]::UTF8).Trim()
return $content
}
return $null
}
function Save-BuildHash {
<#
.SYNOPSIS
Saves the current build hash to the hash file.
#>
param(
[Parameter(Mandatory)]
[string]$HashFilePath,
[Parameter(Mandatory)]
[string]$Hash
)
$directory = [System.IO.Path]::GetDirectoryName($HashFilePath)
if (-not [System.IO.Directory]::Exists($directory)) {
[System.IO.Directory]::CreateDirectory($directory) | Out-Null
}
[System.IO.File]::WriteAllText($HashFilePath, $Hash, [System.Text.Encoding]::UTF8)
}
function Get-PlatformInfo {
<#
.SYNOPSIS
Detects platform and architecture, returns library configuration.
.DESCRIPTION
Determines the operating system (Windows/macOS/Linux), processor architecture,
and appropriate Rust library filename for the current platform.
#>
$runtimeArch = [System.Runtime.InteropServices.RuntimeInformation]::ProcessArchitecture
$architecture = switch ($runtimeArch) {
'X64' { 'x64' }
'Arm64' { 'arm64' }
'X86' { 'x86' }
'Arm' { 'arm' }
default { throw "Unsupported architecture: $runtimeArch" }
}
if ($PSVersionTable.PSVersion.Major -ge 6) {
if ($IsWindows) {
$platform = 'Windows'
$libraryName = 'convert_core.dll'
}
elseif ($IsMacOS) {
$platform = 'macOS'
$libraryName = 'libconvert_core.dylib'
}
else {
$platform = 'Linux'
$libraryName = 'libconvert_core.so'
}
}
else {
$platform = 'Windows'
$libraryName = 'convert_core.dll'
}
return [PSCustomObject]@{
Platform = $platform
Architecture = $architecture
LibraryName = $libraryName
}
}
function Install-RustDependencies {
<#
.SYNOPSIS
Installs required Rust tooling dependencies.
.DESCRIPTION
Ensures all required Rust tools are installed for building, testing, and analyzing.
Installs cargo-nextest for faster test execution and optionally installs
cargo-audit for security scanning.
.PARAMETER IncludeSecurity
Install cargo-audit for security vulnerability scanning.
.PARAMETER IncludeDeep
Install nightly toolchain and miri for deep undefined behavior analysis.
#>
param(
[switch]$IncludeSecurity,
[switch]$IncludeDeep
)
Write-Host 'Checking Rust dependencies...' -ForegroundColor Cyan
$cargoCommand = Get-Command -Name 'cargo' -ErrorAction SilentlyContinue
if (-not $cargoCommand) {
throw @"
Cargo not found. Please install Rust from https://rustup.rs
After installation:
1. Close and reopen your terminal
2. Verify installation: cargo --version
3. Run this build script again
"@
}
$installed = @()
$skipped = @()
$nextestInstalled = $null -ne (Get-Command -Name 'cargo-nextest' -ErrorAction SilentlyContinue)
if (-not $nextestInstalled) {
Write-Host ' Installing cargo-nextest...' -ForegroundColor Gray
& cargo install cargo-nextest --locked
if ($LASTEXITCODE -eq 0) {
$installed += 'cargo-nextest'
Write-Host ' ✓ cargo-nextest installed' -ForegroundColor Green
}
else {
Write-Warning ' ✗ Failed to install cargo-nextest'
}
}
else {
$skipped += 'cargo-nextest (already installed)'
}
if ($IncludeSecurity) {
$auditInstalled = $null -ne (Get-Command -Name 'cargo-audit' -ErrorAction SilentlyContinue)
if (-not $auditInstalled) {
Write-Host ' Installing cargo-audit...' -ForegroundColor Gray
& cargo install cargo-audit --locked
if ($LASTEXITCODE -eq 0) {
$installed += 'cargo-audit'
Write-Host ' ✓ cargo-audit installed' -ForegroundColor Green
}
else {
Write-Warning ' ✗ Failed to install cargo-audit'
}
}
else {
$skipped += 'cargo-audit (already installed)'
}
}
if ($IncludeDeep) {
Write-Host ' Checking nightly toolchain...' -ForegroundColor Gray
$nightlyInstalled = (rustup toolchain list) -match 'nightly'
if (-not $nightlyInstalled) {
Write-Host ' Installing nightly toolchain...' -ForegroundColor Gray
& rustup toolchain install nightly
if ($LASTEXITCODE -eq 0) {
$installed += 'nightly toolchain'
Write-Host ' ✓ nightly toolchain installed' -ForegroundColor Green
}
else {
Write-Warning ' ✗ Failed to install nightly toolchain'
}
}
else {
$skipped += 'nightly toolchain (already installed)'
}
Write-Host ' Checking miri component...' -ForegroundColor Gray
$miriInstalled = (rustup component list --toolchain nightly) -match 'miri.*installed'
if (-not $miriInstalled) {
Write-Host ' Installing miri component...' -ForegroundColor Gray
& rustup component add miri --toolchain nightly
if ($LASTEXITCODE -eq 0) {
$installed += 'miri'
Write-Host ' ✓ miri installed' -ForegroundColor Green
}
else {
Write-Warning ' ✗ Failed to install miri'
}
}
else {
$skipped += 'miri (already installed)'
}
}
Write-Host ''
if ($installed.Count -gt 0) {
Write-Host ('Installed {0} tool(s): {1}' -f $installed.Count, ($installed -join ', ')) -ForegroundColor Green
}
if ($skipped.Count -gt 0) {
Write-Host ('Skipped {0} tool(s): {1}' -f $skipped.Count, ($skipped -join ', ')) -ForegroundColor Gray
}
return @{
Success = $true
Installed = $installed
Skipped = $skipped
}
}
function Invoke-RustBuild {
<#
.SYNOPSIS
Compiles Rust library and copies to module bin directory.
.DESCRIPTION
Executes cargo build --release for specified targets, and copies the
compiled libraries to src/Convert/bin/<architecture>/ for module distribution.
Supports building for current platform only (default) or all supported platforms
for creating a universal module artifact.
.PARAMETER Config
Build configuration object from Initialize-BuildEnvironment.
.PARAMETER All
Build for all supported platforms (Windows x64/arm64, Linux x64/arm64/arm, macOS x64/arm64).
.PARAMETER Targets
Array of specific Rust target triples to build.
#>
param(
[Parameter(Mandatory)]
[PSCustomObject]$Config,
[switch]$All,
[string[]]$Targets = @()
)
$cargoTomlPath = [System.IO.Path]::Combine($Config.LibPath, 'Cargo.toml')
if (-not [System.IO.File]::Exists($cargoTomlPath)) {
Write-Warning "Cargo.toml not found at: $cargoTomlPath. Skipping Rust build."
return $false
}
$cargoCommand = Get-Command -Name 'cargo' -ErrorAction SilentlyContinue
if (-not $cargoCommand) {
throw @"
Cargo not found. Please install Rust from https://rustup.rs
After installation:
1. Close and reopen your terminal
2. Verify installation: cargo --version
3. Run this build script again
"@
}
$allTargets = @(
@{ Triple = 'x86_64-pc-windows-msvc'; Platform = 'Windows'; Arch = 'x64'; Lib = 'convert_core.dll' }
@{ Triple = 'aarch64-pc-windows-msvc'; Platform = 'Windows'; Arch = 'arm64'; Lib = 'convert_core.dll' }
@{ Triple = 'x86_64-unknown-linux-gnu'; Platform = 'Linux'; Arch = 'x64'; Lib = 'libconvert_core.so' }
@{ Triple = 'aarch64-unknown-linux-gnu'; Platform = 'Linux'; Arch = 'arm64'; Lib = 'libconvert_core.so' }
@{ Triple = 'armv7-unknown-linux-gnueabihf'; Platform = 'Linux'; Arch = 'arm'; Lib = 'libconvert_core.so' }
@{ Triple = 'x86_64-apple-darwin'; Platform = 'macOS'; Arch = 'x64'; Lib = 'libconvert_core.dylib' }
@{ Triple = 'aarch64-apple-darwin'; Platform = 'macOS'; Arch = 'arm64'; Lib = 'libconvert_core.dylib' }
)
if ($All) {
$targetsToBuild = $allTargets
Write-Host 'Building Rust library for all platforms...' -ForegroundColor Cyan
}
elseif ($Targets.Count -gt 0) {
$targetsToBuild = $allTargets | Where-Object { $Targets -contains $_.Triple }
if ($targetsToBuild.Count -eq 0) {
throw "No valid targets found matching: $($Targets -join ', ')"
}
Write-Host "Building Rust library for $($targetsToBuild.Count) target(s)..." -ForegroundColor Cyan
}
else {
$platformInfo = Get-PlatformInfo
$targetsToBuild = $allTargets | Where-Object {
$_.Platform -eq $platformInfo.Platform -and $_.Arch -eq $platformInfo.Architecture
}
if ($targetsToBuild.Count -eq 0) {
throw "No target found for current platform: $($platformInfo.Platform) $($platformInfo.Architecture)"
}
Write-Host 'Building Rust library for current platform...' -ForegroundColor Cyan
}
$successCount = 0
$failedTargets = @()
foreach ($target in $targetsToBuild) {
Write-Host " Building: $($target.Triple) ($($target.Platform) $($target.Arch))" -ForegroundColor Gray
$cargoArgs = @('build', '--release', '--target', $target.Triple, '--manifest-path', $cargoTomlPath)
& cargo $cargoArgs
if ($LASTEXITCODE -ne 0) {
$failedTargets += $target.Triple
Write-Host " ✗ Build failed for $($target.Triple)" -ForegroundColor Red
continue
}
$sourceLibPath = [System.IO.Path]::Combine($Config.LibPath, 'target', $target.Triple, 'release', $target.Lib)
if (-not [System.IO.File]::Exists($sourceLibPath)) {
$failedTargets += $target.Triple
Write-Host " ✗ Compiled library not found at: $sourceLibPath" -ForegroundColor Red
continue
}
$destDir = [System.IO.Path]::Combine($Config.SourcePath, 'Private', 'bin', $target.Arch)
if (-not [System.IO.Directory]::Exists($destDir)) {
[System.IO.Directory]::CreateDirectory($destDir) | Out-Null
}
$destLibPath = [System.IO.Path]::Combine($destDir, $target.Lib)
[System.IO.File]::Copy($sourceLibPath, $destLibPath, $true)
Write-Host (' ✓ Copied to: bin/{0}/{1}' -f $target.Arch, $target.Lib) -ForegroundColor Green
$successCount++
}
Write-Host ''
if ($failedTargets.Count -gt 0) {
Write-Host 'Rust build completed with errors:' -ForegroundColor Yellow
Write-Host (' Success: {0}/{1}' -f $successCount, $targetsToBuild.Count) -ForegroundColor Green
Write-Host (' Failed: {0}' -f ($failedTargets -join ', ')) -ForegroundColor Red
return $false
}
else {
Write-Host ('Rust build completed successfully for {0} target(s).' -f $successCount) -ForegroundColor Green
return $true
}
}
function Invoke-RustTest {
<#
.SYNOPSIS
Runs Rust test suite using cargo-nextest.
.DESCRIPTION
Executes cargo nextest run to run all Rust unit and integration tests.
Automatically installs cargo-nextest if not present.
.PARAMETER Config
Build configuration object from Initialize-BuildEnvironment.
#>
param(
[Parameter(Mandatory)]
[PSCustomObject]$Config
)
$cargoTomlPath = [System.IO.Path]::Combine($Config.LibPath, 'Cargo.toml')
if (-not [System.IO.File]::Exists($cargoTomlPath)) {
Write-Warning ('Cargo.toml not found at: {0}. Skipping Rust tests.' -f $cargoTomlPath)
return @{ Success = $false; ExitCode = 1 }
}
$nextestInstalled = $null -ne (Get-Command -Name 'cargo-nextest' -ErrorAction SilentlyContinue)
if ($nextestInstalled) {
Write-Host 'Running Rust tests with cargo-nextest...' -ForegroundColor Cyan
$cargoArgs = @('nextest', 'run', '--manifest-path', $cargoTomlPath)
}
else {
Write-Host 'Running Rust tests with cargo test (nextest not installed)...' -ForegroundColor Cyan
Write-Host 'Tip: Run with dependency installation to use faster nextest runner' -ForegroundColor Yellow
$cargoArgs = @('test', '--manifest-path', $cargoTomlPath)
}
& cargo $cargoArgs
$exitCode = $LASTEXITCODE
if ($exitCode -eq 0) {
Write-Host 'Rust tests passed.' -ForegroundColor Green
} else {
Write-Host ('Rust tests failed with exit code {0}' -f $exitCode) -ForegroundColor Red
}
return @{
Success = ($exitCode -eq 0)
ExitCode = $exitCode
}
}
function Invoke-RustAnalyze {
<#
.SYNOPSIS
Analyzes Rust code for errors, warnings, and style issues.
.DESCRIPTION
Runs cargo check, clippy, and fmt to analyze Rust code quality.
Optionally runs security audit and deep analysis with Miri.
.PARAMETER Config
Build configuration object from Initialize-BuildEnvironment.
.PARAMETER Security
Run cargo audit for security vulnerability scanning.
.PARAMETER Deep
Run cargo miri test for deep undefined behavior detection.
#>
param(
[Parameter(Mandatory)]
[PSCustomObject]$Config,
[switch]$Security,
[switch]$Deep
)
$cargoTomlPath = [System.IO.Path]::Combine($Config.LibPath, 'Cargo.toml')
if (-not [System.IO.File]::Exists($cargoTomlPath)) {
Write-Warning ('Cargo.toml not found at: {0}. Skipping Rust analysis.' -f $cargoTomlPath)
return @{ Success = $false; ExitCode = 1 }
}
Write-Host 'Analyzing Rust code...' -ForegroundColor Cyan
$allPassed = $true
$results = @()
Write-Host ' Running cargo check...' -ForegroundColor Gray
& cargo check --manifest-path $cargoTomlPath
$checkExitCode = $LASTEXITCODE
$results += @{ Tool = 'check'; ExitCode = $checkExitCode }
if ($checkExitCode -ne 0) {
Write-Host ' cargo check failed' -ForegroundColor Red
$allPassed = $false
} else {
Write-Host ' cargo check passed' -ForegroundColor Green
}
Write-Host ' Running cargo clippy...' -ForegroundColor Gray
& cargo clippy --manifest-path $cargoTomlPath --all-targets -- -D warnings
$clippyExitCode = $LASTEXITCODE
$results += @{ Tool = 'clippy'; ExitCode = $clippyExitCode }
if ($clippyExitCode -ne 0) {
Write-Host ' cargo clippy failed' -ForegroundColor Red
$allPassed = $false
} else {
Write-Host ' cargo clippy passed' -ForegroundColor Green
}
Write-Host ' Running cargo fmt --check...' -ForegroundColor Gray
& cargo fmt --manifest-path $cargoTomlPath -- --check
$fmtExitCode = $LASTEXITCODE
$results += @{ Tool = 'fmt'; ExitCode = $fmtExitCode }
if ($fmtExitCode -ne 0) {
Write-Host ' cargo fmt check failed' -ForegroundColor Red
$allPassed = $false
} else {
Write-Host ' cargo fmt check passed' -ForegroundColor Green
}
if ($Security) {
$auditInstalled = $null -ne (Get-Command -Name 'cargo-audit' -ErrorAction SilentlyContinue)
if (-not $auditInstalled) {
Write-Host ' cargo-audit not found. Installing...' -ForegroundColor Yellow
& cargo install cargo-audit --locked
if ($LASTEXITCODE -ne 0) {
Write-Warning 'Failed to install cargo-audit. Skipping security audit.'
$results += @{ Tool = 'audit'; ExitCode = 1 }
$allPassed = $false
}
else {
Write-Host ' cargo-audit installed successfully.' -ForegroundColor Green
}
}
if ($auditInstalled -or $LASTEXITCODE -eq 0) {
Write-Host ' Running cargo audit...' -ForegroundColor Gray
Push-Location $Config.LibPath
try {
& cargo audit
} finally {
Pop-Location
}
$auditExitCode = $LASTEXITCODE
$results += @{ Tool = 'audit'; ExitCode = $auditExitCode }
if ($auditExitCode -ne 0) {
Write-Host ' cargo audit found issues' -ForegroundColor Red
$allPassed = $false
} else {
Write-Host ' cargo audit passed' -ForegroundColor Green
}
}
}
if ($Deep) {
$nightlyInstalled = $null -ne (& rustup toolchain list | Select-String -Pattern 'nightly')
if (-not $nightlyInstalled) {
Write-Host ' Nightly toolchain not found. Installing...' -ForegroundColor Yellow
& rustup toolchain install nightly
if ($LASTEXITCODE -ne 0) {
Write-Warning 'Failed to install nightly toolchain. Skipping Miri analysis.'
$results += @{ Tool = 'miri'; ExitCode = 1 }
$allPassed = $false
}
else {
Write-Host ' Nightly toolchain installed successfully.' -ForegroundColor Green
}
}
if ($nightlyInstalled -or $LASTEXITCODE -eq 0) {
$miriInstalled = $null -ne (& rustup component list --toolchain nightly | Select-String -Pattern 'miri.*installed')
if (-not $miriInstalled) {
Write-Host ' Miri component not found. Installing...' -ForegroundColor Yellow
& rustup component add miri --toolchain nightly
if ($LASTEXITCODE -ne 0) {
Write-Warning 'Failed to install Miri component. Skipping Miri analysis.'
$results += @{ Tool = 'miri'; ExitCode = 1 }
$allPassed = $false
}
else {
Write-Host ' Miri component installed successfully.' -ForegroundColor Green
}
}
if ($miriInstalled -or $LASTEXITCODE -eq 0) {
Write-Host ' Running cargo miri test...' -ForegroundColor Gray
& cargo +nightly miri test --manifest-path $cargoTomlPath
$miriExitCode = $LASTEXITCODE
$results += @{ Tool = 'miri'; ExitCode = $miriExitCode }
if ($miriExitCode -ne 0) {
Write-Host ' cargo miri test failed' -ForegroundColor Red
$allPassed = $false
} else {
Write-Host ' cargo miri test passed' -ForegroundColor Green
}
}
}
}
if ($allPassed) {
Write-Host 'Rust analysis passed.' -ForegroundColor Green
} else {
Write-Host 'Rust analysis failed.' -ForegroundColor Red
}
return @{
Success = $allPassed
Results = $results
}
}
function Invoke-RustFix {
<#
.SYNOPSIS
Automatically fixes Rust code formatting and linting issues.
.DESCRIPTION
Runs cargo fmt to format code and cargo clippy --fix to automatically
apply suggested fixes. Tracks which files were modified.
.PARAMETER Config
Build configuration object from Initialize-BuildEnvironment.
#>
param(
[Parameter(Mandatory)]
[PSCustomObject]$Config
)
$cargoTomlPath = [System.IO.Path]::Combine($Config.LibPath, 'Cargo.toml')
if (-not [System.IO.File]::Exists($cargoTomlPath)) {
Write-Warning ('Cargo.toml not found at: {0}. Skipping Rust fix.' -f $cargoTomlPath)
return @{ Success = $false; ModifiedFiles = @() }
}
Write-Host 'Fixing Rust code...' -ForegroundColor Cyan
$libPath = $Config.LibPath
$beforeFiles = @{}
Get-ChildItem -Path $libPath -Recurse -Filter '*.rs' | ForEach-Object {
$beforeFiles[$_.FullName] = $_.LastWriteTime
}
Write-Host ' Running cargo fmt...' -ForegroundColor Gray
& cargo fmt --manifest-path $cargoTomlPath
$fmtExitCode = $LASTEXITCODE
Write-Host ' Running cargo clippy --fix...' -ForegroundColor Gray
& cargo clippy --manifest-path $cargoTomlPath --all-targets --fix --allow-dirty --allow-staged
$clippyExitCode = $LASTEXITCODE
$modifiedFiles = @()
Get-ChildItem -Path $libPath -Recurse -Filter '*.rs' | ForEach-Object {
if ($beforeFiles.ContainsKey($_.FullName)) {
if ($_.LastWriteTime -ne $beforeFiles[$_.FullName]) {
$modifiedFiles += $_.FullName
}
}
}
if ($modifiedFiles.Count -gt 0) {
Write-Host (' Modified {0} file(s):' -f $modifiedFiles.Count) -ForegroundColor Yellow
foreach ($file in $modifiedFiles) {
$relativePath = $file.Replace($Config.RepositoryRoot, '').TrimStart('\', '/')
Write-Host (' {0}' -f $relativePath) -ForegroundColor Gray
}
} else {
Write-Host ' No files were modified.' -ForegroundColor Green
}
return @{
Success = ($fmtExitCode -eq 0 -and $clippyExitCode -eq 0)
ModifiedFiles = $modifiedFiles
}
}
function Invoke-RustClean {
<#
.SYNOPSIS
Removes Rust build artifacts.
.DESCRIPTION
Runs cargo clean to remove the target directory and all build artifacts.
.PARAMETER Config
Build configuration object from Initialize-BuildEnvironment.
#>
param(
[Parameter(Mandatory)]
[PSCustomObject]$Config
)
$cargoTomlPath = [System.IO.Path]::Combine($Config.LibPath, 'Cargo.toml')
if (-not [System.IO.File]::Exists($cargoTomlPath)) {
Write-Warning ('Cargo.toml not found at: {0}. Skipping Rust clean.' -f $cargoTomlPath)
return @{ Success = $false }
}
Write-Host 'Cleaning Rust build artifacts...' -ForegroundColor Cyan
& cargo clean --manifest-path $cargoTomlPath
$exitCode = $LASTEXITCODE
if ($exitCode -eq 0) {
Write-Host 'Rust clean completed successfully.' -ForegroundColor Green
return @{ Success = $true }
} else {
Write-Host 'Rust clean failed.' -ForegroundColor Red
return @{ Success = $false }
}
}
#endregion
#region PowerShell Operations
function Invoke-PowerShellBuild {
<#
.SYNOPSIS
Assembles the PowerShell module for distribution.
.DESCRIPTION
Copies the module manifest and bin directory to Artifacts/, combines all .ps1 files
into a single .psm1 module file, and removes temporary Private/Public directories.
.PARAMETER Config
Build configuration object from Initialize-BuildEnvironment.
#>
param(
[Parameter(Mandatory)]
[PSCustomObject]$Config
)
Write-Host 'Building PowerShell module...' -ForegroundColor Cyan
$sourcePath = $Config.SourcePath
$artifactsPath = $Config.ArtifactsPath
$moduleName = $Config.ModuleName
$manifestSource = [System.IO.Path]::Combine($sourcePath, ('{0}.psd1' -f $moduleName))
$manifestDest = [System.IO.Path]::Combine($artifactsPath, ('{0}.psd1' -f $moduleName))
if (-not [System.IO.File]::Exists($manifestSource)) {
Write-Host ('Module manifest not found at: {0}' -f $manifestSource) -ForegroundColor Red
return @{ Success = $false }
}
if (-not [System.IO.Directory]::Exists($artifactsPath)) {
Write-Host ' Creating Artifacts directory...' -ForegroundColor Gray
[System.IO.Directory]::CreateDirectory($artifactsPath) | Out-Null
}
Write-Host ' Copying module manifest...' -ForegroundColor Gray
[System.IO.File]::Copy($manifestSource, $manifestDest, $true)
$binSource = [System.IO.Path]::Combine($sourcePath, 'Private', 'bin')
$binDest = [System.IO.Path]::Combine($artifactsPath, 'bin')
if ([System.IO.Directory]::Exists($binSource)) {
Write-Host ' Copying bin directory...' -ForegroundColor Gray
if ([System.IO.Directory]::Exists($binDest)) {
[System.IO.Directory]::Delete($binDest, $true)
}
function Copy-Directory {
param($Source, $Destination)
[System.IO.Directory]::CreateDirectory($Destination) | Out-Null
foreach ($file in [System.IO.Directory]::GetFiles($Source)) {
$fileName = [System.IO.Path]::GetFileName($file)
$destFile = [System.IO.Path]::Combine($Destination, $fileName)
[System.IO.File]::Copy($file, $destFile, $true)
}
foreach ($dir in [System.IO.Directory]::GetDirectories($Source)) {
$dirName = [System.IO.Path]::GetFileName($dir)
$destDir = [System.IO.Path]::Combine($Destination, $dirName)
Copy-Directory -Source $dir -Destination $destDir
}
}
Copy-Directory -Source $binSource -Destination $binDest
} else {
Write-Warning ('bin directory not found at: {0}. Module may not function correctly without Rust library.' -f $binSource)
}
Write-Host ' Combining PowerShell scripts...' -ForegroundColor Gray