Repository navigation
Expand file tree
/
Copy pathprofile.ps1
More file actions
357 lines (287 loc) · 15.2 KB
/
Copy pathprofile.ps1
File metadata and controls
357 lines (287 loc) · 15.2 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
# scripts/windows/tools/profile.ps1 - PowerShell profile writer
#
# Writes dev-setup shortcuts to PowerShell profile (both PS 5.1 and PS 7+)
Set-StrictMode -Version Latest
$ErrorActionPreference = 'Stop'
. "$PSScriptRoot\..\lib\logging.ps1"
function Invoke-HostQuery {
param([string]$Exe)
& $Exe -NoProfile -NonInteractive -NoLogo -Command '$PROFILE' 2>$null
}
function Resolve-ProfilePath {
param([string]$HostExe, [string]$FallbackPath)
if (-not (Get-Command $HostExe -ErrorAction SilentlyContinue)) {
Write-Host "[INFO] $HostExe not found - fallback: $FallbackPath"
return $FallbackPath
}
try {
$raw = Invoke-HostQuery -Exe $HostExe
if ($LASTEXITCODE -ne 0) {
Write-Host "[WARN] $HostExe exited $LASTEXITCODE - fallback: $FallbackPath"
return $FallbackPath
}
$resolved = ($raw.Trim() -split '\r?\n' | Where-Object { $_ } | Select-Object -Last 1).Trim()
if ([string]::IsNullOrEmpty($resolved)) { return $FallbackPath }
if ($resolved -notmatch '^[A-Za-z]:\\') { return $FallbackPath }
Write-Host "[INFO] Resolved $HostExe profile: $resolved"
return $resolved
} catch {
Write-Host "[WARN] Query failed for $HostExe - fallback: $FallbackPath"
return $FallbackPath
}
}
function Write-PowerShellProfile {
param(
# v5.2-D1: optional params allow test override; defaults mirror production paths
[string]$Ps51Fallback = [System.IO.Path]::Combine($HOME, 'Documents', 'WindowsPowerShell', 'Microsoft.PowerShell_profile.ps1'),
[string]$Ps7Fallback = [System.IO.Path]::Combine($HOME, 'Documents', 'PowerShell', 'Microsoft.PowerShell_profile.ps1')
)
# ALL path-resolution and write logic lives inside this function.
# Dot-sourcing profile.ps1 defines functions only; it does NOT execute
# resolution or writes. Tests define mock Invoke-HostQuery AFTER
# dot-sourcing and BEFORE calling Write-PowerShellProfile.
$local:beginMarker = '# BEGIN dev-setup profile' # v5.1-F5
$local:endMarker = '# END dev-setup profile' # v5.1-F5
# Strip only canonical whole-line blocks, including byte-zero and adjacent
# blocks left by older installs. Keep a line break when user text surrounds
# a block, but remove the owned separator at EOF for stable repeat writes.
$stripManagedBlocks = {
param([string]$Content)
$pattern = "(?ms)(?:^|\r?\n)$([regex]::Escape($beginMarker))\r?\n.*?^$([regex]::Escape($endMarker))(?:\r?\n|\z)"
$blocks = [regex]::Matches($Content, $pattern)
# Work backwards: original offsets stay valid, and separator decisions
# see the updated suffix instead of newlines another removal consumes.
for ($i = $blocks.Count - 1; $i -ge 0; $i--) {
$block = $blocks[$i]
$after = $block.Index + $block.Length
$separator = ''
if ($block.Index -gt 0 -and $after -lt $Content.Length -and
$Content[$block.Index - 1] -ne "`n" -and
$Content[$after] -ne "`r" -and $Content[$after] -ne "`n") {
$separator = if ($block.Value.StartsWith("`r`n")) { "`r`n" } else { "`n" }
}
$Content = $Content.Remove($block.Index, $block.Length).Insert($block.Index, $separator)
}
$Content
}
# Resolve actual profile paths by querying each host; deduplicate case-insensitively
$profilePaths = @(
(Resolve-ProfilePath 'powershell' $Ps51Fallback),
(Resolve-ProfilePath 'pwsh' $Ps7Fallback)
) | Sort-Object { $_.ToLower() } -Unique
# Legacy cleanup: strip orphaned blocks at fallback paths not in the resolved set
$legacyPaths = @($Ps51Fallback, $Ps7Fallback)
foreach ($legacy in $legacyPaths) {
$isOrphan = @($profilePaths | Where-Object { $_.ToLower() -eq $legacy.ToLower() }).Count -eq 0
if ($isOrphan -and (Test-Path $legacy) -and
(Select-String -Path $legacy -Pattern $beginMarker -Quiet)) {
$legacyContent = Get-Content $legacy -Raw
$stripped = & $stripManagedBlocks $legacyContent
Set-Content $legacy $stripped.TrimEnd() -NoNewline -Encoding ASCII # v5-H1
Write-Info "Stripped orphaned block from legacy path: $legacy"
}
}
foreach ($profilePath in $profilePaths) {
# If the managed block already exists, strip it out so we can re-inject fresh
if ((Test-Path $profilePath) -and (Select-String -Path $profilePath -Pattern ([regex]::Escape($beginMarker)) -Quiet)) {
Write-Info "Updating PowerShell profile shortcuts in $profilePath..."
$raw = Get-Content $profilePath -Raw
# Strip the managed block (handles both LF and CRLF)
$raw = & $stripManagedBlocks $raw
Set-Content $profilePath $raw -NoNewline -Encoding ASCII
}
}
$profileContent = @'
# BEGIN dev-setup profile
# -- Linux-compatible commands --------------------------------------------------
function Remove-CustomItem {
param(
[Parameter(Position=0, ValueFromRemainingArguments=$true)]
[string[]]$Path
)
Remove-Item -Path $Path -Recurse -Force
}
Remove-Item -Force Alias:\rm -ErrorAction SilentlyContinue
Set-Alias -Name rm -Value Remove-CustomItem -Force -Scope Global
function Set-FileTimestamp {
param([string]$Path)
if (Test-Path $Path) {
(Get-Item $Path).LastWriteTime = Get-Date
} else {
New-Item -ItemType File -Path $Path | Out-Null
}
}
Set-Alias -Name touch -Value Set-FileTimestamp -Force -Scope Global
# -- Git shortcuts --------------------------------------------------------------
function Get-GitStatus { git status -sb $args } # short branch status
Set-Alias -Name gs -Value Get-GitStatus -Force -Scope Global
function Invoke-GitCommit { git commit $args }
Remove-Item -Force Alias:\gc -ErrorAction SilentlyContinue
Set-Alias -Name gc -Value Invoke-GitCommit -Force -Scope Global
function Get-GitBranch { git branch $args }
Set-Alias -Name gb -Value Get-GitBranch -Force -Scope Global
function Add-GitFiles { git add $args }
Set-Alias -Name ga -Value Add-GitFiles -Force -Scope Global
function Get-GitLogPretty { git log --graph --abbrev-commit --pretty=format:'%Cred%h%Creset -%C(yellow)%d%Creset %s %Cgreen(%cr) %C(bold blue)<%an>%Creset' $args }
Remove-Item -Force Alias:\gl -ErrorAction SilentlyContinue
Set-Alias -Name gl -Value Get-GitLogPretty -Force -Scope Global
function Get-GitLog { git log $args }
Set-Alias -Name glog -Value Get-GitLog -Force -Scope Global
function Invoke-GitFetch { git fetch $args }
Set-Alias -Name gf -Value Invoke-GitFetch -Force -Scope Global
function Invoke-GitFetchPrune { git fetch --prune $args }
Set-Alias -Name gfp -Value Invoke-GitFetchPrune -Force -Scope Global
function Invoke-GitStash { git stash $args }
Set-Alias -Name ggs -Value Invoke-GitStash -Force -Scope Global
function Get-GitStashList { git stash list $args }
Set-Alias -Name ggsls -Value Get-GitStashList -Force -Scope Global
function Add-GitAllFiles { git add --all $args } # stage all changes
Set-Alias -Name gaa -Value Add-GitAllFiles -Force -Scope Global
function Invoke-GitCommitMessage { git commit -m $args } # commit with inline message
Remove-Item -Force Alias:\gcm -ErrorAction SilentlyContinue
Set-Alias -Name gcm -Value Invoke-GitCommitMessage -Force -Scope Global
function New-GitBranch { git checkout -b $args } # create and switch to new branch
Remove-Item -Force Alias:\gcb -ErrorAction SilentlyContinue
Set-Alias -Name gcb -Value New-GitBranch -Force -Scope Global
function Invoke-GitCheckout { git checkout $args } # switch branch or restore file
Set-Alias -Name gco -Value Invoke-GitCheckout -Force -Scope Global
function Get-GitDiff { git diff $args } # show unstaged diff
Set-Alias -Name gd -Value Get-GitDiff -Force -Scope Global
function Get-GitDiffStaged { git diff --staged $args } # show staged diff
Set-Alias -Name gds -Value Get-GitDiffStaged -Force -Scope Global
function Invoke-GitStashPop { git stash pop $args } # pop most recent stash
Set-Alias -Name ggsp -Value Invoke-GitStashPop -Force -Scope Global
function Invoke-GitPush { git push $args } # push to remote
Remove-Item -Force Alias:\gp -ErrorAction SilentlyContinue
Set-Alias -Name gp -Value Invoke-GitPush -Force -Scope Global
function Invoke-GitPushForce { git push --force-with-lease $args } # safe force push
Set-Alias -Name gpf -Value Invoke-GitPushForce -Force -Scope Global
function Invoke-GitPull { git pull $args } # pull from remote
Set-Alias -Name gpl -Value Invoke-GitPull -Force -Scope Global
function Invoke-GitRebase { git rebase $args } # rebase onto branch
Remove-Item -Force Alias:\grb -ErrorAction SilentlyContinue
Set-Alias -Name grb -Value Invoke-GitRebase -Force -Scope Global
function Invoke-GitRebaseInteractive { git rebase -i $args } # interactive rebase
Set-Alias -Name grbi -Value Invoke-GitRebaseInteractive -Force -Scope Global
function Invoke-GitRestore { git restore $args } # discard working tree changes
Remove-Item -Force Alias:\grs -ErrorAction SilentlyContinue
Set-Alias -Name grs -Value Invoke-GitRestore -Force -Scope Global
function Invoke-GitRestoreStaged { git restore --staged $args } # unstage a file
Set-Alias -Name grss -Value Invoke-GitRestoreStaged -Force -Scope Global
# -- GitHub CLI shortcuts -------------------------------------------------------
function New-GhPR { gh pr create $args } # open a pull request
Set-Alias -Name ghpr -Value New-GhPR -Force -Scope Global
function Get-GhPRList { gh pr list $args } # list pull requests
Set-Alias -Name ghprl -Value Get-GhPRList -Force -Scope Global
function Get-GhPRView { gh pr view $args } # view a pull request
Set-Alias -Name ghprv -Value Get-GhPRView -Force -Scope Global
function Get-GhIssueList { gh issue list $args } # list issues
Set-Alias -Name ghis -Value Get-GhIssueList -Force -Scope Global
function Get-GhIssueView { gh issue view $args } # view an issue
Set-Alias -Name ghiv -Value Get-GhIssueView -Force -Scope Global
# -- Dev shortcuts --------------------------------------------------------------
function Invoke-NpmInstall { npm install $args } # npm install
Remove-Item -Force Alias:\ni -ErrorAction SilentlyContinue
Set-Alias -Name ni -Value Invoke-NpmInstall -Force -Scope Global
function Invoke-NpmRun { npm run $args } # npm run <script>
Set-Alias -Name nr -Value Invoke-NpmRun -Force -Scope Global
function Invoke-NpmRunDev { npm run dev $args } # npm run dev
Set-Alias -Name nrd -Value Invoke-NpmRunDev -Force -Scope Global
function Invoke-NpmRunTest { npm run test $args } # npm run test
Set-Alias -Name nrt -Value Invoke-NpmRunTest -Force -Scope Global
function Invoke-Python { python $args } # python shorthand
Set-Alias -Name py -Value Invoke-Python -Force -Scope Global
Set-Alias -Name c -Value Clear-Host -Force -Scope Global # clear the screen
# -- Utility --------------------------------------------------------------------
function Get-MyIp { curl.exe -s ifconfig.me $args } # show public IP
Set-Alias -Name myip -Value Get-MyIp -Force -Scope Global
function Invoke-PingBing { ping bing.com $args } # quick connectivity check
Set-Alias -Name pb -Value Invoke-PingBing -Force -Scope Global
Remove-Item -Force Alias:\h -ErrorAction SilentlyContinue
Set-Alias -Name h -Value Get-History -Force -Scope Global # command history
function Edit-Profile { notepad $PROFILE } # open PS profile in editor
Remove-Item -Force Alias:\ep -ErrorAction SilentlyContinue
Set-Alias -Name ep -Value Edit-Profile -Force -Scope Global
# -- Shutdown -------------------------------------------------------------------
function Invoke-ShutdownNow {
# Shut down the machine immediately
shutdown /s /t 0
}
Set-Alias -Name sdn -Value Invoke-ShutdownNow -Force -Scope Global
function Invoke-TimedShutdown {
param(
[Parameter(Mandatory)]
[ValidateRange(1, [int]::MaxValue)]
[int]$Minutes
)
# Schedule shutdown in N minutes (converts minutes to seconds for Windows)
shutdown /s /t ($Minutes * 60)
}
Set-Alias -Name tsdn -Value Invoke-TimedShutdown -Force -Scope Global
function Invoke-CancelTimedShutdown {
# Cancel a pending timed shutdown
$result = shutdown /a 2>&1
if ($LASTEXITCODE -ne 0) {
Write-Host "No pending shutdown to cancel."
}
}
Set-Alias -Name cancel_tsdn -Value Invoke-CancelTimedShutdown -Force -Scope Global
# END dev-setup profile
'@
# Diagnostics: log resolved profile paths (may be deduplicated to one entry)
Write-Info "PS 5.1 profile path (resolved): $($profilePaths[0])"
if (@($profilePaths).Count -gt 1) {
Write-Info "PS 7+ profile path (resolved): $($profilePaths[1])"
} else {
Write-Info "PS 7+ profile path (resolved): (same as PS 5.1 after dedup)"
}
# Diagnostics: log execution policy before writing - helps diagnose load failures on PS 5.1
$execPolicy = Get-ExecutionPolicy -Scope CurrentUser
Write-Info "Execution policy (CurrentUser): $execPolicy"
if ($execPolicy -eq 'Restricted' -or $execPolicy -eq 'Undefined') {
Write-Warn "Execution policy is '$execPolicy' -- profile aliases may not load in new terminals."
Write-Warn "To fix: Set-ExecutionPolicy -Scope CurrentUser RemoteSigned"
}
# Write to each profile path
foreach ($profilePath in $profilePaths) {
$profileDir = Split-Path $profilePath
# Diagnostics: log target directory before creation attempt
Write-Info "Target profile directory: $profileDir"
# Ensure profile directory exists
try {
if (-not (Test-Path $profileDir)) {
New-Item -ItemType Directory -Path $profileDir -Force | Out-Null
}
} catch {
Write-Err "Failed to create profile directory '$profileDir': $_"
continue
}
# Diagnostics: confirm directory exists after creation
if (Test-Path $profileDir) {
Write-Info "Profile directory confirmed: $profileDir"
} else {
Write-Err "Profile directory does not exist after creation attempt: $profileDir"
continue
}
# Diagnostics: log the profile file path being written
Write-Info "Writing profile content to: $profilePath"
# Append to profile (create if absent).
# Separate nonempty user content, but keep empty/fresh targets byte-stable.
try {
if ((Test-Path $profilePath) -and (Get-Item $profilePath).Length -gt 0) {
Add-Content -Path $profilePath -Value "" -Encoding ASCII
}
Add-Content -Path $profilePath -Value $profileContent -Encoding ASCII
} catch {
Write-Err "Failed to write profile to '$profilePath': $_"
continue
}
# Post-write validation: confirm file exists and log size in bytes
if (Test-Path $profilePath) {
$fileSize = (Get-Item $profilePath).Length
Write-Ok "Profile written: $profilePath ($fileSize bytes)"
} else {
Write-Err "Profile write failed - file not found after write: $profilePath"
}
}
}