-
Notifications
You must be signed in to change notification settings - Fork 4
/
pecan-waffle.psm1
1467 lines (1231 loc) · 50.8 KB
/
pecan-waffle.psm1
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
[cmdletbinding()]
param()
# all types here must be strings
$global:pecanwafflesettings = New-Object -TypeName psobject -Property @{
TempDir = ([System.IO.DirectoryInfo]('{0}\pecan-waffle\temp\projtemplates' -f $env:LOCALAPPDATA)).FullName
TempRemoteDir = ([System.IO.DirectoryInfo]('{0}\pecan-waffle\remote\templates' -f $env:LOCALAPPDATA)).FullName
Templates = @()
TemplateSources = @()
GitSources = @()
EnableAddLocalSourceOnLoad = $true
RobocopySystemPath = ('{0}\robocopy.exe' -f [System.Environment]::SystemDirectory)
RobocopyDownloadUrl = 'https://dl.dropboxusercontent.com/u/40134810/SideWaffle/tools/robocopy.exe'
LastTempDir = ''
}
function InternalOverrideSettingsFromEnv{
[cmdletbinding()]
param(
[Parameter(Position=0)]
[object[]]$settings = ($global:PSBuildSettings),
[Parameter(Position=1)]
[string]$prefix
)
process{
foreach($settingsObj in $settings){
if($settingsObj -eq $null){
continue
}
$settingNames = $null
if($settingsObj -is [hashtable]){
$settingNames = $settingsObj.Keys
}
else{
$settingNames = ($settingsObj | Get-Member -MemberType NoteProperty | Select-Object -ExpandProperty Name)
}
foreach($name in ($settingNames.Clone())){
$fullname = ('{0}{1}' -f $prefix,$name)
if(Test-Path "env:$fullname"){
'Updating setting [{0}] to [{1}]' -f ($settingsObj.$name),((get-childitem "env:$fullname").Value) | Write-Verbose
$value = ((get-childitem "env:$fullname").Value)
if(-not [string]::IsNullOrWhiteSpace($value)){
$settingsObj.$name = ((get-childitem "env:$fullname").Value)
}
}
}
}
}
}
InternalOverrideSettingsFromEnv -settings $global:pecanwafflesettings -prefix 'PW'
# todo: enable overriding settings via env var
function InternalGet-ScriptDirectory{
split-path (((Get-Variable MyInvocation -Scope 1).Value).MyCommand.Path)
}
function Get-PecanWaffleVersion{
param()
process{
New-Object -TypeName 'system.version' -ArgumentList '0.0.23.0'
}
}
function Invoke-CommandString{
[cmdletbinding()]
param(
[Parameter(Mandatory=$true,Position=0,ValueFromPipeline=$true)]
[string[]]$command,
[Parameter(Position=1)]
$commandArgs,
$ignoreErrors,
[switch]$disableCommandQuoting
)
process{
foreach($cmdToExec in $command){
'Executing command [{0}]' -f $cmdToExec | Write-Verbose
# write it to a .cmd file
$destPath = "$([System.IO.Path]::GetTempFileName()).cmd"
if(Test-Path $destPath){Remove-Item $destPath|Out-Null}
try{
$commandstr = $cmdToExec
if(-not $disableCommandQuoting -and $commandstr.Contains(' ') -and (-not ($commandstr -match '''.*''|".*"' ))){
$commandstr = ('"{0}"' -f $commandstr)
}
'{0} {1}' -f $commandstr, ($commandArgs -join ' ') | Set-Content -Path $destPath | Out-Null
$actualCmd = ('"{0}"' -f $destPath)
cmd.exe /D /C $actualCmd
if(-not $ignoreErrors -and ($LASTEXITCODE -ne 0)){
$msg = ('The command [{0}] exited with code [{1}]' -f $commandstr, $LASTEXITCODE)
throw $msg
}
}
finally{
if(Test-Path $destPath){Remove-Item $destPath -ErrorAction SilentlyContinue |Out-Null}
}
}
}
}
function Copy-ItemRobocopy{
[cmdletbinding()]
param(
[Parameter(Position=0,Mandatory=$true)]
[ValidateNotNullOrEmpty()]
[string]$sourcePath,
[Parameter(Position=1,Mandatory=$true)]
[ValidateNotNullOrEmpty()]
[string]$destPath,
[Parameter(Position=2)]
[string[]]$fileNames,
[Parameter(Position=3)]
[switch]$move,
[Parameter(Position=4)]
[switch]$ignoreErrors,
[Parameter(Position=5)]
[string[]]$foldersToSkip,
[Parameter(Position=6)]
[string[]]$filesToSkip,
[Parameter(Position=7)]
[switch]$recurse,
[Parameter(Position=8)]
[string]$roboCopyOptions = ('/R:1 /W:2 /XA:SH /XJ /FFT'),
[Parameter(Position=9)]
[string]$roboLoggingOptions = ('/NFL /NDL /NJS /NJH /NP /NS /NC')
)
process{
[System.Text.StringBuilder]$sb = New-Object -TypeName 'System.Text.StringBuilder'
$sb.AppendFormat('"{0}" ',$sourcePath.Trim('"').Trim("'").TrimEnd("\")) | out-null
$sb.AppendFormat('"{0}" ',$destPath.Trim('"').Trim("'").TrimEnd("\")) | out-null
if($fileNames -eq $null){
$fileNames = ,'*.*'
}
if( ($fileNames -ne $null) -and ($fileNames.Count -gt 0)){
foreach($file in $fileNames){
$sb.AppendFormat('"{0}" ',$file)
}
}
if($move){
$sb.Append('/MOVE ')
}
if(-not [string]::IsNullOrWhiteSpace($roboLoggingOptions)){
$sb.AppendFormat('{0} ',$roboLoggingOptions) | out-null
}
if($recurse){
$sb.Append('/E ') | Out-Null
}
if(-not [string]::IsNullOrWhiteSpace($roboCopyOptions)){
$sb.AppendFormat('{0} ',$roboCopyOptions) | out-null
}
if( ($foldersToSkip -ne $null) -and ($foldersToSkip.Length -gt 0)){
$sb.Append('/XD ') | out-null
foreach($folder in $foldersToSkip){
$sb.AppendFormat('"{0}" ',$folder) | out-null
}
}
if( ($filesToSkip -ne $null) -and ($filesToSkip.Length -gt 0)){
$sb.Append('/XF ') | out-null
foreach($file in $filesToSkip){
$sb.AppendFormat('"{0}" ',$file) | out-null
}
}
'Copying files with command [{0} {1}]' -f (Get-Robocopy),$sb.ToString() | write-verbose
$copyArgs = @{
'command' = (Get-Robocopy)
'commandArgs'=$sb.ToString()
}
# TODO: Not sure how to properly handle errors, always ignore
$copyArgs['ignoreErrors']=$true
Invoke-CommandString @copyArgs
}
}
function Get-Robocopy{
[cmdletbinding()]
param(
[Parameter(Position=0)]
[string]$roboCopyPath = ($global:pecanwafflesettings.RobocopySystemPath),
[Parameter(Position=1)]
[string]$roboCopyDownloadUrl = ($global:pecanwafflesettings.RobocopyDownloadUrl)
)
process{
if(Test-Path $roboCopyPath){
# return the path
$roboCopyPath
}
else{
# download it to temp if it's not already there
$roboCopyTemp = (Join-Path $global:pecanwafflesettings.TempDir 'robocopy.exe')
if(-not (Test-Path $roboCopyTemp)){
# download it now
'Downloading robocopy.exe from [{0}] to [{1}]' -f $roboCopyDownloadUrl,$roboCopyTemp | Write-Verbose
(New-Object 'System.Net.WebClient').DownloadFile($roboCopyDownloadUrl,$roboCopyTemp) | write-verbose
}
if(-not (Test-Path $roboCopyPath)){
throw ('Unable to find/download robocopy from [{0}] to [{1}]' -f $roboCopyDownloadUrl,$roboCopyTemp)
}
# return the path
$roboCopyPath
}
}
}
<#
.SYNOPSIS
This will download and import nuget-powershell (https://github.com/ligershark/nuget-powershell),
which is a PowerShell utility that can be used to easily download nuget packages.
If nuget-powershell is already loaded then the download/import will be skipped.
.PARAMETER nugetPsMinModVersion
The minimum version to import
#>
function InternalImport-NuGetPowershell{
[cmdletbinding()]
param(
$nugetPsMinModVersion = '0.2.1.1'
)
process{
# see if nuget-powershell is available and load if not
$nugetpsloaded = $false
if((get-command Get-NuGetPackage -ErrorAction SilentlyContinue)){
# check the module to ensure we have the correct version
$currentversion = (Get-Module -Name nuget-powershell).Version
if( ($currentversion -ne $null) -and ($currentversion.CompareTo([version]::Parse($nugetPsMinModVersion)) -ge 0 )){
$nugetpsloaded = $true
}
}
if(!$nugetpsloaded){
(new-object Net.WebClient).DownloadString("https://raw.githubusercontent.com/ligershark/nuget-powershell/master/get-nugetps.ps1") | iex
}
# check to see that it was loaded
if((get-command Get-NuGetPackage -ErrorAction SilentlyContinue)){
$nugetpsloaded = $true
}
if(-not $nugetpsloaded){
throw ('Unable to load nuget-powershell, unknown error')
}
}
}
function Ensure-DirectoryExists{
param([Parameter(Position=0)][System.IO.DirectoryInfo]$path)
process{
if($path -ne $null){
if(-not (Test-Path $path.FullName)){
New-Item -Path $path.FullName -ItemType Directory
}
}
}
}
#http://jongurgul.com/blog/get-stringhash-get-filehash/
Function InternalGet-StringHash{
[cmdletbinding()]
param(
[String] $text,
$HashName = "MD5"
)
process{
$sb = New-Object System.Text.StringBuilder
[System.Security.Cryptography.HashAlgorithm]::Create($HashName).ComputeHash([System.Text.Encoding]::UTF8.GetBytes($text))|%{
[Void]$sb.Append($_.ToString("x2"))
}
$sb.ToString()
}
}
function Internal-HasProperty{
[cmdletbinding()]
param(
[Parameter(Position=0,Mandatory=$true)]
[ValidateNotNull()]
$inputObject,
[Parameter(Position=1,Mandatory=$true)]
[ValidateNotNullOrEmpty()]
[string]$propertyName
)
process{
[bool]($inputObject.PSObject.Properties.name -match ('^{0}$' -f $propertyName))
}
}
function Internal-AddProperty{
[cmdletbinding()]
param(
[Parameter(Position=1,Mandatory=$true)]
[ValidateNotNull()]
$inputObject,
[Parameter(Position=2,Mandatory=$true)]
[ValidateNotNullOrEmpty()]
[string]$propertyName,
[Parameter(Position=3,Mandatory=$true)]
$propertyValue
)
process{
$inputObject | Add-Member -MemberType NoteProperty -Name $propertyName -Value $propertyValue
}
}
function Get-NewTempDir{
[cmdletbinding()]
param()
process{
Ensure-DirectoryExists -path $global:pecanwafflesettings.TempDir | Out-Null
[System.IO.DirectoryInfo]$newpath = (Join-Path ($global:pecanwafflesettings.TempDir) ([datetime]::UtcNow.Ticks))
if([string]::Equals($newpath,$global:pecanwafflesettings.LastTempDir,[System.StringComparison]::OrdinalIgnoreCase)){
Start-Sleep -Milliseconds 1
$newpath = (Join-Path ($global:pecanwafflesettings.TempDir) ([datetime]::UtcNow.Ticks))
}
$global:pecanwafflesettings.LastTempDir = $newpath
New-Item -ItemType Directory -Path ($newpath.FullName) | out-null
# return the fullpath
$newpath.FullName
}
}
# Items related to template sources
function Add-PWTemplateSource{
[cmdletbinding()]
param(
[Parameter(Position=0,Mandatory=$true)]
[ValidateNotNullOrEmpty()]
[string]$path,
[Parameter(Position=1)]
$branch = 'master',
[Parameter(Position=2)]
[System.IO.DirectoryInfo]$localfolder = ($global:pecanwafflesettings.TempRemoteDir),
[Parameter(Position=3)]
[string]$repoName
)
process{
$isGit = $false
$isLocal = $false
$isZip = $false
$path = $path.Trim()
[string]$pathlastfour = $null
if($path.Length -gt 4){
$pathlastfour = $path.Substring($path.Length -4)
}
if([string]::Compare('.git',$pathlastfour,[System.StringComparison]::OrdinalIgnoreCase) -eq 0){
$isGit = $true
}
elseif([string]::Compare('.zip',$pathlastfour,[System.StringComparison]::OrdinalIgnoreCase) -eq 0){
$isZip = $true
throw ('.zip extension not supported for Add-PWTemplateSource yet')
}
else{
$isLocal = $true
}
[System.IO.DirectoryInfo]$localInstallFolder = $null
if($isLocal){
if(-not [System.IO.Path]::IsPathRooted($path)){
$localInstallFolder = ([System.IO.DirectoryInfo](Join-Path $pwd $path)).FullName
}
else{
$localInstallFolder = ([System.IO.DirectoryInfo]($path)).FullName
}
}
Ensure-DirectoryExists -path $localfolder.FullName
if($isGit){
if([string]::IsNullOrWhiteSpace($repoName)){
$repoName = ( '{0}-{1}' -f (InternalGet-RepoName -url $path),(InternalGet-StringHash -text $path))
}
[System.IO.DirectoryInfo]$localInstallFolder = (Join-Path $localfolder.FullName $repoName)
if(-not (Test-Path $localInstallFolder.FullName)){
InternalAdd-GitFolder -url $path -repoName $repoName -branch $branch -localfolder $localfolder.FullName
}
}
if($localInstallFolder -eq $null){
throw ('localInstallFolder is null')
}
$files = (Get-ChildItem -Path $localInstallFolder.FullName 'pw-templateinfo*.ps1' -Recurse -File -Exclude '.git','node_modules','bower_components' -ErrorAction SilentlyContinue)
foreach($file in $files){
& ([System.IO.FileInfo]$file.FullName)
}
$templateSource = New-Object -TypeName psobject -Property @{
LocalFolder = $repoFolder.FullName
Url = $path
}
$global:pecanwafflesettings.TemplateSources += $templateSource
}
}
Set-Alias Add-TemplateSource Add-PWTemplateSource
function InternalGet-RepoName{
[cmdletbinding()]
param(
[Parameter(Position=1,Mandatory=$true)]
[ValidateNotNullOrEmpty()]
[string]$url
)
process{
$startIndex = $url.LastIndexOf('/')
[string]$repoName = [datetime]::UtcNow.Ticks
if($startIndex -gt 0){
$repoName = $url.Substring($startIndex +1).Replace('.git','')
}
$repoName
}
}
function InternalAdd-GitFolder{
[cmdletbinding()]
param(
[Parameter(Position=1,Mandatory=$true)]
[string]$url,
[Parameter(Position=2)]
[string]$repoName,
[Parameter(Position=3,ParameterSetName='git')]
[string]$branch = 'master',
[Parameter(Position=4)]
[System.IO.DirectoryInfo]$localfolder = ($global:pecanwafflesettings.TempRemoteDir)
)
begin{
# TODO: Improve to only call if not loaded
InternalImport-NuGetPowershell
}
process{
if([string]::IsNullOrWhiteSpace($repoName)){
$repoName = InternalGet-RepoName -url $url
}
$oldPath = Get-Location
[System.IO.DirectoryInfo]$repoFolder = (Join-Path $localfolder.FullName $repoName)
$path =([System.IO.DirectoryInfo]$repoFolder).FullName
try{
Ensure-DirectoryExists -path $localfolder.FullName
Set-Location $localfolder
if(-not (Test-Path $repoFolder.FullName)){
Execute-CommandString "git clone $url --branch $branch --single-branch $repoName" -ignoreExitCode
}
}
finally{
Set-Location $oldPath
}
$templateSource = New-Object -TypeName psobject -Property @{
LocalFolder = $repoFolder.FullName
Url = $url
}
$global:pecanwafflesettings.GitSources += $templateSource
}
}
function Get-PWTemplates{
[cmdletbinding()]
param()
process{
$Global:pecanwafflesettings.Templates | Select-Object -Property Name,Type | Sort-Object -Property Type,Name,Description
}
}
Set-Alias Show-Templates Get-PWTemplates -Description 'obsolete: This was added for back compat and will be removed soon'
function Update-PWRemoteTemplates{
[cmdletbinding()]
param()
begin{
InternalImport-NuGetPowershell
}
process{
foreach($ts in $global:pecanwafflesettings.GitSources){
if( -not ([string]::IsNullOrWhiteSpace($ts.Url)) -and (Test-Path $ts.LocalFolder)){
$oldpath = Get-Location
try{
Set-Location $ts.LocalFolder
Execute-CommandString "git pull" -ignoreExitCode
}
finally{
Set-Location $oldpath
}
}
}
}
}
Set-Alias Update-RemoteTemplates Update-PWRemoteTemplates -Description 'obsolete: This was added for back compat and will be removed soon'
# Item Related to Templates Below
function TemplateAdd-SourceFile{
[cmdletbinding()]
param(
[Parameter(Position=1,Mandatory=$true)]
[ValidateNotNull()]
[string[]]$sourceFiles,
[Parameter(Position=2)]
[ScriptBlock[]]$destFiles,
[Parameter(Position=3,Mandatory=$true,ValueFromPipeline=$true)]
[ValidateNotNull()]
$templateInfo
)
process{
if( ($destFiles -ne $null) -and ($destFiles.Count -gt 0) ){
if($sourceFiles.Count -ne $destFiles.Count){
throw ('Number of source files [{0}] is not equal number of dest files [{1}]',$sourceFiles.Count,$destFiles.Count)
}
}
if(-not (Internal-HasProperty -inputObject $templateInfo -propertyName 'SourceFiles')){
Internal-AddProperty -inputObject $templateInfo -propertyName 'SourceFiles' -propertyValue @()
}
for($i = 0;$i -lt $sourceFiles.Count;$i++){
[ScriptBlock]$dest = $null
if( ($destFiles -ne $null) -and ($destFiles.Count -gt 0) ){
$dest = $destFiles[$i]
}
if($dest -eq $null){
[string]$str = '"{0}"' -f $sourceFiles[$i]
$dest = [ScriptBlock]::Create($str)
}
$templateInfo.SourceFiles += New-Object -TypeName psobject -Property @{
# SourceFile = [System.IO.FileInfo]($sourceFiles[$i])
SourceFile = [string]($sourceFiles[$i])
DestFile = [ScriptBlock]$dest
}
}
}
}
set-alias Add-SourceFile TemplateAdd-SourceFile
function TemplateAdd-Replacement{
[cmdletbinding()]
param(
[Parameter(Position=0,Mandatory=$true)]
$templateInfo,
[Parameter(Position=1,Mandatory=$true)]
[string]$replaceKey,
[Parameter(Position=2,Mandatory=$true)]
[ScriptBlock]$replaceValue,
[Parameter(Position=3)]
[ScriptBlock]$defaultValue,
[Parameter(Position=4)]
[string]$rootDir,
[Parameter(Position=5)]
[string[]]$include = @('*'),
[Parameter(Position=6)]
[string[]]$exclude
)
process{
# make sure it has the properties member, if not add it
if(-not (Internal-HasProperty -inputObject $templateInfo -propertyName 'Replacements')){
Internal-AddProperty -inputObject $templateInfo -propertyName 'Replacements' -propertyValue @()
}
$templateInfo.Replacements += New-Object -TypeName psobject -Property @{
ReplaceKey = $replaceKey
ReplaceValue = $replaceValue
DefaultValue = $defaultValue
RootDir = $rootDir
Include = $include
Exclude = $exclude
}
}
}
Set-Alias replaceitem TemplateAdd-Replacement
function TemplateAdd-ReplacementObject{
param(
[Parameter(Position=1,Mandatory=$true)]
[object[][]]$replacementObject,
[Parameter(Position=2,Mandatory=$true,ValueFromPipeline=$true)]
$templateInfo,
[Parameter(Position=3)]
[string]$rootDir,
[Parameter(Position=4)]
[string[]]$include = @('*'),
[Parameter(Position=5)]
[string[]]$exclude
)
process{
$global:foo = $replacementObject
foreach($repobj in $replacementObject){
# add a replacement for each
if($repobj.length -lt 2){
throw ('replacement object requires at least two items, ReplaceKey and ReplaceValue. Num elements in replacement [{0}]{1}' -f $repobj.length,(Get-PSCallStack|Out-String))
}
$repKey = $repobj[0]
$repValue = $repobj[1]
$defaultValue = [ScriptBlock]$null
if($repobj.length -gt 2){
$defaultValue = $repobj[2]
}
# see if include/exclude is passed in via replacementObject first
if( ($repobj.Length -ge 3) -and ($repobj[3] -ne $null)){
$include = $repobj[3]
}
if( ($repobj.Length -ge 4) -and ($repobj[4] -ne $null)){
$exclude = $repobj[4]
}
$addargs = @{
TemplateInfo = $templateInfo
ReplaceKey = $repKey
ReplaceValue = $repValue
DefaultValue = $defaultValue
RootDir = $rootDir
Include = $include
Exclude = $exclude
}
TemplateAdd-Replacement @addargs
}
}
}
set-alias replace TemplateAdd-ReplacementObject
function TemplateUpdate-FileName{
[cmdletbinding()]
param(
[Parameter(Position=1,Mandatory=$true,ValueFromPipeline = $true)]
$templateInfo,
[Parameter(Position=2,Mandatory=$true)]
[ValidateNotNullOrEmpty()]
[string]$replaceKey,
[Parameter(Position=3,Mandatory=$true)]
[ValidateNotNullOrEmpty()]
[ScriptBlock]$replaceValue,
[Parameter(Position=4)]
[ScriptBlock]$defaultValue,
[Parameter(Position=5)]
[string[]]$include,
[Parameter(Position=6)]
[string[]]$exclude
)
process{
if(-not (Internal-HasProperty -inputObject $templateInfo -propertyName 'UpdateFilenames')){
Internal-AddProperty -inputObject $templateInfo -propertyName 'UpdateFilenames' -propertyValue @()
}
$templateInfo.UpdateFilenames += New-Object -TypeName psobject -Property @{
ReplaceKey = $replaceKey
ReplaceValue = $replaceValue
DefaultValue = $defaultValue
Include = $include
Exclude = $exclude
}
}
}
function TemplateUpdate-FilenameObject{
param(
[Parameter(Position=1,Mandatory=$true)]
[object[][]]$updateObject,
[Parameter(Position=2,Mandatory=$true,ValueFromPipeline = $true)]
$templateInfo
)
process{
foreach($upObj in $updateObject){
if($upObj -ne $null){
if($upObj.length -lt 2){
throw ('Update object requires at least two values but found [{0}] number of values' -f $upObj.length)
}
$defaultValue = [ScriptBlock]$null
if($upObj.length -ge 3){
$defaultValue = $upObj[2]
}
$updateArgs = @{
templateInfo = $templateInfo
replaceKey = ($upObj[0])
replaceValue = ($upObj[1])
defaultValue = $defaultValue
}
if( ($upObj.Length -ge 3) -and ($upObj[3] -ne $null)){
$updateArgs['include'] = $upObj[3]
}
if( ($upObj.Length -ge 4) -and ($upObj[4] -ne $null)){
$updateArgs['exclude'] = $upObj[4]
}
TemplateUpdate-FileName @updateArgs
}
}
}
}
# TODO: Change to Update-Path
Set-Alias Update-FileName TemplateUpdate-FilenameObject
function TemplateBefore-Install{
[cmdletbinding()]
param(
[Parameter(Position=1,Mandatory=$true)]
$templateInfo,
[Parameter(Position=2,Mandatory=$true)]
[ScriptBlock]$beforeInstall
)
process{
if(-not (Internal-HasProperty -inputObject $templateInfo -propertyName 'BeforeInstall')){
Internal-AddProperty -inputObject $templateInfo -propertyName 'BeforeInstall' -propertyValue $beforeInstall
}
else{
$templateInfo.BeforeInstall = $beforeInstall
}
}
}
Set-Alias beforeinstall TemplateBefore-Install
function TemplateAfter-Install{
[cmdletbinding()]
param(
[Parameter(Position=1,Mandatory=$true)]
$templateInfo,
[Parameter(Position=2,Mandatory=$true)]
[ScriptBlock]$afterInstall
)
process{
if(-not (Internal-HasProperty -inputObject $templateInfo -propertyName 'AfterInstall')){
Internal-AddProperty -inputObject $templateInfo -propertyName 'AfterInstall' -propertyValue $afterInstall
}
else{
$templateInfo.AfterInstall = $afterInstall
}
}
}
Set-Alias afterinstall TemplateAfter-Install
function TemplateExclude-File{
[cmdletbinding()]
param(
[Parameter(Position=1,Mandatory=$true)]
[ValidateNotNull()]
[string[]]$excludeFiles,
[Parameter(Position=2,Mandatory=$true,ValueFromPipeline=$true)]
$templateInfo
)
process{
if(-not (Internal-HasProperty -inputObject $templateInfo -propertyName 'ExcludeFiles')){
Internal-AddProperty -inputObject $templateInfo -propertyName 'ExcludeFiles' -propertyValue @()
}
$templateInfo.ExcludeFiles += $excludeFiles
}
}
Set-Alias Exclude-File TemplateExclude-File
function TemplateExclude-Folder{
[cmdletbinding()]
param(
[Parameter(Position=1,Mandatory=$true)]
[ValidateNotNull()]
[string[]]$excludeFolder,
[Parameter(Position=2,Mandatory=$true,ValueFromPipeline=$true)]
$templateInfo
)
process{
if(-not (Internal-HasProperty -inputObject $templateInfo -propertyName 'ExcludeFolder')){
Internal-AddProperty -inputObject $templateInfo -propertyName 'ExcludeFolder' -propertyValue @()
}
$templateInfo.ExcludeFolder += $excludeFolder
}
}
Set-Alias Exclude-Folder TemplateExclude-Folder
function Clear-PWTemplates{
[cmdletbinding()]
param()
process{
$global:pecanwafflesettings.Templates.Clear()
}
}
Set-Alias Clear-AllTemplates Clear-PWTemplates -Description 'obsolete: This was added for back compat and will be removed soon'
function TemplateSet-TemplateInfo{
[cmdletbinding()]
param(
[Parameter(Position=0,Mandatory=$true)]
[ValidateNotNull()]
$templateInfo,
[Parameter(Position=1)]
[System.IO.DirectoryInfo]$templateRoot,
# todo: rename this parameter
[Parameter(Position=3,ParameterSetName='git')]
[System.IO.DirectoryInfo]$localfolder = ($global:pecanwafflesettings.TempRemoteDir)
)
process{
if(-not (Internal-HasProperty -inputObject $templateInfo -propertyName 'TemplatePath')){
Internal-AddProperty -inputObject $templateInfo -propertyName 'TemplatePath' -propertyValue @()
$url = $templateInfo.SourceUri
if(-not [string]::IsNullOrWhiteSpace($url)){
# ensure folder is cloned locally
# TODO: allow override in template
$repoName = InternalGet-RepoName -url $url
$branch = 'master'
if(-not [string]::IsNullOrWhiteSpace($templateInfo.SourceRepoName)){
$repoName = $templateInfo.SourceRepoName
}
if(-not [string]::IsNullOrWhiteSpace($templateInfo.SourceBranch)){
$branch = $templateInfo.SourceBranch
}
[System.IO.DirectoryInfo]$repoFolder = (Join-Path $localfolder.FullName $repoName)
if(-not (Test-Path $repoFolder.FullName)){
# todo: register so that it can be updated later on via Update-RemoteTemplates
InternalAdd-GitFolder -url $url -repoName $repoName -branch $branch -localfolder $localfolder
}
[System.IO.DirectoryInfo]$pathToFolder = $repoFolder.FullName
if(-not [string]::IsNullOrWhiteSpace($templateInfo.ContentPath)){
$pathToFolder = (get-item (Join-Path $repoFolder.FullName $templateInfo.ContentPath)).FullName
}
$templateRoot = $pathToFolder.FullName
}
if($templateRoot -eq $null){
# root is the folder from the calling script
$templateRoot = ((Get-Item ($MyInvocation.PSCommandPath)).Directory.FullName)
}
$templateInfo.TemplatePath = $templateRoot
}
$global:pecanwafflesettings.Templates += $templateInfo
}
}
Set-Alias Set-TemplateInfo TemplateSet-TemplateInfo
function InternalGet-EvaluatedProperty{
[cmdletbinding()]
param(
[Parameter(Position=0,Mandatory=$true)]
[ScriptBlock]$expression,
[Parameter(Position=1)]
[hashtable]$properties,
[Parameter(Position=2)]
[hashtable]$extraProperties
)
process{
[hashtable]$allProps += $properties
if($allProps -eq $null){
$allProps = @{}
}
if($extraProperties -ne $null){
foreach($key in $extraProperties.Keys){
if(-not [string]::IsNullOrEmpty($extraProperties[$key])){
$allProps[$key]=$extraProperties[$key]
}
}
}
$scriptToExec = [ScriptBlock]::Create({$fargs=$args; foreach($f in $fargs.Keys){ New-Variable -Name $f -Value $fargs.$f };}.ToString() + (InternalGet-CreateStringFor -properties $allProps) + ';' + $expression.ToString())
$value = & ($scriptToExec) $allProps
# return the value
$value
}
}
function InternalGet-CreateStringFor{
[cmdletbinding()]
param(
[Parameter(Position=1,Mandatory=$true)]
[hashtable]$properties
)
process{
[System.Text.StringBuilder]$sb = New-Object -TypeName 'System.Text.StringBuilder'
$Sb.AppendLine('$p=@{}') | out-null
foreach($key in $properties.Keys){
$escapedkey = $key.ToString().Replace("'","''")
$escapedvalue = $properties[$key]
if(-not [string]::IsNullOrWhiteSpace($escapedvalue)){
$escapedvalue = $escapedvalue.ToString().Replace("'","''")
}
$str = ('$p[''{0}''] = ''{1}''' -f $escapedkey, $escapedvalue)
$sb.AppendLine($str) | Out-Null
}
# return the result
$sb.ToString()
}
}
function InternalGet-ReplacementValue{
[cmdletbinding()]
param(
[Parameter(Position=0,Mandatory=$true)]
[ValidateNotNull()]
$template,
[Parameter(Position=1,Mandatory=$true)]
[ValidateNotNullOrEmpty()]
[string]$replaceKey,
[Parameter(Position=2)]
[hashtable]$evaluatedProperties
)
process{
$replacement = ($template.Replacements| Where-Object {$_.ReplaceKey -eq $replaceKey} | Select-Object -First 1)
if($replacement -eq $null){
throw ('Did not find replacement with key [{0}]' -f $replaceKey)
}
$value = InternalGet-EvaluatedProperty -expression $replacement.ReplaceValue -properties $evaluatedProperties
if( ($value -eq $null) -or
($value -is [string] -and ([string]::IsNullOrWhiteSpace($value) ) ) ) {
if( ($replacement -ne $null) -and ($replacement.DefaultValue -ne $null)){
$value = InternalGet-EvaluatedProperty -expression $replacement.DefaultValue -properties $evaluatedProperties
}
}