Skip to content

Commit 4de0624

Browse files
committed
On Windows PowerShell, defer Add-Type until prompt executed
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
1 parent 653101c commit 4de0624

File tree

1 file changed

+27
-13
lines changed

1 file changed

+27
-13
lines changed

src/ConsoleMode.ps1

Lines changed: 27 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,18 @@
11
# Hack! https://gist.github.com/lzybkr/f2059cb2ee8d0c13c65ab933b75e998c
22

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

11-
Add-Type @"
15+
$consoleModeSource = @"
1216
using System;
1317
using System.Runtime.InteropServices;
1418
@@ -85,19 +89,29 @@ function Set-ConsoleMode
8589
$StandardInput
8690
)
8791

88-
if ($ANSI)
89-
{
90-
$outputMode = [NativeConsoleMethods]::GetConsoleMode($false)
91-
$null = [NativeConsoleMethods]::SetConsoleMode($false, $outputMode -bor [ConsoleModeOutputFlags]::ENABLE_VIRTUAL_TERMINAL_PROCESSING)
92+
begin {
93+
# Add the NativeConsoleMethods type but only if it hasn't already been added to this session.
94+
# Deferring the Add-Type to the first time this function is called, speeds up module import.
95+
if (!('NativeConsoleMethods' -as [System.Type])) {
96+
Add-Type $consoleModeSource
97+
}
98+
}
9299

93-
if ($StandardInput)
100+
end {
101+
if ($ANSI)
94102
{
95-
$inputMode = [NativeConsoleMethods]::GetConsoleMode($true)
96-
$null = [NativeConsoleMethods]::SetConsoleMode($true, $inputMode -bor [ConsoleModeInputFlags]::ENABLE_VIRTUAL_TERMINAL_PROCESSING)
103+
$outputMode = [NativeConsoleMethods]::GetConsoleMode($false)
104+
$null = [NativeConsoleMethods]::SetConsoleMode($false, $outputMode -bor [ConsoleModeOutputFlags]::ENABLE_VIRTUAL_TERMINAL_PROCESSING)
105+
106+
if ($StandardInput)
107+
{
108+
$inputMode = [NativeConsoleMethods]::GetConsoleMode($true)
109+
$null = [NativeConsoleMethods]::SetConsoleMode($true, $inputMode -bor [ConsoleModeInputFlags]::ENABLE_VIRTUAL_TERMINAL_PROCESSING)
110+
}
111+
}
112+
else
113+
{
114+
[NativeConsoleMethods]::SetConsoleMode($StandardInput, $Mode)
97115
}
98-
}
99-
else
100-
{
101-
[NativeConsoleMethods]::SetConsoleMode($StandardInput, $Mode)
102116
}
103117
}

0 commit comments

Comments
 (0)