refactor(pwsh): purify global scope and environment

This commit is contained in:
L. Yeung 2022-04-21 13:59:00 +08:00 committed by Jan De Dobbeleer
parent 9214b88475
commit c37733e3ec
3 changed files with 32 additions and 42 deletions

2
.vscode/launch.json vendored
View file

@ -11,7 +11,7 @@
"prompt", "prompt",
"print", "print",
"primary", "primary",
"--config==${workspaceRoot}/themes/cinnamon.omp.json", "--config=${workspaceRoot}/themes/cinnamon.omp.json",
"--shell=pwsh", "--shell=pwsh",
"--terminal-width=200", "--terminal-width=200",
] ]

View file

@ -185,7 +185,7 @@ function Set-PoshPrompt {
# Workaround for get-location/push-location/pop-location from within a module # Workaround for get-location/push-location/pop-location from within a module
# https://github.com/PowerShell/PowerShell/issues/12868 # https://github.com/PowerShell/PowerShell/issues/12868
# https://github.com/JanDeDobbeleer/oh-my-posh2/issues/113 # https://github.com/JanDeDobbeleer/oh-my-posh2/issues/113
$global:omp_global_sessionstate = $PSCmdlet.SessionState $global:OMP_GLOBAL_SESSIONSTATE = $PSCmdlet.SessionState
$poshCommand = Get-PoshCommand $poshCommand = Get-PoshCommand
(& $poshCommand init pwsh --config="$config") | Invoke-Expression (& $poshCommand init pwsh --config="$config") | Invoke-Expression

View file

@ -8,15 +8,15 @@ function global:Start-Utf8Process {
$StartInfo = $Process.StartInfo $StartInfo = $Process.StartInfo
$StartInfo.StandardErrorEncoding = $StartInfo.StandardOutputEncoding = [System.Text.Encoding]::UTF8 $StartInfo.StandardErrorEncoding = $StartInfo.StandardOutputEncoding = [System.Text.Encoding]::UTF8
$StartInfo.RedirectStandardError = $StartInfo.RedirectStandardInput = $StartInfo.RedirectStandardOutput = $true $StartInfo.RedirectStandardError = $StartInfo.RedirectStandardInput = $StartInfo.RedirectStandardOutput = $true
$StartInfo.FileName = $filename $StartInfo.FileName = $Filename
$StartInfo.Arguments = $Arguments $StartInfo.Arguments = $Arguments
$StartInfo.UseShellExecute = $false $StartInfo.UseShellExecute = $false
if ($PWD.Provider.Name -eq 'FileSystem') { if ($PWD.Provider.Name -eq 'FileSystem') {
$StartInfo.WorkingDirectory = $PWD.ProviderPath $StartInfo.WorkingDirectory = $PWD.ProviderPath
} }
$StartInfo.CreateNoWindow = $true $StartInfo.CreateNoWindow = $true
$_ = $Process.Start(); $Process.Start() | Out-Null
$_ = $Process.WaitForExit(); $Process.WaitForExit() | Out-Null
$stderr = $Process.StandardError.ReadToEnd().Trim() $stderr = $Process.StandardError.ReadToEnd().Trim()
if ($stderr -ne '') { if ($stderr -ne '') {
$Host.UI.WriteErrorLine($stderr) $Host.UI.WriteErrorLine($stderr)
@ -29,25 +29,19 @@ $env:CONDA_PROMPT_MODIFIER = $false
$env:SHELL_VERSION = $PSVersionTable.PSVersion.ToString() $env:SHELL_VERSION = $PSVersionTable.PSVersion.ToString()
# specific module support (disabled by default) # specific module support (disabled by default)
$omp_value = $env:POSH_GIT_ENABLED if ($null -eq $env:POSH_GIT_ENABLED) {
if ($null -eq $omp_value) {
$env:POSH_GIT_ENABLED = $false $env:POSH_GIT_ENABLED = $false
} }
# used to detect empty hit # used to detect empty hit
$global:omp_lastHistoryId = -1 $global:OMP_LASTHISTORYID = -1
$omp_config = "::CONFIG::" if (Test-Path "::CONFIG::") {
if (Test-Path $omp_config) { $env:POSH_THEME = (Resolve-Path -Path "::CONFIG::").ProviderPath
$env:POSH_THEME = (Resolve-Path -Path $omp_config).ProviderPath
} }
Remove-Variable omp_value -Confirm:$false
Remove-Variable omp_config -Confirm:$false
# set secondary prompt` # set secondary prompt`
$secondaryPrompt = @(Start-Utf8Process "::OMP::" "print secondary --config=""$Env:POSH_THEME""") -join "`n" Set-PSReadLineOption -ContinuationPrompt (@(Start-Utf8Process "::OMP::" "print secondary --config=""$Env:POSH_THEME""") -join "`n")
Set-PSReadLineOption -ContinuationPrompt $secondaryPrompt
function global:Set-PoshContext {} function global:Set-PoshContext {}
@ -66,16 +60,16 @@ function global:Initialize-ModuleSupport {
} }
} }
[ScriptBlock]$Prompt = { Set-Item -Force -Path Function:prompt -Value {
#store if the last command was successful #store if the last command was successful
$lastCommandSuccess = $? $lastCommandSuccess = $?
#store the last exit code for restore #store the last exit code for restore
$realLASTEXITCODE = $global:LASTEXITCODE $realLASTEXITCODE = $global:LASTEXITCODE
$omp = "::OMP::" $omp = "::OMP::"
$cleanPWD, $cleanPSWD = Get-PoshContext $cleanPWD, $cleanPSWD = Get-PoshContext
if ($env:POSH_TRANSIENT -eq $true) { if ($global:POSH_TRANSIENT -eq $true) {
@(Start-Utf8Process $omp "print transient --error=$global:OMP_ERRORCODE --pwd=""$cleanPWD"" --pswd=""$cleanPSWD"" --execution-time=$global:OMP_EXECUTIONTIME --config=""$Env:POSH_THEME"" --shell-version=""$env:SHELL_VERSION""") -join "`n" @(Start-Utf8Process $omp "print transient --error=$global:OMP_ERRORCODE --pwd=""$cleanPWD"" --pswd=""$cleanPSWD"" --execution-time=$global:OMP_EXECUTIONTIME --config=""$Env:POSH_THEME"" --shell-version=""$env:SHELL_VERSION""") -join "`n"
$env:POSH_TRANSIENT = $false $global:POSH_TRANSIENT = $false
return return
} }
if (Test-Path variable:/PSDebugContext) { if (Test-Path variable:/PSDebugContext) {
@ -85,8 +79,8 @@ function global:Initialize-ModuleSupport {
$global:OMP_ERRORCODE = 0 $global:OMP_ERRORCODE = 0
Initialize-ModuleSupport Initialize-ModuleSupport
if ($lastCommandSuccess -eq $false) { if ($lastCommandSuccess -eq $false) {
#native app exit code # native app exit code
if ($realLASTEXITCODE -is [int] -and $realLASTEXITCODE -gt 0) { if ($realLASTEXITCODE -is [int] -and $realLASTEXITCODE -ne 0) {
$global:OMP_ERRORCODE = $realLASTEXITCODE $global:OMP_ERRORCODE = $realLASTEXITCODE
} }
else { else {
@ -94,20 +88,20 @@ function global:Initialize-ModuleSupport {
} }
} }
# read stack count from current stack(if invoked from profile=right value,otherwise use the global variable set in Set-PoshPrompt(stack scoped to module)) # read stack count from current stack(if invoked from profile=right value, otherwise use the global variable set in Set-PoshPrompt(stack scoped to module))
$stackCount = (Get-Location -stack).Count $stackCount = (Get-Location -stack).Count
try { try {
if ($global:omp_global_sessionstate -ne $null) { if ($global:OMP_GLOBAL_SESSIONSTATE -ne $null) {
$stackCount = ($global:omp_global_sessionstate).path.locationstack('').count $stackCount = ($global:OMP_GLOBAL_SESSIONSTATE).path.locationstack('').count
} }
} }
catch {} catch {}
$global:OMP_EXECUTIONTIME = -1 $global:OMP_EXECUTIONTIME = -1
$history = Get-History -ErrorAction Ignore -Count 1 $history = Get-History -ErrorAction Ignore -Count 1
if ($null -ne $history -and $null -ne $history.EndExecutionTime -and $null -ne $history.StartExecutionTime -and $global:omp_lastHistoryId -ne $history.Id) { if ($null -ne $history -and $null -ne $history.EndExecutionTime -and $null -ne $history.StartExecutionTime -and $global:OMP_LASTHISTORYID -ne $history.Id) {
$global:OMP_EXECUTIONTIME = ($history.EndExecutionTime - $history.StartExecutionTime).TotalMilliseconds $global:OMP_EXECUTIONTIME = ($history.EndExecutionTime - $history.StartExecutionTime).TotalMilliseconds
$global:omp_lastHistoryId = $history.Id $global:OMP_LASTHISTORYID = $history.Id
} }
Set-PoshContext Set-PoshContext
$terminalWidth = $Host.UI.RawUI.WindowSize.Width $terminalWidth = $Host.UI.RawUI.WindowSize.Width
@ -120,11 +114,7 @@ function global:Initialize-ModuleSupport {
# the output can be multiline, joining these ensures proper rendering by adding line breaks with `n # the output can be multiline, joining these ensures proper rendering by adding line breaks with `n
$standardOut -join "`n" $standardOut -join "`n"
$global:LASTEXITCODE = $realLASTEXITCODE $global:LASTEXITCODE = $realLASTEXITCODE
#remove temp variables
Remove-Variable realLASTEXITCODE -Confirm:$false
Remove-Variable lastCommandSuccess -Confirm:$false
} }
Set-Item -Path Function:prompt -Value $Prompt -Force
<# <#
.SYNOPSIS .SYNOPSIS
@ -189,7 +179,7 @@ function global:Enable-PoshTooltips {
function global:Enable-PoshTransientPrompt { function global:Enable-PoshTransientPrompt {
Set-PSReadlineKeyHandler -Key Enter -ScriptBlock { Set-PSReadlineKeyHandler -Key Enter -ScriptBlock {
$env:POSH_TRANSIENT = $true $global:POSH_TRANSIENT = $true
$previousOutputEncoding = [Console]::OutputEncoding $previousOutputEncoding = [Console]::OutputEncoding
[Console]::OutputEncoding = [Text.Encoding]::UTF8 [Console]::OutputEncoding = [Text.Encoding]::UTF8
try { try {
@ -270,18 +260,18 @@ function global:Get-PoshThemes() {
else { else {
$omp = "::OMP::" $omp = "::OMP::"
$themes | ForEach-Object -Process { $themes | ForEach-Object -Process {
Write-Host "Theme: $(Get-Hyperlink -uri $_.fullname -name $_.BaseName.Replace('.omp', ''))" Write-Host "Theme: $(Get-Hyperlink -uri $_.fullname -name $_.BaseName.Replace('.omp', ''))`n"
Write-Host ""
@(Start-Utf8Process $omp "print primary --config=""$($_.FullName)"" --pwd=""$PWD"" --shell pwsh") @(Start-Utf8Process $omp "print primary --config=""$($_.FullName)"" --pwd=""$PWD"" --shell pwsh")
Write-Host "" Write-Host "`n"
Write-Host ""
} }
} }
Write-Host "" Write-Host @"
Write-Host "Themes location: $(Get-Hyperlink -uri "$Path")"
Write-Host "" Themes location: $(Get-Hyperlink -uri "$Path")
Write-Host "To change your theme, adjust the init script in $PROFILE."
Write-Host "Example:" To change your theme, adjust the init script in $PROFILE.
Write-Host " oh-my-posh init pwsh --config $Path/jandedobbeleer.omp.json | Invoke-Expression" Example:
Write-Host "" oh-my-posh init pwsh --config $Path/jandedobbeleer.omp.json | Invoke-Expression
"@
} }