-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinstall.ps1
More file actions
1062 lines (880 loc) · 33.3 KB
/
Copy pathinstall.ps1
File metadata and controls
1062 lines (880 loc) · 33.3 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
[CmdletBinding()]
param(
[switch]$DryRun,
[Alias('y')]
[switch]$Force,
[switch]$Minimal,
[switch]$CleanBackups,
[switch]$Sync,
[switch]$RestoreGitDefaults
)
Set-StrictMode -Version Latest
$ErrorActionPreference = 'Stop'
$ProgressPreference = 'SilentlyContinue'
function Write-Section {
param([string]$Message)
Write-Host "`n🪟 $Message" -ForegroundColor Cyan
}
function Write-Info {
param([string]$Message)
Write-Host " $Message" -ForegroundColor Gray
}
function Write-Success {
param([string]$Message)
Write-Host " ✅ $Message" -ForegroundColor Green
}
function Write-Highlight {
param([string]$Message)
Write-Host " ➜ $Message" -ForegroundColor Magenta
}
function Test-CommandExists {
param([string]$Name)
return [bool](Get-Command $Name -ErrorAction SilentlyContinue)
}
function Test-IsWindows {
return $env:OS -eq 'Windows_NT'
}
function Get-GitDefaults {
param([Parameter(Mandatory = $true)][string]$Path)
if (-not (Test-Path -LiteralPath $Path)) {
throw "Missing Git defaults manifest at $Path."
}
foreach ($line in Get-Content -LiteralPath $Path) {
$entry = $line.Trim()
if ([string]::IsNullOrWhiteSpace($entry) -or $entry.StartsWith('#')) {
continue
}
$separator = $entry.IndexOf('=')
if ($separator -lt 1) {
throw "Invalid Git defaults entry: $line"
}
[pscustomobject]@{
Key = $entry.Substring(0, $separator)
Value = $entry.Substring($separator + 1)
}
}
}
function Resolve-WindowsPackageEntry {
param(
[Parameter(Mandatory = $true)]
[object]$PackageEntry,
[Parameter(Mandatory = $true)]
[string]$Manager
)
if ($PackageEntry -is [string]) {
return [pscustomobject]@{
Name = $PackageEntry
Id = $PackageEntry
Source = if ($Manager -eq 'Winget') { 'winget' } else { $null }
}
}
$entry = if ($PackageEntry -is [hashtable]) { [pscustomobject]$PackageEntry } else { $PackageEntry }
$id = $entry.Id
if ([string]::IsNullOrWhiteSpace($id)) {
$id = $entry.PackageId
}
if ([string]::IsNullOrWhiteSpace($id)) {
$id = $entry.Name
}
$name = $entry.Name
if ([string]::IsNullOrWhiteSpace($name)) {
$name = $entry.DisplayName
}
if ([string]::IsNullOrWhiteSpace($name)) {
$name = $id
}
$source = $entry.Source
if ($Manager -eq 'Winget' -and [string]::IsNullOrWhiteSpace($source)) {
$source = 'winget'
}
return [pscustomobject]@{
Name = $name
Id = $id
Source = $source
}
}
function Format-WindowsPackageEntry {
param([object]$Package)
if ($null -eq $Package) {
return ''
}
if ([string]::IsNullOrWhiteSpace($Package.Source) -or $Package.Source -eq 'winget') {
return $Package.Name
}
return "$($Package.Name) [$($Package.Source):$($Package.Id)]"
}
function Ensure-ParentDirectory {
param([string]$Path)
$parent = Split-Path -Parent $Path
if (-not [string]::IsNullOrWhiteSpace($parent) -and -not (Test-Path $parent)) {
if ($DryRun) {
Write-Info "Would create $parent"
} else {
New-Item -ItemType Directory -Path $parent -Force | Out-Null
}
}
}
function Ensure-Directory {
param([string]$Path)
if ([string]::IsNullOrWhiteSpace($Path) -or (Test-Path -LiteralPath $Path)) {
return
}
if ($DryRun) {
Write-Info "Would create directory $Path"
} else {
New-Item -ItemType Directory -Path $Path -Force | Out-Null
}
}
function Get-GitConfigValues {
param([Parameter(Mandatory = $true)][string]$Key)
return @(
git config --global --get-all $Key 2>$null |
ForEach-Object { [string]$_ }
)
}
function Get-StateValues {
param(
[Parameter(Mandatory = $true)][object]$Section,
[Parameter(Mandatory = $true)][string]$Key
)
$property = $Section.PSObject.Properties[$Key]
if ($null -eq $property) {
return @()
}
return @($property.Value | ForEach-Object { [string]$_ })
}
function Test-StringSequence {
param(
[string[]]$Actual,
[string[]]$Expected
)
if ($Actual.Count -ne $Expected.Count) {
return $false
}
for ($index = 0; $index -lt $Actual.Count; $index += 1) {
if ($Actual[$index] -ne $Expected[$index]) {
return $false
}
}
return $true
}
function Save-GitConfigState {
param(
[Parameter(Mandatory = $true)][string]$DefaultsPath,
[Parameter(Mandatory = $true)][string]$IgnoreTarget,
[Parameter(Mandatory = $true)][string]$StatePath
)
if (-not (Test-CommandExists git) -or (Test-Path -LiteralPath $StatePath)) {
return
}
Ensure-Directory -Path (Split-Path -Parent $StatePath)
$snapshot = [ordered]@{}
$managed = [ordered]@{ 'core.excludesfile' = @($IgnoreTarget) }
$keys = @('core.excludesfile')
foreach ($default in Get-GitDefaults -Path $DefaultsPath) {
$keys += $default.Key
$managed[$default.Key] = @($default.Value)
}
foreach ($key in $keys) {
$snapshot[$key] = @(Get-GitConfigValues -Key $key)
}
[pscustomobject]@{
Version = 1
Snapshot = [pscustomobject]$snapshot
Managed = [pscustomobject]$managed
} | ConvertTo-Json -Depth 4 | Set-Content -LiteralPath $StatePath -Encoding utf8
}
function Restore-GitConfigState {
param([Parameter(Mandatory = $true)][string]$StatePath)
if (-not (Test-Path -LiteralPath $StatePath)) {
Write-Info 'No saved Git defaults found.'
return
}
if ($DryRun) {
Write-Info 'Would restore Git defaults managed by this installer.'
return
}
if (-not (Test-CommandExists git)) {
Write-Warning 'git not found; leaving installer-managed Git defaults in place.'
return
}
$state = Get-Content -LiteralPath $StatePath -Raw | ConvertFrom-Json
if ($state.Version -ne 1 -or $null -eq $state.Snapshot -or $null -eq $state.Managed) {
throw "Invalid Git defaults state at $StatePath."
}
$restoreFailed = $false
foreach ($managedProperty in $state.Managed.PSObject.Properties) {
$key = $managedProperty.Name
$expected = Get-StateValues -Section $state.Managed -Key $key
$current = Get-GitConfigValues -Key $key
if (-not (Test-StringSequence -Actual $current -Expected $expected)) {
Write-Warning "Keeping Git setting $key because it changed after installation."
$restoreFailed = $true
continue
}
git config --global --unset-all $key 2>$null
foreach ($value in Get-StateValues -Section $state.Snapshot -Key $key) {
git config --global --add $key $value
}
}
if (-not $restoreFailed) {
Remove-Item -LiteralPath $StatePath -Force
}
}
function Get-BackupPath {
param([string]$Path)
$timestamp = [DateTimeOffset]::UtcNow.ToString('yyyyMMddHHmmssfff')
$candidate = "$Path.bak.$timestamp"
$counter = 0
while (Test-Path -LiteralPath $candidate) {
$counter += 1
$candidate = "$Path.bak.$timestamp.$counter"
}
return $candidate
}
function Backup-Path {
param([string]$Path)
if (-not (Test-Path -LiteralPath $Path)) {
return
}
$backupPath = Get-BackupPath -Path $Path
if ($DryRun) {
Write-Highlight "Would back up $Path -> $backupPath"
} else {
Move-Item -LiteralPath $Path -Destination $backupPath
Write-Success "Backed up $Path -> $backupPath"
}
}
function Test-FileLikePath {
param([string]$Path)
if (-not (Test-Path -LiteralPath $Path)) {
return $false
}
return -not (Get-Item -LiteralPath $Path -Force).PSIsContainer
}
function Test-SameFileContent {
param(
[string]$Source,
[string]$Target
)
if (-not (Test-FileLikePath $Source) -or -not (Test-FileLikePath $Target)) {
return $false
}
$sourceHash = (Get-FileHash -LiteralPath $Source -Algorithm SHA256).Hash
$targetHash = (Get-FileHash -LiteralPath $Target -Algorithm SHA256).Hash
return $sourceHash -eq $targetHash
}
function Copy-WithBackup {
param(
[string]$Source,
[string]$Target
)
Ensure-ParentDirectory -Path $Target
if ((Test-Path -LiteralPath $Target) -and (Test-SameFileContent -Source $Source -Target $Target)) {
Write-Info "Already up to date: $Target"
return
}
if (Test-Path -LiteralPath $Target) {
Backup-Path -Path $Target
}
if ($DryRun) {
Write-Highlight "Would copy $Source -> $Target"
} else {
Copy-Item -LiteralPath $Source -Destination $Target -Force
Write-Success "Copied $Source -> $Target"
}
}
function Install-Profile {
param(
[string]$Source,
[string]$Target
)
Copy-WithBackup -Source $Source -Target $Target
}
function Install-ProfileShim {
param(
[string]$Target
)
Ensure-ParentDirectory -Path $Target
$shimContent = @'
# Managed by dotfiles.
# Keep this profile empty so the shared profile.ps1 loads once.
'@
if (Test-Path -LiteralPath $Target) {
$existing = Get-Content -LiteralPath $Target -Raw -ErrorAction SilentlyContinue
if (-not [string]::IsNullOrWhiteSpace($existing) -and $existing.Trim() -eq $shimContent.Trim()) {
Write-Info "Already up to date: $Target"
return
}
Backup-Path -Path $Target
}
if ($DryRun) {
Write-Highlight "Would write profile shim -> $Target"
} else {
Set-Content -LiteralPath $Target -Value $shimContent -NoNewline
Write-Success "Wrote profile shim -> $Target"
}
}
function Get-WindowsPowerShellProfileTargets {
$documentsRoot = [Environment]::GetFolderPath('MyDocuments')
$profileRoots = @(
(Join-Path $documentsRoot 'PowerShell')
(Join-Path $documentsRoot 'WindowsPowerShell')
) | Select-Object -Unique
$sharedTargets = @()
$hostTargets = @()
foreach ($profileRoot in $profileRoots) {
$sharedTargets += (Join-Path $profileRoot 'profile.ps1')
$hostTargets += (Join-Path $profileRoot 'Microsoft.PowerShell_profile.ps1')
}
return [pscustomobject]@{
Shared = @($sharedTargets | Select-Object -Unique)
Host = @($hostTargets | Select-Object -Unique)
}
}
function Install-GitIgnore {
param(
[string]$Source,
[string]$Target
)
Copy-WithBackup -Source $Source -Target $Target
if ($DryRun) {
Write-Info "Would configure git core.excludesfile -> $Target"
} elseif (Test-CommandExists git) {
git config --global core.excludesfile "$Target"
Write-Info "Configured git core.excludesfile -> $Target"
} else {
Write-Warning "git not found; skipping core.excludesfile configuration."
}
}
function Install-GitDefaults {
param([Parameter(Mandatory = $true)][string]$DefaultsPath)
if (-not (Test-CommandExists git)) {
Write-Warning "git not found; skipping global Git defaults."
return
}
Write-Section 'Git defaults'
$defaults = @(Get-GitDefaults -Path $DefaultsPath)
if ($DryRun) {
Write-Info "Would merge recommended Git defaults into global config."
return
}
foreach ($default in $defaults) {
git config --global $default.Key $default.Value
}
Write-Info "Merged recommended Git defaults into global config."
}
function Get-BackupFiles {
param([string]$RootPath)
if ([string]::IsNullOrWhiteSpace($RootPath) -or -not (Test-Path -LiteralPath $RootPath)) {
return @()
}
return @(Get-ChildItem -Path $RootPath -Filter '*.bak.*' -File -Force -ErrorAction SilentlyContinue)
}
function Remove-BackupFiles {
param([string]$RootPath)
$backups = @(Get-BackupFiles -RootPath $RootPath)
if ($backups.Count -eq 0) {
Write-Info "No backup files found in $RootPath."
return
}
Write-Section "Backup cleanup"
Write-Info "Found the following backup files:"
foreach ($backup in $backups) {
Write-Info " - $($backup.FullName)"
}
if ($DryRun) {
foreach ($backup in $backups) {
Write-Info "Would remove $($backup.FullName)"
}
Write-Info "Dry-run complete. No backup files were removed."
return
}
if ($Force) {
$confirm = 'y'
} else {
$confirm = Read-Host "Delete all of these backup files? [y/N]"
}
if ($confirm -match '^[Yy]$') {
foreach ($backup in $backups) {
Write-Info "Removing $($backup.FullName)"
Remove-Item -LiteralPath $backup.FullName -Force
}
Write-Info "Done cleaning up backups."
} else {
Write-Info "Skipped backup cleanup."
}
}
function Resolve-WindowsPackageManifestPath {
param(
[string[]]$EnvironmentVariables,
[string]$LocalPath,
[string]$SourcePath
)
foreach ($environmentVariable in $EnvironmentVariables) {
$environmentValue = [Environment]::GetEnvironmentVariable($environmentVariable)
if (-not [string]::IsNullOrWhiteSpace($environmentValue) -and (Test-Path -LiteralPath $environmentValue)) {
return $environmentValue
}
}
if (-not [string]::IsNullOrWhiteSpace($SourcePath) -and (Test-Path -LiteralPath $SourcePath)) {
return $SourcePath
}
if (-not [string]::IsNullOrWhiteSpace($LocalPath) -and (Test-Path -LiteralPath $LocalPath)) {
return $LocalPath
}
return $null
}
function Resolve-WindowsTerminalSettingsPath {
$packageRoots = @(
Join-Path $env:LOCALAPPDATA 'Packages\Microsoft.WindowsTerminal_8wekyb3d8bbwe\LocalState\settings.json'
Join-Path $env:LOCALAPPDATA 'Packages\Microsoft.WindowsTerminalPreview_8wekyb3d8bbwe\LocalState\settings.json'
)
foreach ($candidate in $packageRoots) {
if (Test-Path -LiteralPath $candidate) {
return $candidate
}
}
$packagesRoot = Join-Path $env:LOCALAPPDATA 'Packages'
if (Test-Path -LiteralPath $packagesRoot) {
$terminalRoots = @(Get-ChildItem -LiteralPath $packagesRoot -Directory -Filter 'Microsoft.WindowsTerminal*' -ErrorAction SilentlyContinue | Sort-Object Name)
foreach ($root in $terminalRoots) {
$candidate = Join-Path $root.FullName 'LocalState\settings.json'
if (Test-Path -LiteralPath $candidate) {
return $candidate
}
}
if ($terminalRoots.Count -gt 0) {
return (Join-Path $terminalRoots[0].FullName 'LocalState\settings.json')
}
}
return $packageRoots[0]
}
function Get-WindowsPackageManifestEntries {
$repoRoot = Split-Path -Parent $PSCommandPath
$windowsRoot = Join-Path $repoRoot 'windows'
$localRoot = Join-Path $HOME '.config\dotfiles\windows'
$manifestSpecs = @(
[pscustomobject]@{
Name = 'Core'
Env = @('DOTFILES_WINDOWS_PACKAGE_MANIFEST', 'DOTFILES_WINDOWS_PACKAGE_CORE_MANIFEST')
LocalPath = Join-Path $localRoot 'packages.psd1'
SourcePath = Join-Path $windowsRoot 'packages.psd1'
}
[pscustomobject]@{
Name = 'Optional'
Env = @('DOTFILES_WINDOWS_PACKAGE_OPTIONAL_MANIFEST')
LocalPath = Join-Path $localRoot 'packages.optional.psd1'
SourcePath = Join-Path $windowsRoot 'packages.optional.psd1'
}
[pscustomobject]@{
Name = 'Private'
Env = @('DOTFILES_WINDOWS_PACKAGE_PRIVATE_MANIFEST')
LocalPath = Join-Path $localRoot 'packages.private.psd1'
SourcePath = $null
}
)
$manifests = @()
foreach ($spec in $manifestSpecs) {
$resolvedPath = Resolve-WindowsPackageManifestPath -EnvironmentVariables $spec.Env -LocalPath $spec.LocalPath -SourcePath $spec.SourcePath
if ([string]::IsNullOrWhiteSpace($resolvedPath)) {
continue
}
try {
$data = Import-PowerShellDataFile -LiteralPath $resolvedPath
} catch {
Write-Warning "Unable to load $($spec.Name) package manifest: $resolvedPath"
continue
}
$manifests += [pscustomobject]@{
Name = $spec.Name
Path = $resolvedPath
Data = $data
}
}
return $manifests
}
function Test-WingetPackageInstalled {
param(
[Parameter(Mandatory = $true)][string]$PackageId,
[string]$Source = 'winget'
)
$sourceName = if ([string]::IsNullOrWhiteSpace($Source)) { 'winget' } else { $Source }
if ($sourceName -eq 'winget') {
$installedIds = Get-WingetInstalledPackageIds
if (@($installedIds) -contains $PackageId) {
return $true
}
}
if (-not (Test-CommandExists winget)) {
return $false
}
& winget list --id $PackageId --exact --source $sourceName --accept-source-agreements *> $null
if ($LASTEXITCODE -eq 0) {
if ($sourceName -eq 'winget') {
$installedIds = Get-WingetInstalledPackageIds
$script:WingetInstalledPackageIds = @($installedIds + $PackageId | Sort-Object -Unique)
}
return $true
}
return $false
}
function Get-WingetInstalledPackageIds {
if (-not (Test-CommandExists winget)) {
return @()
}
if (Get-Variable -Scope Script -Name WingetInstalledPackageIds -ErrorAction SilentlyContinue) {
return $script:WingetInstalledPackageIds
}
$tempFile = Join-Path $env:TEMP "dotfiles-winget-export-$PID.json"
if (Test-Path -LiteralPath $tempFile) {
Remove-Item -LiteralPath $tempFile -Force
}
& winget export -o $tempFile --source winget --include-versions --accept-source-agreements *> $null
if ($LASTEXITCODE -ne 0 -or -not (Test-Path -LiteralPath $tempFile)) {
$script:WingetInstalledPackageIds = @()
return @()
}
try {
$export = Get-Content -LiteralPath $tempFile -Raw | ConvertFrom-Json
$ids = $export.Sources.Packages.PackageIdentifier | Where-Object { -not [string]::IsNullOrWhiteSpace($_) }
$script:WingetInstalledPackageIds = @($ids | Sort-Object -Unique)
} catch {
$script:WingetInstalledPackageIds = @()
} finally {
Remove-Item -LiteralPath $tempFile -Force -ErrorAction SilentlyContinue
}
return $script:WingetInstalledPackageIds
}
function Get-NpmGlobalRoot {
if (-not (Test-CommandExists npm)) {
return $null
}
$root = & npm root -g 2>$null
if ($LASTEXITCODE -ne 0 -or [string]::IsNullOrWhiteSpace($root)) {
return $null
}
return $root.Trim()
}
function Resolve-TrafficMonitorConfigTargets {
$targets = @(
(Join-Path $HOME 'AppData\Local\TrafficMonitor\config.ini')
(Join-Path $env:LOCALAPPDATA 'Microsoft\WinGet\Packages\zhongyang219.TrafficMonitor.Full_Microsoft.Winget.Source_8wekyb3d8bbwe\TrafficMonitor\config.ini')
)
return @($targets | Select-Object -Unique)
}
function Test-NpmGlobalPackageInstalled {
param([Parameter(Mandatory = $true)][string]$PackageName)
$root = Get-NpmGlobalRoot
if ([string]::IsNullOrWhiteSpace($root)) {
return $false
}
$packagePath = if ($PackageName -like '@*/*') {
Join-Path $root ($PackageName -replace '/', '\')
} else {
Join-Path $root $PackageName
}
return Test-Path -LiteralPath $packagePath
}
function Get-WindowsPackageComparison {
param([array]$Manifests)
if (-not $Manifests -or $Manifests.Count -eq 0) {
return @()
}
$comparison = @()
foreach ($manifest in $Manifests) {
foreach ($section in @(
[pscustomobject]@{ Manager = 'Winget'; Packages = @($manifest.Data.Winget) }
[pscustomobject]@{ Manager = 'NpmGlobal'; Packages = @($manifest.Data.NpmGlobal) }
)) {
foreach ($packageEntry in $section.Packages) {
$package = Resolve-WindowsPackageEntry -PackageEntry $packageEntry -Manager $section.Manager
$installed = $false
switch ($section.Manager) {
'Winget' { $installed = Test-WingetPackageInstalled -PackageId $package.Id -Source $package.Source }
'NpmGlobal' { $installed = Test-NpmGlobalPackageInstalled -PackageName $package.Name }
}
$comparison += [pscustomobject]@{
Manifest = $manifest.Name
Manager = $section.Manager
Package = (Format-WindowsPackageEntry -Package $package)
Installed = [bool]$installed
}
}
}
}
return $comparison
}
function Install-WindowsPackageBaseline {
param(
[array]$Manifests,
[string[]]$ManifestNames
)
if (-not $Manifests -or $Manifests.Count -eq 0) {
Write-Warning 'No curated Windows package manifest found.'
return
}
$selectedManifests = @($Manifests | Where-Object { -not $ManifestNames -or ($ManifestNames -contains $_.Name) })
if ($selectedManifests.Count -eq 0) {
Write-Info 'No matching package manifests selected.'
return
}
Write-Section 'Curated package install'
foreach ($manifest in $selectedManifests) {
Write-Info "$($manifest.Name):"
foreach ($section in @(
[pscustomobject]@{ Manager = 'Winget'; Command = 'winget'; Packages = @($manifest.Data.Winget) }
[pscustomobject]@{ Manager = 'NpmGlobal'; Command = 'npm'; Packages = @($manifest.Data.NpmGlobal) }
)) {
if ($section.Packages.Count -eq 0) {
Write-Info " $($section.Manager): nothing to install."
continue
}
if (-not (Test-CommandExists $section.Command)) {
Write-Warning " $($section.Manager) not available; skipping."
continue
}
Write-Info " $($section.Manager):"
foreach ($packageEntry in $section.Packages) {
$package = Resolve-WindowsPackageEntry -PackageEntry $packageEntry -Manager $section.Manager
$installed = $false
switch ($section.Manager) {
'Winget' { $installed = Test-WingetPackageInstalled -PackageId $package.Id -Source $package.Source }
'NpmGlobal' { $installed = Test-NpmGlobalPackageInstalled -PackageName $package.Name }
}
if ($installed) {
Write-Success " already installed: $(Format-WindowsPackageEntry -Package $package)"
continue
}
if ($DryRun) {
Write-Info " would install: $(Format-WindowsPackageEntry -Package $package)"
continue
}
switch ($section.Manager) {
'Winget' {
$wingetSource = if ([string]::IsNullOrWhiteSpace($package.Source)) { 'winget' } else { $package.Source }
$wingetArgs = @(
'install'
'--id'
$package.Id
'--exact'
'--accept-package-agreements'
'--accept-source-agreements'
'--source'
$wingetSource
)
if ($wingetSource -eq 'winget') {
$wingetArgs += '--silent'
}
& winget @wingetArgs
if ($LASTEXITCODE -eq 0) {
Write-Success " installed: $(Format-WindowsPackageEntry -Package $package)"
} else {
Write-Warning " failed: $(Format-WindowsPackageEntry -Package $package)"
}
}
'NpmGlobal' {
& npm install -g $package.Name
if ($LASTEXITCODE -eq 0) {
Write-Success " installed: $(Format-WindowsPackageEntry -Package $package)"
} else {
Write-Warning " failed: $(Format-WindowsPackageEntry -Package $package)"
}
}
}
}
}
}
}
function Write-WindowsPackageManifestSummary {
param([array]$Manifests)
if (-not $Manifests -or $Manifests.Count -eq 0) {
Write-Warning 'No curated Windows package manifest found.'
return
}
Write-Section 'Curated package manifests'
foreach ($manifest in $Manifests) {
$total = @($manifest.Data.Winget).Count + @($manifest.Data.NpmGlobal).Count
Write-Info "$($manifest.Name) ($total) -> $($manifest.Path)"
foreach ($sectionName in @('Winget', 'NpmGlobal')) {
$items = @($manifest.Data.$sectionName)
if ($items.Count -eq 0) {
continue
}
Write-Info " $sectionName ($($items.Count))"
foreach ($item in $items) {
if ($sectionName -eq 'Winget') {
$label = Format-WindowsPackageEntry -Package (Resolve-WindowsPackageEntry -PackageEntry $item -Manager $sectionName)
} else {
$label = $item
}
Write-Info " - $label"
}
}
}
}
function Write-WindowsAliasSummary {
$aliases = @(
[pscustomobject]@{ Name = 'l'; MapsTo = 'Invoke-ListDirectory (eza defaults)' }
[pscustomobject]@{ Name = 'la'; MapsTo = 'Invoke-ListDirectory -Force' }
[pscustomobject]@{ Name = 'll'; MapsTo = 'Invoke-ListDirectory -Force' }
[pscustomobject]@{ Name = 'lt'; MapsTo = 'Invoke-ListDirectory -Force -TotalSize' }
[pscustomobject]@{ Name = 'gl'; MapsTo = 'git pull --rebase --autostash' }
[pscustomobject]@{ Name = 'rld'; MapsTo = 'Reload the PowerShell profile' }
[pscustomobject]@{ Name = 'npmupg'; MapsTo = 'npm outdated -g && npm update -g' }
[pscustomobject]@{ Name = 'wingup'; MapsTo = 'winget upgrade && winget upgrade --all' }
)
Write-Section 'Quick aliases'
foreach ($alias in $aliases) {
$present = Test-CommandExists $alias.Name
$line = "$($alias.Name) -> $($alias.MapsTo)"
if ($present) {
Write-Success $line
} else {
Write-Info $line
}
}
}
if (-not (Test-IsWindows)) {
throw "install.ps1 is intended for Windows."
}
if ($Sync -and ($Minimal -or $Force -or $CleanBackups)) {
throw '-Sync cannot be combined with -Minimal, -Force, or -CleanBackups.'
}
if ($RestoreGitDefaults -and ($Sync -or $Minimal -or $Force -or $CleanBackups)) {
throw '-RestoreGitDefaults cannot be combined with installation options.'
}
$RepoRoot = Split-Path -Parent $PSCommandPath
$WindowsProfileSource = Join-Path $RepoRoot 'windows/profile.ps1'
$WindowsCorePackageManifest = Join-Path $RepoRoot 'windows/packages.psd1'
$WindowsOptionalPackageManifest = Join-Path $RepoRoot 'windows/packages.optional.psd1'
$WindowsPrivatePackageExample = Join-Path $RepoRoot 'windows/packages.private.example.psd1'
$WindowsTrafficMonitorConfigSource = Join-Path $RepoRoot 'windows/trafficmonitor/config.ini'
$GitIgnoreSource = Join-Path $RepoRoot 'git/global.gitignore'
$GitDefaultsSource = Join-Path $RepoRoot 'git/defaults.conf'
$GitConfigStatePath = Join-Path $HOME '.config\dotfiles\installer-state\git-config.before.windows.json'
$PowerShellProfileTargets = Get-WindowsPowerShellProfileTargets
$GitIgnoreTarget = Join-Path $HOME '.gitignore_global'
$WindowsConfigRoot = Join-Path $HOME '.config\dotfiles\windows'
$WindowsTerminalSettingsSource = Join-Path $RepoRoot 'windows\terminal\settings.json'
$WindowsTerminalSettingsTarget = Resolve-WindowsTerminalSettingsPath
$WindowsCorePackageTarget = Join-Path $WindowsConfigRoot 'packages.psd1'
$WindowsOptionalPackageTarget = Join-Path $WindowsConfigRoot 'packages.optional.psd1'
$WindowsPrivatePackageTarget = Join-Path $WindowsConfigRoot 'packages.private.psd1'
$WindowsOverlayDir = Join-Path $HOME '.config\dotfiles\windows\profile.d'
Write-Section "Windows dotfiles setup"
Write-Info "Detected PowerShell edition: $($PSVersionTable.PSEdition)"
Write-Info "Keeping PowerShell 5 and 7 profiles in sync."
if ($RestoreGitDefaults) {
Write-Section 'Restore Git defaults'
Restore-GitConfigState -StatePath $GitConfigStatePath
exit 0
}
if (-not (Test-Path $WindowsProfileSource)) {
throw "Missing Windows profile template at $WindowsProfileSource."
}
foreach ($profileTarget in $PowerShellProfileTargets.Shared) {
Install-Profile -Source $WindowsProfileSource -Target $profileTarget
}
foreach ($profileShimTarget in $PowerShellProfileTargets.Host) {
Install-ProfileShim -Target $profileShimTarget
}
if (-not $DryRun) {
Save-GitConfigState -DefaultsPath $GitDefaultsSource -IgnoreTarget $GitIgnoreTarget -StatePath $GitConfigStatePath
}
Install-GitIgnore -Source $GitIgnoreSource -Target $GitIgnoreTarget
Install-GitDefaults -DefaultsPath $GitDefaultsSource
Ensure-Directory -Path $WindowsConfigRoot
Copy-WithBackup -Source $WindowsCorePackageManifest -Target $WindowsCorePackageTarget
if (Test-Path -LiteralPath $WindowsOptionalPackageManifest) {
Copy-WithBackup -Source $WindowsOptionalPackageManifest -Target $WindowsOptionalPackageTarget
}
if (Test-Path -LiteralPath $WindowsTerminalSettingsSource) {
Copy-WithBackup -Source $WindowsTerminalSettingsSource -Target $WindowsTerminalSettingsTarget
}
if (Test-Path -LiteralPath $WindowsTrafficMonitorConfigSource) {
foreach ($trafficMonitorConfigTarget in (Resolve-TrafficMonitorConfigTargets)) {
Copy-WithBackup -Source $WindowsTrafficMonitorConfigSource -Target $trafficMonitorConfigTarget
}
}
if (-not (Test-Path -LiteralPath $WindowsPrivatePackageTarget)) {
if (Test-Path -LiteralPath $WindowsPrivatePackageExample) {
if ($DryRun) {
Write-Info "Would create private package scaffold at $WindowsPrivatePackageTarget"
} else {
Copy-Item -LiteralPath $WindowsPrivatePackageExample -Destination $WindowsPrivatePackageTarget
Write-Success "Created private package scaffold at $WindowsPrivatePackageTarget"
}
}
}
Ensure-Directory -Path $WindowsOverlayDir
Write-Info "Local overlay example: $($RepoRoot)\windows\profile.local.example.ps1"
if ($CleanBackups) {
Remove-BackupFiles -RootPath $HOME
}
Write-Section "Package managers"
if (Test-CommandExists winget) { $wingetState = 'available' } else { $wingetState = 'not found' }
Write-Info "winget: $wingetState"
if (Test-CommandExists winget) {
Write-Info "winget is assumed to come from App Installer; this script does not bootstrap it."
} else {
Write-Warning "winget not found; install App Installer if you want the Windows Store package manager."
}
$manifests = @(Get-WindowsPackageManifestEntries)
if ($manifests.Count -gt 0) {
Write-WindowsPackageManifestSummary -Manifests $manifests
} else {
Write-Warning 'Curated Windows package manifests not found.'
}