A PowerShell environment for Git
Table of contents:
posh-git is a PowerShell module that integrates Git and PowerShell by providing Git status summary information that can be displayed in the PowerShell prompt, e.g.:
posh-git also provides tab completion support for common git commands, branch names, paths and more. For example, with posh-git, PowerShell can tab complete git commands like
checkoutby typing
git chand pressing the tab key. That will tab complete to
git checkoutand if you keep pressing tab, it will cycle through other command matches such as
cherryand
cherry-pick. You can also tab complete remote names and branch names e.g.:
git pull or matab completes to
git pull origin main.
| Windows (AppVeyor) | Linux/macOS (Travis) | Code Coverage Status |
|--------------------|----------------------|----------------------|
| |
|
|
posh-gitand moved into the new module posh-sshell
| Windows (AppVeyor) | Code Coverage Status |
|--------------------|----------------------|
| |
|
These installation instructions, as well as rest of this readme, applies only to version 1.x of posh-git. For v0.x installation instructions see this README.
Before installing posh-git make sure the following prerequisites have been met.
Windows PowerShell 5.x or PowerShell Core 6.0. You can get PowerShell Core 6.0 for Windows, Linux or macOS from here. Check your PowerShell version by executing
$PSVersionTable.PSVersion.
On Windows, script execution policy must be set to either
RemoteSignedor
Unrestricted. Check the script execution policy setting by executing
Get-ExecutionPolicy. If the policy is not set to one of the two required values, run PowerShell as Administrator and execute
Set-ExecutionPolicy RemoteSigned -Scope CurrentUser -Confirm.
Git must be installed and available via the PATH environment variable. Check that
gitis accessible from PowerShell by executing
git --versionfrom PowerShell. If
gitis not recognized as the name of a command, verify that you have Git installed. If not, install Git from https://git-scm.com. If you have Git installed, make sure the path to git is in your PATH environment variable.
posh-git is available on the PowerShell Gallery and can be installed using the built-in PowerShellGet module.
Start Windows PowerShell 5.x or PowerShell >= v6 (
pwsh).
Execute one of the following two commands from an elevated PowerShell prompt, depending on whether (A) you've never installed posh-git, or (B) you've already installed a previous version:
# (A) You've never installed posh-git from the PowerShell Gallery PowerShellGet\Install-Module posh-git -Scope CurrentUser -Force
NOTE: If you're asked to trust packages from the PowerShell Gallery, answer
yesto continue installation of posh-git
OR
# (B) You've already installed a previous version of posh-git from the PowerShell Gallery PowerShellGet\Update-Module posh-git
If you prefer to manage posh-git as a Windows package, you can use Chocolatey to install posh-git. If you don't have Chocolatey, you can install it from the Chocolately Install page. With Chocolatey installed, execute the following command to install posh-git:
choco install poshgit
Another popular package manager for Windows is Scoop, which you can also use to install posh-git. With Scoop installed, execute these commands to install posh-git and import it into your profile:
scoop install posh-git Add-PoshGitToProfile
If you need to test/debug changes prior to contributing here, or would otherwise prefer to install posh-git without the aid of a package manager, you can execute
Import-Module. For example, if you have git cloned posh-git to
~\git\posh-gityou can import this version of posh-git by executing
Import-Module ~\git\posh-git\src\posh-git.psd1.
After you have installed posh-git, you need to configure your PowerShell session to use the posh-git module.
The first step is to import the module into your PowerShell session which will enable git tab completion. You can do this with the command
Import-Module posh-git.
You do not want to have to manually execute the
Import-Modulecommand every time you open a new PowerShell prompt. Let's have PowerShell import this module for you in each new PowerShell session. We can do this by either executing the command
Add-PoshGitToProfileor by editing your PowerShell profile script and adding the command
Import-Module posh-git.
If you want posh-git to be available in all your PowerShell hosts (console, ISE, etc) then execute
Add-PoshGitToProfile -AllHosts. This will add a line containing
Import-Module posh-gitto the file
$profile.CurrentUserAllHosts.
If you want posh-git to be available in just the current host, then execute
Add-PoshGitToProfile. This will add the same command but to the file
$profile.CurrentUserCurrentHost.
If you want posh-git to be available for all users on the system, start PowerShell as Administrator or via sudo (
sudo pwsh) on Linux/macOS then execute
Add-PoshGitToProfile -AllUsers -AllHosts. This will add the import command to
$profile.AllUsersAllHosts.
If you want to configure posh-git for all users but only for the current host, drop the
-AllHostsparameter and the command will modify
$profile.AllUsersCurrentHost.
If you'd prefer, you can manually edit the desired PowerShell profile script. Open (or create) your profile script with the command
notepad $profile.CurrentUserAllHosts. In the profile script, add the following line:
Import-Module posh-git
Save the profile script, then close PowerShell and open a new PowerShell session. Type
git feand then press tab. If posh-git has been imported, that command should tab complete to
git fetch.
If you want posh-git to detect your own aliases for git, then you must have set the alias before importing posh-git. So if you have
Set-Alias g gitthen ensure it is executed before
Import-Module posh-git, and
g checkoutwill complete as if you'd typed
git.
The Git status summary information provides a wealth of "Git status" information at a glance, all the time in your prompt.
By default, the status summary has the following format:
[{HEAD-name} S +A ~B -C !D | +E ~F -G !H W]
[(
BeforeStatus)
{HEAD-name}is the current branch, or the SHA of a detached HEAD
Srepresents the branch status in relation to remote (tracked origin) branch.
Note: This status information reflects the state of the remote tracked branch after the last
git fetch/pullof the remote. Execute
git fetchto update to the latest on the default remote repo. If you have multiple remotes, execute
git fetch --all.
≡= The local branch in at the same commit level as the remote branch (
BranchIdenticalStatus)
↑= The local branch is ahead of the remote branch by the specified number of commits; a
git pushis required to update the remote branch (
BranchAheadStatus)
↓= The local branch is behind the remote branch by the specified number of commits; a
git pullis required to update the local branch (
BranchBehindStatus)
↕= The local branch is both ahead of the remote branch by the specified number of commits (a) and behind by the specified number of commits (b); a rebase of the local branch is required before pushing local changes to the remote branch (
BranchBehindAndAheadStatus). NOTE: this status is only available if
$GitPromptSettings.BranchBehindAndAheadDisplayis set to
Compact.
×= The local branch is tracking a branch that is gone from the remote (
BranchGoneStatus)
ABCDrepresent the index;
|(
DelimStatus);
EFGHrepresent the working directory
+= Added files
~= Modified files
-= Removed files
!= Conflicted files
As with
git statusoutput, index status is displayed in dark green and working directory status in dark red
Wrepresents the overall status of the working directory
!= There are unstaged changes in the working tree (
LocalWorkingStatusSymbol)
~= There are uncommitted changes i.e. staged changes in the working tree waiting to be committed (
LocalStagedStatusSymbol)
None = There are no unstaged or uncommitted changes to the working tree (
LocalDefaultStatusSymbol)
](
AfterStatus)
The symbols and surrounding text can be customized by the corresponding properties on
$GitPromptSettings.
For example, a status of
[main ≡ +0 ~2 -1 | +1 ~1 -0]corresponds to the following
git status:
# On branch main # # Changes to be committed: # (use "git reset HEAD ..." to unstage) # # modified: this-changed.txt # modified: this-too.txt # deleted: gone.ps1 # # Changed but not updated: # (use "git add ..." to update what will be committed) # (use "git checkout -- ..." to discard changes in working directory) # # modified: not-staged.ps1 # # Untracked files: # (use "git add ..." to include in what will be committed) # # new.file
posh-git adds variables to your session to let you customize it, including
$GitPromptSettings,
$GitTabSettings, and
$TortoiseGitSettings. For an example of how to configure your PowerShell profile script to import the posh-git module and create a custom prompt function that displays git status info, see the Customizing Your PowerShell Prompt section below.
Note on performance: Displaying file status in the git prompt for a very large repo can be prohibitively slow. Rather than turn off file status entirely (
$GitPromptSettings.EnableFileStatus = $false), you can disable it on a repo-by-repo basis by adding individual repository paths to
$GitPromptSettings.RepositoriesInWhichToDisableFileStatus.
When you import the posh-git module, it will replace PowerShell's default prompt function with a new prompt function. The posh-git prompt function will display Git status summary information when the current directory is inside a Git repository. posh-git will not replace the prompt function if it has detected that you have your own, customized prompt function.
The prompt function provided by posh-git creates a prompt that looks like this:
You can customize the posh-git prompt function or define your own custom prompt function. The rest of this section covers how to customize posh-git's prompt function using the global variable
$GitPromptSettings.
If you'd like to make any of following changes permanent, i.e. available whenever you start PowerShell, put the corresponding setting(s) in one of your profile scripts after the line that imports posh-git.
For instance, you can customize the default prompt prefix to display a colored timestamp with these settings:
$GitPromptSettings.DefaultPromptPrefix.Text = '$(Get-Date -f "MM-dd HH:mm:ss") ' $GitPromptSettings.DefaultPromptPrefix.ForegroundColor = [ConsoleColor]::Magenta
This will change the prompt to:
If you would prefer not to have any path under your home directory abbreviated with
~, use the following setting:
$GitPromptSettings.DefaultPromptAbbreviateHomeDirectory = $false
This will change the prompt to:
If you would like to change the color of the path, you can use the following setting on Windows:
$GitPromptSettings.DefaultPromptPath.ForegroundColor = 'Orange'
Note: Setting the ForegroundColor to a color name, other than one of the standard ConsoleColor names, only works on Windows. On Windows, posh-git uses the
[System.Drawing.ColorTranslator]::FromHtml(string colorName)method to parse a color name as an HTML color. For a complete list of HTML colors, see this W3Schools page.
If you are on Linux or macOS and desire an Orange path, you will need to specify the RGB value for Orange e.g.:
$GitPromptSettings.DefaultPromptPath.ForegroundColor = 0xFFA500
This will change the prompt to:
If you would like to make your prompt span two lines, with a newline after the Git status summary, use this setting:
$GitPromptSettings.DefaultPromptBeforeSuffix.Text = '`n'
This will change the prompt to:
You can swap the order of the path and the Git status summary with the following setting:
$GitPromptSettings.DefaultPromptWriteStatusFirst = $true
This will change the prompt to:
Finally, you can combine these settings to customize the posh-git prompt fairly significantly. In the
DefaultPromptSuffixfield below, we are prepending the PowerShell history id number before the prompt char
>e.g.:
$GitPromptSettings.DefaultPromptWriteStatusFirst = $true $GitPromptSettings.DefaultPromptBeforeSuffix.Text = '`n$([DateTime]::now.ToString("MM-dd HH:mm:ss"))' $GitPromptSettings.DefaultPromptBeforeSuffix.ForegroundColor = 0x808080 $GitPromptSettings.DefaultPromptSuffix = ' $((Get-History -Count 1).id + 1)$(">" * ($nestedPromptLevel + 1)) '
This will change the prompt to:
Finally, the path portion of the prompt can be contained within delimiters. For instance, if you would like the containing characters to be red, curly braces, the following settings can be used:
$GitPromptSettings.BeforePath = '{' $GitPromptSettings.AfterPath = '}' $GitPromptSettings.BeforePath.ForegroundColor = 'Red' $GitPromptSettings.AfterPath.ForegroundColor = 'Red'
With these additional values, the previous prompt would become
For reference, the following layouts show the relative position of the various parts of the posh-git prompt. Note that
<>denotes parts of the prompt that may not appear depending on the status of settings and whether or not the current dir is in a Git repository. To simplify the layout,
DPis being used as an abbreviation for
DefaultPromptsettings.
Default prompt layout:
{DPPrefix}{BeforePath}{DPPath}{AfterPath}{PathStatusSeparator}{DPBeforeSuffix}{DPSuffix}
Prompt layout when DefaultPromptWriteStatusFirst is set to $true:
{DPPrefix}{PathStatusSeparator}{BeforePath}{DPPath}{AfterPath}{DPBeforeSuffix}{DPSuffix}
If you want to display the error status of the last command, you can use the values stored in the
$global:GitPromptValuesobject which includes the value of
$LastExitCodeand
$?(represented by the property
DollarQuestion). Here is a prompt customization that displays a Red exit code value when
$LastExitCodeis non-zero or a Red
!if
$?is
$false:
function global:PromptWriteErrorInfo() { if ($global:GitPromptValues.DollarQuestion) { return }if ($global:GitPromptValues.LastExitCode) { "`e[31m(" + $global:GitPromptValues.LastExitCode + ") `e[0m" } else { "`e[31m! `e[0m" }
}
$global:GitPromptSettings.DefaultPromptBeforeSuffix.Text = '`n$(PromptWriteErrorInfo)$([DateTime]::now.ToString("MM-dd HH:mm:ss"))'
When a PowerShell command fails, this is the prompt you will see:
When an external application returns a non-zero exit code, 1 in this case, you will see the exit code in the prompt:
Note that until you run an external application that sets
$LASTEXITCODEto zero or you manually set the variable to 0, you will see the exit code for any error. In addition to
LastExitCodeand
DollarQuestion,
$global:GitPromptValuesalso has
IsAdminand
LastPromptproperties. The
LastPromptproperty contains the ANSI escaped string that was used for the last prompt. This can be useful for debugging your prompt display particularly when using ANSI/VT sequences.
If you require even more customization than
$GitPromptSettingsprovides, you can create your own prompt function to show whatever information you want. See the Customizing Your PowerShell Prompt wiki page for details.
However, if you need a custom prompt just to perform some non-prompt logic, you can still use posh-git's prompt function to write out the prompt string. This can be done with the
$GitPromptScriptBlockvariable as shown below e.g.:
# my profile.ps1 function prompt { # Your non-prompt logic here# Have posh-git display its default prompt & $GitPromptScriptBlock
}
And if you'd like to write prompt text before and/or after the posh-git prompt, you can use posh-git's
Write-Promptcommand as shown below:
# my profile.ps1 function prompt { # Your non-prompt logic here $prompt = Write-Prompt "Text before posh-git prompt " -ForegroundColor ([ConsoleColor]::Green) $prompt += & $GitPromptScriptBlock $prompt += Write-Prompt "Text after posh-git prompt" -ForegroundColor ([ConsoleColor]::Magenta) if ($prompt) { "$prompt " } else { " " } }