From 4de06247942756712d8c042f8f51e1bd22cbc669 Mon Sep 17 00:00:00 2001 From: Keith Hill Date: Thu, 1 Nov 2018 00:01:27 -0600 Subject: [PATCH] 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 --- src/ConsoleMode.ps1 | 40 +++++++++++++++++++++++++++------------- 1 file changed, 27 insertions(+), 13 deletions(-) diff --git a/src/ConsoleMode.ps1 b/src/ConsoleMode.ps1 index 59b71e7e2..07e42ef43 100644 --- a/src/ConsoleMode.ps1 +++ b/src/ConsoleMode.ps1 @@ -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; @@ -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) } }