forked from ModuleBuild/ModuleBuild
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathInvokePlaster.ps1
More file actions
1551 lines (1319 loc) · 72.5 KB
/
Copy pathInvokePlaster.ps1
File metadata and controls
1551 lines (1319 loc) · 72.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
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
## DEVELOPERS NOTES & CONVENTIONS
##
## 1. All text displayed to the user except for Write-Debug (or $PSCmdlet.WriteDebug()) text must be added to the
## string tables in:
## en-US\Plaster.psd1
## Plaster.psm1
## 2. If a new manifest element is added, it must be added to the Schema\PlasterManifest-v1.xsd file and then
## processed in the appropriate function in this script. Any changes to <parameter> attributes must be
## processed not only in the ProcessParameter function but also in the dynamicparam function.
##
## 3. Non-exported functions should avoid using the PowerShell standard Verb-Noun naming convention.
## They should use PascalCase instead.
##
## 4. Please follow the scripting style of this file when adding new script.
function Invoke-Plaster {
[System.Diagnostics.CodeAnalysis.SuppressMessage('PSAvoidShouldContinueWithoutForce', '', Scope = 'Function', Target = 'CopyFileWithConflictDetection')]
[System.Diagnostics.CodeAnalysis.SuppressMessage('PSAvoidUsingConvertToSecureStringWithPlainText', '', Scope = 'Function', Target = 'ProcessParameter')]
[System.Diagnostics.CodeAnalysis.SuppressMessage('PSShouldProcess', '', Scope = 'Function', Target = 'CopyFileWithConflictDetection')]
[System.Diagnostics.CodeAnalysis.SuppressMessage('PSShouldProcess', '', Scope = 'Function', Target = 'ProcessFile')]
[System.Diagnostics.CodeAnalysis.SuppressMessage('PSShouldProcess', '', Scope = 'Function', Target = 'ProcessModifyFile')]
[System.Diagnostics.CodeAnalysis.SuppressMessage('PSShouldProcess', '', Scope = 'Function', Target = 'ProcessNewModuleManifest')]
[System.Diagnostics.CodeAnalysis.SuppressMessage('PSShouldProcess', '', Scope = 'Function', Target = 'ProcessRequireModule')]
[CmdletBinding(SupportsShouldProcess = $true)]
param(
[Parameter(Position = 0, Mandatory = $true)]
[ValidateNotNullOrEmpty()]
[string]
$TemplatePath,
[Parameter(Position = 1, Mandatory = $true)]
[ValidateNotNullOrEmpty()]
[string]
$DestinationPath,
[Parameter()]
[switch]
$Force,
[Parameter()]
[switch]
$NoLogo,
[Parameter()]
[switch]
$PassThru
)
# Process the template's Plaster manifest file to convert parameters defined there into dynamic parameters.
dynamicparam {
$paramDictionary = New-Object System.Management.Automation.RuntimeDefinedParameterDictionary
$manifest = $null
$manifestPath = $null
$templateAbsolutePath = $null
# Nothing to do until the TemplatePath parameter has been provided.
if ($null -eq $TemplatePath) {
return
}
try {
# Let's convert non-terminating errors in this function to terminating so we
# catch and format the error message as a warning.
$ErrorActionPreference = 'Stop'
# The constrained runspace is not available in the dynamicparam block. Shouldn't be needed
# since we are only evaluating the parameters in the manifest - no need for EvaluateConditionAttribute as we
# are not building up multiple parametersets. And no need for EvaluateAttributeValue since we are only
# grabbing the parameter's value which is static.
$templateAbsolutePath = $ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath($TemplatePath)
if (!(Test-Path -LiteralPath $templateAbsolutePath -PathType Container)) {
throw ($LocalizedData.ErrorTemplatePathIsInvalid_F1 -f $templateAbsolutePath)
}
# Load manifest file using culture lookup
$manifestPath = GetPlasterManifestPathForCulture $templateAbsolutePath $PSCulture
if (($null -eq $manifestPath) -or (!(Test-Path $manifestPath))) {
return
}
$manifest = Plaster\Test-PlasterManifest -Path $manifestPath -ErrorAction Stop 3>$null
# The user-defined parameters in the Plaster manifest are converted to dynamic parameters
# which allows the user to provide the parameters via the command line.
# This enables non-interactive use cases.
foreach ($node in $manifest.plasterManifest.parameters.ChildNodes) {
if ($node -isnot [System.Xml.XmlElement]) {
continue
}
$name = $node.name
$type = $node.type
$prompt = if ($node.prompt) { $node.prompt }
else { $LocalizedData.MissingParameterPrompt_F1 -f $name }
if (!$name -or !$type) { continue }
# Configure ParameterAttribute and add to attr collection
$attributeCollection = New-Object System.Collections.ObjectModel.Collection[System.Attribute]
$paramAttribute = New-Object System.Management.Automation.ParameterAttribute
$paramAttribute.HelpMessage = $prompt
$attributeCollection.Add($paramAttribute)
switch -regex ($type) {
'text|user-fullname|user-email' {
$param = New-Object System.Management.Automation.RuntimeDefinedParameter `
-ArgumentList ($name, [string], $attributeCollection)
break
}
'choice|multichoice' {
$choiceNodes = $node.ChildNodes
$setValues = New-Object string[] $choiceNodes.Count
$i = 0
foreach ($choiceNode in $choiceNodes) {
$setValues[$i++] = $choiceNode.value
}
$validateSetAttr = New-Object System.Management.Automation.ValidateSetAttribute $setValues
$attributeCollection.Add($validateSetAttr)
$type = if ($type -eq 'multichoice') { [string[]] }
else { [string] }
$param = New-Object System.Management.Automation.RuntimeDefinedParameter `
-ArgumentList ($name, $type, $attributeCollection)
break
}
default { throw ($LocalizedData.UnrecognizedParameterType_F2 -f $type, $name) }
}
$paramDictionary.Add($name, $param)
}
}
catch {
Write-Warning ($LocalizedData.ErrorProcessingDynamicParams_F1 -f $_)
}
$paramDictionary
}
begin {
# Write out the Plaster logo if necessary
$plasterLogo = @'
____ _ _
| _ \| | __ _ ___| |_ ___ _ __
| |_) | |/ _` / __| __/ _ \ '__|
| __/| | (_| \__ \ || __/ |
|_| |_|\__,_|___/\__\___|_|
'@
if (!$NoLogo) {
$versionString = "v$PlasterVersion"
Write-Host $plasterLogo
Write-Host ((" " * (50 - $versionString.Length)) + $versionString)
Write-Host ("=" * 50)
}
$boundParameters = $PSBoundParameters
$constrainedRunspace = $null
$templateCreatedFiles = @{}
$defaultValueStore = @{}
$fileConflictConfirmNoToAll = $false
$fileConflictConfirmYesToAll = $false
$flags = @{
DefaultValueStoreDirty = $false
}
# Verify TemplatePath parameter value is valid.
$templateAbsolutePath = $PSCmdlet.GetUnresolvedProviderPathFromPSPath($TemplatePath)
if (!(Test-Path -LiteralPath $templateAbsolutePath -PathType Container)) {
throw ($LocalizedData.ErrorTemplatePathIsInvalid_F1 -f $templateAbsolutePath)
}
# We will have a null manifest if the dynamicparam scriptblock was unable to load the template manifest
# or it wasn't valid. If so, let's try to load it here. If anything, we can provide better errors here.
if ($null -eq $manifest) {
if ($null -eq $manifestPath) {
$manifestPath = GetPlasterManifestPathForCulture $templateAbsolutePath $PSCulture
}
if (Test-Path -LiteralPath $manifestPath -PathType Leaf) {
$manifest = Plaster\Test-PlasterManifest -Path $manifestPath -ErrorAction Stop 3>$null
$PSCmdlet.WriteDebug("In begin, loading manifest file '$manifestPath'")
}
else {
throw ($LocalizedData.ManifestFileMissing_F1 -f $manifestPath)
}
}
# If the destination path doesn't exist, create it.
$destinationAbsolutePath = $PSCmdlet.GetUnresolvedProviderPathFromPSPath($DestinationPath)
if (!(Test-Path -LiteralPath $destinationAbsolutePath)) {
New-Item $destinationAbsolutePath -ItemType Directory > $null
}
# Prepare output object if user has specified the -PassThru parameter.
if ($PassThru) {
$InvokePlasterInfo = [PSCustomObject]@{
TemplatePath = $templateAbsolutePath
DestinationPath = $destinationAbsolutePath
Success = $false
TemplateType = if ($manifest.plasterManifest.templateType) {$manifest.plasterManifest.templateType}
else {'Unspecified'}
CreatedFiles = [string[]]@()
UpdatedFiles = [string[]]@()
MissingModules = [string[]]@()
OpenFiles = [string[]]@()
}
}
# Create the pre-defined Plaster variables.
InitializePredefinedVariables $templateAbsolutePath $destinationAbsolutePath
# Check for any existing default value store file and load default values if file exists.
$templateId = $manifest.plasterManifest.metadata.id
$templateVersion = $manifest.plasterManifest.metadata.version
$templateName = $manifest.plasterManifest.metadata.name
$storeFilename = "$templateName-$templateVersion-$templateId.clixml"
$defaultValueStorePath = Join-Path $ParameterDefaultValueStoreRootPath $storeFilename
if (Test-Path $defaultValueStorePath) {
try {
$PSCmdlet.WriteDebug("Loading default value store from '$defaultValueStorePath'.")
$defaultValueStore = Import-Clixml $defaultValueStorePath -ErrorAction Stop
}
catch {
Write-Warning ($LocalizedData.ErrorFailedToLoadStoreFile_F1 -f $defaultValueStorePath)
}
}
function NewConstrainedRunspace() {
$iss = [System.Management.Automation.Runspaces.InitialSessionState]::Create()
if (!$IsCoreCLR) {
$iss.ApartmentState = [System.Threading.ApartmentState]::STA
}
$iss.LanguageMode = [System.Management.Automation.PSLanguageMode]::ConstrainedLanguage
$iss.DisableFormatUpdates = $true
$sspe = New-Object System.Management.Automation.Runspaces.SessionStateProviderEntry 'Environment', ([Microsoft.PowerShell.Commands.EnvironmentProvider]), $null
$iss.Providers.Add($sspe)
$sspe = New-Object System.Management.Automation.Runspaces.SessionStateProviderEntry 'FileSystem', ([Microsoft.PowerShell.Commands.FileSystemProvider]), $null
$iss.Providers.Add($sspe)
$ssce = New-Object System.Management.Automation.Runspaces.SessionStateCmdletEntry 'Get-Content', ([Microsoft.PowerShell.Commands.GetContentCommand]), $null
$iss.Commands.Add($ssce)
$ssce = New-Object System.Management.Automation.Runspaces.SessionStateCmdletEntry 'Get-Date', ([Microsoft.PowerShell.Commands.GetDateCommand]), $null
$iss.Commands.Add($ssce)
$ssce = New-Object System.Management.Automation.Runspaces.SessionStateCmdletEntry 'Get-ChildItem', ([Microsoft.PowerShell.Commands.GetChildItemCommand]), $null
$iss.Commands.Add($ssce)
$ssce = New-Object System.Management.Automation.Runspaces.SessionStateCmdletEntry 'Get-Item', ([Microsoft.PowerShell.Commands.GetItemCommand]), $null
$iss.Commands.Add($ssce)
$ssce = New-Object System.Management.Automation.Runspaces.SessionStateCmdletEntry 'Get-ItemProperty', ([Microsoft.PowerShell.Commands.GetItemPropertyCommand]), $null
$iss.Commands.Add($ssce)
$ssce = New-Object System.Management.Automation.Runspaces.SessionStateCmdletEntry 'Get-Module', ([Microsoft.PowerShell.Commands.GetModuleCommand]), $null
$iss.Commands.Add($ssce)
$ssce = New-Object System.Management.Automation.Runspaces.SessionStateCmdletEntry 'Get-Variable', ([Microsoft.PowerShell.Commands.GetVariableCommand]), $null
$iss.Commands.Add($ssce)
$ssce = New-Object System.Management.Automation.Runspaces.SessionStateCmdletEntry 'Test-Path', ([Microsoft.PowerShell.Commands.TestPathCommand]), $null
$iss.Commands.Add($ssce)
$ssce = New-Object System.Management.Automation.Runspaces.SessionStateCmdletEntry 'Out-String', ([Microsoft.PowerShell.Commands.OutStringCommand]), $null
$iss.Commands.Add($ssce)
$scopedItemOptions = [System.Management.Automation.ScopedItemOptions]::AllScope
$plasterVars = Get-Variable -Name PLASTER_*, PSVersionTable
if (Test-Path Variable:\IsLinux) {
$plasterVars += Get-Variable -Name IsLinux
}
if (Test-Path Variable:\IsOSX) {
$plasterVars += Get-Variable -Name IsOSX
}
if (Test-Path Variable:\IsWindows) {
$plasterVars += Get-Variable -Name IsWindows
}
foreach ($var in $plasterVars) {
$ssve = New-Object System.Management.Automation.Runspaces.SessionStateVariableEntry `
$var.Name, $var.Value, $var.Description, $scopedItemOptions
$iss.Variables.Add($ssve)
}
# Create new runspace with the above defined entries. Then open and set its working dir to $destinationAbsolutePath
# so all condition attribute expressions can use a relative path to refer to file paths e.g.
# condition="Test-Path src\${PLASTER_PARAM_ModuleName}.psm1"
$runspace = [System.Management.Automation.Runspaces.RunspaceFactory]::CreateRunspace($iss)
$runspace.Open()
if ($destinationAbsolutePath) {
$runspace.SessionStateProxy.Path.SetLocation($destinationAbsolutePath) > $null
}
$runspace
}
function ExecuteExpressionImpl([string]$Expression) {
try {
$powershell = [PowerShell]::Create()
if ($null -eq $constrainedRunspace) {
$constrainedRunspace = NewConstrainedRunspace
}
$powershell.Runspace = $constrainedRunspace
try {
$powershell.AddScript($Expression) > $null
$res = $powershell.Invoke()
$res
}
catch {
throw ($LocalizedData.ExpressionInvalid_F2 -f $Expression, $_)
}
# Check for non-terminating errors.
if ($powershell.Streams.Error.Count -gt 0) {
$err = $powershell.Streams.Error[0]
throw ($LocalizedData.ExpressionNonTermErrors_F2 -f $Expression, $err)
}
}
finally {
if ($powershell) {
$powershell.Dispose()
}
}
}
function InterpolateAttributeValue([string]$Value, [string]$Location) {
if ($null -eq $Value) {
return [string]::Empty
}
elseif ([string]::IsNullOrWhiteSpace($Value)) {
return $Value
}
try {
$res = @(ExecuteExpressionImpl "`"$Value`"")
[string]$res[0]
}
catch {
throw ($LocalizedData.InterpolationError_F3 -f $Value.Trim(), $Location, $_)
}
}
function EvaluateConditionAttribute([string]$Expression, [string]$Location) {
if ($null -eq $Expression) {
return [string]::Empty
}
elseif ([string]::IsNullOrWhiteSpace($Expression)) {
return $Expression
}
try {
$res = @(ExecuteExpressionImpl $Expression)
[bool]$res[0]
}
catch {
throw ($LocalizedData.ExpressionInvalidCondition_F3 -f $Expression, $Location, $_)
}
}
function EvaluateExpression([string]$Expression, [string]$Location) {
if ($null -eq $Expression) {
return [string]::Empty
}
elseif ([string]::IsNullOrWhiteSpace($Expression)) {
return $Expression
}
try {
$res = @(ExecuteExpressionImpl $Expression)
[string]$res[0]
}
catch {
throw ($LocalizedData.ExpressionExecError_F2 -f $Location, $_)
}
}
function EvaluateScript([string]$Script, [string]$Location) {
if ($null -eq $Script) {
return @([string]::Empty)
}
elseif ([string]::IsNullOrWhiteSpace($Script)) {
return $Script
}
try {
$res = @(ExecuteExpressionImpl $Script)
[string[]]$res
}
catch {
throw ($LocalizedData.ExpressionExecError_F2 -f $Location, $_)
}
}
function GetErrorLocationFileAttrVal([string]$ElementName, [string]$AttributeName) {
$LocalizedData.ExpressionErrorLocationFile_F2 -f $ElementName, $AttributeName
}
function GetErrorLocationModifyAttrVal([string]$AttributeName) {
$LocalizedData.ExpressionErrorLocationModify_F1 -f $AttributeName
}
function GetErrorLocationNewModManifestAttrVal([string]$AttributeName) {
$LocalizedData.ExpressionErrorLocationNewModManifest_F1 -f $AttributeName
}
function GetErrorLocationParameterAttrVal([string]$ParameterName, [string]$AttributeName) {
$LocalizedData.ExpressionErrorLocationParameter_F2 -f $ParameterName, $AttributeName
}
function GetErrorLocationRequireModuleAttrVal([string]$ModuleName, [string]$AttributeName) {
$LocalizedData.ExpressionErrorLocationRequireModule_F2 -f $ModuleName, $AttributeName
}
function ConvertToDestinationRelativePath($Path) {
$fullDestPath = $DestinationPath
if (![System.IO.Path]::IsPathRooted($fullDestPath)) {
$fullDestPath = $PSCmdlet.GetUnresolvedProviderPathFromPSPath($DestinationPath)
}
$fullPath = $PSCmdlet.GetUnresolvedProviderPathFromPSPath($Path)
if (!$fullPath.StartsWith($fullDestPath, 'OrdinalIgnoreCase')) {
throw ($LocalizedData.ErrorPathMustBeUnderDestPath_F2 -f $fullPath, $fullDestPath)
}
$fullPath.Substring($fullDestPath.Length).TrimStart('\', '/')
}
function VerifyPathIsUnderDestinationPath([ValidateNotNullOrEmpty()][string]$FullPath) {
if (![System.IO.Path]::IsPathRooted($FullPath)) {
$PSCmdlet.WriteDebug("The FullPath parameter '$FullPath' must be an absolute path.")
}
$fullDestPath = $DestinationPath
if (![System.IO.Path]::IsPathRooted($fullDestPath)) {
$fullDestPath = $PSCmdlet.GetUnresolvedProviderPathFromPSPath($DestinationPath)
}
if (!$FullPath.StartsWith($fullDestPath, [StringComparison]::OrdinalIgnoreCase)) {
throw ($LocalizedData.ErrorPathMustBeUnderDestPath_F2 -f $FullPath, $fullDestPath)
}
}
function WriteContentWithEncoding([string]$path, [string[]]$content, [string]$encoding) {
if ($encoding -match '-nobom') {
$encoding, $dummy = $encoding -split '-'
$noBomEncoding = $null
switch ($encoding) {
'utf8' { $noBomEncoding = New-Object System.Text.UTF8Encoding($false) }
}
if ($null -eq $content) {
$content = [string]::Empty
}
[System.IO.File]::WriteAllLines($path, $content, $noBomEncoding)
}
else {
Set-Content -LiteralPath $path -Value $content -Encoding $encoding
}
}
function ColorForOperation($operation) {
switch ($operation) {
$LocalizedData.OpConflict { 'Red' }
$LocalizedData.OpCreate { 'Green' }
$LocalizedData.OpForce { 'Yellow' }
$LocalizedData.OpIdentical { 'Cyan' }
$LocalizedData.OpModify { 'Magenta' }
$LocalizedData.OpUpdate { 'Green' }
$LocalizedData.OpMissing { 'Red' }
$LocalizedData.OpVerify { 'Green' }
default { $Host.UI.RawUI.ForegroundColor }
}
}
function GetMaxOperationLabelLength {
($LocalizedData.OpCreate, $LocalizedData.OpIdentical,
$LocalizedData.OpConflict, $LocalizedData.OpForce,
$LocalizedData.OpMissing, $LocalizedData.OpModify,
$LocalizedData.OpUpdate, $LocalizedData.OpVerify |
Measure-Object -Property Length -Maximum).Maximum
}
function WriteOperationStatus($operation, $message) {
$maxLen = GetMaxOperationLabelLength
Write-Host ("{0,$maxLen} " -f $operation) -ForegroundColor (ColorForOperation $operation) -NoNewline
Write-Host $message
}
function WriteOperationAdditionalStatus([string[]]$Message) {
$maxLen = GetMaxOperationLabelLength
foreach ($msg in $Message) {
$lines = $msg -split "`n"
foreach ($line in $lines) {
Write-Host ("{0,$maxLen} {1}" -f "", $line)
}
}
}
function GetGitConfigValue($name) {
# Very simplistic git config lookup
# Won't work with namespace, just use final element, e.g. 'name' instead of 'user.name'
# The $Home dir may not be reachable e.g. if on network share and/or script not running as admin.
# See issue https://github.com/PowerShell/Plaster/issues/92
if (!(Test-Path -LiteralPath $Home)) {
return
}
$gitConfigPath = Join-Path $Home '.gitconfig'
$PSCmdlet.WriteDebug("Looking for '$name' value in Git config: $gitConfigPath")
if (Test-Path -LiteralPath $gitConfigPath) {
$matches = Select-String -LiteralPath $gitConfigPath -Pattern "\s+$name\s+=\s+(.+)$"
if (@($matches).Count -gt 0) {
$matches.Matches.Groups[1].Value
}
}
}
function PromptForInput($prompt, $default) {
do {
$value = Read-Host -Prompt $prompt
if (!$value -and $default) {
$value = $default
}
} while (!$value)
$value
}
function PromptForChoice([string]$ParameterName, [ValidateNotNull()]$ChoiceNodes, [string]$prompt,
[int[]]$defaults, [switch]$IsMultiChoice) {
$choices = New-Object 'System.Collections.ObjectModel.Collection[System.Management.Automation.Host.ChoiceDescription]'
$values = New-Object object[] $ChoiceNodes.Count
$i = 0
foreach ($choiceNode in $ChoiceNodes) {
$label = InterpolateAttributeValue $choiceNode.label (GetErrorLocationParameterAttrVal $ParameterName label)
$help = InterpolateAttributeValue $choiceNode.help (GetErrorLocationParameterAttrVal $ParameterName help)
$value = InterpolateAttributeValue $choiceNode.value (GetErrorLocationParameterAttrVal $ParameterName value)
$choice = New-Object System.Management.Automation.Host.ChoiceDescription -Arg $label, $help
$choices.Add($choice)
$values[$i++] = $value
}
$retval = [PSCustomObject]@{Values = @(); Indices = @()}
if ($IsMultiChoice) {
$selections = $Host.UI.PromptForChoice('', $prompt, $choices, $defaults)
foreach ($selection in $selections) {
$retval.Values += $values[$selection]
$retval.Indices += $selection
}
}
else {
if ($defaults.Count -gt 1) {
throw ($LocalizedData.ParameterTypeChoiceMultipleDefault_F1 -f $ChoiceNodes.ParentNode.name)
}
$selection = $Host.UI.PromptForChoice('', $prompt, $choices, $defaults[0])
$retval.Values = $values[$selection]
$retval.Indices = $selection
}
$retval
}
# All Plaster variables should be set via this method so that the ConstrainedRunspace can be
# configured to use the new variable. This method will null out the ConstrainedRunspace so that
# later, when we need to evaluate script in that runspace, it will get recreated first with all
# the latest Plaster variables.
function SetPlasterVariable() {
param(
[Parameter(Mandatory = $true)]
[ValidateNotNullOrEmpty()]
[string]$Name,
[Parameter(Mandatory = $true)]
$Value,
[Parameter()]
[bool]
$IsParam = $true
)
# Variables created from a <parameter> in the Plaster manifset are prefixed PLASTER_PARAM all others
# are just PLASTER_.
$variableName = if ($IsParam) { "PLASTER_PARAM_$Name" }
else { "PLASTER_$Name" }
Set-Variable -Name $variableName -Value $Value -Scope Script -WhatIf:$false
# If the constrained runspace has been created, it needs to be disposed so that the next string
# expansion (or condition eval) gets an updated runspace that contains this variable or its new value.
if ($null -ne $script:ConstrainedRunspace) {
$script:ConstrainedRunspace.Dispose()
$script:ConstrainedRunspace = $null
}
}
function ProcessParameter([ValidateNotNull()]$Node) {
$name = $Node.name
$type = $Node.type
$store = $Node.store
$prompt = InterpolateAttributeValue $Node.prompt (GetErrorLocationParameterAttrVal $name prompt)
$default = InterpolateAttributeValue $Node.default (GetErrorLocationParameterAttrVal $name default)
# Check if parameter was provided via a dynamic parameter.
if ($boundParameters.ContainsKey($name)) {
$value = $boundParameters[$name]
}
else {
# Not a dynamic parameter so prompt user for the value but first check for a stored default value.
if ($store -and ($null -ne $defaultValueStore[$name])) {
$default = $defaultValueStore[$name]
$PSCmdlet.WriteDebug("Read default value '$default' for parameter '$name' from default value store.")
if (($store -eq 'encrypted') -and ($default -is [System.Security.SecureString])) {
try {
$cred = New-Object -TypeName PSCredential -ArgumentList 'jsbplh', $default
$default = $cred.GetNetworkCredential().Password
$PSCmdlet.WriteDebug("Unencrypted default value for parameter '$name'.")
}
catch [System.Exception] {
Write-Warning ($LocalizedData.ErrorUnencryptingSecureString_F1 -f $name)
}
}
}
# If the prompt message failed to evaluate or was empty, supply a diagnostic prompt message
if (!$prompt) {
$prompt = $LocalizedData.MissingParameterPrompt_F1 -f $name
}
# Some default values might not come from the template e.g. some are harvested from .gitconfig if it exists.
$defaultNotFromTemplate = $false
# Now prompt user for parameter value based on the parameter type.
switch -regex ($type) {
'text' {
# Display an appropriate "default" value in the prompt string.
if ($default) {
if ($store -eq 'encrypted') {
$obscuredDefault = $default -replace '(....).*', '$1****'
$prompt += " ($obscuredDefault)"
}
else {
$prompt += " ($default)"
}
}
# Prompt the user for text input.
$value = PromptForInput $prompt $default
$valueToStore = $value
}
'user-fullname' {
# If no default, try to get a name from git config.
if (!$default) {
$default = GetGitConfigValue('name')
$defaultNotFromTemplate = $true
}
if ($default) {
if ($store -eq 'encrypted') {
$obscuredDefault = $default -replace '(....).*', '$1****'
$prompt += " ($obscuredDefault)"
}
else {
$prompt += " ($default)"
}
}
# Prompt the user for text input.
$value = PromptForInput $prompt $default
$valueToStore = $value
}
'user-email' {
# If no default, try to get an email from git config
if (-not $default) {
$default = GetGitConfigValue('email')
$defaultNotFromTemplate = $true
}
if ($default) {
if ($store -eq 'encrypted') {
$obscuredDefault = $default -replace '(....).*', '$1****'
$prompt += " ($obscuredDefault)"
}
else {
$prompt += " ($default)"
}
}
# Prompt the user for text input.
$value = PromptForInput $prompt $default
$valueToStore = $value
}
'choice|multichoice' {
$choices = $Node.ChildNodes
$defaults = [int[]]($default -split ',')
# Prompt the user for choice or multichoice selection input.
$selections = PromptForChoice $name $choices $prompt $defaults -IsMultiChoice:($type -eq 'multichoice')
$value = $selections.Values
$OFS = ","
$valueToStore = "$($selections.Indices)"
}
default { throw ($LocalizedData.UnrecognizedParameterType_F2 -f $type, $Node.LocalName) }
}
# If parameter specifies that user's input be stored as the default value,
# store it to file if the value has changed.
if ($store -and (($default -ne $valueToStore) -or $defaultNotFromTemplate)) {
if ($store -eq 'encrypted') {
$PSCmdlet.WriteDebug("Storing new, encrypted default value for parameter '$name' to default value store.")
$defaultValueStore[$name] = ConvertTo-SecureString -String $valueToStore -AsPlainText -Force
}
else {
$PSCmdlet.WriteDebug("Storing new default value '$valueToStore' for parameter '$name' to default value store.")
$defaultValueStore[$name] = $valueToStore
}
$flags.DefaultValueStoreDirty = $true
}
}
# Make template defined parameters available as a PowerShell variable PLASTER_PARAM_<parameterName>.
SetPlasterVariable -Name $name -Value $value -IsParam $true
}
function ProcessMessage([ValidateNotNull()]$Node) {
$text = InterpolateAttributeValue $Node.InnerText '<message>'
$nonewline = $Node.nonewline -eq 'true'
# Eliminate whitespace before and after the text that just happens to get inserted because you want
# the text on different lines than the start/end element Tags.
$trimmedText = $text -replace '^[ \t]*\n', '' -replace '\n[ \t]*$', ''
$condition = $Node.condition
if ($condition -and !(EvaluateConditionAttribute $condition "'<$($Node.LocalName)>'")) {
$debugText = $trimmedText -replace '\r|\n', ' '
$maxLength = [Math]::Min(40, $debugText.Length)
$PSCmdlet.WriteDebug("Skipping message '$($debugText.Substring(0, $maxLength))', condition evaluated to false.")
return
}
Write-Host $trimmedText -NoNewline:($nonewline -eq 'true')
}
function CopyModuleManifestPropertyToHashtable([PSModuleInfo]$oldModuleManifest, [hashtable]$hashtable, [string[]]$Property) {
foreach ($prop in $Property) {
# if the property exists in the old manifest file but not in our existing hash then add it.
if (($oldModuleManifest.$prop) -and ($null -eq $hashtable.$prop)) {
if (($prop -eq 'Tags') -and (($oldModuleManifest.$prop).Count -gt 0)) {
$hashtable[$prop] = @($oldModuleManifest.$prop)
}
else {
$hashtable[$prop] = ($oldModuleManifest.$prop).ToString()
}
}
}
}
function ProcessNewModuleManifest([ValidateNotNull()]$Node) {
# First if a condition is defined and not met then there is nothing to do
$condition = $Node.condition
if ($condition -and !(EvaluateConditionAttribute $condition "'<$($Node.LocalName)>'")) {
$PSCmdlet.WriteDebug("Skipping module manifest generation for '$dstPath', condition evaluated to false.")
return
}
# Get defined properties in the manifest
$DefinedProperties = @($node | Get-Member -Type:Property).Name
# Our future hash for splatting the new-modulemanifest command
$newModuleManifestParams = @{}
# Pull all the new-modulemanifest parameters to account for future version changes and such
$CmdParams = (Get-Command New-ModuleManifest).Parameters
# Some ignored parameters that we either overwrite (like Path) or will not be splatting (the adv function variables)
$IgnoredManifestVals = @(
'Path',
'PrivateData',
'PassThru',
'Verbose',
'Debug',
'ErrorAction',
'WarningAction',
'InformationAction',
'ErrorVariable',
'WarningVariable',
'InformationVariable',
'OutVariable',
'OutBuffer',
'PipelineVariable',
'WhatIf',
'Confirm'
)
# Get all non-advanced function parameters that new-modulemanifest uses
$ValidModuleManifestParams = $CmdParams.keys | Where-Object {($IgnoredManifestVals -notcontains $_)}
# Create a hash of parameter types so we know how to process module manifest entries (as arrays or strings)
$paramTypes = @{}
$ValidModuleManifestParams | ForEach-Object {
$ParamTypes[$_] = $CmdParams[$_].ParameterType.BaseType.ToString()
}
# Now go through all the defined module properties in the manifest, get the value, and build the splat
ForEach ($ModProp in $DefinedProperties) {
$PSCmdlet.WriteDebug("Determining how to handle the modulemanifest property - $ModProp.")
$PropVal = InterpolateAttributeValue $Node.$ModProp (GetErrorLocationNewModManifestAttrVal $ModProp)
# We are only concerned about the values which align with a new-modulemanifest parameter
if (($null -ne $PropVal) -and ($ValidModuleManifestParams -contains $ModProp)) {
#if (![string]::IsNullOrWhiteSpace($PropVal) -and ($ValidModuleManifestParams -contains $ModProp)) {
# take action based on the type of parameter being splatted
switch ($ParamTypes[$ModProp]) {
'System.Array' {
# If this is an array type then assume it is a comma separated list of values
$newModuleManifestParams[$ModProp] = @($PropVal -split ',' | ForEach-Object {$_.trim()})
}
Default {
# Otherwise just pass it on as a string
# We could process the enum for ProcessorArchitecture and such separately I suppose.
$newModuleManifestParams[$ModProp] = $PropVal
}
}
}
else {
# Process everything else accordingly (leave logic for future non-parameter based modulemanifest schema additions)
switch ($ModProp) {
'destination' {
$dstRelPath = $PropVal
}
'encoding' {
$encoding = $Node.encoding
}
'openInEditor' {}
Default {}
}
}
}
# No encoding defined? Make it default then.
if (!$encoding) {
$encoding = $DefaultEncoding
}
# We could choose to not check this if the condition eval'd to false
# but I think it is better to let the template author know they've broken the
# rules for any of the file directives (not just the ones they're testing/enabled).
if ([System.IO.Path]::IsPathRooted($dstRelPath)) {
throw ($LocalizedData.ErrorPathMustBeRelativePath_F2 -f $dstRelPath, $Node.LocalName)
}
$dstPath = $PSCmdlet.GetUnresolvedProviderPathFromPSPath((Join-Path $DestinationPath $dstRelPath))
if ($PSCmdlet.ShouldProcess($dstPath, $LocalizedData.ShouldProcessNewModuleManifest)) {
$manifestDir = Split-Path $dstPath -Parent
if (!(Test-Path $manifestDir)) {
VerifyPathIsUnderDestinationPath $manifestDir
Write-Verbose ($LocalizedData.NewModManifest_CreatingDir_F1 -f $manifestDir)
New-Item $manifestDir -ItemType Directory > $null
}
# If there is an existing module manifest, load it so we can reuse old values not specified by
# template.
if (Test-Path -LiteralPath $dstPath) {
$oldModuleManifest = Test-ModuleManifest -Path $dstPath -ErrorAction SilentlyContinue
if ($? -and $oldModuleManifest) {
$PSCmdlet.WriteDebug("We found an existing manifest file. Pulling in all values not defined in the Plaster manifest file.")
# Get a list of properties that have values already from the old manifest but
# are not defined in the plaster manifest and are also valid new-modulemanifest parameters
$props = @(($oldModuleManifest | Get-member -Type 'Property' |
Where-Object {($null -ne $oldModuleManifest.($_.Name)) -and
($_.Name -ne 'PSData') -and
(-not [string]::IsNullOrEmpty(($oldModuleManifest))) -and
($ValidModuleManifestParams -contains $_.Name)}).Name |
Where-Object {$DefinedProperties -notcontains $_})
if ($props.count -gt 0) {
CopyModuleManifestPropertyToHashtable $oldModuleManifest $newModuleManifestParams $props
}
}
}
$tempFile = $null
try {
$tempFileBaseName = "moduleManifest-" + [Guid]::NewGuid()
$tempFile = [System.IO.Path]::GetTempPath() + "${tempFileBaseName}.psd1"
$PSCmdlet.WriteDebug("Created temp file for new module manifest - $tempFile")
$newModuleManifestParams['Path'] = $tempFile
# Generate manifest into a temp file.
New-ModuleManifest @newModuleManifestParams
# Typically the manifest is re-written with a new encoding (UTF8-NoBOM) because Git hates UTF-16.
$content = Get-Content -LiteralPath $tempFile -Raw
# Replace the temp filename in the generated manifest file's comment header with the actual filename.
$dstBaseName = [System.IO.Path]::GetFileNameWithoutExtension($dstPath)
$content = $content -replace "(?<=\s*#.*?)$tempFileBaseName", $dstBaseName
WriteContentWithEncoding -Path $tempFile -Content $content -Encoding $encoding
CopyFileWithConflictDetection $tempFile $dstPath
if ($PassThru -and ($Node.openInEditor -eq 'true')) {
$InvokePlasterInfo.OpenFiles += $dstPath
}
}
finally {
if ($tempFile -and (Test-Path $tempFile)) {
Remove-Item -LiteralPath $tempFile
$PSCmdlet.WriteDebug("Removed temp file for new module manifest - $tempFile")
}
}
}
}
#
# Begin ProcessFile helper methods
#
function NewBackupFilename([string]$Path) {
$dir = [System.IO.Path]::GetDirectoryName($Path)
$filename = [System.IO.Path]::GetFileName($Path)
$backupPath = Join-Path -Path $dir -ChildPath "${filename}.bak"
$i = 1;
while (Test-Path -LiteralPath $backupPath) {
$backupPath = Join-Path -Path $dir -ChildPath "${filename}.bak$i"
$i++
}
$backupPath
}
function AreFilesIdentical($Path1, $Path2) {
$file1 = Get-Item -LiteralPath $Path1 -Force
$file2 = Get-Item -LiteralPath $Path2 -Force
if ($file1.Length -ne $file2.Length) {
return $false
}
$hash1 = (Get-FileHash -LiteralPath $path1 -Algorithm SHA1).Hash
$hash2 = (Get-FileHash -LiteralPath $path2 -Algorithm SHA1).Hash
$hash1 -eq $hash2
}
function NewFileSystemCopyInfo([string]$srcPath, [string]$dstPath) {
[PSCustomObject]@{SrcFileName = $srcPath; DstFileName = $dstPath}
}
function ExpandFileSourceSpec([string]$srcRelPath, [string]$dstRelPath) {
$srcPath = Join-Path $templateAbsolutePath $srcRelPath
$dstPath = Join-Path $destinationAbsolutePath $dstRelPath
if ($srcRelPath.IndexOfAny([char[]]('*', '?')) -lt 0) {
# No wildcard spec in srcRelPath so return info on single file.
# Also, if dstRelPath is empty, then use source rel path.
if (!$dstRelPath) {
$dstPath = Join-Path $destinationAbsolutePath $srcRelPath
}
return NewFileSystemCopyInfo $srcPath $dstPath
}
# Prepare parameter values for call to Get-ChildItem to get list of files based on wildcard spec.
$gciParams = @{}
$parent = Split-Path $srcPath -Parent
$leaf = Split-Path $srcPath -Leaf
$gciParams['LiteralPath'] = $parent
$gciParams['File'] = $true
if ($leaf -eq '**') {
$gciParams['Recurse'] = $true
}
else {
if ($leaf.IndexOfAny([char[]]('*', '?')) -ge 0) {
$gciParams['Filter'] = $leaf
}
$leaf = Split-Path $parent -Leaf
if ($leaf -eq '**') {
$parent = Split-Path $parent -Parent
$gciParams['LiteralPath'] = $parent
$gciParams['Recurse'] = $true
}
}