-
Notifications
You must be signed in to change notification settings - Fork 17
/
prompt.ps1
359 lines (310 loc) · 11.8 KB
/
prompt.ps1
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
<#
.SYNOPSIS
Custom prompt for powershell
.DESCRIPTION
Custom prompt for powershell
in ps open $PROFILE and add the following:
code $PROFILE
version 231121 add stashes list
.LINK
[net.servicePointManager]::Expect100Continue = $true;[net.servicePointManager]::SecurityProtocol = [net.SecurityProtocolType]::Tls12;
invoke-webRequest "https://raw.githubusercontent.com/jagilber/powershellScripts/master/prompt.ps1" -outFile "$pwd\prompt.ps1";
code $PROFILE
code .\prompt.ps1
#>
# autoload modules
$PSModuleAutoLoadingPreference = 2
#$DebugPreference = "Continue"
$global:promptInfo = $null
# set terminal tab completion same as editor
#Set-PSReadLineKeyHandler -Chord Tab -Function TabCompleteNext # default
#Set-PSReadLineKeyHandler -Chord Tab -Function AcceptSuggestion
#Set-PSReadLineKeyHandler -Chord Tab -Function MenuComplete
# symbols
$branchSymbol = [char]0x2325
$deltaSymbol = [char]0x0394
$downArrow = [char]0x2193
$upArrow = [char]0x2191
$stashSymbol = [char]0x21B2
function prompt() {
$path = "'$pwd'"#.ToLower()
write-debug "prompt() path: $path command: $LastHistoryEntry"
new-promptInfo
try {
$newPath = (!($promptInfo.path) -or ($path -ine $promptInfo.path))
$isGitCommand = $LastHistoryEntry -and $LastHistoryEntry.tostring().startswith('git')
$cacheTimeout = ((get-date) - $promptInfo.cacheTimer).TotalMinutes -gt $promptInfo.cacheMinutes
if ($newPath -or $cacheTimeout -or $isGitCommand) {
$promptInfo.cacheTimer = get-date
$promptInfo.path = $path
$promptInfo.status = get-gitInfo -newPath $newPath -gitCommand $isGitCommand -cacheTimeout $cacheTimeout
$promptInfo.ps = get-psEnv
}
$date = (get-date).ToString('HH:mm:ss')
write-host "$($promptInfo.ps)$(get-commandDuration) $date" -ForegroundColor DarkGray -NoNewline
if ($promptInfo.enablePathOnPromptLine) {
$path = $path.trim("'")
write-host "$($promptInfo.status)" -ForegroundColor DarkCyan
return "$path>"
}
else {
write-host "$($promptInfo.status)" -ForegroundColor DarkCyan -NoNewline
write-host " $path" -ForegroundColor White
return ">"
}
}
catch {
write-host "Error: $($psitem.Exception.Message)`r`n$($psitem.scriptStackTrace)" -ForegroundColor Red -NoNewline
return "$path>"
}
}
function add-status($status = "", [switch]$reset) {
write-debug "add-status($status) reset: $reset current status: $($promptInfo.status)"
if ($reset) {
write-debug "resetting status"
$promptInfo.status = $status
}
else {
$promptInfo.status += $status
}
write-debug "new status: $($promptInfo.status)"
}
function get-branches() {
write-debug "get-branches()"
$branches = @(git branch)
$branchesChanged = compare-object $branches $promptInfo.branches
$remoteBranches = @(git branch -r)
$remoteBranchesChanged = compare-object $remoteBranches $promptInfo.remoteBranches
if ($branchesChanged) {
write-debug "branches changed. $($branches) -ne $($promptInfo.branches)"
$promptInfo.branches = @(git branch)
$promptInfo.remoteBranches = @(git branch -r)
$additionalBranches = $promptInfo.branches.count - $promptInfo.defaultBranchCount
$additionalBranchInfo = ""
if ($additionalBranches -gt 0) {
$additionalBranchInfo = "(+$additionalBranches) additional branches. all branches in `$promptInfo.branches"
}
write-host "local branches:`n$($promptInfo.branches | Select-Object -First $promptInfo.defaultBranchCount | Out-String)$additionalBranchInfo" -ForegroundColor DarkYellow
write-debug "changed branches:`n$($branchesChanged | out-string)"
}
else {
write-debug "branches are the same"
}
if ($remoteBranchesChanged) {
write-debug "remote branches changed. $($remoteBranches) -ne $($promptInfo.remoteBranches)"
$additionalBranches = $promptInfo.remoteBranches.count - $promptInfo.defaultBranchCount
$additionalBranchInfo = ""
if ($additionalBranches -gt 0) {
$additionalBranchInfo = "(+$additionalBranches) additional remote branches. all remote branches in `$promptInfo.remoteBranches"
}
write-host "remote branches:`n$($promptInfo.remoteBranches | Select-Object -First $promptInfo.defaultBranchCount | Out-String)$additionalBranchInfo" -ForegroundColor DarkCyan
write-debug "changed branches:`n$($remoteBranchesChanged | out-string)"
}
else {
write-debug "remote branches are the same"
}
}
function get-commandDuration() {
$precision = 'ms'
write-debug "get-commandDuration()"
if (!$promptInfo.enableCommandDuration) {
write-debug "command duration disabled. returning"
return $null
}
$lastCommand = get-history -count 1
if (!$lastCommand) {
write-debug "no last command found. returning"
$durationMs = 0
}
else {
$durationMs = [int]$lastCommand.Duration.TotalMilliseconds.toString('.')
}
if ($promptInfo.forceDurationMs) {
# add commas to the number
$durationMs = "{0:N0}" -f $durationMs
}
else {
if ($durationMs -gt 1000) {
$durationMs = [math]::Round($durationMs / 1000, 2)
$precision = 's'
if ($durationMs -gt 60) {
$durationMs = [math]::Round($durationMs / 60, 2)
$precision = 'm'
if ($durationMs -gt 60) {
$durationMs = [math]::Round($durationMs / 60, 2)
$precision = 'h'
}
}
}
}
$promptInfo.commandDurationMs = "$($deltaSymbol)$($durationMs)$($precision)"
return " $($promptInfo.commandDurationMs)"
}
function get-currentBranch() {
write-debug "get-currentBranch()"
$currentBranch = @(git branch --show-current 2>&1)
# if there is a configuration or security issue, git will return an error starting with 'fatal:'. check for this and return
if($currentBranch -imatch 'not a git repository') {
write-verbose "not a git repository"
return
}
elseif ($currentBranch -match '^fatal:') {
write-host "git error: $($currentBranch)" -ForegroundColor Red
return
}
$currentBranchChanged = compare-object $currentBranch $promptInfo.branch
if ($currentBranchChanged) {
write-debug "branch changed. continuing"
$promptInfo.branch = $currentBranch
}
else {
write-debug "current branch is the same"
}
if (!$promptInfo.branch) {
$promptInfo.repo = $null
add-status -reset
write-debug "no branch found. returning"
return $null
}
add-status " $($branchSymbol) ($($promptInfo.branch))"
return $promptInfo.branch
}
function get-diffs() {
write-debug "get-diffs()"
$diff = @(git status --porcelain).Count
if ($diff -gt 0) {
add-status " $($branchSymbol) ($($promptInfo.branch)*$($diff))" -reset
}
}
function get-remotes($gitCommand = $false) {
write-debug "get-remotes($gitCommand)"
$pattern = "(?<remote>\S+?)\s+(?<repo>.+?)\s+?\(\w+?\)"
$remotes = @(git remote -v)
$remoteMatches = [regex]::Matches($remotes, $pattern)
[void]$promptInfo.remotes.clear()
if (!$remoteMatches) {
write-debug "no remotes found. returning"
$promptInfo.repo = $null
return $null
}
$repo = $remoteMatches[0].groups['repo'].value
$sameRepo = $repo -and $repo -eq $promptInfo.repo
if (!$sameRepo -or $gitCommand) {
$promptInfo.repo = $repo
$null = get-branches
}
else {
write-debug "repo is the same"
}
foreach ($remoteMatch in $remoteMatches) {
$remote = $remoteMatch.groups['remote'].value
$repoRemote = "($remote/$($promptInfo.branch)) $repo"
if (!($promptInfo.remotes.contains($remote))) {
[void]$promptInfo.remotes.add($remote)
}
# only do this once per repo
if (!($promptInfo.fetchedRepos.contains($repoRemote))) {
[void]$promptInfo.fetchedRepos.add($repoRemote)
write-host "fetching:$repoRemote" -ForegroundColor DarkMagenta
git fetch $remote
}
}
}
function get-revisions() {
write-debug "get-revisions()"
foreach ($remote in $promptInfo.remotes) {
try {
$aheadBehind = git rev-list --left-right --count "$($remote)/$($promptInfo.branch)...$($promptInfo.branch)"
}
catch {
$aheadBehind = "0 0"
}
if ($aheadBehind) {
$aheadBehind = [regex]::replace($aheadBehind, '(\d+)\s+(\d+)', "$($downArrow)`$1/$($upArrow)`$2")
add-status "[$($remote):$($aheadBehind)]"
}
}
}
function get-stashes() {
write-debug "get-stashes()"
$stashes = @(git stash list)
$stashesChanged = compare-object $stashes $promptInfo.stashes
if ($stashesChanged) {
write-debug "stashes changed. $($stashes) -ne $($promptInfo.stashes)"
$promptInfo.stashes = $stashes
$additionalStashes = $promptInfo.stashes.count - $promptInfo.defaultBranchCount
$additionalStashInfo = ""
if ($additionalStashes -gt 0) {
$additionalStashInfo = "(+$additionalStashes) additional stashes. all stashes in `$promptInfo.stashes"
}
write-host "stashes:`n$($promptInfo.stashes | Select-Object -First $promptInfo.defaultBranchCount | Out-String)$additionalStashInfo" -ForegroundColor Yellow
}
else {
write-debug "stashes are the same"
}
if ($promptInfo.stashes) {
write-debug "stashes found. adding to status"
add-status "{$($stashSymbol)$($promptInfo.stashes.count)}"
}
}
function get-gitInfo([bool]$newPath = $false, [bool]$gitCommand = $false, [bool]$cacheTimeout = $false) {
write-debug "get-gitInfo([bool]newPath = $newPath, [bool]gitCommand = $gitCommand, [bool]cacheTimeout = $cacheTimeout)"
add-status -reset
if (!$promptInfo.enableGit) {
write-debug "git disabled. returning"
return (add-status -reset)
}
if (!(get-currentBranch)) {
return (add-status -reset)
}
get-diffs
get-stashes
get-remotes -gitCommand $gitCommand
get-revisions
write-debug "returning status: $status"
return $promptInfo.status
}
function get-psEnv() {
write-debug "get-psEnv()"
if ($env:VSCMD_VER) {
$psEnv = "vs$($env:VSCMD_VER) "
}
$psEnv += if ($IsCoreCLR) { 'pwsh' } else { 'ps' }
return $psEnv
}
function init-promptInfoEnv() {
write-debug "init-promptInfo()"
$openai = '\github\jagilber\powershellscripts\openai.ps1'
if ((test-path $openai -WarningAction SilentlyContinue)) {
. $openai -init -quiet
}
else {
write-debug "openai.ps1 not found"
}
}
function new-promptInfo() {
if (!$global:promptInfo) {
init-promptInfoEnv
write-debug "new-promptInfo()"
$global:promptInfo = @{
path = ""
branch = ""
cacheMinutes = 1
branches = @()
defaultBranchCount = 20
remoteBranches = @()
remotes = [collections.arraylist]::new()
stashes = [collections.arraylist]::new()
repo = ""
status = ""
ps = get-psEnv
cacheTimer = [datetime]::MinValue
enableGit = $true
enableCommandDuration = $true
enablePathOnPromptLine = $false
fetchedRepos = [collections.arraylist]::new()
commandDurationMs = 0
forceDurationMs = $false
}
}
}