-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGitAliases.Extras.psm1
More file actions
424 lines (366 loc) · 14.7 KB
/
GitAliases.Extras.psm1
File metadata and controls
424 lines (366 loc) · 14.7 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
# ===================================================================
# GitAliases.Extras.psm1
#
# Extends posh-git and git-aliases with custom functions and
# adds robust tab completion for all git aliases.
#
# Mainly inspired by: https://github.com/zh30/zsh-shortcut-git
# ===================================================================
# --- Custom Helper Functions ---
function Test-InGitRepo {
try {
git rev-parse --is-inside-work-tree *> $null
$true
} catch {
$false
}
}
function Test-GitInProgress {
if (-not (Test-InGitRepo)) { return $false }
$gitDir = git rev-parse --git-dir
$inProgressFiles = @("MERGE_HEAD", "REBASE_HEAD", "CHERRY_PICK_HEAD", "REVERT_HEAD", "BISECT_LOG")
foreach ($file in $inProgressFiles) {
if (Test-Path (Join-Path $gitDir $file)) { return $true }
}
$false
}
function Test-WorkingTreeClean {
if (-not (Test-InGitRepo)) { return $false }
# Checks for both unstaged and staged changes.
& git diff --quiet --exit-code
$isClean = ($LASTEXITCODE -eq 0)
& git diff --cached --quiet --exit-code
$isClean = $isClean -and ($LASTEXITCODE -eq 0)
return $isClean
}
function Get-CurrentBranch {
if (Test-InGitRepo) {
$branch = git rev-parse --abbrev-ref HEAD
if ($branch -ne "HEAD") {
return $branch.Trim()
}
}
return $null
}
function Test-GitRefExists {
param(
[Parameter(Mandatory=$true)]
[string]$RefName
)
& git show-ref --verify --quiet $RefName
return ($LASTEXITCODE -eq 0)
}
function Convert-ToPowerShellBranchCompletionText {
param(
[Parameter(Mandatory = $true)]
[string]$BranchName
)
if ($BranchName.StartsWith('#')) {
$escaped = $BranchName -replace "'", "''"
return "'$escaped'"
}
return $BranchName
}
# --- Custom Git Command Functions ---
function UpMerge {
[CmdletBinding()]
param(
[string]$Src = "origin/main",
[switch]$AllowDirty, [switch]$AllowInProgress, [switch]$NoFetch, [switch]$NoFF
)
if (-not (Test-InGitRepo)) { throw "Not a git repository." }
$tgt = Get-CurrentBranch; if (-not $tgt) { throw "Detached HEAD. Cannot merge." }
if (-not $AllowInProgress -and (Test-GitInProgress)) { throw "Another git operation is in progress." }
if (-not $AllowDirty -and -not (Test-WorkingTreeClean)) { throw "Working tree is not clean." }
if (-not $NoFetch) { git fetch --all --prune; if ($LASTEXITCODE -ne 0) { throw "git fetch failed." } }
$msg = "chore(sync): merge $Src into $tgt"
if ($NoFF) { git merge --no-ff --no-edit $Src -m $msg } else { git merge --no-edit $Src -m $msg }
}
function UpRebase {
[CmdletBinding()]
param(
[string]$Src = "origin/main",
[switch]$AllowDirty, [switch]$AllowInProgress, [switch]$NoFetch, [switch]$Autostash
)
if (-not (Test-InGitRepo)) { throw "Not a git repository." }
$tgt = Get-CurrentBranch; if (-not $tgt) { throw "Detached HEAD. Cannot rebase." }
if (-not $AllowInProgress -and (Test-GitInProgress)) { throw "Another git operation is in progress." }
if (-not $AllowDirty -and -not (Test-WorkingTreeClean)) { throw "Working tree is not clean." }
if (-not $NoFetch) { git fetch --all --prune; if ($LASTEXITCODE -ne 0) { throw "git fetch failed." } }
if ($Autostash) { git rebase --autostash $Src } else { git rebase $Src }
}
function gapt { git apply --3way @args }
function gcor { git checkout --recurse-submodules @args }
function gdct { git describe --tags (git rev-list --tags --max-count=1) }
function gdt { git diff-tree --no-commit-id --name-only -r @args }
function gdnolock { git diff @args ":(exclude)package-lock.json" ":(exclude)*.lock" }
function gdv { git diff -w @args | Out-String | less }
function gfo { git fetch origin @args }
function glp { param([string]$format) if($format){ git log --pretty=$format } else { git log } }
function gmtl { git mergetool --no-prompt @args }
function gmtlvim{ git mergetool --no-prompt --tool=vimdiff @args }
function gtv { git tag | Sort-Object { $_ -as [version] } }
function gtl { param($p='') git tag --sort=-v:refname -n -l "$p*" }
function gwip { git add -A; git rm (git ls-files --deleted) 2>$null; git commit --no-verify --no-gpg-sign -m "--wip-- [skip ci]" }
function gunwip { if (git log -n 1 | Select-String -Quiet -- "--wip--") { git reset HEAD~1 } }
function grsh { git reset --soft HEAD~1 }
function gccd {
param([Parameter(ValueFromRemainingArguments=$true)][string[]]$rest)
git clone --recurse-submodules @rest
$last = if ($rest.Count) { $rest[-1] } else { '' }
if ($last -match '\.git$') { $last = $last -replace '\.git$','' }
if ($last) {
$dirName = Split-Path $last -Leaf
if (Test-Path $dirName) {
Set-Location $dirName
}
}
}
function grl { git reflog @args }
# Get commit hash - returns the hash of HEAD or HEAD~n
# Usage: ghash [steps] [-Short]
# ghash - full hash of HEAD
# ghash 3 - full hash of HEAD~3
# ghash -Short - short hash of HEAD
# ghash 3 -Short - short hash of HEAD~3
function ghash {
[CmdletBinding()]
param(
[Parameter(Position=0)]
[int]$StepsBack = 0,
[Alias('s')]
[switch]$Short
)
if (-not (Test-InGitRepo)) {
Write-Error "Not a git repository." -ErrorAction Stop
return
}
$ref = if ($StepsBack -eq 0) { "HEAD" } else { "HEAD~$StepsBack" }
try {
if ($Short) {
$hash = git rev-parse --short $ref 2>$null
} else {
$hash = git rev-parse $ref 2>$null
}
if ($LASTEXITCODE -eq 0 -and $hash) {
$hash.Trim()
} else {
Write-Error "Invalid reference: $ref" -ErrorAction Stop
}
} catch {
Write-Error "Failed to get commit hash: $_" -ErrorAction Stop
}
}
function gfp {
[CmdletBinding()]
param(
[Parameter(Position = 0)]
[string]$TargetBranch,
[Parameter(Position = 1)]
[string]$OutputFile = 'series.mbox'
)
if (-not (Test-InGitRepo)) {
throw "Not a git repository."
}
$defaultRemote = git config --get checkout.defaultRemote 2>$null
if (-not $defaultRemote) { $defaultRemote = 'origin' }
if (-not $TargetBranch) {
if (Test-GitRefExists "refs/remotes/$defaultRemote/main") {
$TargetBranch = 'main'
} elseif (Test-GitRefExists "refs/remotes/$defaultRemote/master") {
$TargetBranch = 'master'
} else {
$remoteHead = git symbolic-ref --quiet "refs/remotes/$defaultRemote/HEAD" 2>$null
if ($LASTEXITCODE -eq 0 -and $remoteHead) {
$prefix = "refs/remotes/$defaultRemote/"
if ($remoteHead.StartsWith($prefix)) {
$TargetBranch = $remoteHead.Substring($prefix.Length).Trim()
}
}
}
if (-not $TargetBranch) { $TargetBranch = 'main' }
}
$range = "$defaultRemote/$TargetBranch..HEAD"
$resolvedOutput = if ([IO.Path]::IsPathRooted($OutputFile)) {
$OutputFile
} else {
Join-Path (Get-Location) $OutputFile
}
$outputDir = Split-Path -Parent $resolvedOutput
if ($outputDir -and -not (Test-Path $outputDir)) {
New-Item -ItemType Directory -Path $outputDir -Force | Out-Null
}
$stderrFile = [IO.Path]::GetTempFileName()
try {
$process = Start-Process -FilePath 'git' `
-ArgumentList @('format-patch', '--cover-letter', '--stat', '--stdout', $range) `
-NoNewWindow `
-PassThru `
-Wait `
-RedirectStandardOutput $resolvedOutput `
-RedirectStandardError $stderrFile
$stderrText = Get-Content -LiteralPath $stderrFile -Raw -ErrorAction SilentlyContinue
if ($stderrText) {
$stderrText = $stderrText.Trim()
if ($stderrText) {
Write-Host $stderrText
}
}
if ($process.ExitCode -ne 0) {
Remove-Item -LiteralPath $resolvedOutput -Force -ErrorAction SilentlyContinue
throw "git format-patch failed for '$range' (exit code: $($process.ExitCode))."
}
return $resolvedOutput
} finally {
Remove-Item -LiteralPath $stderrFile -Force -ErrorAction SilentlyContinue
}
}
function gsw {
[CmdletBinding()]
param(
[Parameter(ValueFromRemainingArguments=$true)]
[string[]]$rest
)
# Keep native behavior for advanced invocations (flags, start-points, etc.).
if ($rest.Count -ne 1 -or $rest[0].StartsWith('-')) {
git switch @rest
return
}
if (-not (Test-InGitRepo)) {
git switch @rest
return
}
$target = $rest[0].Trim()
if (-not $target) {
git switch @rest
return
}
# Prefer an existing local branch first.
if (Test-GitRefExists "refs/heads/$target") {
git switch $target
return
}
# If only remote exists, create a tracking local branch explicitly.
# This avoids ambiguous SHA/ref parsing for numeric names like "8695".
$defaultRemote = git config --get checkout.defaultRemote 2>$null
if (-not $defaultRemote) { $defaultRemote = 'origin' }
if (Test-GitRefExists "refs/remotes/$defaultRemote/$target") {
git switch --track "$defaultRemote/$target"
return
}
git switch @rest
}
function gswc { git switch -c @args }
# Alias for shorter command
# --- Set Aliases for Custom Functions ---
Set-Alias gum UpMerge
Set-Alias gur UpRebase
Set-Alias gh ghash
# ===================================================================
# Tab Completion Registration
# ===================================================================
function Register-GitAliasCompletion {
# 1. Build a map of alias functions to their git subcommands
$script:gitAliasMap = @{}
$aliasRegex = '^\s*git\s+([\w-]+)\s+'
# Get all aliases from the 'git-aliases' module
Get-Command -Module git-aliases | ForEach-Object {
$definition = (Get-Content Function:\$($_.Name)).ToString()
if ($definition -match $aliasRegex) {
$script:gitAliasMap[$_.Name] = $matches[1]
}
}
# Add custom aliases from this module without module-name lookups
# to avoid self-import recursion during module initialization.
$moduleName = $ExecutionContext.SessionState.Module.Name
Get-Command -CommandType Function |
Where-Object { $_.ModuleName -eq $moduleName } |
ForEach-Object {
$func = $_
$definition = $func.ScriptBlock.ToString()
if ($definition -match $aliasRegex) {
$subCommand = $matches[1]
$script:gitAliasMap[$func.Name] = $subCommand
}
}
# Manually add complex functions that don't fit the regex pattern
$script:gitAliasMap['gum'] = 'merge'
$script:gitAliasMap['gur'] = 'rebase'
$script:gitAliasMap['gccd'] = 'clone'
$script:gitAliasMap['gsw'] = 'switch'
if ($script:gitAliasMap.Count -eq 0) {
Write-Warning "No git alias functions were found to register for completion."
return
}
# 2. Create the proxy completer script block
$proxyCompleter = {
param($wordToComplete, $commandAst, $cursorPosition)
$commandName = $commandAst.CommandElements[0].Value
$subCommand = $script:gitAliasMap[$commandName]
# Reconstruct the command line as if 'git <subcommand>' was typed
$line = $commandAst.Extent.Text
$gitLine = $line -replace "^$commandName", "git $subCommand"
$offset = ("git $subCommand").Length - $commandName.Length
$gitCursorPosition = $cursorPosition + $offset
if ($gitCursorPosition -lt 0) { $gitCursorPosition = 0 }
if ($gitCursorPosition -gt $gitLine.Length) { $gitCursorPosition = $gitLine.Length }
# Use posh-git's official completion function
if (Get-Command GitTabExpansion -ErrorAction SilentlyContinue) {
try {
$results = GitTabExpansion $gitLine $gitCursorPosition
if ($subCommand -in @('checkout', 'switch', 'merge', 'rebase', 'branch', 'reset', 'revert')) {
return $results | ForEach-Object {
if ($null -eq $_) { return }
$completionText = $_.CompletionText
if ($completionText -is [string] -and $completionText.StartsWith('#')) {
$safeText = Convert-ToPowerShellBranchCompletionText -BranchName $completionText
return [System.Management.Automation.CompletionResult]::new(
$safeText,
$_.ListItemText,
$_.ResultType,
$_.ToolTip
)
}
return $_
}
}
return $results
} catch {
Write-Warning "posh-git's GitTabExpansion failed for alias '$commandName'."
}
}
# Fallback if posh-git isn't loaded or its function fails
if ($subCommand -in @('checkout', 'switch', 'merge', 'rebase', 'branch', 'reset', 'revert')) {
try {
$branches = git branch -a --format='%(refname:short)' |
ForEach-Object { $_ -replace '^remotes/origin/', '' } |
Sort-Object -Unique |
Where-Object { $_ -like "$wordToComplete*" }
if ($branches) {
return $branches | ForEach-Object {
$branchName = $_
$safeText = Convert-ToPowerShellBranchCompletionText -BranchName $branchName
[System.Management.Automation.CompletionResult]::new($safeText, $branchName, 'ParameterValue', $branchName)
}
}
} catch {
return @()
}
}
# Return nothing if no completions are found
return @()
}
# 3. Register the completer for every alias found
foreach ($aliasName in $script:gitAliasMap.Keys) {
# Ensure we only register for commands that actually exist
if (Get-Command $aliasName -ErrorAction SilentlyContinue) {
Register-ArgumentCompleter -CommandName $aliasName -ScriptBlock $proxyCompleter
}
}
Write-Host "Git alias tab completion is now active for $($script:gitAliasMap.Count) aliases." -ForegroundColor Cyan
}
# --- Run Registration and Export Members ---
# This runs when the module is imported
Register-GitAliasCompletion
# Export all public functions and aliases for use in the shell
Export-ModuleMember -Function * -Alias *