Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Prompt only renders in ansi #771

Closed
tvfischer opened this issue May 20, 2020 · 38 comments
Closed

Prompt only renders in ansi #771

tvfischer opened this issue May 20, 2020 · 38 comments

Comments

@tvfischer
Copy link

System Details

  • posh-git version/path: 1.0.0 beta4 D:\tvfischer\PowerShell\Modules\posh-git\1.0.0
  • PowerShell version: 7.0.1
  • git version 2.21.0
  • OS: Microsoft Windows NT 10.0.18363.0

Issue Description

I am experiencing a problem with with the rendering of the prompt. It is constantly displaying what looks like the ansi version of the prompt information. See picture below.
image

Terminal code page is utf8:

[console]::inputencoding

Preamble          :
BodyName          : utf-8
EncodingName      : Unicode (UTF-8)
HeaderName        : utf-8
WebName           : utf-8
WindowsCodePage   : 1200
IsBrowserDisplay  : True
IsBrowserSave     : True
IsMailNewsDisplay : True
IsMailNewsSave    : True
IsSingleByte      : False
EncoderFallback   : System.Text.EncoderReplacementFallback
DecoderFallback   : System.Text.DecoderReplacementFallback
IsReadOnly        : True
CodePage          : 65001

If i try version 0.7.3 it renders a bit better but doesn't quite work and fails with oh-my-posh.

@GoatHead
Copy link

Same here. the prompt is not showing Hangul.
image

@rkeithhill
Copy link
Collaborator

I have a few questions. What is PS running in? PowerShell console, Windows Terminal, ConEmu, Cmder, etc? What do you get for $host.ui.SupportsVirtualTerminal? Also, the code page I see is 437. Are you running on a non-English system? Finally, what do you get if you start pwsh like so pwsh -noprofile then execute, ipmo posh-git and the cd into a Git repo?

@tvfischer
Copy link
Author

For my part, I am running it in the default pwsh console under W10 w/cmdline "C:\Program Files\PowerShell\7\pwsh.exe" -WorkingDirectory ~
I also ran it in the recent final release of windows terminal. Both show the problem.

  • pwsh window: $host.ui.SupportsVirtualTerminal = True
  • windows terminal: $host.ui.SupportsVirtualTerminal = True

I'm running on a US English W10Pro. I am however running with multiple languages
image

image

image

Same issue with noprofile
image

@rkeithhill
Copy link
Collaborator

Thanks for the extra information! That helps narrow things down. Can you check a couple of other things? Run pwsh -noprofile again and import the module while in a git dir. After the funky prompt text comes back, execute $error and post the output here. Also, execute $GitPromptValues | fl and post the output here. Thanks!

@tvfischer
Copy link
Author

Done.
$error is null when i execute it after loading the module
out put of $GitPromptValues

> $gitpromptvalues | fl

LastExitCode   : 0
DollarQuestion : True
IsAdmin        : False
LastPrompt     : D:\tvfischer\Devs\git\PoSHsnippets `e[93m[`e[39m`e[92mfvt-azshara`e[39m`e[92m ↑12`e[39m`e[31m +4`e[39m`e[31m ~1`e[39m`e[31m -0`e[39m`e[31m
                 !`e[39m`e[93m]`e[39m>

@rkeithhill
Copy link
Collaborator

No errors, hmm. FWIW, this is what you're supposed to see:
image
I'm curious about your console's ability to disolay VT sequences. Start pwsh -noprofile and show me what the following string outputs :

"`e[36;45mHello World`e[0m"

It should look like this:
image

One last thing, if you open up the Console properties, make sure the "Use legacy console" checkbox is NOT checked:
image

@tvfischer
Copy link
Author

tvfischer commented May 25, 2020

That all works. see screenshot below
image

and without the module loaded the prompt string displays fine
image

@rkeithhill
Copy link
Collaborator

rkeithhill commented May 25, 2020

I wonder if this is related to some console mode tweaks posh-git makes. Can you go to the directory where posh-git is installed and open ConsoleMode.ps1 and modify line 4? Change it from this:

if (($PSVersionTable.PSVersion.Major -ge 6) -and !$IsWindows) {

to this:

if ($PSVersionTable.PSVersion.Major -ge 6) {

This will prevent the console mode tweaks. Try importing the modified module in a pwsh -noprofile and see if the prompt displays correctly.

If the above doesn't fix it then there is only one other thing that I can think of. That is the Invoke-Utf8ConsoleCommand function. It attempts to temp change the output encoding to UTF8 and then set it back to its original encoding. It only does this if the original encoding is a single byte encoding. To see if that might be the case - assuming the ConsoleMode tweak doesn't fix this - what output do you get for these commands (run from a Git repo dir):

# Open a fresh pwsh -noprofile session
# The following ANSI string should display correctly:
"D:\tvfischer\Devs\git\PoSHsnippets `e[93m[`e[39m`e[92mfvt-azshara`e[39m`e[92m ↑12`e[39m`e[31m +4`e[39m`e[31m ~1`e[39m`e[31m -0`e[39m`e[31m!`e[39m`e[93m]`e[39m>"

# This bit is essentially what the Invoke-Utf8ConsoleCommand does without the error checking
$currentEncoding = [Console]::OutputEncoding
$currentEncoding.IsSingleByte
if ($currentEncoding.IsSingleByte) { [Console]::OutputEncoding = [Text.Encoding]::UTF8 }
git -c core.quotepath=false -c color.status=false status -unormal --short --branch 2>$null
if ($currentEncoding.IsSingleByte) { [Console]::OutputEncoding = $currentEncoding }

# Now see if the ANSI string still displays correctly:
"D:\tvfischer\Devs\git\PoSHsnippets `e[93m[`e[39m`e[92mfvt-azshara`e[39m`e[92m ↑12`e[39m`e[31m +4`e[39m`e[31m ~1`e[39m`e[31m -0`e[39m`e[31m!`e[39m`e[93m]`e[39m>"

Sorry for asking this of you. It would be easier if I could repro this but I haven't been able to. Anyway, I appreciate your willingness to help!

@tvfischer
Copy link
Author

tvfischer commented May 27, 2020

no problem happy to help.
So if I removed the code as requested in ConsoleMode.ps1. Didn't change anything, still showing the wrong prompt.
Below is screenshot of the second action you asked
image

It still isn't showing properly

@tvfischer
Copy link
Author

I'm not sure if this would have any impact but I use cygwin and the default git.exe that gets executed is the one from the cygwin installation.

@rkeithhill
Copy link
Collaborator

Good observation. Thanks because I was running out of things to try and possible failure mechanisms. BTW if you set $GitPromptSettings.AnsiConosle = $false, does that make your prompt display work for now?

@tvfischer
Copy link
Author

tvfischer commented May 30, 2020

yes it does. I ran $GitPromptSettings.AnsiConsole = $false after importing the module while in a git repo directory:

  1. cd into repo directory
  2. import module
  3. ran $GitPromptSettings.AnsiConsole = $false

image

So i guess the question is how do we make this automatic or improve the module to handle this scenario

@rkeithhill
Copy link
Collaborator

Another fix would be to use Git for Windows but yeah, there's something going on with the cygwin version of git.exe. We need to figure out if that is something we can adapt to or if not, we could disable $GitPromptSettings.AnsiConsole if we detect cygwin's git.

@tvfischer
Copy link
Author

it's funny though, cause I checked the git packages in

  • atlassian sourcetree
  • github app
  • git for windows
    they are all based on mingw which is a minimalist version/port and shares a lot of similarities with cygwin. I wonder what the difference is.
    I played around with the paths in my env variable and put git-for-windows in priority. This helped.

@rkeithhill
Copy link
Collaborator

rkeithhill commented Jun 4, 2020

I believe console apps have to declare that they support ANSI console mode. Perhaps these mingw-based versions of Git haven't done that yet. See this comment: PowerShell/PowerShell#11449 (comment) and a follow tweak to someone's console app: dialex/JColor@baa3b95#diff-df3dc36270b358a02b972f5066b69a74R332

@johnmbaughman
Copy link

johnmbaughman commented Oct 23, 2020

Just as an FYI, I get the same results in ConEmu (v 191012 [64]) with all the suggested ideas.

When I switch off ANSI, I get the listing of PowerShell color settings in the middle of the prompt using just:

$prompt += & $GitPromptScriptBlock
if ($prompt) { "$prompt" } else { "" }

image

With my prompt (a little complex, but works well for me...) and ANSI on, I don't see the prompt at all. But turn it off, I get the PS settings mixed in.

image

My prompt function:

function global:prompt {
	if (Test-Administrator) {  # Use different username if elevated
        $prompt = Write-Prompt "(Elevated) " -ForegroundColor DarkRed
    }
    else {
    	$prompt = ""
    }
	
	if ($versionIs51) {
		$charge = Get-WmiObject Win32_Battery -Property EstimatedChargeRemaining
	} 
	else {
		$charge = Get-CimInstance Win32_Battery -Property EstimatedChargeRemaining
	}
    $chargeAlert = "Gray"
    if ($charge.EstimatedChargeRemaining -lt 50)
    {
       	$chargeAlert = "Yellow"
    }
    if ($charge.EstimatedChargeRemaining -lt 25)
    {
       	$chargeAlert = "Red"
    }
    if ($charge.EstimatedChargeRemaining -lt 50) {
    	$prompt += Write-Prompt "Batt $($charge.EstimatedChargeRemaining)% : " -ForegroundColor $chargeAlert
    }
   
    $prompt += Write-Prompt "$Env:USERNAME@" -ForegroundColor DarkYellow
    $prompt += Write-Prompt "$Env:COMPUTERNAME : " -ForegroundColor DarkGray

	$GitPromptSettings.DefaultPromptAbbreviateHomeDirectory = $true
	$GitPromptSettings.DefaultPromptSuffix = '`n$(">" * ($nestedPromptLevel + 1)) '
	#$GitPromptSettings.DefaultPromptDebugSuffix = '`n [DBG]$(">" * ($nestedPromptLevel + 1)) '	  
	$prompt += Write-Prompt "$(Get-Date -Format "yyyy-MM-dd HH:mm:ss") : " -ForegroundColor DarkCyan
        $prompt += & $GitPromptScriptBlock
	 
	if ($prompt) { "$prompt" } else { "" }
}

What it should look like...

image

Just thought I'd throw this in for added info about what is going on with what I see. Going back to PS 5 for a while... ;) (J/K, I'll live with the dead prompt until you get something worked out to try again.)

@dahlbyk
Copy link
Owner

dahlbyk commented Oct 26, 2020

So turning off ANSI seems to fix cygwin, but I'd generally expect cygwin to understand ANSI so we should be able to fix it somehow.

I played around with the paths in my env variable and put git-for-windows in priority. This helped.

@tvfischer to clarify, by "this helped" do you mean the prompt works as expected with git.exe from Git for Windows?

In #771 (comment) you tried a few ANSI tests in a clean shell. I'd be curious if ANSI continues to work after you've run cygwin git (still without posh-git loaded).

When I switch off ANSI, I get the listing of PowerShell color settings in the middle of the prompt...

This seems like a bug/quirk we could fix. With AnsiConsole = $false I'd expect "$(& $GitPromptScriptBlock)" to be empty, with the git status already written to the host. That you're seeing PS> instead suggests an error. @johnmbaughman, can you check $error and $GitPromptValues | fl?

@johnmbaughman
Copy link

johnmbaughman commented Oct 26, 2020

Here ya go... From a git repository:

PS>$error

Message                     : Cannot process argument transformation on parameter 'Color'. Cannot convert the "ForegroundColor:    Red, BackgroundColor:
                              <default>" value of type "PoshGitCellColor" to type "PoshGitCellColor".
ParameterName               : Color
ParameterType               : PoshGitCellColor
TypeSpecified               : PoshGitCellColor
ErrorId                     : ParameterArgumentTransformationError
Line                        : 932
Offset                      : 50
CommandInvocation           : System.Management.Automation.InvocationInfo
ErrorRecord                 : Cannot process argument transformation on parameter 'Color'. Cannot convert the "ForegroundColor:    Red, BackgroundColor:
                              <default>" value of type "PoshGitCellColor" to type "PoshGitCellColor".
WasThrownFromThrowStatement : False
TargetSite                  : System.Collections.ObjectModel.Collection`1[System.Management.Automation.PSObject] Invoke(System.Collections.IEnumerable)
StackTrace                  :    at System.Management.Automation.Runspaces.PipelineBase.Invoke(IEnumerable input)
                                 at System.Management.Automation.Runspaces.Pipeline.Invoke()
                                 at Microsoft.PowerShell.Executor.ExecuteCommandHelper(Pipeline tempPipeline, Exception& exceptionThrown, ExecutionOptions
                              options)
Data                        : {System.Management.Automation.Interpreter.InterpretedFrameInfo}
InnerException              : System.Management.Automation.ArgumentTransformationMetadataException: Cannot convert the "ForegroundColor:    Red,
                              BackgroundColor: <default>" value of type "PoshGitCellColor" to type "PoshGitCellColor".
                               ---> System.Management.Automation.PSInvalidCastException: Cannot convert the "ForegroundColor:    Red, BackgroundColor:
                              <default>" value of type "PoshGitCellColor" to type "PoshGitCellColor".
                                 at System.Management.Automation.LanguagePrimitives.ThrowInvalidCastException(Object valueToConvert, Type resultType)
                                 at System.Management.Automation.LanguagePrimitives.ConvertNoConversion(Object valueToConvert, Type resultType, Boolean
                              recurse, PSObject originalValueToConvert, IFormatProvider formatProvider, TypeTable backupTable)
                                 at System.Management.Automation.LanguagePrimitives.ConversionData`1.Invoke(Object valueToConvert, Type resultType, Boolean
                              recurse, PSObject originalValueToConvert, IFormatProvider formatProvider, TypeTable backupTable)
                                 at System.Management.Automation.LanguagePrimitives.ConvertTo(Object valueToConvert, Type resultType, Boolean recursion,
                              IFormatProvider formatProvider, TypeTable backupTypeTable)
                                 at System.Management.Automation.ArgumentTypeConverterAttribute.Transform(EngineIntrinsics engineIntrinsics, Object inputData,
                              Boolean bindingParameters, Boolean bindingScriptCmdlet)
                                 --- End of inner exception stack trace ---
                                 at System.Management.Automation.ArgumentTypeConverterAttribute.Transform(EngineIntrinsics engineIntrinsics, Object inputData,
                              Boolean bindingParameters, Boolean bindingScriptCmdlet)
                                 at System.Management.Automation.ParameterBinderBase.BindParameter(CommandParameterInternal parameter,
                              CompiledCommandParameter parameterMetadata, ParameterBindingFlags flags)
HelpLink                    :
Source                      : System.Management.Automation
HResult                     : -2146233087


Write-Prompt: C:\Users\me\Documents\PowerShell\Modules\posh-git\1.0.0\GitPrompt.ps1:932
Line |
 932 |  …            $sb | Write-Prompt $errorText -Color $s.ErrorColor > $null
     |                                                    ~~~~~~~~~~~~~
     | Cannot process argument transformation on parameter 'Color'. Cannot convert the "ForegroundColor:    Red, BackgroundColor:
     | <default>" value of type "PoshGitCellColor" to type "PoshGitCellColor".


Write-Prompt: C:\Users\me\Documents\PowerShell\Modules\posh-git\1.0.0\GitPrompt.ps1:691
Line |
 691 |  … lder | Write-Prompt $workingStatusText -Color $s.WorkingColor > $null
     |                                                  ~~~~~~~~~~~~~~~
     | Cannot process argument transformation on parameter 'Color'. Cannot convert the "ForegroundColor:    DarkRed, BackgroundColor:
     | <default>" value of type "PoshGitCellColor" to type "PoshGitCellColor".


MethodInvocationException: C:\Program Files\PowerShell\7-preview\Modules\posh-git\src\AnsiUtils.ps1:70
Line |
  70 |                  $color = $ColorTranslatorType::FromHtml($color)
     |                  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     | Exception calling "FromHtml" with "1" argument(s): "DarkYellow is not a valid value for Int32. (Parameter 'htmlColor')"


MethodInvocationException: C:\Program Files\PowerShell\7-preview\Modules\posh-git\src\AnsiUtils.ps1:70
Line |
  70 |                  $color = $ColorTranslatorType::FromHtml($color)
     |                  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     | Exception calling "FromHtml" with "1" argument(s): "DarkYellow is not a valid value for Int32. (Parameter 'htmlColor')"
PS>$GitPromptValues | fl

LastExitCode   : 0
DollarQuestion : True
IsAdmin        : True
LastPrompt     : C:\Users\jbaughma\Desktop
                 >



PS>

Outside of a git repo, the prompt works fine.

Let me know if you need anything else!

@dahlbyk
Copy link
Owner

dahlbyk commented Oct 27, 2020

Someone reached out by email the other day with a similar issue. Switching from cygwin git to Git for Windows resolved the issue for her.

I just noticed the reported git --version is 2.21.0, rather than something like 2.21.0.windows.1. If we can't figure out why cygwin is broken, we could add a warning on load for Windows users who don't seem to be using Git for Windows?


Message : Cannot process argument transformation on parameter 'Color'. Cannot convert the "ForegroundColor: Red, BackgroundColor:
" value of type "PoshGitCellColor" to type "PoshGitCellColor".

I'm at a loss here. Is there some way you might be loading posh-git twice resulting in different types of the same name?

@dahlbyk
Copy link
Owner

dahlbyk commented Oct 27, 2020

@DHowett does anything here ring a bell to you?

@DHowett
Copy link

DHowett commented Oct 28, 2020

This one is pretty terrible and utterly unavoidable 😄 I did an investigation in microsoft/terminal#4921 (comment).

In short, the Cygwin/MSYS2 runtime likes to fiddle with the console mode, even after a process has detached from the console.

We've seen instances of git (though it's just a stand-in for any Cygwin application) turning off VT handling in the middle of powershell printing its colored prompt.

Turning it back on would be an endless arms race... but there's hope that the Cygwin runtime >=3.1 helps?

@dahlbyk
Copy link
Owner

dahlbyk commented Oct 28, 2020

@tvfischer (or anyone with Git for Cygwin handy) when you have a moment, could you check if #807 shows you a warning and works (turns off AnsiConsole automatically)?

@johnmbaughman
Copy link

Something to add with the issues I commented on, the prompt appears "correctly" with the extra config parameters when there are waiting commits to be pushed. Otherwise, it is the PS> prompt.

@johnmbaughman
Copy link

johnmbaughman commented Oct 30, 2020

I'm at a loss here. Is there some way you might be loading posh-git twice resulting in different types of the same name?

I load it once in my profile based on the version of PS I'm running.

# Make things pretty...
Write-Host "Setting prompt..." -ForegroundColor DarkGreen

if ($null -ne (Get-InstalledModule -Name "posh-git")) {
	if (($versionIs51)) {
		Import-Module posh-git
	}
	else {
		Import-Module 'C:\Program Files\PowerShell\7-preview\Modules\posh-git\src\posh-git.psd1'	
	}	
}

PS 7.1
image

And 5.1
image

Since I need to debug in 5.1 for other dev purposes, it has to be this way until someone at work here decides to upgrade a couple thousand Win10 clients to 7.1... ;)

@johnmbaughman
Copy link

Ok, I thought that upgrading to PS preview 7.2 had fixed my prompt. It had. Until I fixed the profile situation. It seems that any custom rendering fails. If I remove my custom prompt from the equation, posh-git prompt works flawlessly with the standard prompt configuration.

At least there's that much more info to go on...

@dahlbyk
Copy link
Owner

dahlbyk commented Dec 2, 2020

@tvfischer have you found posh-git v1.x doesn't work in PS 5.1? It should, so you shouldn't need the conditional import.

Can you try adding -Verbose to your Import-Module to see exactly when/what it's loading?

@johnmbaughman
Copy link

image

@dahlbyk
Copy link
Owner

dahlbyk commented Dec 3, 2020

If the module only gets imported once, I am not sure what else to try. I assume you are still getting the same type assignment error?

@drichardson
Copy link

drichardson commented Dec 9, 2020

I ran into a similar problem, and can reproduce it with PowerShell echo (Write-Output alias) and Git for Windows cat.exe.

I reported it to PowerShell/PowerShell#14360.

$ pwsh.exe -noprofile
PowerShell 7.1.0
Copyright (c) Microsoft Corporation.

https://aka.ms/powershell
Type 'help' to get help.

PS C:\Users\doug> function prompt { $ESC = [char]27; "$ESC[38;2;0;255;0mMyPrompt$ESC[0m>" }
MyPrompt>echo "n"| & 'C:\Program Files\Git\usr\bin\cat.exe'
n
←[38;2;0;255;0mMyPrompt←[0m>
MyPrompt>

If this is indeed the same issue, then the problem will not occur under Windows Powershell (only PowerShell Core). If so, this looks like a PowerShell core problem, not a posh git specific issue.

@rkeithhill
Copy link
Collaborator

@drichardson RE the original problem in this issue - I saw this PR go by on PowerShell 7 - may be related.

@drichardson
Copy link

@drichardson RE the original problem in this issue - I saw this PR go by on PowerShell 7 - may be related.

Yes, that fix is for the issue I reported (see PR context).

@johnmbaughman
Copy link

johnmbaughman commented Dec 16, 2020

The fix may possibly be in the new preview... Downloading now...

https://aka.ms/PowerShell-Release?tag=v7.2.0-preview.2

Edit: No, it isn't yet. But getting the latest regardless.

@drichardson
Copy link

FYI, fix has finally made it into master. Now just need to wait for a preview to test (I couldn't find any downloadable daily builds to test).

@drichardson
Copy link

Fix is in. I verified it fixed my problem. I don't use posh, but perhaps someone here can see if it fixes this issue too.

https://github.com/PowerShell/PowerShell/releases/tag/v7.2.0-preview.4

@johnmbaughman
Copy link

johnmbaughman commented Mar 17, 2021

My initial tests show no errors, but also a PS>_ prompt now when in a git repo. Prompt returns to "normal" when out of a git repo.

Prompt code is still this:

    $prompt += Write-Prompt "$Env:USERNAME@" -ForegroundColor DarkYellow
    $prompt += Write-Prompt "$Env:COMPUTERNAME : " -ForegroundColor DarkGray

    $GitPromptSettings.DefaultPromptAbbreviateHomeDirectory = $true
    $GitPromptSettings.DefaultPromptSuffix = '`n$(">" * ($nestedPromptLevel + 1)) '
    #$GitPromptSettings.DefaultPromptDebugSuffix = '`n [DBG]$(">" * ($nestedPromptLevel + 1)) '	  
    $prompt += Write-Prompt "$(Get-Date -Format "yyyy-MM-dd HH:mm:ss") : " -ForegroundColor DarkCyan
    $prompt += & $GitPromptScriptBlock
	 
    if ($prompt) { "$prompt" } else { "" }

@johnmbaughman
Copy link

johnmbaughman commented Mar 17, 2021

And from $error:


erroneous error message I received...

Edit: IT WORKS!

I had to play with installing the release version of posh-git, the new PS release, and a minor tweak to my profile, but it works!

@dahlbyk
Copy link
Owner

dahlbyk commented Mar 17, 2021

Great!

@tvfischer this issue has gone far afield, but it seems like things are working OK? Please reopen if you're still struggling with this.

@dahlbyk dahlbyk closed this as completed Mar 17, 2021
@RickWassum
Copy link

I know this is a really old issue, but I just had the problem where suddenly had my prompt for posh-git stop working and rendering things like this: "←[93m[←[39m←[96mmain←[39m←[93m]←[39m" where it should just have had [main]. The problem turned out to be that I had copied info from my .gitconfig at work to my .gitconfig on my home machine and it contained the line:

fsmonitor = true

This option was apparently not supported by the version of git on my home machine which resulted in posh-git displaying an incorrect prompt. Once I updated my version of git to the latest version, the problem went away.

So in short, if your prompt for posh-git stops working correctly, make sure you have not introduced issues in your git configuration.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

8 participants