forked from kelleyma49/PSFzf
-
Notifications
You must be signed in to change notification settings - Fork 0
/
PSFzf.Git.ps1
553 lines (492 loc) · 21.6 KB
/
PSFzf.Git.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
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
$script:GitKeyHandlers = @()
$script:foundGit = $false
$script:bashPath = $null
$script:grepPath = $null
if ($PSVersionTable.PSEdition -eq 'Core') {
$script:pwshExec = "pwsh"
}
else {
$script:pwshExec = "powershell"
}
$script:IsWindowsCheck = ($PSVersionTable.PSVersion.Major -le 5) -or $IsWindows
if ($RunningInWindowsTerminal -or -not $script:IsWindowsCheck) {
$script:filesString = '📁 Files'
$script:hashesString = '🍡 Hashes'
$script:allBranchesString = '🌳 All branches'
$script:branchesString = '🌲 Branches'
$script:tagsString = '📛 Tags'
$script:stashesString = '🥡 Stashes'
}
else {
$script:filesString = 'Files'
$script:hashesString = 'Hashes'
$script:allBranchesString = 'All branches'
$script:branchesString = 'Branches'
$script:tagsString = 'Tags'
$script:stashesString = 'Stashes'
}
function Get-GitFzfArguments() {
# take from https://github.com/junegunn/fzf-git.sh/blob/f72ebd823152fa1e9b000b96b71dd28717bc0293/fzf-git.sh#L89
return @{
Ansi = $true
Layout = "reverse"
Multi = $true
Height = '50%'
MinHeight = 20
Border = $true
Color = 'header:italic:underline'
PreviewWindow = 'right,50%,border-left'
Bind = @('ctrl-/:change-preview-window(down,50%,border-top|hidden|)')
}
}
function SetupGitPaths() {
if (-not $script:foundGit) {
if ($IsLinux -or $IsMacOS) {
# TODO: not tested on Mac
$script:foundGit = $null -ne $(Get-Command git -ErrorAction Ignore)
$script:bashPath = 'bash'
$script:grepPath = 'grep'
}
else {
$gitInfo = Get-Command git.exe -ErrorAction Ignore
$script:foundGit = $null -ne $gitInfo
if ($script:foundGit) {
# Detect if scoop is installed
$script:scoopInfo = Get-Command scoop -ErrorAction Ignore
if ($null -ne $script:scoopInfo) {
# Detect if git is installed using scoop (using shims)
if ($gitInfo.Source -match 'scoop[\\/]shims') {
# Get the proper git position relative to scoop shims" position
$gitInfo = Get-Command "$($gitInfo.Source)\..\..\apps\git\current\bin\git.exe"
}
}
$gitPathLong = Split-Path (Split-Path $gitInfo.Source -Parent) -Parent
# hack to get short path:
$a = New-Object -ComObject Scripting.FileSystemObject
$f = $a.GetFolder($gitPathLong)
$script:bashPath = Join-Path $f.ShortPath "bin\bash.exe"
$script:bashPath = Resolve-Path $script:bashPath
$script:grepPath = Join-Path ${gitPathLong} "usr\bin\grep.exe"
}
}
}
return $script:foundGit
}
function SetGitKeyBindings($enable) {
if ($enable) {
if (-not $(SetupGitPaths)) {
Write-Error "Failed to register git key bindings - git executable not found"
return
}
if (Get-Command Set-PSReadLineKeyHandler -ErrorAction Ignore) {
@('ctrl+g,ctrl+b', 'Select Git branches via fzf', { Update-CmdLine $(Invoke-PsFzfGitBranches) }), `
@('ctrl+g,ctrl+f', 'Select Git files via fzf', { Update-CmdLine $(Invoke-PsFzfGitFiles) }), `
@('ctrl+g,ctrl+h', 'Select Git hashes via fzf', { Update-CmdLine $(Invoke-PsFzfGitHashes) }), `
@('ctrl+g,ctrl+p', 'Select Git pull requests via fzf', { Update-CmdLine $(Invoke-PsFzfGitPulLRequests) }), `
@('ctrl+g,ctrl+s', 'Select Git stashes via fzf', { Update-CmdLine $(Invoke-PsFzfGitStashes) }), `
@('ctrl+g,ctrl+t', 'Select Git tags via fzf', { Update-CmdLine $(Invoke-PsFzfGitTags) }) `
| ForEach-Object {
$script:GitKeyHandlers += $_[0]
Set-PSReadLineKeyHandler -Chord $_[0] -Description $_[1] -ScriptBlock $_[2]
}
}
else {
Write-Error "Failed to register git key bindings - PSReadLine module not loaded"
return
}
}
}
function RemoveGitKeyBindings() {
$script:GitKeyHandlers | ForEach-Object {
Remove-PSReadLineKeyHandler -Chord $_
}
}
function IsInGitRepo() {
git rev-parse HEAD 2>&1 | Out-Null
return $?
}
function Get-ColorAlways($setting = ' --color=always') {
if ($RunningInWindowsTerminal -or -not $IsWindowsCheck) {
return $setting
}
else {
return ''
}
}
function Get-HeaderStrings() {
$header = "CTRL-A (Select all) / CTRL-D (Deselect all) / CTRL-T (Toggle all)"
$keyBinds = 'ctrl-a:select-all,ctrl-d:deselect-all,ctrl-t:toggle-all'
return $Header, $keyBinds
}
function Update-CmdLine($result) {
InvokePromptHack
if ($result.Length -gt 0) {
$result = $result -join " "
[Microsoft.PowerShell.PSConsoleReadLine]::Insert($result)
}
}
function Invoke-PsFzfGitFiles() {
if (-not (IsInGitRepo)) {
return
}
if (-not $(SetupGitPaths)) {
Write-Error "git executable could not be found"
return
}
$previewCmd = "${script:bashPath} \""" + $(Join-Path $PsScriptRoot 'helpers/PsFzfGitFiles-Preview.sh') + "\"" {-1}" + $(Get-ColorAlways) + " \""$($pwd.ProviderPath)\"""
$result = @()
$headerStrings = Get-HeaderStrings
$gitCmdsHeader = "`nALT-S (Git add) / ALT-R (Git reset)"
$headerStr = $headerStrings[0] + $gitCmdsHeader + "`n`n"
$statusCmd = "git $(Get-ColorAlways '-c color.status=always') status --short"
$reloadBindCmd = "reload($statusCmd)"
$stageScriptPath = Join-Path $PsScriptRoot 'helpers/PsFzfGitFiles-GitAdd.sh'
$gitStageBind = "alt-s:execute-silent(" + """${script:bashPath}"" '${stageScriptPath}' {+2..})+down+${reloadBindCmd}"
$resetScriptPath = Join-Path $PsScriptRoot 'helpers/PsFzfGitFiles-GitReset.sh'
$gitResetBind = "alt-r:execute-silent(" + """${script:bashPath}"" '${resetScriptPath}' {+2..})+down+${reloadBindCmd}"
$fzfArguments = Get-GitFzfArguments
$fzfArguments['Bind'] += $headerStrings[1], $gitStageBind, $gitResetBind
Invoke-Expression "& $statusCmd" | `
Invoke-Fzf @fzfArguments `
-BorderLabel "$script:filesString" `
-Preview "$previewCmd" -Header $headerStr | `
foreach-object {
$result += $_.Substring('?? '.Length)
}
$result
}
<#
.PARAMETER GitLogSubCommand
The git log subcommand to use. Default is 'log'.
.EXAMPLE
Invoke-PsFzfGitHashes -GitLogSubCommand 'log -3'
.EXAMPLE
Invoke-PsFzfGitHashes -GitLogSubCommand 'log --since="2 weeks ago"'
#>
function Invoke-PsFzfGitHashes() {
param(
[string]$GitLogSubCommand = 'log'
)
if (-not (IsInGitRepo)) {
return
}
if (-not $(SetupGitPaths)) {
Write-Error "git executable could not be found"
return
}
$previewCmd = "${script:bashPath} \""" + $(Join-Path $PsScriptRoot 'helpers/PsFzfGitHashes-Preview.sh') + "\"" {}" + $(Get-ColorAlways) + " \""$pwd\"""
$result = @()
$fzfArguments = Get-GitFzfArguments
Invoke-Expression ("git $GitLogSubCommand" + " --date=short --format=""%C(green)%C(bold)%cd %C(auto)%h%d %s (%an)"" $($(Get-ColorAlways).Trim()) --graph") | `
Invoke-Fzf @fzfArguments -NoSort `
-BorderLabel "$script:hashesString" `
-Preview "$previewCmd" | ForEach-Object {
if ($_ -match '\d\d-\d\d-\d\d\s+([a-f0-9]+)\s+') {
$result += $Matches.1
}
}
$result
}
function Invoke-PsFzfGitBranches() {
if (-not (IsInGitRepo)) {
return
}
if (-not $(SetupGitPaths)) {
Write-Error "git executable could not be found"
return
}
$fzfArguments = Get-GitFzfArguments
$fzfArguments['PreviewWindow'] = 'down,border-top,40%'
$gitBranchesHelperPath = Join-Path $PsScriptRoot 'helpers/PsFzfGitBranches.sh'
$ShortcutBranchesAll = "ctrl-a:change-prompt" + "($script:allBranchesString> )+reload(" + """${script:bashPath}"" '${gitBranchesHelperPath}' all-branches)"
$fzfArguments['Bind'] += 'ctrl-/:change-preview-window(down,70%|hidden|)', $ShortcutBranchesAll
$previewCmd = "${script:bashPath} \""" + $(Join-Path $PsScriptRoot 'helpers/PsFzfGitBranches-Preview.sh') + "\"" {}"
$result = @()
# use pwsh to prevent bash from trying to write to host output:
$branches = & $script:pwshExec -NoProfile -NonInteractive -Command "& ${script:bashPath} '$gitBranchesHelperPath' branches"
$branches |
Invoke-Fzf @fzfArguments -Preview "$previewCmd" -BorderLabel "$script:branchesString" -HeaderLines 2 -Tiebreak begin -ReverseInput | `
ForEach-Object {
$result += $($_.Substring('* '.Length) -split ' ')[0]
}
$result
}
function Invoke-PsFzfGitTags() {
if (-not (IsInGitRepo)) {
return
}
if (-not $(SetupGitPaths)) {
Write-Error "git executable could not be found"
return
}
$fzfArguments = Get-GitFzfArguments
$fzfArguments['PreviewWindow'] = 'right,70%'
$previewCmd = "git show --color=always {}"
$result = @()
git tag --sort -version:refname |
Invoke-Fzf @fzfArguments -Preview "$previewCmd" -BorderLabel "$script:tagsString" | `
ForEach-Object {
$result += $_
}
$result
}
function Invoke-PsFzfGitStashes() {
if (-not (IsInGitRepo)) {
return
}
if (-not $(SetupGitPaths)) {
Write-Error "git executable could not be found"
return
}
$fzfArguments = Get-GitFzfArguments
$fzfArguments['Bind'] += 'ctrl-x:execute-silent(git stash drop {1})+reload(git stash list)'
$header = "CTRL-X (drop stash)`n`n"
$previewCmd = 'git show --color=always {1}'
$result = @()
git stash list --color=always |
Invoke-Fzf @fzfArguments -Header $header -Delimiter ':' -Preview "$previewCmd" -BorderLabel "$script:stashesString" | `
ForEach-Object {
$result += $_.Split(':')[0]
}
$result
}
function Invoke-PsFzfGitPullRequests() {
if (-not (IsInGitRepo)) {
return
}
if (-not $(SetupGitPaths)) {
Write-Error "git executable could not be found"
return
}
$filterCurrentUser = $true
$reloadPrList = $false
# loop due to requesting possibly selecting current user
do {
# find the repo remote URL
$remoteUrl = git config --get remote.origin.url
# GitHub
if ($remoteUrl -match 'github.com') {
$script:ghCmdInfo = Get-Command gh -ErrorAction Ignore
if ($null -ne $script:ghCmdInfo) {
if ($filterCurrentUser) {
$currentUser = Invoke-Expression "gh api user --jq '.login'"
$listAllPrsCmdJson = Invoke-Expression "gh pr list --json id,author,title,number --author $currentUser"
}
else {
$currentUser = $null
$listAllPrsCmdJson = Invoke-Expression "gh pr list --json id,author,title,number"
}
$objs = $listAllPrsCmdJson | ConvertFrom-Json | ForEach-Object {
[PSCustomObject]@{
PR = "$($PSStyle.Foreground.Green)" + $_.number
Title = "$($PSStyle.Foreground.Magenta)" + $_.title
Creator = "$($PSStyle.Foreground.Yellow)" + $_.author.login
}
}
}
else {
Write-Error "Repo is a GitHub repo and gh command not found"
return
}
$webCmd = 'gh pr view {1} --web'
$previewCmd = 'gh pr view {1} && gh pr diff {1}'
$checkoutCmd = 'gh pr checkout {0}'
}
# Azure DevOps
elseif ($remoteUrl -match 'dev.azure.com|visualstudio.com') {
$script:azCmdInfo = Get-Command az -ErrorAction Ignore
if ($null -ne $script:azCmdInfo) {
if ($filterCurrentUser) {
$currentUser = Invoke-Expression "az account show --query user.name --output tsv"
$listAllPrsCmdJson = Invoke-Expression $('az repos pr list --status "active" --query "[].{title: title, number: pullRequestId, creator: createdBy.uniqueName}"' + "--creator $currentUser")
}
else {
$currentUser = $null
$listAllPrsCmdJson = Invoke-Expression 'az repos pr list --status "active" --query "[].{title: title, number: pullRequestId, creator: createdBy.uniqueName}"'
}
$objs = $listAllPrsCmdJson | ConvertFrom-Json | ForEach-Object {
[PSCustomObject]@{
PR = "$($PSStyle.Foreground.Green)" + $_.number
Title = "$($PSStyle.Foreground.Magenta)" + $_.title
Creator = "$($PSStyle.Foreground.Yellow)" + $_.creator
}
}
}
else {
Write-Error "Repo is an Azure DevOps repo and az command not found"
return
}
$webCmd = 'az repos pr show --id {1} --open --output none'
# currently errors on query. Need to fix instead of output everything
#$previewCmd = 'az repos pr show --id {1} --query "{Created:creationDate, Closed:closedDate, Creator:createdBy.displayName, PR:codeReviewId, Title:title, Repo:repository.name, Reviewers:join('', '',reviewers[].displayName), Source:sourceRefName, Target:targetRefName}" --output yamlc'
$previewCmd = 'az repos pr show --id {1} --output yamlc'
$checkoutCmd = 'az repos pr checkout --id {0}'
}
$fzfArguments = Get-GitFzfArguments
$fzfArguments['Bind'] += 'ctrl-o:execute-silent(' + $webCmd + ')'
$header = "CTRL-O (open in browser) / CTRL-X (checks) / CTRL+U (toggle user filter) / CTRL+P (checkout PR)`n`n"
$prevCLICOLOR_FORCE = $env:CLICOLOR_FORCE
if ($PSStyle) {
$prevOutputRendering = $PSStyle.OutputRendering
}
$env:CLICOLOR_FORCE = 1 # make gh show keep colors
if ($PSStyle) {
$PSStyle.OutputRendering = 'Ansi'
}
try {
$borderLabel = "Pull Requests"
if ($currentUser) {
$borderLabel += " by $currentUser"
}
$result = $objs | out-string -Stream | `
Where-Object { -not [string]::IsNullOrWhiteSpace($_) } | `
Invoke-Fzf @fzfArguments -Expect "ctrl-x,ctrl-u,ctrl-p" -Header $header -Preview "$previewCmd" -HeaderLines 2 -BorderLabel $borderLabel
if ($result -is [array]) {
if ($result.Length -ge 2) {
$prId = $result[1].Split(' ')[0] # get the PR ID
}
else {
$prId = $null
}
$reloadPrList = $result[0] -eq 'ctrl-u' # reload if user filter toggled
}
else {
$reloadPrList = $result -eq 'ctrl-u' # reload if user filter toggled
}
$checks = $null
# reload with user filter toggled:
if ($reloadPrList) {
$filterCurrentUser = -not $filterCurrentUser
}
# checkout PR:
elseif ($result[0] -eq 'ctrl-p') {
Write-Warning "Checking out PR $prId into $($(Get-Location).Path) ..."
Invoke-Expression ($checkoutCmd -f $prId)
}
# open checks for PR:
elseif ($result[0] -eq 'ctrl-x') {
if ($remoteUrl -match 'github.com') {
$env:CLICOLOR_FORCE = $prevCLICOLOR_FORCE
$checksCmd = "gh pr view $prId --json ""statusCheckRollup"""
$checksJsonTxt = Invoke-Expression $checksCmd
$checksJson = $checksJsonTxt | ConvertFrom-Json
$checks = $checksJson.statusCheckRollup | ForEach-Object {
if ($_.status -eq 'COMPLETED') {
if ($_.conclusion -eq 'SUCCESS') {
$status = "$($PSStyle.Foreground.Green)" + '? Success'
}
else {
$status = "$($PSStyle.Foreground.Red)" + '? Failed'
}
}
else {
$status = "$($PSStyle.Foreground.Yellow)" + '?'
}
[PSCustomObject]@{
Status = $status
Check = "$($PSStyle.Foreground.Magenta)" + $_.name
Link = $_.detailsUrl
}
}
#$runCheckCmd = $null
$runCheckCmd = 'echo running '
}
elseif ($remoteUrl -match 'dev.azure.com|visualstudio.com') {
$checksCmd = "az repos pr policy list --id $prId --output json"
$checksJsonTxt = Invoke-Expression $checksCmd
$checksJson = $checksJsonTxt | ConvertFrom-Json
# only worried about blocking checks, for now:
$checks = $checksJson | Where-Object { $_.configuration.isBlocking } | ForEach-Object {
$context = $_.context
$settings = $_.configuration.settings
$type = $_.configuration.type
$link = $remoteUrl, "pullrequest/$($prId)" -join '/' # default to opening PR in browser
# find check status:
switch ($_.status) {
'approved' {
$status = "$($PSStyle.Foreground.Green)" + '? Approved'
}
'rejected' {
$status = "$($PSStyle.Foreground.Red)" + '? Rejected'
}
'queued' {
if ($context -and $context.IsExpired) {
$status = "$($PSStyle.Foreground.Red)" + '? Expired'
}
else {
$status = "$($PSStyle.Foreground.BrightBlue)" + '?? Queued'
}
}
'running' {
$status = "$($PSStyle.Foreground.BrightBlue)" + '? Running'
}
default {
$status = $_.status # unknown status
}
}
# find check name and build link:
switch ($type.displayName) {
'Build' {
$check = $settings.displayName
if ([string]::IsNullOrWhiteSpace($check)) {
$check = $context.buildDefinitionName
}
if ($context) {
$buildId = $context.buildId
$link = $remoteUrl.split('/_git/')[0], "_build/results?buildId=$buildId" -join '/'
}
}
'Status' {
$check = $settings.defaultDisplayName
}
default {
$check = $type.displayName
}
}
[PSCustomObject]@{
EvaluationId = "$($PSStyle.Foreground.Blue)" + $_.evaluationId
Status = $status
Check = "$($PSStyle.Foreground.Magenta)" + $check
Link = $link
}
}
$runCheckCmd = "az repos pr policy queue --id $prId --output none --evaluation-id "
}
}
# 2. Run the checks command, if selected in previous command:
if ($null -ne $checks) {
$fzfArguments = Get-GitFzfArguments
#$fzfArguments['Bind'] += 'ctrl-r:execute(' + $runCheckCmd + ')'
if ($runCheckCmd) {
$fzfArguments['Expect'] = "ctrl-r"
$header = "CTRL-R (run selected checks)`n`n"
}
else {
$header = "`n"
}
$env:CLICOLOR_FORCE = 1 # make gh show keep colors
if ($PSStyle) {
$PSStyle.OutputRendering = 'Ansi'
}
$result = $checks | out-string -Stream | `
Where-Object { -not [string]::IsNullOrWhiteSpace($_) } | `
Invoke-Fzf @fzfArguments -Header $header -HeaderLines 2 -BorderLabel $('? Checks' + " for PR $prId")
if ($runCheckCmd -and $result[0] -eq 'ctrl-r') {
$result = $result[1..($result.Length - 1)]
$result | ForEach-Object {
$cmd = $($runCheckCmd + $($_ -split ' ')[0])
Write-Warning "Running check using command '$cmd'..."
Invoke-Expression $cmd
}
}
}
}
finally {
$env:CLICOLOR_FORCE = $prevCLICOLOR_FORCE
if ($PSStyle) {
$PSStyle.OutputRendering = $prevOutputRendering
}
}
} while ($reloadPrList)
$prId
}