# ===== Microsoft.PowerShell_profile.ps1 =====
if (-not [Environment]::UserInteractive) { return }
# ---------- PSReadLine: suggestion, history, completion ----------
if (Get-Module -Name PSReadLine) {
Set-PSReadLineOption -EditMode Windows
Set-PSReadLineOption -PredictionSource History # Inline prediction from history
Set-PSReadLineOption -PredictionViewStyle InlineView # Press F2 to switch to ListView
Set-PSReadLineOption -HistoryNoDuplicates
Set-PSReadLineOption -HistorySearchCursorMovesToEnd
Set-PSReadLineOption -MaximumHistoryCount 20000
Set-PSReadLineOption -BellStyle None
Set-PSReadLineOption -ShowToolTips
Set-PSReadLineOption -Colors @{ InlinePrediction = $PSStyle.Foreground.BrightBlack }
# Prefix history search with Up/Down arrows
Set-PSReadLineKeyHandler -Key UpArrow -Function HistorySearchBackward
Set-PSReadLineKeyHandler -Key DownArrow -Function HistorySearchForward
# Tab opens selection menu instead of cycling
Set-PSReadLineKeyHandler -Key Tab -Function MenuComplete
# Exclude commands containing secrets from persistent history
Set-PSReadLineOption -AddToHistoryHandler {
param([string]$line)
if ($line -match 'password|passwd|secret|token|apikey|api_key|AsPlainText|SecureString') {
return [Microsoft.PowerShell.AddToHistoryOption]::MemoryOnly
}
return [Microsoft.PowerShell.AddToHistoryOption]::MemoryAndFile
}
}
# ---------- Lightweight git completion (no posh-git required) ----------
Register-ArgumentCompleter -Native -CommandName git -ScriptBlock {
param($wordToComplete, $commandAst, $cursorPosition)
$subcommands = 'add','am','apply','bisect','blame','branch','checkout','cherry-pick','clean',
'clone','commit','config','describe','diff','fetch','grep','init','log','merge','mv','pull',
'push','rebase','reflog','remote','reset','restore','revert','rm','show','stash','status',
'submodule','switch','tag','worktree'
$refCommands = 'checkout','switch','merge','rebase','branch','diff','log','show','cherry-pick',
'reset','push','pull','fetch','revert'
$tokens = @($commandAst.CommandElements | Select-Object -Skip 1 | ForEach-Object { $_.ToString() })
if ($wordToComplete) { $tokens = @($tokens | Select-Object -SkipLast 1) }
$sub = $tokens | Where-Object { $_ -notlike '-*' } | Select-Object -First 1
$items = @()
if (-not $sub) {
$items = $subcommands
}
elseif ($sub -in $refCommands -and $wordToComplete -notlike '-*') {
$items = @(git for-each-ref --format='%(refname:short)' refs/heads refs/remotes 2>$null) |
Where-Object { $_ -notlike '*/HEAD' }
if ($sub -in 'push','pull','fetch') { $items = @(git remote 2>$null) + $items }
}
$items | Where-Object { $_.StartsWith($wordToComplete, [StringComparison]::OrdinalIgnoreCase) } |
ForEach-Object { [System.Management.Automation.CompletionResult]::new($_, $_, 'ParameterValue', $_) }
# Fallback to filesystem completion if empty
}
# ---------- Cached Git status prompt with file counts ----------
$global:GitStatusTtlSeconds = 5 # Refresh git status at most once every 5 seconds
$global:GitStatusShowUntracked = $true # Set $false on massive repos (-uno) for speed
$script:GitCache = @{ Root = $null; Time = [datetime]::MinValue; Text = ''; HistId = -1 }
function Get-GitStatusText([string]$root) {
$gitArgs = @('--no-optional-locks', '-c', 'core.quotepath=off', 'status', '--porcelain=v2', '--branch')
$gitArgs += if ($global:GitStatusShowUntracked) { '-unormal' } else { '-uno' }
$out = & git -C $root @gitArgs 2>$null
if ($LASTEXITCODE -ne 0 -or -not $out) { return '' }
$branch = ''; $oid = ''; $ahead = 0; $behind = 0
$sA = 0; $sM = 0; $sD = 0 # staged: added / modified / deleted
$wM = 0; $wD = 0 # working tree: modified / deleted
$untracked = 0; $conflict = 0
foreach ($l in $out) {
if ($l[0] -eq '#') {
if ($l.StartsWith('# branch.head ')) { $branch = $l.Substring(14) }
elseif ($l.StartsWith('# branch.oid ')) { $oid = $l.Substring(13) }
elseif ($l.StartsWith('# branch.ab ')) {
$p = $l.Substring(12).Split(' ')
$ahead = [int]$p[0].TrimStart('+'); $behind = [int]$p[1].TrimStart('-')
}
}
elseif ($l[0] -eq '1' -or $l[0] -eq '2') {
$x = $l[2]; $y = $l[3]
switch ($x) { 'A' { $sA++ } 'M' { $sM++ } 'R' { $sM++ } 'C' { $sA++ } 'T' { $sM++ } 'D' { $sD++ } }
switch ($y) { 'M' { $wM++ } 'T' { $wM++ } 'D' { $wD++ } }
}
elseif ($l[0] -eq 'u') { $conflict++ }
elseif ($l[0] -eq '?') { $untracked++ }
}
if ($branch -eq '(detached)') { $branch = if ($oid.Length -ge 7) { $oid.Substring(0, 7) } else { 'detached' } }
$s = $PSStyle
$t = "$($s.Foreground.Yellow)($branch$($s.Reset)"
if ($ahead) { $t += " $($s.Foreground.Cyan)↑$ahead$($s.Reset)" }
if ($behind) { $t += " $($s.Foreground.Cyan)↓$behind$($s.Reset)" }
if ($sA -or $sM -or $sD) {
$t += " $($s.Foreground.Green)+$sA ~$sM -$sD$($s.Reset)"
}
if ($wM -or $wD) {
$t += " $($s.Foreground.Red)~$wM -$wD$($s.Reset)"
}
if ($untracked) { $t += " $($s.Foreground.BrightBlack)?$untracked$($s.Reset)" }
if ($conflict) { $t += " $($s.Foreground.BrightRed)!$conflict$($s.Reset)" }
$t += "$($s.Foreground.Yellow))$($s.Reset)"
return $t
}
function global:prompt {
$ok = $?
$loc = $ExecutionContext.SessionState.Path.CurrentLocation
$cwd = $loc.Path
if ($cwd.StartsWith($HOME, [StringComparison]::OrdinalIgnoreCase)) { $cwd = '~' + $cwd.Substring($HOME.Length) }
$gitInfo = ''
if ($loc.Provider.Name -eq 'FileSystem') {
# Traverse parent directories to find repository root without invoking git.exe
$dir = $loc.ProviderPath; $root = $null
while ($dir) {
$g = [IO.Path]::Combine($dir, '.git')
if ([IO.Directory]::Exists($g) -or [IO.File]::Exists($g)) { $root = $dir; break }
$dir = [IO.Path]::GetDirectoryName($dir)
}
if ($root) {
$c = $script:GitCache
$last = Get-History -Count 1
$histId = if ($last) { $last.Id } else { 0 }
# Immediately refresh status if previous command was git or a git alias
$afterGit = $last -and $histId -ne $c.HistId -and
$last.CommandLine -match '^\s*(git|g(st|aa|cmsg|push|pull|fa|df|lg|undo))\b'
$stale = $c.Root -ne $root -or
([datetime]::UtcNow - $c.Time).TotalSeconds -gt $global:GitStatusTtlSeconds
if ($stale -or $afterGit) {
$c.Root = $root; $c.Text = Get-GitStatusText $root
$c.Time = [datetime]::UtcNow
}
$c.HistId = $histId
if ($c.Text) { $gitInfo = ' ' + $c.Text }
}
}
$arrow = if ($ok) { $PSStyle.Foreground.Green } else { $PSStyle.Foreground.Red }
"$($PSStyle.Foreground.Cyan)$cwd$($PSStyle.Reset)$gitInfo`n$arrow>$($PSStyle.Reset) "
}
# ---------- Git aliases ----------
function gst { git status -sb @args }
function gaa { git add -A @args }
function gcmsg { git commit -m @args }
function gpush { git push @args }
function gpull { git pull @args }
function gfa { git fetch --all --prune @args }
function gdf { git diff @args }
function glg { git log --oneline --graph --decorate -n 20 @args }
function gundo { git reset --soft HEAD~1 }