-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathPSDotFiles.psm1
1839 lines (1513 loc) · 70 KB
/
PSDotFiles.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
# See the help for Set-StrictMode for what this enables
Set-StrictMode -Version 3.0
$DefaultGlobalIgnorePaths = @(
'.stow-local-ignore'
)
Function Get-DotFiles {
<#
.SYNOPSIS
Enumerates dotfiles components
.DESCRIPTION
Enumerates the available dotfiles components, where each component is represented by a top-level folder in the folder specified by the $DotFilesPath variable or the -Path parameter.
For each component a Component object is returned which specifies the component's basic details, availability, installation state, and other configuration settings.
.PARAMETER AllowNestedSymlinks
Toggles allowing directory symlinks to destinations outside of the source component path earlier in the path hierarchy.
This overrides any default specified in $DotFilesAllowNestedSymlinks. If neither is specified the default is disabled.
.PARAMETER Autodetect
Toggles automatic detection of available components without any metadata.
This overrides any default specified in $DotFilesAutodetect. If neither is specified the default is disabled.
.PARAMETER Path
Use the specified directory as the dotfiles directory.
This overrides any default specified in $DotFilesPath.
.EXAMPLE
Get-DotFiles
Enumerates all available dotfiles components and returns a collection of Component objects representing the status of each.
.EXAMPLE
Get-DotFiles -Autodetect
Enumerates all available dotfiles components, attempting automatic detection of those that lack a metadata file.
.LINK
https://github.com/ralish/PSDotFiles
#>
[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseSingularNouns', '')]
[CmdletBinding(ConfirmImpact = 'Low', SupportsShouldProcess)]
[OutputType([Void], [Component[]])]
Param(
[String]$Path,
[Switch]$Autodetect,
[Switch]$AllowNestedSymlinks
)
Initialize-PSDotFiles @PSBoundParameters
return (Get-DotFilesInternal @PSBoundParameters).ToArray()
}
Function Install-DotFiles {
<#
.SYNOPSIS
Installs dotfiles components
.DESCRIPTION
Installs all available dotfiles components, or the nominated subset provided via a collection of Component objects as previously returned by the Get-DotFiles cmdlet.
For each installed component a Component object is returned which specifies the component's basic details, availability, installation state, and other configuration settings.
.PARAMETER AllowNestedSymlinks
Toggles allowing directory symlinks to destinations outside of the source component path earlier in the path hierarchy.
This overrides any default specified in $DotFilesAllowNestedSymlinks. If neither is specified the default is disabled.
.PARAMETER Autodetect
Toggles automatic detection of available components without any metadata.
This overrides any default specified in $DotFilesAutodetect. If neither is specified the default is disabled.
.PARAMETER Components
A collection of Component objects to be installed as previously returned by Get-DotFiles.
Note that only the Component objects with an appropriate Availability state will be installed.
.PARAMETER Path
Use the specified directory as the dotfiles directory.
This overrides any default specified in $DotFilesPath.
.EXAMPLE
Install-DotFiles
Installs all available dotfiles components and returns a collection of Component objects representing the status of each.
.EXAMPLE
Get-DotFiles | ? Name -in git, vim | Install-DotFiles
Installs only the git and vim dotfiles components, as provided by a filtered set of the components returned by Get-DotFiles.
.LINK
https://github.com/ralish/PSDotFiles
#>
[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseSingularNouns', '')]
[CmdletBinding(DefaultParameterSetName = 'Retrieve', ConfirmImpact = 'Low', SupportsShouldProcess)]
[OutputType([Void], [Component[]])]
Param(
[Parameter(ParameterSetName = 'Retrieve')]
[String]$Path,
[Parameter(ParameterSetName = 'Retrieve')]
[Switch]$Autodetect,
[Parameter(ParameterSetName = 'Pipeline', Mandatory, ValueFromPipeline)]
[AllowEmptyCollection()]
[Component[]]$Components,
[Switch]$AllowNestedSymlinks
)
Begin {
Initialize-PSDotFiles @PSBoundParameters
if (!($IsAdministrator -or $IsWin10DevMode)) {
if ($WhatIfPreference) {
Write-Warning -Message 'Missing privileges to create symlinks but ignoring due to -WhatIf.'
} else {
Write-Warning -Message 'We appear to be running under a user account without permission to create symlinks.'
Write-Warning -Message 'To fix this perform one of the following:'
Write-Warning -Message '- Run as an elevated user (ie. with Administrator privileges)'
Write-Warning -Message "- If you're on Windows 10 Creators Update or newer enable Developer Mode"
throw 'Unable to run Install-DotFiles as missing privileges to create symlinks.'
}
}
$WriteProgressParams = @{
Activity = 'Installing dotfiles components'
}
$Processed = [Collections.Generic.List[Component]]::new()
if ($PSCmdlet.ParameterSetName -eq 'Retrieve') {
Write-Progress @WriteProgressParams -Status 'Running Get-DotFiles'
$Components = Get-DotFilesInternal @PSBoundParameters -ProgressId 1
}
}
Process {
[Component[]]$ToInstall = $Components | Where-Object Availability -In ([Availability]::Available, [Availability]::AlwaysInstall)
# Required as we're in strict mode. If filtering on the component
# availability returns no results then $ToInstall will be null and the
# Count property cannot be referenced.
if (!$ToInstall) {
return
}
for ($Index = 0; $Index -lt $ToInstall.Count; $Index++) {
$Component = $ToInstall[$Index]
$WriteProgressParams['Status'] = 'Installing {0}' -f $Component.Name
if ($PSCmdlet.ParameterSetName -eq 'Retrieve') {
$WriteProgressParams['PercentComplete'] = $Index / $ToInstall.Count * 100
}
Write-Progress @WriteProgressParams
Write-Debug -Message ('[{0}] Source directory is: {1}' -f $Component.Name, $Component.SourcePath)
Write-Debug -Message ('[{0}] Installation path is: {1}' -f $Component.Name, $Component.InstallPath)
$Parameters = @{
Component = $Component
SourceDirectories = $Component.SourcePath
}
if (!($PSCmdlet.ShouldProcess($Component.Name, 'Install'))) {
$Parameters['Simulate'] = $true
}
$Results = [Collections.Generic.List[Boolean]]::new()
$Result = Install-DotFilesComponentDirectory @Parameters
$Results.AddRange($Result)
$Component.State = Get-ComponentInstallResult -Results $Results
$Processed.Add($Component)
}
}
End {
Write-Progress @WriteProgressParams -Completed
return $Processed.ToArray()
}
}
Function Remove-DotFiles {
<#
.SYNOPSIS
Removes dotfiles components
.DESCRIPTION
Removes all installed dotfiles components, or the nominated subset provided via a collection of Component objects as previously returned by the Get-DotFiles cmdlet.
For each removed component a Component object is returned which specifies the component's basic details, availability, installation state, and other configuration settings.
.PARAMETER AllowNestedSymlinks
Toggles allowing directory symlinks to destinations outside of the source component path earlier in the path hierarchy.
This overrides any default specified in $DotFilesAllowNestedSymlinks. If neither is specified the default is disabled.
.PARAMETER Autodetect
Toggles automatic detection of available components without any metadata.
This overrides any default specified in $DotFilesAutodetect. If neither is specified the default is disabled.
.PARAMETER Components
A collection of Component objects to be removed as previously returned by Get-DotFiles.
Note that only the Component objects with an appropriate Installed state will be removed.
.PARAMETER Path
Use the specified directory as the dotfiles directory.
This overrides any default specified in $DotFilesPath.
.EXAMPLE
Remove-DotFiles
Removes all installed dotfiles components and returns a collection of Component objects representing the status of each.
.EXAMPLE
Get-DotFiles | ? Name -in git, vim | Remove-DotFiles
Removes only the git and vim dotfiles components, as provided by a filtered set of the components returned by Get-DotFiles.
.LINK
https://github.com/ralish/PSDotFiles
#>
[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseSingularNouns', '')]
[CmdletBinding(DefaultParameterSetName = 'Retrieve', ConfirmImpact = 'Low', SupportsShouldProcess)]
[OutputType([Void], [Component[]])]
Param(
[Parameter(ParameterSetName = 'Retrieve')]
[String]$Path,
[Parameter(ParameterSetName = 'Retrieve')]
[Switch]$Autodetect,
[Parameter(ParameterSetName = 'Pipeline', Mandatory, ValueFromPipeline)]
[AllowEmptyCollection()]
[Component[]]$Components,
[Switch]$AllowNestedSymlinks
)
Begin {
Initialize-PSDotFiles @PSBoundParameters
$WriteProgressParams = @{
Activity = 'Removing dotfiles components'
}
$Processed = [Collections.Generic.List[Component]]::new()
if ($PSCmdlet.ParameterSetName -eq 'Retrieve') {
Write-Progress @WriteProgressParams -Status 'Running Get-DotFiles'
$Components = Get-DotFilesInternal @PSBoundParameters -ProgressId 1
}
}
Process {
[Component[]]$ToRemove = $Components | Where-Object State -In ([InstallState]::Installed, [InstallState]::PartialInstall)
# Required as we're in strict mode. If filtering on the component state
# returns no results then $ToRemove will be null and the Count property
# cannot be referenced.
if (!$ToRemove) {
return
}
for ($Index = 0; $Index -lt $ToRemove.Count; $Index++) {
$Component = $ToRemove[$Index]
$WriteProgressParams['Status'] = 'Removing {0}' -f $Component.Name
if ($PSCmdlet.ParameterSetName -eq 'Retrieve') {
$WriteProgressParams['PercentComplete'] = $Index / $ToRemove.Count * 100
}
Write-Progress @WriteProgressParams
Write-Debug -Message ('[{0}] Source directory is: {1}' -f $Component.Name, $Component.SourcePath)
Write-Debug -Message ('[{0}] Installation path is: {1}' -f $Component.Name, $Component.InstallPath)
$Parameters = @{
Component = $Component
SourceDirectories = $Component.SourcePath
}
if (!($PSCmdlet.ShouldProcess($Component.Name, 'Remove'))) {
$Parameters['Simulate'] = $true
}
$Results = [Collections.Generic.List[Boolean]]::new()
$Result = Remove-DotFilesComponentDirectory @Parameters
$Results.AddRange($Result)
$Component.State = Get-ComponentInstallResult -Results $Results -Removal
$Processed.Add($Component)
}
}
End {
Write-Progress @WriteProgressParams -Completed
return $Processed.ToArray()
}
}
Function Get-DotFilesInternal {
[CmdletBinding(SupportsShouldProcess)]
[OutputType([Object[]])]
Param(
[String]$Path,
[Switch]$Autodetect,
[Switch]$AllowNestedSymlinks,
[Int]$ProgressId = 0
)
$WriteProgressParams = @{
Id = $ProgressId
Activity = 'Getting dotfiles components'
}
Write-Progress @WriteProgressParams -Status 'Enumerating components' -PercentComplete 0
$Components = [Collections.Generic.List[Component]]::new()
$Directories = @(Get-ChildItem -Path $DotFilesPath -Directory)
for ($Index = 0; $Index -lt $Directories.Count; $Index++) {
$Directory = $Directories[$Index]
$WriteProgressParams['Status'] = 'Retrieving: {0}' -f $Directory.Name
$WriteProgressParams['PercentComplete'] = $Index / $Directories.Count * 100
Write-Progress @WriteProgressParams
$Component = Get-DotFilesComponent -Directory $Directory
if ($Component.Availability -in ([Availability]::Available, [Availability]::AlwaysInstall)) {
$Results = [Collections.Generic.List[Boolean]]::new()
$Result = Install-DotFilesComponentDirectory -Component $Component -SourceDirectories $Component.SourcePath -Verify
$Results.AddRange($Result)
$Component.State = Get-ComponentInstallResult -Results $Results
}
$Components.Add($Component)
}
Write-Progress @WriteProgressParams -Completed
if (!$Components) {
Write-Warning -Message 'Get-DotFiles returned no results. Are you sure your $DotFilesPath is set correctly?'
}
return , $Components
}
Function Initialize-PSDotFiles {
[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSAvoidGlobalVars', '')]
[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSShouldProcess', '')]
[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseSingularNouns', '')]
[CmdletBinding(SupportsShouldProcess)]
[OutputType([Void])]
Param(
[String]$Path,
[Switch]$Autodetect,
[Switch]$AllowNestedSymlinks
)
if ($Path) {
$Script:DotFilesPath = Test-DotFilesPath -Path $Path
if (!$Script:DotFilesPath) {
throw "The provided dotfiles path is either not a directory or it can't be accessed."
}
} elseif (Get-Variable -Name 'DotFilesPath' -Scope Global -ErrorAction Ignore) {
$Script:DotFilesPath = Test-DotFilesPath -Path $Global:DotFilesPath
if (!$Script:DotFilesPath) {
throw "The default dotfiles path (`$DotFilesPath) is either not a directory or it can't be accessed."
}
} else {
throw 'No dotfiles path was provided and the default path ($DotFilesPath) has not been configured.'
}
Write-Verbose -Message ('dotfiles directory: {0}' -f $DotFilesPath)
if (Get-Variable -Name 'DotFilesSkipMetadataSchemaChecks' -Scope Global -ErrorAction Ignore) {
$Script:SkipMetadataSchemaChecks = $Global:DotFilesSkipMetadataSchemaChecks
} else {
$Script:SkipMetadataSchemaChecks = $false
}
if (!$SkipMetadataSchemaChecks) {
$MetadataSchemaPath = Join-Path -Path $PSScriptRoot -ChildPath 'Metadata.xsd'
$Script:MetadataSchema = New-Object -TypeName 'Xml.Schema.XmlSchemaSet'
$null = $MetadataSchema.Add($null, (Get-Item -Path $MetadataSchemaPath))
# Implied on the first validation but do so now to ensure it's sane
$MetadataSchema.Compile()
Write-Debug -Message ('Metadata schema: {0}' -f $MetadataSchemaPath)
} else {
Write-Warning -Message 'Skipping validation of metadata files against XML schema.'
}
$Script:GlobalMetadataPath = Join-Path -Path $PSScriptRoot -ChildPath 'metadata'
Write-Debug -Message ('Global metadata: {0}' -f $GlobalMetadataPath)
$Script:DotFilesMetadataPath = Join-Path -Path $DotFilesPath -ChildPath 'metadata'
Write-Debug -Message ('Dotfiles metadata: {0}' -f $DotFilesMetadataPath)
if ($PSBoundParameters.ContainsKey('Autodetect')) {
$Script:DotFilesAutodetect = $Autodetect
} elseif (Get-Variable -Name 'DotFilesAutodetect' -Scope Global -ErrorAction Ignore) {
$Script:DotFilesAutodetect = $Global:DotFilesAutodetect
} else {
$Script:DotFilesAutodetect = $false
}
Write-Verbose -Message ('Automatic component detection: {0}' -f $DotFilesAutodetect)
if ($PSBoundParameters.ContainsKey('AllowNestedSymlinks')) {
$Script:NestedSymlinks = $AllowNestedSymlinks
} elseif (Get-Variable -Name 'DotFilesAllowNestedSymlinks' -Scope Global -ErrorAction Ignore) {
$Script:NestedSymlinks = $Global:DotFilesAllowNestedSymlinks
} else {
$Script:NestedSymlinks = $false
}
Write-Verbose -Message ('Nested symlinks permitted: {0}' -f $NestedSymlinks)
if (Get-Variable -Name 'DotFilesGlobalIgnorePaths' -Scope Global -ErrorAction Ignore) {
$Script:GlobalIgnorePaths = $Global:DotFilesGlobalIgnorePaths
} else {
$Script:GlobalIgnorePaths = $DefaultGlobalIgnorePaths
}
Write-Verbose -Message ('Global ignore paths: {0}' -f [String]::Join(', ', $GlobalIgnorePaths))
# Cache these results for usage later
$Script:IsAdministrator = Test-IsAdministrator
$Script:IsAppxCompatNeeded = Test-IsAppxCompatNeeded
$Script:IsMkLinkNeeded = Test-IsMkLinkNeeded
$Script:IsPowerShellCore = Test-IsPowerShellCore
$Script:IsWin10DevMode = Test-IsWin10DevMode
$Script:RefreshInstalledPrograms = $true
}
Function Initialize-DotFilesComponent {
[CmdletBinding()]
[OutputType([Component])]
Param(
[Parameter(ParameterSetName = 'New', Mandatory)]
[String]$Name,
[Parameter(ParameterSetName = 'Override', Mandatory)]
[Component]$Component,
[Parameter(ParameterSetName = 'New')]
[Parameter(ParameterSetName = 'Override', Mandatory)]
[Xml]$Metadata
)
# Ensures XML methods are always available
if (!$Metadata) {
$Metadata = New-Object -TypeName 'Xml.XmlDocument'
}
# Create the component if we're not overriding
if ($PSCmdlet.ParameterSetName -eq 'New') {
$Component = [Component]::new($Name, $DotFilesPath)
} else {
$Name = $Component.Name
}
# Set the friendly name if one was provided
if ($Metadata.SelectSingleNode('//Component/FriendlyName')) {
$Component.FriendlyName = $Metadata.Component.Friendlyname
}
# Append any base path to the source path
if ($Metadata.SelectSingleNode('//Component/BasePath')) {
$Component.SourcePath = Join-Path -Path $Component.SourcePath -ChildPath $Metadata.Component.BasePath
}
# Configure ignore paths
if ($Metadata.SelectSingleNode('//Component/IgnorePaths')) {
foreach ($Path in $Metadata.Component.IgnorePaths.IgnorePath) {
$Component.IgnorePaths += $Path
}
}
# Configure additional paths
if ($Metadata.SelectSingleNode('//Component/AdditionalPaths')) {
foreach ($Path in $Metadata.Component.AdditionalPaths.AdditionalPath) {
$Component.AdditionalPaths[$Path.source] += @($Path.TargetPath.symlink)
}
}
# Configure rename paths
if ($Metadata.SelectSingleNode('//Component/RenamePaths')) {
foreach ($Path in $Metadata.Component.RenamePaths.RenamePath) {
$Component.RenamePaths[$Path.source] = $Path.symlink
}
}
# Configure symlink hiding
if ($Metadata.SelectSingleNode('//Component/InstallPath/HideSymlinks')) {
if ($Metadata.Component.InstallPath.HideSymlinks -eq 'true') {
$Component.HideSymlinks = $true
}
}
# Determine the detection method
if ($Metadata.SelectSingleNode('//Component/Detection')) {
$DetectionMethod = $Metadata.Component.Detection.Method
} elseif ($PSCmdlet.ParameterSetName -eq 'New') {
$DetectionMethod = 'Automatic'
} else {
$DetectionMethod = $false
}
# Run component detection
if ($DetectionMethod -eq 'Automatic') {
$Parameters = @{
Name = $Name
RegularExpression = $false
CaseSensitive = $false
}
if ($Metadata.SelectSingleNode('//Component/Detection/MatchRegEx')) {
if ($Metadata.Component.Detection.MatchRegEx -eq 'true') {
$Parameters['RegularExpression'] = $true
}
}
if ($Metadata.SelectSingleNode('//Component/Detection/MatchCase')) {
if ($Metadata.Component.Detection.MatchCase -eq 'true') {
$Parameters['CaseSensitive'] = $true
}
}
if ($Metadata.SelectSingleNode('//Component/Detection/MatchPattern')) {
$Parameters['Pattern'] = $Metadata.Component.Detection.MatchPattern
}
$MatchingPrograms = Find-DotFilesComponent @Parameters
if ($MatchingPrograms) {
$NumMatchingPrograms = ($MatchingPrograms | Measure-Object).Count
if ($NumMatchingPrograms -ge 1) {
if ($NumMatchingPrograms -gt 1) {
Write-Warning -Message ('[{0}] Automatic detection found {1} matching programs.' -f $Name, $NumMatchingPrograms)
}
$Component.Availability = [Availability]::Available
if (!$Component.FriendlyName -and $MatchingPrograms.Name) {
$Component.FriendlyName = [String]::Join(', ', ($MatchingPrograms.Name | Where-Object { ![String]::IsNullOrWhiteSpace($_) } | Sort-Object ))
}
} else {
Write-Error -Message ('[{0}] Automatic detection found {1} matching programs.' -f $Name, $NumMatchingPrograms)
}
} else {
$Component.Availability = [Availability]::Unavailable
}
} elseif ($DetectionMethod -eq 'FindInPath') {
if ($Metadata.SelectSingleNode('//Component/Detection/FindInPath')) {
$FindBinary = $Metadata.Component.Detection.FindInPath
} else {
$FindBinary = $Component.Name
}
if (Get-Command -Name $FindBinary -ErrorAction Ignore) {
$Component.Availability = [Availability]::Available
} else {
$Component.Availability = [Availability]::Unavailable
}
} elseif ($DetectionMethod -eq 'PathExists') {
if (Test-Path -Path $Metadata.Component.Detection.PathExists) {
$Component.Availability = [Availability]::Available
} else {
$Component.Availability = [Availability]::Unavailable
}
} elseif ($DetectionMethod -eq 'Static') {
$Availability = $Metadata.Component.Detection.Availability
$Component.Availability = [Availability]::$Availability
}
# Set the default installation path initially
if ($PSCmdlet.ParameterSetName -eq 'New') {
$Component.InstallPath = [Environment]::GetFolderPath('UserProfile')
}
# Configure install path
if ($Metadata.SelectSingleNode('//Component/InstallPath')) {
$SpecialFolder = $false
$Destination = $false
# Are we installing to a special folder?
if ($Metadata.SelectSingleNode('//Component/InstallPath/SpecialFolder')) {
$SpecialFolder = $Metadata.Component.InstallPath.SpecialFolder
}
# Are we installing to a custom destination?
if ($Metadata.SelectSingleNode('//Component/InstallPath/Destination')) {
$Destination = $Metadata.Component.InstallPath.Destination
}
# Determine the installation path
if ($SpecialFolder -and $Destination) {
if (!([IO.Path]::IsPathRooted($Destination))) {
$InstallPath = Join-Path -Path ([Environment]::GetFolderPath($SpecialFolder)) -ChildPath $Destination
if (Test-Path -Path $InstallPath -PathType Container -IsValid) {
$Component.InstallPath = $InstallPath
} else {
Write-Error -Message ('[{0}] The destination path for symlinking is invalid: {1}' -f $Name, $InstallPath)
}
} else {
Write-Error -Message ('[{0}] The destination path for symlinking is not a relative path: {1}' -f $Name, $Destination)
}
} elseif (!$SpecialFolder -and $Destination) {
if ([IO.Path]::IsPathRooted($Destination)) {
if (Test-Path -Path $Destination -PathType Container -IsValid) {
$Component.InstallPath = $Destination
} else {
Write-Error -Message ('[{0}] The destination path for symlinking is invalid: {1}' -f $Name, $Destination)
}
} else {
Write-Error -Message ('[{0}] The destination path for symlinking is not an absolute path: {1}' -f $Name, $Destination)
}
} elseif ($SpecialFolder -and !$Destination) {
$Component.InstallPath = [Environment]::GetFolderPath($SpecialFolder)
}
}
return $Component
}
Function Install-DotFilesComponentDirectory {
[CmdletBinding(DefaultParameterSetName = 'Install')]
[OutputType([Object[]])]
Param(
[Parameter(Mandatory)]
[Component]$Component,
[Parameter(Mandatory)]
[IO.DirectoryInfo[]]$SourceDirectories,
[Parameter(ParameterSetName = 'Simulate')]
[Switch]$Simulate,
[Parameter(ParameterSetName = 'Verify')]
[Switch]$Verify
)
# Beware: This function is called recursively!
$Name = $Component.Name
$SourcePath = $Component.SourcePath
$InstallPath = $Component.InstallPath
$Results = [Collections.Generic.List[Boolean]]::new()
foreach ($SourceDirectory in $SourceDirectories) {
# Check if we're operating on the top-level directory of a component or
# have recursed into a subdirectory. If the latter, we need the
# relative path from the top-level directory so we can adjust the
# target installation directory appropriately. Further, subdirectories
# may be ignored by an <IgnorePaths> configuration, so also check this
# before proceeding further.
if ($SourceDirectory.FullName -eq $SourcePath.FullName) {
$ComponentRootDir = $true
$TargetDirectory = $InstallPath
# We need to check the source directory does actually exist. There
# are some edge cases where this may not be the case, with a common
# case being an invalid BasePath setting.
$SourceDirectory = Get-Item -Path $SourcePath.FullName -Force -ErrorAction Ignore
if ($SourceDirectory -isnot [IO.DirectoryInfo]) {
$Results.Add($false)
if ($PSCmdlet.ParameterSetName -ne 'Install') {
Write-Error -Message ('[{0}] Unable to retrieve source directory: {1}' -f $Name, $SourcePath.FullName)
}
continue
}
} else {
$ComponentRootDir = $false
$SourceDirectoryRelative = $SourceDirectory.FullName.Substring($SourcePath.FullName.Length + 1)
if ($SourceDirectoryRelative -in $GlobalIgnorePaths -or
$SourceDirectoryRelative -in $Component.IgnorePaths) {
Write-Debug -Message ('[{0}] Ignoring directory: {1}' -f $Name, $SourceDirectoryRelative)
continue
}
$TargetDirectory = Join-Path -Path $InstallPath -ChildPath $SourceDirectoryRelative
}
# We've got the directory source and target paths and have confirmed
# the source path is not ignored. Start by trying to retrieve any item
# which may already exist at the target path.
try {
$ExistingTarget = Get-Item -Path $TargetDirectory -Force -ErrorAction Stop
} catch {
# Missing directory on a verification means the component is not or
# partially installed.
if ($Verify) {
$Results.Add($false)
continue
}
# Missing directory on a simulation means this directory will be
# symlinked on install.
if ($Simulate) {
Write-Verbose -Message ('[{0}] Will symlink directory: "{1}" -> "{2}"' -f $Name, $TargetDirectory, $SourceDirectory.FullName)
$Results.Add($true)
continue
}
# When operating on the top-level directory of a component we need
# to check that the parent directory of the target path actually
# exists. If not, we'll create it.
if ($ComponentRootDir) {
$TargetParentDirectory = Split-Path -Path $TargetDirectory -Parent
if (!(Test-Path -Path $TargetParentDirectory -PathType Container)) {
Write-Verbose -Message ('[{0}] Creating parent directory for target symlink: {1}' -f $Name, $TargetParentDirectory)
$null = New-Item -Path $TargetParentDirectory -ItemType Directory
}
}
# Nothing exists at the target path so we can create the directory
# symlink.
Write-Verbose -Message ('[{0}] Symlinking directory: "{1}" -> "{2}"' -f $Name, $TargetDirectory, $SourceDirectory.FullName)
$Symlink = New-Symlink -Path $TargetDirectory -Target $SourceDirectory.FullName
# Set the hidden and system attributes if requested
if ($Component.HideSymlinks) {
$Attributes = Set-SymlinkAttributes -Symlink $Symlink
if (!$Attributes) {
$Results.Add($false)
Write-Error -Message ('[{0}] Unable to set Hidden and System attributes on directory symlink: "{1}"' -f $Name, $TargetDirectory)
continue
}
}
$Results.Add($true)
continue
}
# We found an item but it's not a directory! The user will need to fix
# this conflict.
if ($ExistingTarget -isnot [IO.DirectoryInfo]) {
$Results.Add($false)
if ($PSCmdlet.ParameterSetName -ne 'Install') {
Write-Error -Message ('[{0}] Expected a directory but found a file: {1}' -f $Name, $TargetDirectory)
}
continue
}
# We found a symbolic link. Either:
# - It points where we expect -> nothing to do
# - It points somewhere else -> recurse into it (NestedSymlinks)
# - It points somewhere unexpected -> unable to symlink this path
if ($ExistingTarget.LinkType -eq 'SymbolicLink') {
$SymlinkTarget = Get-SymlinkTarget -Symlink $ExistingTarget
if ($SourceDirectory.FullName -eq $SymlinkTarget) {
$Results.Add($true)
Write-Debug -Message ('[{0}] Valid directory symlink: "{1}" -> "{2}"' -f $Name, $TargetDirectory, $SymlinkTarget)
continue
} elseif ($NestedSymlinks) {
Write-Debug -Message ('[{0}] Recursing into existing symlink with target: "{1}" -> "{2}"' -f $Name, $TargetDirectory, $SymlinkTarget)
} else {
$Results.Add($false)
if ($PSCmdlet.ParameterSetName -ne 'Install') {
Write-Error -Message ('[{0}] Found a directory symlink to an unexpected target: "{1}" -> "{2}"' -f $Name, $TargetDirectory, $SymlinkTarget)
}
continue
}
}
# We found a regular directory or a directory symlink to an unexpected
# target. As we can't create a directory symlink recurse into the
# source path and attempt to symlink each file into the target.
$NextFiles = Get-ChildItem -Path $SourceDirectory.FullName -File -Force
if ($NextFiles) {
if ($Verify) {
$Result = Install-DotFilesComponentFile -Component $Component -SourceFiles $NextFiles -Verify
} elseif ($Simulate) {
$Result = Install-DotFilesComponentFile -Component $Component -SourceFiles $NextFiles -Simulate
} else {
$Result = Install-DotFilesComponentFile -Component $Component -SourceFiles $NextFiles
}
$Results.AddRange($Result)
}
# As above, but now symlink each of the directories
$NextDirectories = Get-ChildItem -Path $SourceDirectory.FullName -Directory -Force
if ($NextDirectories) {
if ($Verify) {
$Result = Install-DotFilesComponentDirectory -Component $Component -SourceDirectories $NextDirectories -Verify
} elseif ($Simulate) {
$Result = Install-DotFilesComponentDirectory -Component $Component -SourceDirectories $NextDirectories -Simulate
} else {
$Result = Install-DotFilesComponentDirectory -Component $Component -SourceDirectories $NextDirectories
}
$Results.AddRange($Result)
}
# Warn if there were no items in the source path and we couldn't
# symlink the directory.
if (!$NextFiles -and !$NextDirectories) {
Write-Warning -Message ('[{0}] Unable to symlink empty directory as target exists: "{1}" -> "{2}"' -f $Name, $TargetDirectory, $SymlinkTarget)
}
}
return , $Results
}
Function Install-DotFilesComponentFile {
[CmdletBinding(DefaultParameterSetName = 'Install')]
[OutputType([Object[]])]
Param(
[Parameter(Mandatory)]
[Component]$Component,
[Parameter(Mandatory)]
[IO.FileInfo[]]$SourceFiles,
[Parameter(ParameterSetName = 'Simulate')]
[Switch]$Simulate,
[Parameter(ParameterSetName = 'Verify')]
[Switch]$Verify
)
# Beware: This function is called recursively!
$Name = $Component.Name
$SourcePath = $Component.SourcePath
$InstallPath = $Component.InstallPath
$Results = [Collections.Generic.List[Boolean]]::new()
foreach ($SourceFile in $SourceFiles) {
# We always need to determine the relative path of files from the
# top-level directory of the component so we can adjust the target
# installation path appropriately.
$SourceFileRelative = $SourceFile.FullName.Substring($SourcePath.FullName.Length + 1)
# Like directories, files may also be ignored by an <IgnorePaths>
# configuration.
if ($SourceFileRelative -in $GlobalIgnorePaths -or
$SourceFileRelative -in $Component.IgnorePaths) {
Write-Debug -Message ('[{0}] Ignoring file: {1}' -f $Name, $SourceFileRelative)
continue
}
Write-Debug -Message ('[{0}] Processing file: {1}' -f $Name, $SourceFileRelative)
$TargetFiles = [Collections.Generic.List[String]]::new()
# Determine additional target symlink paths
if ($Component.AdditionalPaths.ContainsKey($SourceFileRelative)) {
foreach ($AdditionalPath in $Component.AdditionalPaths[$SourceFileRelative]) {
$TargetFile = Join-Path -Path $InstallPath -ChildPath $AdditionalPath
Write-Debug -Message ('[{0}] Adding additional path: {1}' -f $Name, $TargetFile)
$TargetFiles.Add($TargetFile)
}
}
# Determine the target symlink with reference to any defined renamed
# path.
if ($Component.RenamePaths.ContainsKey($SourceFileRelative)) {
$TargetFile = Join-Path -Path $InstallPath -ChildPath $Component.RenamePaths[$SourceFileRelative]
Write-Debug -Message ('[{0}] Using renamed target path: {1}' -f $Name, $TargetFile)
} else {
$TargetFile = Join-Path -Path $InstallPath -ChildPath $SourceFileRelative
Write-Debug -Message ('[{0}] Using target path: {1}' -f $Name, $TargetFile)
}
$TargetFiles.Add($TargetFile)
foreach ($TargetFile in $TargetFiles) {
# We've got the file source and target paths and have confirmed the
# source path is not ignored. Start by trying to retrieve any item
# which may already exist at the target path.
try {
$ExistingTarget = Get-Item -Path $TargetFile -Force -ErrorAction Stop
} catch {
# Missing file on a verification means the component is not or
# partially installed.
if ($Verify) {
$Results.Add($false)
continue
}
# Missing file on a simulation means this file will be
# symlinked on install.
if ($Simulate) {
Write-Verbose -Message ('[{0}] Will symlink file: "{1}" -> "{2}"' -f $Name, $TargetFile, $SourceFile.FullName)
$Results.Add($true)
continue
}
# Nothing exists at the target path so we can create the file
# symlink.
Write-Verbose -Message ('[{0}] Symlinking file: "{1}" -> "{2}"' -f $Name, $TargetFile, $SourceFile.FullName)
$Symlink = New-Symlink -Path $TargetFile -Target $SourceFile.FullName
# Set the hidden and system attributes if requested
if ($Component.HideSymlinks) {
$Attributes = Set-SymlinkAttributes -Symlink $Symlink
if (!$Attributes) {
$Results.Add($true)
Write-Error -Message ('[{0}] Unable to set Hidden and System attributes on file symlink: "{1}"' -f $Name, $TargetFile)
continue
}
}
$Results.Add($true)
continue
}
# We found an item but it's not a file! The user will need to fix
# this conflict.
if ($ExistingTarget -isnot [IO.FileInfo]) {
$Results.Add($false)
if ($PSCmdlet.ParameterSetName -ne 'Install') {
Write-Error -Message ('[{0}] Expected a file but found a directory: {1}' -f $Name, $TargetFile)
}
continue
}
# We found a file. We can't replace it so this is another conflict
# for the user.
if ($ExistingTarget.LinkType -ne 'SymbolicLink') {
$Results.Add($false)
if ($PSCmdlet.ParameterSetName -ne 'Install') {
Write-Error -Message ('[{0}] Unable to create symlink as a file already exists: {1}' -f $Name, $TargetFile)
}
continue
}
# We found a symbolic link. Either it points where we expect it to
# and all is well, or it points somewhere unexpected, and the user
# will need to investigate why that is.
$SymlinkTarget = Get-SymlinkTarget -Symlink $ExistingTarget
if ($SourceFile.FullName -eq $SymlinkTarget) {
$Results.Add($true)
Write-Debug -Message ('[{0}] Valid file symlink: "{1}" -> "{2}"' -f $Name, $TargetFile, $SymlinkTarget)
} else {
$Results.Add($false)
if ($PSCmdlet.ParameterSetName -ne 'Install') {
Write-Error -Message ('[{0}] Found a file symlink to an unexpected target: "{1}" -> "{2}"' -f $Name, $TargetFile, $SymlinkTarget)
}
}
}
}
return , $Results
}
Function Remove-DotFilesComponentDirectory {
[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', '')]
[CmdletBinding()]
[OutputType([Object[]])]
Param(
[Parameter(Mandatory)]
[Component]$Component,
[Parameter(Mandatory)]
[IO.DirectoryInfo[]]$SourceDirectories,
[Switch]$Simulate
)
# Beware: This function is called recursively!
$Name = $Component.Name
$SourcePath = $Component.SourcePath
$InstallPath = $Component.InstallPath
$Results = [Collections.Generic.List[Boolean]]::new()
foreach ($SourceDirectory in $SourceDirectories) {
# Check if we're operating on the top-level directory of a component or
# have recursed into a subdirectory. If the latter, we need the
# relative path from the top-level directory so we can adjust the
# target installation directory appropriately. Further, subdirectories
# may be ignored by an <IgnorePaths> configuration, so also check this
# before proceeding further.
if ($SourceDirectory.FullName -eq $SourcePath.FullName) {
$TargetDirectory = $InstallPath
# We need to check the source directory does actually exist. There
# are some edge cases where this may not be the case, with a common
# case being an invalid BasePath setting.
$SourceDirectory = Get-Item -Path $SourcePath.FullName -Force -ErrorAction Ignore
if ($SourceDirectory -isnot [IO.DirectoryInfo]) {
$Results.Add($false)
Write-Error -Message ('[{0}] Unable to retrieve source directory: {1}' -f $Name, $SourcePath.FullName)
continue
}
} else {
$SourceDirectoryRelative = $SourceDirectory.FullName.Substring($SourcePath.FullName.Length + 1)