-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsetup-profile.ps1
More file actions
513 lines (409 loc) · 15.5 KB
/
Copy pathsetup-profile.ps1
File metadata and controls
513 lines (409 loc) · 15.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
[CmdletBinding(SupportsShouldProcess)]
param()
$ErrorActionPreference = 'Stop'
Set-StrictMode -Version Latest
$fontDownloadUrl = 'https://github.com/ryanoasis/nerd-fonts/releases/download/v3.4.0/CascadiaCode.zip'
$fontExpectedSha256 = '8d80993351a0a6b69a998e5c72060b7200c4f1af1f32b3ad4d8cad27c245940e'
$terminalFontFace = 'CaskaydiaCove NF'
$profileContent = @'
Import-Module posh-git
Import-Module Terminal-Icons
if ($PSVersionTable.PSVersion -ge [version]'7.4') {
Import-Module -Name Microsoft.WinGet.CommandNotFound
}
$GitPromptSettings.DefaultPromptPrefix.Text = '$(Get-Date -f "MM-dd HH:mm:ss") '
$GitPromptSettings.DefaultPromptPrefix.ForegroundColor = [ConsoleColor]::Magenta
$GitPromptSettings.DefaultPromptAbbreviateHomeDirectory = $true
$GitPromptSettings.DefaultPromptPath.ForegroundColor = 'Orange'
$GitPromptSettings.DefaultPromptBeforeSuffix.Text = '`n'
Set-PSReadLineKeyHandler -Key Ctrl+d -Function DeleteCharOrExit
function code {
& code-insiders @args
}
Set-Alias -Name c -Value code
Set-Alias -Name codei -Value code-insiders
function reload-profile {
. $PROFILE.CurrentUserAllHosts
}
function which {
Get-Command @args
}
function touch {
param(
[Parameter(Mandatory, ValueFromRemainingArguments)]
[string[]]$Path
)
foreach ($item in $Path) {
if (Test-Path $item) {
(Get-Item $item).LastWriteTime = Get-Date
continue
}
New-Item -ItemType File -Path $item -Force | Out-Null
}
}
function git-status {
git status @args
}
function git-graph {
git log --oneline --graph --decorate @args
}
function git-root {
$root = git rev-parse --show-toplevel 2>$null
if ($LASTEXITCODE -ne 0 -or [string]::IsNullOrWhiteSpace($root)) {
Write-Error 'Not currently inside a Git repository.'
return
}
Set-Location $root.Trim()
}
'@
$targetProfile = $PROFILE.CurrentUserAllHosts
function New-DirectoryIfMissing {
[CmdletBinding(SupportsShouldProcess)]
param(
[Parameter(Mandatory)]
[string]$Path
)
if (Test-Path -Path $Path) {
if (-not (Test-Path -Path $Path -PathType Container)) {
throw "Path exists but is not a directory: $Path"
}
return
}
if ($PSCmdlet.ShouldProcess($Path, 'Create directory')) {
New-Item -ItemType Directory -Path $Path -Force | Out-Null
}
}
function Remove-JsonComments {
param(
[Parameter(Mandatory)]
[string]$Content
)
$builder = New-Object System.Text.StringBuilder
$inString = $false
$inLineComment = $false
$inBlockComment = $false
$isEscaped = $false
for ($index = 0; $index -lt $Content.Length; $index++) {
$currentChar = $Content[$index]
$nextChar = if ($index + 1 -lt $Content.Length) { $Content[$index + 1] } else { [char]0 }
if ($inLineComment) {
if ($currentChar -eq "`n") {
$inLineComment = $false
[void]$builder.Append($currentChar)
}
continue
}
if ($inBlockComment) {
if ($currentChar -eq '*' -and $nextChar -eq '/') {
$inBlockComment = $false
$index++
}
continue
}
if (-not $inString -and $currentChar -eq '/' -and $nextChar -eq '/') {
$inLineComment = $true
$index++
continue
}
if (-not $inString -and $currentChar -eq '/' -and $nextChar -eq '*') {
$inBlockComment = $true
$index++
continue
}
[void]$builder.Append($currentChar)
if ($currentChar -eq '"' -and -not $isEscaped) {
$inString = -not $inString
}
if ($inString -and $currentChar -eq '\\' -and -not $isEscaped) {
$isEscaped = $true
} else {
$isEscaped = $false
}
}
return [regex]::Replace($builder.ToString(), ',\s*(?=[}\]])', '')
}
function Read-JsonFile {
param(
[Parameter(Mandatory)]
[string]$Path
)
if (-not (Test-Path -Path $Path)) {
return [ordered]@{}
}
$content = Get-Content -Path $Path -Raw
if ([string]::IsNullOrWhiteSpace($content)) {
return [ordered]@{}
}
try {
return $content | ConvertFrom-Json -AsHashtable -Depth 100
} catch {
$sanitizedContent = Remove-JsonComments -Content $content
return $sanitizedContent | ConvertFrom-Json -AsHashtable -Depth 100
}
}
function Get-PropertyValue {
param(
[Parameter(Mandatory)]
[object]$InputObject,
[Parameter(Mandatory)]
[string]$Name
)
if ($InputObject -is [System.Collections.IDictionary]) {
return $InputObject[$Name]
}
$property = $InputObject.PSObject.Properties[$Name]
if ($null -ne $property) {
return $property.Value
}
return $null
}
function Write-JsonFile {
[CmdletBinding(SupportsShouldProcess)]
param(
[Parameter(Mandatory)]
[string]$Path,
[Parameter(Mandatory)]
[object]$Data
)
New-DirectoryIfMissing -Path (Split-Path -Parent $Path)
if ($PSCmdlet.ShouldProcess($Path, 'Write JSON settings file')) {
$Data | ConvertTo-Json -Depth 100 | Set-Content -Path $Path -Encoding UTF8
return $true
}
return $false
}
function Install-NerdFont {
[CmdletBinding(SupportsShouldProcess)]
param(
[Parameter(Mandatory)]
[string]$DownloadUrl,
[Parameter(Mandatory)]
[string]$ExpectedSha256
)
$fontInstallDir = Join-Path -Path $env:LOCALAPPDATA -ChildPath 'Microsoft\Windows\Fonts'
$fontRegistryPath = 'HKCU:\Software\Microsoft\Windows NT\CurrentVersion\Fonts'
# Skip installation if the font files and registry entries already exist.
$existingFontFiles = @(Get-ChildItem -Path $fontInstallDir -Filter 'CaskaydiaCoveNerdFont*' -File -ErrorAction SilentlyContinue)
$registryKey = Get-Item -Path $fontRegistryPath -ErrorAction SilentlyContinue
$existingRegistryEntries = @(if ($null -ne $registryKey) {
$registryKey.Property | Where-Object { $_ -like 'CaskaydiaCoveNerdFont*' }
})
$alreadyInstalled = ($existingFontFiles.Count -gt 0) -and ($existingRegistryEntries.Count -gt 0)
if ($alreadyInstalled) {
Write-Host 'CaskaydiaCove Nerd Font is already installed. Skipping.' -ForegroundColor Cyan
return $true
}
$tempRoot = Join-Path -Path $env:TEMP -ChildPath 'setup-profile-fonts'
$zipPath = Join-Path -Path $tempRoot -ChildPath 'CascadiaCode.zip'
$extractPath = Join-Path -Path $tempRoot -ChildPath 'CascadiaCode'
New-DirectoryIfMissing -Path $tempRoot
if (Test-Path -Path $extractPath) {
if ($PSCmdlet.ShouldProcess($extractPath, 'Reset font extraction directory')) {
Remove-Item -Path $extractPath -Recurse -Force
}
}
New-DirectoryIfMissing -Path $extractPath
New-DirectoryIfMissing -Path $fontInstallDir
if (-not $PSCmdlet.ShouldProcess($fontInstallDir, 'Install CascadiaCode Nerd Font for current user')) {
return $false
}
Write-Host 'Downloading CascadiaCode Nerd Font...' -ForegroundColor Yellow
Invoke-WebRequest -Uri $DownloadUrl -OutFile $zipPath
$actualHash = (Get-FileHash -Path $zipPath -Algorithm SHA256).Hash
if ($actualHash -ine $ExpectedSha256) {
Remove-Item -Path $zipPath -Force
throw "SHA256 checksum mismatch for downloaded font archive. Expected '$ExpectedSha256', got '$actualHash'."
}
Expand-Archive -Path $zipPath -DestinationPath $extractPath -Force
$fontFiles = Get-ChildItem -Path $extractPath -Recurse -File |
Where-Object {
$_.Extension -in '.ttf', '.otf' -and
$_.BaseName -like 'CaskaydiaCoveNerdFont*'
}
if (-not $fontFiles) {
throw 'No CaskaydiaCove Nerd Font files were found in the downloaded archive.'
}
foreach ($fontFile in $fontFiles) {
$destinationPath = Join-Path -Path $fontInstallDir -ChildPath $fontFile.Name
Copy-Item -Path $fontFile.FullName -Destination $destinationPath -Force
$registryValueName = '{0} (TrueType)' -f $fontFile.BaseName
New-ItemProperty -Path $fontRegistryPath -Name $registryValueName -Value $fontFile.Name -PropertyType String -Force | Out-Null
}
if (-not ('FontChangeBroadcast' -as [type])) {
Add-Type @"
using System;
using System.Runtime.InteropServices;
public static class FontChangeBroadcast {
[DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)]
public static extern IntPtr SendMessageTimeout(
IntPtr hWnd,
uint Msg,
UIntPtr wParam,
string lParam,
uint fuFlags,
uint uTimeout,
out UIntPtr lpdwResult);
}
"@
}
$result = [UIntPtr]::Zero
[void][FontChangeBroadcast]::SendMessageTimeout(
[IntPtr]0xffff,
0x001D,
[UIntPtr]::Zero,
$null,
0x0002,
1000,
[ref]$result)
Write-Host 'Installed CascadiaCode Nerd Font files for the current user.' -ForegroundColor Green
return $true
}
function Set-WindowsTerminalPowerShellFont {
[CmdletBinding(SupportsShouldProcess)]
param(
[Parameter(Mandatory)]
[string]$FontFace
)
$candidatePaths = @(
(Join-Path -Path $env:LOCALAPPDATA -ChildPath 'Packages\Microsoft.WindowsTerminal_8wekyb3d8bbwe\LocalState\settings.json')
(Join-Path -Path $env:LOCALAPPDATA -ChildPath 'Packages\Microsoft.WindowsTerminalPreview_8wekyb3d8bbwe\LocalState\settings.json')
(Join-Path -Path $env:LOCALAPPDATA -ChildPath 'Microsoft\Windows Terminal\settings.json')
) | Select-Object -Unique
$updatedPaths = @()
$matchedPaths = @()
foreach ($settingsPath in $candidatePaths) {
if (-not (Test-Path -Path $settingsPath)) {
continue
}
try {
$settings = Read-JsonFile -Path $settingsPath
} catch {
Write-Warning "Skipping Windows Terminal settings at $settingsPath because the file could not be parsed."
continue
}
if (-not $settings.ContainsKey('profiles') -or $null -eq $settings.profiles) {
$settings.profiles = [ordered]@{}
}
if (-not $settings.profiles.ContainsKey('list') -or $null -eq $settings.profiles.list) {
Write-Warning "Skipping Windows Terminal settings at $settingsPath because no profiles.list section was found."
continue
}
$profiles = @($settings.profiles.list)
$powerShellProfile = $profiles |
Where-Object {
$profileName = Get-PropertyValue -InputObject $_ -Name 'name'
$profileSource = Get-PropertyValue -InputObject $_ -Name 'source'
$profileCommandLine = Get-PropertyValue -InputObject $_ -Name 'commandline'
$profileName -eq 'PowerShell' -or
$profileSource -eq 'Windows.Terminal.PowershellCore' -or
$profileCommandLine -match 'pwsh|powershell'
} |
Select-Object -First 1
if (-not $powerShellProfile) {
Write-Warning "Skipping Windows Terminal settings at $settingsPath because no PowerShell profile was found."
continue
}
$matchedPaths += $settingsPath
if (-not $powerShellProfile.ContainsKey('font') -or $null -eq $powerShellProfile.font) {
$powerShellProfile.font = [ordered]@{}
}
$powerShellProfile.font.face = $FontFace
if (Write-JsonFile -Path $settingsPath -Data $settings) {
$updatedPaths += $settingsPath
}
}
if ($matchedPaths.Count -eq 0) {
Write-Warning 'Windows Terminal settings were not updated because no supported settings file was found.'
return
}
foreach ($updatedPath in $updatedPaths) {
Write-Host "Updated Windows Terminal font in $updatedPath" -ForegroundColor Green
}
}
function Set-VSCodeTerminalFont {
[CmdletBinding(SupportsShouldProcess)]
param(
[Parameter(Mandatory)]
[string]$FontFace
)
$candidatePaths = @(
(Join-Path -Path $env:APPDATA -ChildPath 'Code\User\settings.json')
(Join-Path -Path $env:APPDATA -ChildPath 'Code - Insiders\User\settings.json')
) | Select-Object -Unique
$existingPaths = @($candidatePaths | Where-Object { Test-Path -Path $_ })
if ($existingPaths.Count -eq 0) {
$existingPaths = @($candidatePaths[0])
}
$updatedPaths = @()
foreach ($settingsPath in $existingPaths) {
try {
$settings = Read-JsonFile -Path $settingsPath
} catch {
Write-Warning "Skipping VS Code settings at $settingsPath because the file could not be parsed."
continue
}
$settings['terminal.integrated.fontFamily'] = $FontFace
if (Write-JsonFile -Path $settingsPath -Data $settings) {
$updatedPaths += $settingsPath
Write-Host "Updated VS Code terminal font in $settingsPath" -ForegroundColor Green
}
}
return $updatedPaths.Count -gt 0
}
Write-Host "Bootstrapping PowerShell all-hosts profile..." -ForegroundColor Cyan
Write-Host "Target profile: $targetProfile" -ForegroundColor DarkGray
if (-not (Get-PackageProvider -Name NuGet -ErrorAction SilentlyContinue)) {
if ($PSCmdlet.ShouldProcess('NuGet package provider', 'Install package provider for current user')) {
Install-PackageProvider -Name NuGet -Force -Scope CurrentUser
}
}
if (-not (Get-Module -ListAvailable -Name PowerShellGet)) {
if ($PSCmdlet.ShouldProcess('PowerShellGet', 'Install PowerShell module for current user')) {
Install-Module -Name PowerShellGet -Force -Scope CurrentUser
}
}
try {
if ($PSCmdlet.ShouldProcess('PSGallery', 'Set installation policy to Trusted')) {
Set-PSRepository -Name PSGallery -InstallationPolicy Trusted
}
} catch {
Write-Warning "Could not mark PSGallery as trusted. Continuing."
}
$modules = @(
'posh-git'
'Terminal-Icons'
)
if ($PSVersionTable.PSVersion -ge [version]'7.4') {
$modules += 'Microsoft.WinGet.CommandNotFound'
} else {
Write-Warning "Skipping Microsoft.WinGet.CommandNotFound because it requires PowerShell 7.4+."
}
foreach ($module in $modules) {
if (-not (Get-Module -ListAvailable -Name $module)) {
if ($PSCmdlet.ShouldProcess($module, 'Install PowerShell module')) {
Write-Host "Installing $module..." -ForegroundColor Yellow
Install-Module -Name $module -Scope CurrentUser -Force -AllowClobber
}
} else {
Write-Host "$module is already installed." -ForegroundColor DarkGray
}
}
$profileDir = Split-Path -Parent $targetProfile
New-DirectoryIfMissing -Path $profileDir
$profileWritten = $false
if ($PSCmdlet.ShouldProcess($targetProfile, 'Write PowerShell profile')) {
Set-Content -Path $targetProfile -Value $profileContent -Encoding UTF8
$profileWritten = $true
}
Install-NerdFont -DownloadUrl $fontDownloadUrl -ExpectedSha256 $fontExpectedSha256 | Out-Null
Set-WindowsTerminalPowerShellFont -FontFace $terminalFontFace | Out-Null
Set-VSCodeTerminalFont -FontFace $terminalFontFace | Out-Null
if ($profileWritten) {
Write-Host "Profile written to $targetProfile" -ForegroundColor Green
}
if ($profileWritten -and (Test-Path $targetProfile) -and $PSCmdlet.ShouldProcess('current session', 'Load updated profile')) {
. $targetProfile
Write-Host 'Profile loaded into the current session.' -ForegroundColor Green
} else {
Write-Host 'Restart PowerShell to load the new profile.' -ForegroundColor Green
}