Skip to content

Commit

Permalink
On Windows PowerShell, defer Add-Type until prompt executedOn PS Core…
Browse files Browse the repository at this point in the history
…, do not set the console mode at all.PS Core, since the release of 6.0.0 has handled setting/resetting theconsole mode, so no need for posh-git to do this.This speeds up module import by ~.5 to .7 seconds on PSCore and by~150-200 msecs on Windows PowerShell.Fix #637
  • Loading branch information
rkeithhill committed Nov 3, 2018
1 parent 9d5a214 commit a682e05
Showing 1 changed file with 27 additions and 13 deletions.
40 changes: 27 additions & 13 deletions src/ConsoleMode.ps1
Original file line number Diff line number Diff line change
@@ -1,14 +1,18 @@
# Hack! https://gist.github.com/lzybkr/f2059cb2ee8d0c13c65ab933b75e998c

if ($IsWindows -eq $false) {
# We do not need to set the console mode in PowerShell Core on any platform.
# On Windows, PowerShell Core added this support in this PR:
# https://github.com/PowerShell/PowerShell/pull/2991
if ($PSVersionTable.PSVersion.Major -ge 6) {
function Set-ConsoleMode {
[Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSUseShouldProcessForStateChangingFunctions", "")]
param()
}

return
}

Add-Type @"
$consoleModeSource = @"
using System;
using System.Runtime.InteropServices;
Expand Down Expand Up @@ -85,19 +89,29 @@ function Set-ConsoleMode
$StandardInput
)

if ($ANSI)
{
$outputMode = [NativeConsoleMethods]::GetConsoleMode($false)
$null = [NativeConsoleMethods]::SetConsoleMode($false, $outputMode -bor [ConsoleModeOutputFlags]::ENABLE_VIRTUAL_TERMINAL_PROCESSING)
begin {
# Module import is speeded up by deferring the Add-Type until the first time this function is called.
# Add the NativeConsoleMethods type but only once per session.
if (!('NativeConsoleMethods' -as [System.Type])) {
Add-Type $consoleModeSource
}
}

if ($StandardInput)
end {
if ($ANSI)
{
$inputMode = [NativeConsoleMethods]::GetConsoleMode($true)
$null = [NativeConsoleMethods]::SetConsoleMode($true, $inputMode -bor [ConsoleModeInputFlags]::ENABLE_VIRTUAL_TERMINAL_PROCESSING)
$outputMode = [NativeConsoleMethods]::GetConsoleMode($false)
$null = [NativeConsoleMethods]::SetConsoleMode($false, $outputMode -bor [ConsoleModeOutputFlags]::ENABLE_VIRTUAL_TERMINAL_PROCESSING)

if ($StandardInput)
{
$inputMode = [NativeConsoleMethods]::GetConsoleMode($true)
$null = [NativeConsoleMethods]::SetConsoleMode($true, $inputMode -bor [ConsoleModeInputFlags]::ENABLE_VIRTUAL_TERMINAL_PROCESSING)
}
}
else
{
[NativeConsoleMethods]::SetConsoleMode($StandardInput, $Mode)
}
}
else
{
[NativeConsoleMethods]::SetConsoleMode($StandardInput, $Mode)
}
}

0 comments on commit a682e05

Please sign in to comment.