-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGenXdev.Coding.PowerShell.Modules.psm1
More file actions
7408 lines (6202 loc) · 290 KB
/
Copy pathGenXdev.Coding.PowerShell.Modules.psm1
File metadata and controls
7408 lines (6202 loc) · 290 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
<##############################################################################
Part of PowerShell module : GenXdev.Coding.PowerShell.Modules
Original cmdlet filename : Assert-GenXdevCmdlet.ps1
Original author : René Vaessen / GenXdev
Version : 3.26.2026
Copyright (c) 2026 René Vaessen / GenXdev
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
################################################################################>
<#
.SYNOPSIS
Improves GenXdev cmdlet documentation and implementation through AI assistance.
.DESCRIPTION
This function enhances GenXdev cmdlets by analyzing and improving their code
through AI prompts. It can integrate cmdlets into modules, update documentation,
and verify proper implementation. The function supports custom prompt templates
and can open files in Visual Studio Code or Visual Studio.
.PARAMETER CmdletName
The name or search pattern of the cmdlet to improve. Supports wildcards.
.PARAMETER BaseModuleName
Array of GenXdev module names to search within. Must match pattern
"GenXdev.*".
.PARAMETER PromptKey
The key identifying which AI prompt template to use for improvements.
.PARAMETER Prompt
Custom prompt text to override the template prompt.
.PARAMETER NoLocal
Skip searching local module versions.
.PARAMETER OnlyPublished
Only search published module versions.
.PARAMETER FromScripts
Search in script files rather than module files.
.PARAMETER Code
Opens the cmdlet in Visual Studio Code.
.PARAMETER VisualStudio
Opens the cmdlet in Visual Studio.
.PARAMETER EditPrompt
Only edit the AI prompt template without processing the cmdlet.
.PARAMETER Integrate
Integrate the cmdlet into a module if it's currently a standalone script.
.EXAMPLE
Assert-GenXdevCmdlet -CmdletName "Get-Something" -PromptKey "CheckDocs" -Code
.EXAMPLE
improvecmdlet Get-Something CheckDocs -c
#>
function Assert-GenXdevCmdlet {
[CmdletBinding()]
[Alias('improvecmdlet')]
param(
[parameter(
Mandatory = $false,
Position = 0,
ValueFromRemainingArguments = $false,
HelpMessage = 'Search pattern to filter cmdlets'
)]
[Alias('Filter', 'CmdLet', 'Cmd', 'FunctionName', 'Name')]
[SupportsWildcards()]
[ValidateNotNullOrEmpty()]
[string] $CmdletName,
[parameter(
Mandatory = $false,
ValueFromPipeline = $true,
ValueFromPipelineByPropertyName = $true,
HelpMessage = 'GenXdev module names to search'
)]
[ValidateNotNullOrEmpty()]
[Alias('Module', 'BaseModuleName', 'SubModuleName')]
[ValidatePattern('^(GenXdev|GenXde[v]\*|GenXdev(\.[\w\*\[\]\?]*)+)+$')]
[SupportsWildcards()]
[string[]] $ModuleName,
[parameter(
Mandatory = $false,
Position = 1,
HelpMessage = 'The AI prompt key to use for template selection'
)]
[ValidateNotNull()]
[string] $PromptKey = 'CheckAllRequirements',
[parameter(
Position = 2,
HelpMessage = 'Custom AI prompt text to use'
)]
[AllowEmptyString()]
[string] $Prompt = '',
[Parameter(
Mandatory = $false,
HelpMessage = 'Skip local module versions'
)]
[switch] $NoLocal,
[Parameter(
Mandatory = $false,
HelpMessage = 'Only include published versions'
)]
[switch] $OnlyPublished,
[Parameter(
Mandatory = $false,
HelpMessage = 'Search in script files'
)]
[switch] $FromScripts,
[Parameter(
Mandatory = $false,
HelpMessage = 'Open in Visual Studio Code'
)]
[Alias('c')]
[switch] $Code,
[Parameter(
Mandatory = $false,
HelpMessage = 'Open in Visual Studio'
)]
[Alias('vs')]
[switch] $VisualStudio,
[parameter(
ParameterSetName = 'PromptKey',
HelpMessage = 'Only edit the AI prompt'
)]
[switch] $EditPrompt,
[parameter(
HelpMessage = 'Integrate cmdlet into module'
)]
[switch] $Integrate
)
begin {
try {
# retrieve and validate target cmdlet existence
$invocationParams = GenXdev\Copy-IdenticalParamValues `
-FunctionName 'GenXdev\Get-GenXDevCmdlet' `
-BoundParameters $PSBoundParameters
$invocationParams.ExactMatch = $true
$invocationParams.CmdletName = $CmdletName`
# select first matching cmdlet
$cmdlet = GenXdev\Get-GenXDevCmdlet @invocationParams |
Microsoft.PowerShell.Utility\Select-Object -First 1
# validate cmdlet was found
if ($null -eq $cmdlet) {
throw [System.ArgumentException]::new(
"Could not find GenXdev cmdlet matching filter: $CmdletName")
}
# initialize core variables
$CmdletName = $cmdlet.Name
Microsoft.PowerShell.Utility\Write-Verbose "Processing cmdlet: $CmdletName"
# check if integration is needed based on script location
$requiresIntegration = $Integrate -and ($cmdlet.ScriptFilePath.StartsWith(
(GenXdev\Expand-Path (
"$($MyInvocation.MyCommand.Module.ModuleBase)\..\..\..\Scripts\"))))
# warn if integration not needed
if ($Integrate -and -not $requiresIntegration) {
Microsoft.PowerShell.Utility\Write-Warning ('Cmdlet already integrated into module. ' +
'Integration step will be skipped.')
$Integrate = $false
}
Microsoft.PowerShell.Utility\Write-Verbose "Integration required: $requiresIntegration"
# handle module integration if requested
if ($Integrate) {
# get full official cmdlet name
$CmdletName = [IO.Path]::GetFileNameWithoutExtension(($cmdlet.Name))
# integrate the cmdlet into a module
$options = [System.Management.Automation.Host.ChoiceDescription[]] @(
. GenXdev\Invoke-OnEachGenXdevModule {
Microsoft.PowerShell.Management\Get-ChildItem -LiteralPath '.\' -Filter *.psm1 |
Microsoft.PowerShell.Core\ForEach-Object { [IO.Path]::GetFileNameWithoutExtension($_) }
}
)
$selected = @($options |
Microsoft.PowerShell.Utility\Out-GridView -Title 'Select a module' -PassThru)
if ($null -eq $selected) {
throw 'No module selected'
}
if ($selected.Count -ne 1) {
throw 'You should only select a single module'
}
# move the script file to the module
$baseDestinationParts = "$($($selected)[0].Label)".Split('.');
$baseDestinationModule = $baseDestinationParts[0] + '.' + $baseDestinationParts[1];
$ModuleName = "$($($selected)[0].Label)"
$destination = GenXdev\Expand-Path "$($MyInvocation.MyCommand.Module.ModuleBase)\..\..\\$baseDestinationModule\3.26.2026\Functions\$ModuleName\$CmdletName.ps1" -CreateDirectory
# move the script file
GenXdev\Move-ItemWithTracking -Path $cmdlet.ScriptFilePath -Destination $destination
[IO.File]::WriteAllText(
$destination,
(
"function $CmdletName {`r`n" +
(GenXdev\alignScript -script (
[IO.File]::ReadAllText($destination).Replace(
"`$PSScriptRoot\..",
"`$($MyInvocation.MyCommand.Module.ModuleBase)\..\..\.."
).Replace(
"$($CmdletName).ps1",
"$($CmdletName)"
) + "`r`n}"
) -spaces 4)
)
);
# also move the test script file if it exists
if ([IO.Path]::Exists($cmdlet.ScriptTestFilePath)) {
GenXdev\Move-ItemWithTracking -Path $cmdlet.ScriptTestFilePath -Destination ([IO.Path]::ChangeExtension($destination, '.Tests.ps1')) -Force
}
# add dot source reference to corresponding psm1 file
GenXdev\_SplitUpPsm1File -Path "$($MyInvocation.MyCommand.Module.ModuleBase)\..\..\$baseDestinationModule\3.26.2026\$ModuleName.psm1"
. GenXdev\Invoke-OnEachGenXdevModule {
Microsoft.PowerShell.Management\Get-ChildItem -LiteralPath '.\' -Filter '*.ps1' -File -Recurse | Microsoft.PowerShell.Core\ForEach-Object {
[IO.File]::WriteAllText(
$PSItem.FullName,
[IO.File]::ReadAllText(($PSItem.FullName)).Replace(
"$($CmdletName).ps1",
"$($CmdletName)"
)
)
}
}
# retrieve information about the target cmdlet
$params = GenXdev\Copy-IdenticalParamValues `
-FunctionName 'GenXdev\Get-GenXDevCmdlet' `
-BoundParameters $PSBoundParameters
$params.ExactMatch = $true
$params.CmdletName = $CmdletName
$cmdlet = GenXdev\Get-GenXDevCmdlet @params
# retrieve and validate the target cmdlet exists
$invocationParams = GenXdev\Copy-IdenticalParamValues `
-FunctionName 'GenXdev\Get-GenXDevCmdlet' `
-BoundParameters $PSBoundParameters
$invocationParams.CmdletName = $CmdletName
$invocationParams.ModuleName = $($ModuleName)
$invocationParams.ExactMatch = $true
$cmdlet = GenXdev\Get-GenXDevCmdlet @invocationParams | Microsoft.PowerShell.Utility\Select-Object -First 1
if ($null -eq $cmdlet) {
throw "Could not find GenXdev cmdlet $CmdletName"
}
}
# process prompt template if specified
if (-not [string]::IsNullOrWhiteSpace($PromptKey)) {
# determine template path based on location
$promptFilePath = GenXdev\Expand-Path -CreateFile -FilePath (
"$($MyInvocation.MyCommand.Module.ModuleBase)\Prompts\GenXdev.Coding.PowerShell.Modules\" +
"Assert-$PromptKey.txt")
# check for script-specific template
$scriptsPath = GenXdev\Expand-Path " \..\..\..\Scripts\" `
-CreateDirectory
if ($cmdlet.ScriptFilePath -like "$scriptsPath\*.ps1") {
$promptFilePath = GenXdev\Expand-Path -CreateFile -FilePath (
"$($MyInvocation.MyCommand.Module.ModuleBase)\Prompts\GenXdev.Coding.PowerShell." +
"Modules\Assert-$PromptKey-script.txt")
}
# load and process template
$Prompt = [System.IO.File]::ReadAllText($promptFilePath).Replace(
"`$Prompt",
$Prompt
)
}
# replace template variables in prompt text
$Prompt = $Prompt.Replace("`$CmdletName", $cmdlet.Name)
$Prompt = $Prompt.Replace("`$CmdLetNoTestName", $cmdlet.Name)
$Prompt = $Prompt.Replace(
"`$FullModuleName",
$cmdlet.ModuleName
)
$Prompt = $Prompt.Replace(
"`$BaseModuleName",
[string]::Join('.', ($cmdlet.ModuleName.Split('.') | Microsoft.PowerShell.Utility\Select-Object -First 2 -ErrorAction SilentlyContinue))
)
$Prompt = $Prompt.Replace(
"`$ScriptFileName",
[System.IO.Path]::GetFileName($cmdlet.ScriptFilePath)
)
$Prompt = $Prompt.Replace("`t", ' ')
# copy final prompt to clipboard for use
$previousClipboard = Microsoft.PowerShell.Management\Get-Clipboard
$Prompt | Microsoft.PowerShell.Management\Set-Clipboard
Microsoft.PowerShell.Utility\Write-Verbose 'Prepared prompt and copied to clipboard:'
Microsoft.PowerShell.Utility\Write-Verbose $Prompt
}
catch {
Microsoft.PowerShell.Utility\Write-Error -Exception $_.Exception `
-Message 'Failed to initialize Assert-GenXdevCmdlet'
throw
}
}
process {
try {
# handle prompt editing if requested
if ($EditPrompt) {
p -c
GenXdev\VSCode $promptFilePath
return
}
# open cmdlet in vscode and insert prompt
$invocationParams = GenXdev\Copy-IdenticalParamValues `
-FunctionName 'GenXdev\Show-GenXdevCmdLetInIde' `
-BoundParameters $PSBoundParameters
$invocationParams.CmdletName = $CmdletName
$invocationParams.KeysToSend = @(
"^``", "^``", '^+i', '^n', '^a', '{DELETE}', '^%b',
'^+%{F12}', '{ENTER}', '^v', '{ENTER}', '^{ENTER}', "^``"
)
GenXdev\Show-GenXdevCmdLetInIde @invocationParams
Microsoft.PowerShell.Utility\Start-Sleep 4;
# handle unit test scenarios based on test file existence
if ([IO.File]::Exists($cmdlet.ScriptTestFilePath)) {
switch ($host.ui.PromptForChoice(
'Make a choice',
'What to do next?',
@('&Stop', "&Run unit-tests for $CmdletName", 'Redo &Last'),
1)) {
0 { throw 'Stopped' }
1 { return GenXdev\Assert-GenXdevTest -CmdletName $CmdletName -TestFailedAction SolveWithAI -IncludeScripts }
2 {
return GenXdev\Assert-GenXdevCmdlet @PSBoundParameters
}
}
}
else {
switch ($host.ui.PromptForChoice(
'Make a choice',
'What to do next?',
@('&Stop', "&Create unit tests for $CmdletName", 'Redo &Last'),
0)) {
0 { throw 'Stopped' }
1 { return GenXdev\Assert-GenXdevCmdletTests -CmdletName $CmdletName }
2 {
return GenXdev\Assert-GenXdevCmdlet @PSBoundParameters
}
}
}
}
catch {
Microsoft.PowerShell.Utility\Write-Error -Exception $_.Exception -Message 'Failed to process cmdlet improvements'
throw
}
}
end {
# restore original clipboard content
$null = Microsoft.PowerShell.Management\Set-Clipboard -Value $previousClipboard
}
}
<##############################################################################
Part of PowerShell module : GenXdev.Coding.PowerShell.Modules
Original cmdlet filename : Assert-GenXdevCmdletTests.ps1
Original author : René Vaessen / GenXdev
Version : 3.26.2026
Copyright (c) 2026 René Vaessen / GenXdev
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
################################################################################>
<#
.SYNOPSIS
Asserts and improves unit-tests of a specified GenXdev cmdlet.
.DESCRIPTION
This function helps maintain and improve unit tests for GenXdev cmdlets by:
1. Creating test files if they don't exist
2. Opening the cmdlet in VS Code
3. Preparing and applying AI prompts for test generation/improvement
4. Managing test execution workflow
.PARAMETER CmdletName
The name of the cmdlet to improve unit-tests for. Required.
.PARAMETER Prompt
Custom AI prompt text to use for test generation. Optional.
.PARAMETER EditPrompt
Switch to only edit the AI prompt without modifying the cmdlet. Optional.
.PARAMETER AssertFailedTest
Switch to indicate assertion of a failed test. Optional.
.EXAMPLE
Assert-GenXdevCmdletTests -CmdletName "Get-GenXDevModuleInfo" -EditPrompt
.EXAMPLE
improvecmdlettests Get-GenXDevModuleInfo -AssertFailedTest
###############################################################################>
function Assert-GenXdevCmdletTests {
[CmdletBinding()]
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseSingularNouns', '')]
[Alias('improvecmdlettests')]
param(
[Alias('cmd')]
[parameter(
Mandatory = $true,
Position = 0,
ValueFromPipeline = $true,
ValueFromPipelineByPropertyName = $true,
HelpMessage = 'The name of the cmdlet to improve unit-tests for'
)]
[ValidateNotNullOrEmpty()]
[string] $CmdletName,
[parameter(
Position = 1,
Mandatory = $false,
HelpMessage = 'Custom AI prompt text to use'
)]
[AllowEmptyString()]
[string] $Prompt = '',
[parameter(
Position = 2,
Mandatory = $false,
HelpMessage = 'The AI prompt key to use for template selection'
)]
[AllowEmptyString()]
[string] $PromptKey,
[parameter(
Mandatory = $false,
HelpMessage = 'Switch to only edit the AI prompt'
)]
[switch] $EditPrompt,
[parameter(
Mandatory = $false,
HelpMessage = 'Indicates to assert a failed test'
)]
[switch] $AssertFailedTest,
[Parameter(
Mandatory = $false,
HelpMessage = 'Search in script files instead of modules'
)]
[switch] $FromScripts,
[switch] $ContinuationHandled
)
begin {
# get target cmdlet information including script position
$params = GenXdev\Copy-IdenticalParamValues `
-FunctionName 'GenXdev\Get-GenXDevCmdlet' `
-BoundParameters $PSBoundParameters
$params.ExactMatch = $true
$params.CmdletName = $CmdletName
$cmdlet = GenXdev\Get-GenXDevCmdlet @params |
Microsoft.PowerShell.Utility\Select-Object -First 1
# validate cmdlet exists
if ($null -eq $cmdlet) {
throw "Could not find GenXdev cmdlet $CmdletName"
}
# store cmdlet name for later use
$CmdletName = $cmdlet.Name
$functionDefinition = '';
# determine which prompt template to use based on test file existence
if (-not [string]::IsNullOrWhiteSpace($PromptKey)) {
$PromptKey = 'CreateUnitTests'
$functionDefinition = [System.IO.File]::ReadAllText($cmdlet.ScriptFilePath)
if ([IO.File]::Exists($cmdlet.ScriptTestFilePath) -and
(-not [string]::IsNullOrWhiteSpace($functionDefinition))) {
$PromptKey = $AssertFailedTest ? 'ResolveFailedTest' : 'ImproveUnitTest'
}
}
# process prompt template if key provided
if (-not [string]::IsNullOrWhiteSpace($PromptKey)) {
# construct path to prompt template file
$promptFilePath = GenXdev\Expand-Path "$($MyInvocation.MyCommand.Module.ModuleBase)\Prompts\GenXdev.Coding.PowerShell.Modules\Assert-$PromptKey.txt"
# ensure prompt directory exists and expand path
$promptFilePath = GenXdev\Expand-Path -FilePath $promptFilePath `
-CreateDirectory
# load template and replace placeholder
$Prompt = [System.IO.File]::ReadAllText($promptFilePath).Replace(
"`$Prompt",
$Prompt
)
}
# populate template variables
$Prompt = $Prompt.Replace("`$CmdletName", $cmdlet.Name)
$Prompt = $Prompt.Replace("`$CmdLetNoTestName", $cmdlet.Name)
$Prompt = $Prompt.Replace(
"`$ScriptTestFileName",
[System.IO.Path]::GetFileName($cmdlet.ScriptTestFilePath)
)
$Prompt = $Prompt.Replace(
"`$FullModuleName",
$cmdlet.ModuleName
)
$Prompt = $Prompt.Replace(
"`$BaseModuleName",
[string]::Join('.', ($cmdlet.ModuleName.Split('.') | Microsoft.PowerShell.Utility\Select-Object -First 2 -ErrorAction SilentlyContinue))
)
$Prompt = $Prompt.Replace(
"`$ScriptFileName",
[System.IO.Path]::GetFileName($cmdlet.ScriptFilePath)
)
$Prompt = $Prompt.Replace(
"`$FunctionDefinition",
$functionDefinition
)
$Prompt = $Prompt.Replace("`t", ' ')
# copy final prompt for use
$previousClipboard = Microsoft.PowerShell.Management\Get-Clipboard
$null = Microsoft.PowerShell.Management\Set-Clipboard -Value $Prompt
}
process {
# handle prompt editing request
if ($EditPrompt) {
p -c
code $promptFilePath
return
}
$found = $true
# create test file if missing
if (-not [IO.File]::Exists($cmdlet.ScriptTestFilePath) -or
([IO.File]::ReadAllText($cmdlet.ScriptTestFilePath).Trim() -eq [string]::Empty)) {
$found = $false
Microsoft.PowerShell.Utility\Write-Verbose 'Creating new unit test file'
$null = GenXdev\Expand-Path -FilePath ($cmdlet.ScriptTestFilePath) -CreateFile
}
# ensure copilot keyboard shortcut is configured
GenXdev\EnsureCopilotKeyboardShortCut
# open cmdlet in vscode and activate copilot
# open cmdlet in vscode and insert prompt
# open cmdlet in vscode and insert prompt
$invocationParams = GenXdev\Copy-IdenticalParamValues `
-FunctionName 'GenXdev\Show-GenXdevCmdLetInIde' `
-BoundParameters $PSBoundParameters
$invocationParams.UnitTests = $true
$invocationParams.CmdletName = $CmdletName
$invocationParams.Code = $true
$keysToSendFirst = @(
"^``", "^``", '^+i', '^n', '^a', '{DELETE}', '^%b'
)
$keysToSendLast = @('^+%{F12}', '{ENTER}', '^v', '{ENTER}', '^{ENTER}', "^``")
$invocationParams.KeysToSend = $keysToSendFirst + $keysToSendLast;
GenXdev\Show-GenXdevCmdLetInIde @invocationParams
# switch to test file and paste prompt
Microsoft.PowerShell.Utility\Write-Verbose 'Applying AI prompt from clipboard'
$invocationParams.KeysToSend = $keysToSendLast
$invocationParams.UnitTests = $false
GenXdev\Show-GenXdevCmdLetInIde @invocationParams
Microsoft.PowerShell.Utility\Start-Sleep 1;
$null = Microsoft.PowerShell.Management\Set-Clipboard -Value $previousClipboard
Microsoft.PowerShell.Utility\Start-Sleep 4;
if ($ContinuationHandled) {
return;
}
# handle workflow based on whether test file existed
if (-not $found) {
switch ($host.ui.PromptForChoice(
'Make a choice',
'What to do next?',
@('&Stop', '&Test the new unit tests', 'Redo &Last'),
1)) {
0 { throw 'Stopped'; return }
1 { return (GenXdev\Assert-GenXdevTest -CmdletName $CmdletName -TestFailedAction SolveWithAI -IncludeScripts) }
2 { return GenXdev\Assert-GenXdevCmdletTests @PSBoundParameters }
}
}
else {
switch ($host.ui.PromptForChoice(
'Make a choice',
'What to do next?',
@('&Stop', '&Test the improved unit tests', 'Redo &Last'),
1)) {
0 { throw 'Stopped'; return }
1 { return (GenXdev\Assert-GenXdevTest -CmdletName $CmdletName -TestFailedAction SolveWithAI -IncludeScripts) }
2 { return GenXdev\Assert-GenXdevCmdletTests @PSBoundParameters }
}
}
}
end {
}
}
<##############################################################################
Part of PowerShell module : GenXdev.Coding.PowerShell.Modules
Original cmdlet filename : Assert-GenXdevDependencyUsage.ps1
Original author : René Vaessen / GenXdev
Version : 3.26.2026
Copyright (c) 2026 René Vaessen / GenXdev
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
################################################################################>
# Don't remove this line [dontrefactor]
<#
.SYNOPSIS
Validates dependency usage across GenXdev modules to ensure proper module
hierarchy is maintained.
.DESCRIPTION
This function analyzes GenXdev modules to ensure they follow the correct
dependency hierarchy. It checks that modules only reference dependencies
that are listed in their RequiredModules manifest, and prevents circular
dependencies by validating that modules don't reference modules that come
later in the dependency chain.
.PARAMETER ModuleName
Filter to apply to module names. Must match GenXdev naming pattern. Defaults
to checking all GenXdev modules.
.PARAMETER FromScripts
Search in script files instead of module files.
.EXAMPLE
Assert-GenXdevDependencyUsage -ModuleName "GenXdev.Coding"
.EXAMPLE
checkgenxdevdependencies "GenXdev*" -FromScripts
#>
function Assert-GenXdevDependencyUsage {
[CmdletBinding()]
[Alias('checkgenxdevdependencies')]
param(
[Parameter(
Mandatory = $false,
Position = 1,
ValueFromPipeline = $true,
ValueFromPipelineByPropertyName = $true,
HelpMessage = 'Filter to apply to module names'
)]
[ValidateNotNullOrEmpty()]
[ValidatePattern('^(GenXdev|GenXde[v]\*|GenXdev(\.[\w\*\[\]\?]*)+)+$')]
[SupportsWildcards()]
[string[]] $ModuleName = @('GenXdev*'),
[Parameter(
Mandatory = $false,
HelpMessage = 'Search in script files instead of module files'
)]
[switch] $FromScripts
)
begin {
# retrieve ordered list of all genxdev modules by dependency hierarchy
$dependencies = @(GenXdev\Get-GenXDevNewModulesInOrderOfDependency |
Microsoft.PowerShell.Core\ForEach-Object ModuleName) +
@('GenXdev.Local')
}
process {
# temporarily disabled functionality - early return
return;
# invoke processing on each matching genxdev module
GenXdev\Invoke-OnEachGenXdevModule `
-ModuleName:$ModuleName `
-FromScripts:$FromScripts `
-OnlyPublished `
-NoLocal `
-ScriptBlock {
param($module)
# extract module name from current module object
$moduleName = $module.Name;
# construct path to module manifest file
$moduleManifestPath = GenXdev\Expand-Path (
".\$moduleName.psd1")
# load module manifest data for dependency analysis
$moduleManifest = Microsoft.PowerShell.Utility\Import-PowerShellDataFile `
-LiteralPath $moduleManifestPath
# find current module's position in dependency hierarchy
$index = $dependencies.IndexOf($moduleName)
# validate module exists in dependency list
if ($index -lt 0) {
Microsoft.PowerShell.Utility\Write-Error (
"Module $moduleName not found in dependencies list")
return
}
# check for invalid references to modules later in dependency chain
for ($i = $index + 1; $i -lt $dependencies.Count; $i++) {
# get dependency name from current position
$dependency = $dependencies[$i]
# extract module name if dependency is object with modulename property
if ($null -ne $dependency.ModuleName) {
$dependency = $dependency.ModuleName
}
# log dependency checking activity
Microsoft.PowerShell.Utility\Write-Verbose (
"Checking if $moduleName references $dependency")
# search for references to this dependency in module files
$references = GenXdev\Find-Item `
-PassThru `
-SearchMask '.\*.ps1' `
-Pattern "$([System.Text.RegularExpressions.Regex]::Escape($dependency))\\" `
-ErrorAction 'SilentlyContinue' |
Microsoft.PowerShell.Core\ForEach-Object FullName
# process any found references
if ($references) {
# skip test files as they may reference other modules for testing
if ($references -like '*.Tests.ps1') {
continue
}
# analyze each reference file for dependency violations
$references |
Microsoft.PowerShell.Core\ForEach-Object {
# read file content to check for allowed reference patterns
[string] $content = [IO.File]::ReadAllText($_)
# skip files with install-module commands or allowed local references
if ($content.Contains("Install-Module $dependency") -or
$content.Contains('GenXdev\KeyValueStores') -or
$content.Contains("`"`$($MyInvocation.MyCommand.Module.ModuleBase)\..\..\GenXdev.Local\")) {
return
}
# report dependency violation
Microsoft.PowerShell.Utility\Write-Error (
"Module $moduleName references $dependency in file $_")
}
}
}
# check for missing dependencies in module manifest
for ($i = 0; $i -lt $index; $i++) {
# get dependency name from current position
$dependency = $dependencies[$i]
# extract module name if dependency is object with modulename property
if ($null -ne $dependency.ModuleName) {
$dependency = $dependency.ModuleName
}
# log dependency checking activity
Microsoft.PowerShell.Utility\Write-Verbose (
"Checking if $moduleName references $dependency")
# search for references to this dependency in module files
$references = GenXdev\Find-Item `
-PassThru `
-SearchMask '.\*.ps1' `
-Pattern "$([System.Text.RegularExpressions.Regex]::Escape($dependency))\\" `
-ErrorAction 'SilentlyContinue' |
Microsoft.PowerShell.Core\ForEach-Object FullName
# process any found references
if ($references) {
# skip test files as they may reference other modules for testing
if ($references -like '*.Tests.ps1') {
continue
}
# analyze each reference file for missing manifest entries
$references |
Microsoft.PowerShell.Core\ForEach-Object {
# check if dependency is properly declared in module manifest
$hasDependency = ($dependency -eq $moduleName) -or
(@($moduleManifest.RequiredModules.ModuleName |
Microsoft.PowerShell.Core\Where-Object {
$_ -like $dependency }).Count -gt 0);
# validate dependency declaration
if (-not $hasDependency) {
# allow install-module references without manifest declaration
if ([IO.File]::ReadAllText($_).Contains("Install-Module $dependency")) {
Microsoft.PowerShell.Utility\Write-Verbose (
("Module $moduleName references $dependency in file, " +
"but has Install-Module $dependency in file. File: $_"))
return
}
# report missing dependency in module manifest
Microsoft.PowerShell.Utility\Write-Error (
("Module $moduleName references $dependency in file, " +
"but has module $dependency not listed in " +
"RequiredModules of $moduleManifestPath. File: $_"))
}
}
}
}
}
}
end {
}
}
<##############################################################################
Part of PowerShell module : GenXdev.Coding.PowerShell.Modules
Original cmdlet filename : Assert-GenXdevTest.ps1
Original author : René Vaessen / GenXdev
Version : 3.26.2026
Copyright (c) 2026 René Vaessen / GenXdev
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
################################################################################>
<#
.SYNOPSIS
Executesunit tests for GenXdev modules, sub-modules, or cmdlets
with intelligent debugging and AI-powered error resolution.
.DESCRIPTION
This function provides a testing framework for GenXdev modules,
offering multi-level test execution from entire modules down to individual
cmdlets. It integrates PSScriptAnalyzer for static code analysis, Pester for
unit testing, and PSScriptAnalyzer for static code analysis. The
function includes intelligent error handling with AI-powered resolution
capabilities and detailed progress reporting for development workflows.
.PARAMETER CmdletName
Search pattern to filter cmdlets for testing. Supports wildcards and allows
targeting specific cmdlets or groups of cmdlets matching the pattern.
.PARAMETER DefinitionMatches
Regular expression to match cmdlet definitions during the search process.
This allows for advanced filtering based on cmdlet implementation patterns.
.PARAMETER ModuleName
GenXdev module names to search and test. Must follow the pattern starting
with 'GenXdev' followed by optional sub-module components. Supports wildcards
for broad module selection.
.PARAMETER NoLocal
Skip searching in local module paths during cmdlet discovery. When specified,
only published module paths will be considered for testing.
.PARAMETER OnlyPublished
Limit search to published module paths only. This excludes local development
modules and focuses on officially published GenXdev modules.
.PARAMETER FromScripts
Search in script files instead of module files. This allows testing of
standalone PowerShell scripts within the GenXdev ecosystem.
.PARAMETER IncludeScripts
Include the scripts directory in addition to regular modules. This expands
the test scope to cover both modular and script-based functionality.
.PARAMETER OnlyReturnModuleNames
Return only unique module names instead of full cmdlet details. Useful for
discovery and inventory operations rather than detailed testing.
.PARAMETER ExactMatch
Require exact matches for cmdlet names rather than wildcard matching. This
provides precise targeting for specific cmdlet testing scenarios.
.PARAMETER Verbosity
Output detail level for test execution. Controls the amount of information
displayed during test runs, from minimal to diagnostic output.
.PARAMETER StackTraceVerbosity
Stack trace detail level for error reporting. Determines how much call stack
information is included when errors occur during testing.
.PARAMETER TestFailedAction
Action to take when a test fails. Options include interactive prompting,
automatic continuation, stopping execution, AI-powered resolution, error
logging, or exception throwing for integration scenarios.
.PARAMETER AllowLongRunningTests
Include unit tests that have long running durations in the test execution.
This enables testing including performance and integration tests.
.PARAMETER SkipModuleImports
Skip importing GenXdev modules before testing. This is useful when modules
are already loaded or when testing specific module loading scenarios.