¿Cómo puedo mostrar mi actual git branch nombre en mi PowerShell?
-
18-09-2019 - |
Pregunta
Básicamente estoy después de este pero para PowerShell en lugar de bash.
Puedo usar git en windows a través de PowerShell.Si es posible, me gustaría que mi actual nombre de la sucursal a la que aparece como parte de la línea de comandos.
Solución
Una forma más fácil sería simplemente instalar el módulo de Powershell pijo-GIT . Se sale de la caja con el símbolo deseado:
el símbolo
PowerShell genera su pronta mediante la ejecución de una función del sistema, si es que existe. elegante-GIT define una función tal en profile.example.ps1 que emite el directorio de trabajo actual seguido de un estado de git abreviado:
C:\Users\Keith [master]>
Por defecto, el resumen de estado tiene el siguiente formato:
[{HEAD-name} +A ~B -C !D | +E ~F -G !H]
(para instalar elegante-GIT se sugiere emplear psget )
Si usted no tiene psget utilice el siguiente comando:
(new-object Net.WebClient).DownloadString("http://psget.net/GetPsGet.ps1") | iex
Para instalar pijo-GIT utilice el comando:
Install-Module posh-git
Para asegurar cargas elegante-GIT para cada shell, utilice el comando Add-PoshGitToPrompt
.
Otros consejos
@ Pablo -
Mi perfil PowerShell para Git se basa apagado de un script que encontré aquí:
http: // techblogging .wordpress.com / 2008/10/12 / visualización-git-rama-en-su-PowerShell-prompt /
He modificado un poco para mostrar la ruta del directorio y un poco de formato. También establece la ruta de mi lugar de bin Git desde que uso PortableGit.
# General variables
$pathToPortableGit = "D:\shared_tools\tools\PortableGit"
$scripts = "D:\shared_tools\scripts"
# Add Git executables to the mix.
[System.Environment]::SetEnvironmentVariable("PATH", $Env:Path + ";" + (Join-Path $pathToPortableGit "\bin") + ";" + $scripts, "Process")
# Setup Home so that Git doesn't freak out.
[System.Environment]::SetEnvironmentVariable("HOME", (Join-Path $Env:HomeDrive $Env:HomePath), "Process")
$Global:CurrentUser = [System.Security.Principal.WindowsIdentity]::GetCurrent()
$UserType = "User"
$CurrentUser.Groups | foreach {
if ($_.value -eq "S-1-5-32-544") {
$UserType = "Admin" }
}
function prompt {
# Fun stuff if using the standard PowerShell prompt; not useful for Console2.
# This, and the variables above, could be commented out.
if($UserType -eq "Admin") {
$host.UI.RawUI.WindowTitle = "" + $(get-location) + " : Admin"
$host.UI.RawUI.ForegroundColor = "white"
}
else {
$host.ui.rawui.WindowTitle = $(get-location)
}
Write-Host("")
$status_string = ""
$symbolicref = git symbolic-ref HEAD
if($symbolicref -ne $NULL) {
$status_string += "GIT [" + $symbolicref.substring($symbolicref.LastIndexOf("/") +1) + "] "
$differences = (git diff-index --name-status HEAD)
$git_update_count = [regex]::matches($differences, "M`t").count
$git_create_count = [regex]::matches($differences, "A`t").count
$git_delete_count = [regex]::matches($differences, "D`t").count
$status_string += "c:" + $git_create_count + " u:" + $git_update_count + " d:" + $git_delete_count + " | "
}
else {
$status_string = "PS "
}
if ($status_string.StartsWith("GIT")) {
Write-Host ($status_string + $(get-location) + ">") -nonewline -foregroundcolor yellow
}
else {
Write-Host ($status_string + $(get-location) + ">") -nonewline -foregroundcolor green
}
return " "
}
Hasta ahora, esto ha funcionado muy bien. Mientras que en un acuerdo de recompra, el símbolo felizmente se ve así:
GIT [maestro] c: 0 u: 1 d: 0 | J: \ Proyectos \ horquillas \ fluidez-nhibernate>
* NOTA: Se ha actualizado con las sugerencias de Jakub Narębski.
-
llamadas de estado
- git branch Eliminado / Git.
- Resuelve un problema por el que 'git config --global' sería -. Fracasar debido a $ HOME no se estableció
- Resuelve un problema por el que la navegación en un directorio que no tiene el directorio .git haría que el formato para volver a la línea de PS.
Esta es mi opinión sobre ella. He editado los colores un poco para que sea más legible.
Microsoft.PowerShell_profile.ps1
function Write-BranchName () {
try {
$branch = git rev-parse --abbrev-ref HEAD
if ($branch -eq "HEAD") {
# we're probably in detached HEAD state, so print the SHA
$branch = git rev-parse --short HEAD
Write-Host " ($branch)" -ForegroundColor "red"
}
else {
# we're on an actual branch, so print it
Write-Host " ($branch)" -ForegroundColor "blue"
}
} catch {
# we'll end up here if we're in a newly initiated git repo
Write-Host " (no branches yet)" -ForegroundColor "yellow"
}
}
function prompt {
$base = "PS "
$path = "$($executionContext.SessionState.Path.CurrentLocation)"
$userPrompt = "$('>' * ($nestedPromptLevel + 1)) "
Write-Host "`n$base" -NoNewline
if (Test-Path .git) {
Write-Host $path -NoNewline -ForegroundColor "green"
Write-BranchName
}
else {
# we're not in a repo so don't bother displaying branch name/sha
Write-Host $path -ForegroundColor "green"
}
return $userPrompt
}
Ejemplo 1:
Ejemplo 2:
He ajustado el símbolo de código (de @david-longnecker respuesta) para ser un poco más colorido.
Editar: De junio de 2019 - Actualiza para mostrar sin seguimiento, escondites, cambia el nombre.Ajustado visual para mostrar el índice.
Por qué Yo el uso de este (más elegantes-git, etc):
- Aprendizaje:Aprender cosas sobre git/SCM conceptos como cuando me tweak
- Terminar la fijación de los problemas resueltos por posh-git, pero tengo que aprender más a través de este
- La Plataforma De La Cruz:Tienen el mismo símbolo en POSIX conchas, el código es casi idéntico.
- Flexible:He ajustado mi mensaje para mostrar sin marcar/escondites/índice/cambia el nombre.
- Ligero Y Portátil:No obtención de módulos externos (esto es beneficio menor, pero bueno)
El código de powershell:
NOTA: Algunos comandos usados son de porcelana (no se recomienda para la creación de scripts/análisis de, por ejemplo, git status
).Eventualmente migrar a plomería los comandos, pero esto funciona por ahora.
Function Prompt {
$SYMBOL_GIT_BRANCH='⑂'
$SYMBOL_GIT_MODIFIED='*'
$SYMBOL_GIT_PUSH='↑'
$SYMBOL_GIT_PULL='↓'
if (git rev-parse --git-dir 2> $null) {
$symbolicref = $(git symbolic-ref --short HEAD 2>$NULL)
if ($symbolicref) {#For branches append symbol
$branch = $symbolicref.substring($symbolicref.LastIndexOf("/") +1)
$branchText=$SYMBOL_GIT_BRANCH + ' ' + $branch
} else {#otherwise use tag/SHA
$symbolicref=$(git describe --tags --always 2>$NULL)
$branch=$symbolicref
$branchText=$symbolicref
}
} else {$symbolicref = $NULL}
if ($symbolicref -ne $NULL) {
# Tweak:
# When WSL and Powershell terminals concurrently viewing same repo
# Stops from showing CRLF/LF differences as updates
git status > $NULL
#Do git fetch if no changes in last 10 minutes
# Last Reflog: Last time upstream was updated
# Last Fetch: Last time fetch/pull was ATTEMPTED
# Between the two can identify when last updated or attempted a fetch.
$MaxFetchSeconds = 600
$upstream = $(git rev-parse --abbrev-ref "@{upstream}")
$lastreflog = $(git reflog show --date=iso $upstream -n1)
if ($lastreflog -eq $NULL) {
$lastreflog = (Get-Date).AddSeconds(-$MaxFetchSeconds)
}
else {
$lastreflog = [datetime]$($lastreflog | %{ [Regex]::Matches($_, "{(.*)}") }).groups[1].Value
}
$gitdir = $(git rev-parse --git-dir)
$TimeSinceReflog = (New-TimeSpan -Start $lastreflog).TotalSeconds
if (Test-Path $gitdir/FETCH_HEAD) {
$lastfetch = (Get-Item $gitdir/FETCH_HEAD).LastWriteTime
$TimeSinceFetch = (New-TimeSpan -Start $lastfetch).TotalSeconds
} else {
$TimeSinceFetch = $MaxFetchSeconds + 1
}
#Write-Host "Time since last reflog: $TimeSinceReflog"
#Write-Host "Time since last fetch: $TimeSinceFetch"
if (($TimeSinceReflog -gt $MaxFetchSeconds) -AND ($TimeSinceFetch -gt $MaxFetchSeconds)) {
git fetch --all | Out-Null
}
#Identify stashes
$stashes = $(git stash list 2>$NULL)
if ($stashes -ne $NULL) {
$git_stashes_count=($stashes | Measure-Object -Line).Lines
}
else {$git_stashes_count=0}
#Identify how many commits ahead and behind we are
#by reading first two lines of `git status`
#Identify how many untracked files (matching `?? `)
$marks=$NULL
(git status --porcelain --branch 2>$NULL) | ForEach-Object {
If ($_ -match '^##') {
If ($_ -match 'ahead\ ([0-9]+)') {$git_ahead_count=[int]$Matches[1]}
If ($_ -match 'behind\ ([0-9]+)') {$git_behind_count=[int]$Matches[1]}
}
#Identify Added/UnTracked files
elseIf ($_ -match '^A\s\s') {
$git_index_added_count++
}
elseIf ($_ -match '^\?\?\ ') {
$git_untracked_count++
}
#Identify Modified files
elseIf ($_ -match '^MM\s') {
$git_index_modified_count++
$git_modified_count++
}
elseIf ($_ -match '^M\s\s') {
$git_index_modified_count++
}
elseIf ($_ -match '^\sM\s') {
$git_modified_count++
}
#Identify Renamed files
elseIf ($_ -match '^R\s\s') {
$git_index_renamed_count++
}
#Identify Deleted files
elseIf ($_ -match '^D\s\s') {
$git_index_deleted_count++
}
elseIf ($_ -match '^\sD\s') {
$git_deleted_count++
}
}
$branchText+="$marks"
}
if (test-path variable:/PSDebugContext) {
Write-Host '[DBG]: ' -nonewline -foregroundcolor Yellow
}
Write-Host "PS " -nonewline -foregroundcolor White
Write-Host $($executionContext.SessionState.Path.CurrentLocation) -nonewline -foregroundcolor White
if ($symbolicref -ne $NULL) {
Write-Host (" [ ") -nonewline -foregroundcolor Magenta
#Output the branch in prettier colors
If ($branch -eq "master") {
Write-Host ($branchText) -nonewline -foregroundcolor White
}
else {Write-Host $branchText -nonewline -foregroundcolor Red}
#Output commits ahead/behind, in pretty colors
If ($git_ahead_count -gt 0) {
Write-Host (" $SYMBOL_GIT_PUSH") -nonewline -foregroundcolor White
Write-Host ($git_ahead_count) -nonewline -foregroundcolor Green
}
If ($git_behind_count -gt 0) {
Write-Host (" $SYMBOL_GIT_PULL") -nonewline -foregroundcolor White
Write-Host ($git_behind_count) -nonewline -foregroundcolor Yellow
}
#Output staged changes count, if any, in pretty colors
If ($git_index_added_count -gt 0) {
Write-Host (" Ai:") -nonewline -foregroundcolor White
Write-Host ($git_index_added_count) -nonewline -foregroundcolor Green
}
If ($git_index_renamed_count -gt 0) {
Write-Host (" Ri:") -nonewline -foregroundcolor White
Write-Host ($git_index_renamed_count) -nonewline -foregroundcolor DarkGreen
}
If ($git_index_modified_count -gt 0) {
Write-Host (" Mi:") -nonewline -foregroundcolor White
Write-Host ($git_index_modified_count) -nonewline -foregroundcolor Yellow
}
If ($git_index_deleted_count -gt 0) {
Write-Host (" Di:") -nonewline -foregroundcolor White
Write-Host ($git_index_deleted_count) -nonewline -foregroundcolor Red
}
#Output unstaged changes count, if any, in pretty colors
If (($git_index_added_count) -OR ($git_index_modified_count) -OR ($git_index_deleted_count)) {
If (($git_modified_count -gt 0) -OR ($git_deleted_count -gt 0)) {
Write-Host (" |") -nonewline -foregroundcolor White
}
}
If ($git_modified_count -gt 0) {
Write-Host (" M:") -nonewline -foregroundcolor White
Write-Host ($git_modified_count) -nonewline -foregroundcolor Yellow
}
If ($git_deleted_count -gt 0) {
Write-Host (" D:") -nonewline -foregroundcolor White
Write-Host ($git_deleted_count) -nonewline -foregroundcolor Red
}
If (($git_untracked_count -gt 0) -OR ($git_stashes_count -gt 0)) {
Write-Host (" |") -nonewline -foregroundcolor White
}
If ($git_untracked_count -gt 0) {
Write-Host (" untracked:") -nonewline -foregroundcolor White
Write-Host ($git_untracked_count) -nonewline -foregroundcolor Red
}
If ($git_stashes_count -gt 0) {
Write-Host (" stashes:") -nonewline -foregroundcolor White
Write-Host ($git_stashes_count) -nonewline -foregroundcolor Yellow
}
Write-Host (" ]") -nonewline -foregroundcolor Magenta
}
$(Write-Host $('>' * ($nestedPromptLevel + 1)) -nonewline -foregroundcolor White)
return " "}#Powershell requires a return, otherwise defaults to factory prompt
El resultado (VSCode, el Uso de Powershell terminal):
Aquí están los comandos de resultado para ver lo que se vería como:
mkdir "c:\git\newrepo" | Out-Null
cd "c:\git\newrepo"
git init
"test" >> ".gitignore"
"test" >> ".gitignore2"
git add -A
git commit -m "test commit" | Out-Null
"test" >> ".gitignore1"
git add -A
"test1" >> ".gitignore2"
git rm .gitignore
git add -A
git commit -m "test commit2" | Out-Null
git checkout -b "newfeature1"
"test" >> ".test"
mv .gitignore1 .gitignore3
git add -A
git stash
git checkout "master"
cd c:\git\test #Just a sample repo had that was ahead 1 commit
#Remove-Item "c:\git\newrepo" -Recurse -Force #Cleanup