Skip to content

Commit

Permalink
On Windows PowerShell, defer Add-Type until prompt executed
Browse files Browse the repository at this point in the history
On PS Core, do not set the console mode at all.
PS Core, since the release of 6.0.0 has handled setting/resetting the
console 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 1, 2018
1 parent 653101c commit 4de0624
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 {
# Add the NativeConsoleMethods type but only if it hasn't already been added to this session.
# Deferring the Add-Type to the first time this function is called, speeds up module import.
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 4de0624

Please sign in to comment.