2009-08-17 12 views

Respuesta

28

Una manera más fácil sería simplemente instalar el módulo Powershell posh-git. Se sale de la caja con el símbolo deseado:

el símbolo

PowerShell genera por su pronta ejecución de una función pronto, si es que existe. pijo-GIT define una función de este tipo en profile.example.ps1 que emite el directorio de trabajo actual seguido de un git status abreviada:

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 la instalación elegante-GIT se sugiere emplear psget)

I f usted no tiene psget utilizar 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 pijo-GIT para todos los depósitos, utilice el Add-PoshGitToPrompt command.

+0

¿Cómo habilito este módulo en el inicio? Parece que powershell olvida este módulo cada vez que abro una nueva instancia. – Mihir

+0

@Mihir tienes que crear un perfil, mira las respuestas https://stackoverflow.com/questions/24914589/how-to-create-permanent-powershell-aliases# –

+1

@NicolaPeluchetti ¡Gracias! Seguí https://www.howtogeek.com/50236/customizing-your-powershell-profile/ y acabo de agregar 'Import-Module posh-git' en mi perfil de Powershell. ¡Trabajado como un encanto! – Mihir

23

@ Paul-

Mi perfil PowerShell para Git se basa apagado de un script que encontré aquí:

http://techblogging.wordpress.com/2008/10/12/displaying-git-branch-on-your-powershell-prompt/

He modificado un poco para mostrar la ruta del directorio y un poco de formateo. También establece el camino a mi ubicación de la papelera de Git ya 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 está en un repositorio, el mensaje se ve felizmente como:

GIT [maestro] c: 0 u: 1 d: 0 | J: \ Projects \ forks \ fluent-nhibernate>

* NOTA: Actualizado con sugerencias de Jakub Narębski.

  • Se han eliminado las llamadas de estado de git branch/git.
  • Resolvió un problema por el cual 'git config --global' fallaría porque $ HOME no estaba configurado.
  • Se solucionó un problema por el que navegar a un directorio que no tenía el directorio .git ocasionaba que el formato volviera al indicador de PS.
+0

Cheers David, pude modificar esto fácilmente y usar las instrucciones de la publicación enlazada en el blog para poner en marcha algo que me conviene. –

+6

No raspe la salida de git-branch para obtener el nombre de la rama actual; es para el usuario final (es porcelana). Use 'git symbolic-ref HEAD'. No use git-status; está destinado para el usuario final y está sujeto a cambios (cambiaría en 1.7.0). Utilice git-diff-files, git-diff-tree, git-diff-index. –

+0

#Jakub Narębski - Actualicé el código según sus sugerencias - muchas gracias. Como no llama a la rama y al estado, también es bastante más rápido. –

1

Pellizqué el código de solicitud (de @ david-longnecker answer) para ser un poco más colorido.

Aquí está mi código

Function Prompt { 
Write-Host("") 
Remove-Variable status_string 
Remove-Variable branch 
Remove-Variable localchanges 
$symbolicref = git symbolic-ref HEAD 

if($symbolicref -ne $NULL) { 
    $status_string += "GIT" 
    $branch = $symbolicref.substring($symbolicref.LastIndexOf("/") +1) 

    $differences = (git diff-index --name-status HEAD) 
    If ($differences -ne $NULL) { 
    $localchanges = $true 
    $git_create_count = [regex]::matches($differences, "A`t").count 
    $git_update_count = [regex]::matches($differences, "M`t").count 
    $git_delete_count = [regex]::matches($differences, "D`t").count 
    } 
    else { 
    $localchanges = $false 
    $git_create_count = 0 
    $git_update_count = 0 
    $git_delete_count = 0 
    } 
    #$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) -nonewline -foregroundcolor White 

    #Output the branch in prettier colors 
    Write-Host (" [") -nonewline -foregroundcolor White 
     If ($branch -ne "master") {Write-Host ($branch) -nonewline -foregroundcolor Red} 
     else {Write-Host ($branch) -nonewline -foregroundcolor DarkYellow} 
    Write-Host ("] ") -nonewline -foregroundcolor White 

    #Output changes count, if any, in pretty colors 
    If ($localchanges) { 
    Write-Host ("c:") -nonewline -foregroundcolor White 
     If ($git_create_count -gt 0) {Write-Host ($git_create_count) -nonewline -foregroundcolor Green} 
     else {Write-Host ($git_create_count) -nonewline -foregroundcolor White} 
    Write-Host (" u:") -nonewline -foregroundcolor White 
     If ($git_update_count -gt 0) {Write-Host ($git_update_count) -nonewline -foregroundcolor Yellow} 
     else {Write-Host ($git_update_count) -nonewline -foregroundcolor White} 
    Write-Host (" d:") -nonewline -foregroundcolor White 
     If ($git_delete_count -gt 0) {Write-Host ($git_delete_count) -nonewline -foregroundcolor Red} 
     else {Write-Host ($git_delete_count + " ") -nonewline -foregroundcolor White} 
    } 

    #Output the normal prompt details, namely the path 
    Write-Host ("| " + $((get-location).Path) + ">") -nonewline -foregroundcolor White 
} 
else { 
    Write-Host ($status_string + $((get-location).Path) + ">") -nonewline -foregroundcolor White 
} 
return " "} 

El resultado: Results

Éstos son los comandos de resultado para ver lo que se vería así:

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" 
git checkout "master" 
8

Aquí está mi opinión sobre ella. He editado los colores un poco para hacerlo 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:

enter image description here

Ejemplo 2:

enter image description here

+0

¡Aseado! Acabo de cambiar los colores de mi fondo. ¿Cuál es tu color de fondo? –

+0

@YogeeshSeralathan Estoy usando el tema de Monokai para ConEmu. El color de fondo es # 272822 – tamj0rd2

Cuestiones relacionadas