From f0151d2c981fb938cf649b41eb2dd8ba52b69f59 Mon Sep 17 00:00:00 2001 From: Robert Holt Date: Mon, 17 Aug 2020 15:42:17 -0700 Subject: [PATCH 01/40] Update `README` links and `metadata.json` for `7.1.0-preview.6` (#13437) --- README.md | 34 +++++++++++++++++----------------- tools/metadata.json | 4 ++-- 2 files changed, 19 insertions(+), 19 deletions(-) diff --git a/README.md b/README.md index 340077182b1..eb60eb33e7e 100644 --- a/README.md +++ b/README.md @@ -87,23 +87,23 @@ You can also download the PowerShell binary archives for Windows, macOS and Linu [rl-arm64]: https://github.com/PowerShell/PowerShell/releases/download/v7.0.3/powershell-7.0.3-linux-arm64.tar.gz [rl-snap]: https://snapcraft.io/powershell -[pv-windows-64]: https://github.com/PowerShell/PowerShell/releases/download/v7.1.0-preview.5/PowerShell-7.1.0-preview.5-win-x64.msi -[pv-windows-86]: https://github.com/PowerShell/PowerShell/releases/download/v7.1.0-preview.5/PowerShell-7.1.0-preview.5-win-x86.msi -[pv-ubuntu18]: https://github.com/PowerShell/PowerShell/releases/download/v7.1.0-preview.5/powershell-preview_7.1.0-preview.5-1.ubuntu.18.04_amd64.deb -[pv-ubuntu16]: https://github.com/PowerShell/PowerShell/releases/download/v7.1.0-preview.5/powershell-preview_7.1.0-preview.5-1.ubuntu.16.04_amd64.deb -[pv-debian9]: https://github.com/PowerShell/PowerShell/releases/download/v7.1.0-preview.5/powershell-preview_7.1.0-preview.5-1.debian.9_amd64.deb -[pv-debian10]: https://github.com/PowerShell/PowerShell/releases/download/v7.1.0-preview.5/powershell-preview_7.1.0-preview.5-1.debian.10_amd64.deb -[pv-centos]: https://github.com/PowerShell/PowerShell/releases/download/v7.1.0-preview.5/powershell-preview-7.1.0_preview.5-1.rhel.7.x86_64.rpm -[pv-centos8]: https://github.com/PowerShell/PowerShell/releases/download/v7.1.0-preview.5/powershell-preview-7.1.0_preview.5-1.centos.8.x86_64.rpm -[pv-macos]: https://github.com/PowerShell/PowerShell/releases/download/v7.1.0-preview.5/powershell-7.1.0-preview.5-osx-x64.pkg -[pv-winarm]: https://github.com/PowerShell/PowerShell/releases/download/v7.1.0-preview.5/PowerShell-7.1.0-preview.5-win-arm32.zip -[pv-winarm64]: https://github.com/PowerShell/PowerShell/releases/download/v7.1.0-preview.5/PowerShell-7.1.0-preview.5-win-arm64.zip -[pv-winx86-zip]: https://github.com/PowerShell/PowerShell/releases/download/v7.1.0-preview.5/PowerShell-7.1.0-preview.5-win-x86.zip -[pv-winx64-zip]: https://github.com/PowerShell/PowerShell/releases/download/v7.1.0-preview.5/PowerShell-7.1.0-preview.5-win-x64.zip -[pv-macos-tar]: https://github.com/PowerShell/PowerShell/releases/download/v7.1.0-preview.5/powershell-7.1.0-preview.5-osx-x64.tar.gz -[pv-linux-tar]: https://github.com/PowerShell/PowerShell/releases/download/v7.1.0-preview.5/powershell-7.1.0-preview.5-linux-x64.tar.gz -[pv-arm32]: https://github.com/PowerShell/PowerShell/releases/download/v7.1.0-preview.5/powershell-7.1.0-preview.5-linux-arm32.tar.gz -[pv-arm64]: https://github.com/PowerShell/PowerShell/releases/download/v7.1.0-preview.5/powershell-7.1.0-preview.5-linux-arm64.tar.gz +[pv-windows-64]: https://github.com/PowerShell/PowerShell/releases/download/v7.1.0-preview.6/PowerShell-7.1.0-preview.6-win-x64.msi +[pv-windows-86]: https://github.com/PowerShell/PowerShell/releases/download/v7.1.0-preview.6/PowerShell-7.1.0-preview.6-win-x86.msi +[pv-ubuntu18]: https://github.com/PowerShell/PowerShell/releases/download/v7.1.0-preview.6/powershell-preview_7.1.0-preview.6-1.ubuntu.18.04_amd64.deb +[pv-ubuntu16]: https://github.com/PowerShell/PowerShell/releases/download/v7.1.0-preview.6/powershell-preview_7.1.0-preview.6-1.ubuntu.16.04_amd64.deb +[pv-debian9]: https://github.com/PowerShell/PowerShell/releases/download/v7.1.0-preview.6/powershell-preview_7.1.0-preview.6-1.debian.9_amd64.deb +[pv-debian10]: https://github.com/PowerShell/PowerShell/releases/download/v7.1.0-preview.6/powershell-preview_7.1.0-preview.6-1.debian.10_amd64.deb +[pv-centos]: https://github.com/PowerShell/PowerShell/releases/download/v7.1.0-preview.6/powershell-preview-7.1.0_preview.6-1.rhel.7.x86_64.rpm +[pv-centos8]: https://github.com/PowerShell/PowerShell/releases/download/v7.1.0-preview.6/powershell-preview-7.1.0_preview.6-1.centos.8.x86_64.rpm +[pv-macos]: https://github.com/PowerShell/PowerShell/releases/download/v7.1.0-preview.6/powershell-7.1.0-preview.6-osx-x64.pkg +[pv-winarm]: https://github.com/PowerShell/PowerShell/releases/download/v7.1.0-preview.6/PowerShell-7.1.0-preview.6-win-arm32.zip +[pv-winarm64]: https://github.com/PowerShell/PowerShell/releases/download/v7.1.0-preview.6/PowerShell-7.1.0-preview.6-win-arm64.zip +[pv-winx86-zip]: https://github.com/PowerShell/PowerShell/releases/download/v7.1.0-preview.6/PowerShell-7.1.0-preview.6-win-x86.zip +[pv-winx64-zip]: https://github.com/PowerShell/PowerShell/releases/download/v7.1.0-preview.6/PowerShell-7.1.0-preview.6-win-x64.zip +[pv-macos-tar]: https://github.com/PowerShell/PowerShell/releases/download/v7.1.0-preview.6/powershell-7.1.0-preview.6-osx-x64.tar.gz +[pv-linux-tar]: https://github.com/PowerShell/PowerShell/releases/download/v7.1.0-preview.6/powershell-7.1.0-preview.6-linux-x64.tar.gz +[pv-arm32]: https://github.com/PowerShell/PowerShell/releases/download/v7.1.0-preview.6/powershell-7.1.0-preview.6-linux-arm32.tar.gz +[pv-arm64]: https://github.com/PowerShell/PowerShell/releases/download/v7.1.0-preview.6/powershell-7.1.0-preview.6-linux-arm64.tar.gz [pv-snap]: https://snapcraft.io/powershell-preview [in-windows]: https://docs.microsoft.com/powershell/scripting/install/installing-powershell-core-on-windows diff --git a/tools/metadata.json b/tools/metadata.json index 06f80b39cb0..18dce2808d5 100644 --- a/tools/metadata.json +++ b/tools/metadata.json @@ -1,9 +1,9 @@ { "StableReleaseTag": "v7.0.3", - "PreviewReleaseTag": "v7.1.0-preview.5", + "PreviewReleaseTag": "v7.1.0-preview.6", "ServicingReleaseTag": "v6.2.7", "ReleaseTag": "v7.0.3", "LTSReleaseTag" : ["v7.0.3"], - "NextReleaseTag": "v7.1.0-preview.6", + "NextReleaseTag": "v7.1.0-preview.7", "LTSRelease": false } From f8b9e8e9db88a7f9a385c8e680213934a384f679 Mon Sep 17 00:00:00 2001 From: "James Truher [MSFT]" Date: Mon, 17 Aug 2020 22:19:22 -0700 Subject: [PATCH 02/40] Create warnings when UTF7 is specified as an encoding (#13430) --- .../commands/utility/CsvCommands.cs | 32 +++++++++++++++++-- .../FormatAndOutput/format-hex/Format-Hex.cs | 15 ++++++++- .../FormatAndOutput/out-file/Out-File.cs | 16 +++++++++- .../utility/ImplicitRemotingCommands.cs | 16 +++++++++- .../commands/utility/MatchString.cs | 16 +++++++++- .../commands/utility/Send-MailMessage.cs | 16 +++++++++- .../commands/utility/XmlCommands.cs | 16 +++++++++- .../namespaces/FileSystemProvider.cs | 19 +++++++++-- .../resources/PathUtilsStrings.resx | 3 ++ .../utils/EncodingUtils.cs | 19 +++++++++++ .../engine/Basic/Encoding.Tests.ps1 | 26 +++++++++++++++ 11 files changed, 184 insertions(+), 10 deletions(-) diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/CsvCommands.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/CsvCommands.cs index 0372298d7b5..dab4a4b3340 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/CsvCommands.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/CsvCommands.cs @@ -217,7 +217,21 @@ public string LiteralPath [ArgumentToEncodingTransformationAttribute] [ArgumentEncodingCompletionsAttribute] [ValidateNotNullOrEmpty] - public Encoding Encoding { get; set; } = ClrFacade.GetDefaultEncoding(); + public Encoding Encoding + { + get + { + return _encoding; + } + + set + { + EncodingConversion.WarnIfObsolete(this, value); + _encoding = value; + } + } + + private Encoding _encoding = ClrFacade.GetDefaultEncoding(); /// /// Gets or sets property that sets append parameter. @@ -592,7 +606,21 @@ public string[] LiteralPath [ArgumentToEncodingTransformationAttribute] [ArgumentEncodingCompletionsAttribute] [ValidateNotNullOrEmpty] - public Encoding Encoding { get; set; } = ClrFacade.GetDefaultEncoding(); + public Encoding Encoding + { + get + { + return _encoding; + } + + set + { + EncodingConversion.WarnIfObsolete(this, value); + _encoding = value; + } + } + + private Encoding _encoding = ClrFacade.GetDefaultEncoding(); /// /// Avoid writing out duplicate warning messages when there are one or more unspecified names. diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/format-hex/Format-Hex.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/format-hex/Format-Hex.cs index a0225c8ea6a..d370110b8f2 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/format-hex/Format-Hex.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/format-hex/Format-Hex.cs @@ -71,7 +71,20 @@ public sealed class FormatHex : PSCmdlet [ArgumentToEncodingTransformationAttribute()] [ArgumentEncodingCompletionsAttribute] [ValidateNotNullOrEmpty] - public Encoding Encoding { get; set; } = ClrFacade.GetDefaultEncoding(); + public Encoding Encoding + { + get + { + return _encoding; + } + set + { + EncodingConversion.WarnIfObsolete(this, value); + _encoding = value; + } + } + + private Encoding _encoding = ClrFacade.GetDefaultEncoding(); /// /// Gets or sets count of bytes to read from the input stream. diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/out-file/Out-File.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/out-file/Out-File.cs index f3f84c6da37..9885cbcaa47 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/out-file/Out-File.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/out-file/Out-File.cs @@ -78,7 +78,21 @@ public string LiteralPath [ArgumentToEncodingTransformationAttribute()] [ArgumentEncodingCompletionsAttribute] [ValidateNotNullOrEmpty] - public Encoding Encoding { get; set; } = ClrFacade.GetDefaultEncoding(); + public Encoding Encoding + { + get + { + return _encoding; + } + + set + { + EncodingConversion.WarnIfObsolete(this, value); + _encoding = value; + } + } + + private Encoding _encoding = ClrFacade.GetDefaultEncoding(); /// /// Property that sets append parameter. diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ImplicitRemotingCommands.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ImplicitRemotingCommands.cs index feeb0cd091b..9198250dd75 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ImplicitRemotingCommands.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ImplicitRemotingCommands.cs @@ -76,7 +76,21 @@ public SwitchParameter Force [ArgumentToEncodingTransformationAttribute()] [ArgumentEncodingCompletionsAttribute] [ValidateNotNullOrEmpty] - public Encoding Encoding { get; set; } = ClrFacade.GetDefaultEncoding(); + public Encoding Encoding + { + get + { + return _encoding; + } + + set + { + EncodingConversion.WarnIfObsolete(this, value); + _encoding = value; + } + } + + private Encoding _encoding = ClrFacade.GetDefaultEncoding(); #endregion Parameters diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/MatchString.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/MatchString.cs index 3a5d4c77a5f..667f55e50cf 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/MatchString.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/MatchString.cs @@ -1349,7 +1349,21 @@ public string[] Exclude [ArgumentToEncodingTransformationAttribute()] [ArgumentEncodingCompletionsAttribute] [ValidateNotNullOrEmpty] - public Encoding Encoding { get; set; } = ClrFacade.GetDefaultEncoding(); + public Encoding Encoding + { + get + { + return _encoding; + } + + set + { + EncodingConversion.WarnIfObsolete(this, value); + _encoding = value; + } + } + + private Encoding _encoding = ClrFacade.GetDefaultEncoding(); /// /// Gets or sets the number of context lines to collect. If set to a diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Send-MailMessage.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Send-MailMessage.cs index 78e65d806a3..957c21d465d 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Send-MailMessage.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Send-MailMessage.cs @@ -63,7 +63,21 @@ public sealed class SendMailMessage : PSCmdlet [ValidateNotNullOrEmpty] [ArgumentEncodingCompletionsAttribute] [ArgumentToEncodingTransformationAttribute] - public Encoding Encoding { get; set; } = Encoding.ASCII; + public Encoding Encoding + { + get + { + return _encoding; + } + + set + { + EncodingConversion.WarnIfObsolete(this, value); + _encoding = value; + } + } + + private Encoding _encoding = Encoding.ASCII; /// /// Gets or sets the address collection that contains the diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/XmlCommands.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/XmlCommands.cs index 8736965fd61..9d4264b8b18 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/XmlCommands.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/XmlCommands.cs @@ -114,7 +114,21 @@ public SwitchParameter NoClobber [ArgumentToEncodingTransformationAttribute()] [ArgumentEncodingCompletionsAttribute] [ValidateNotNullOrEmpty] - public Encoding Encoding { get; set; } = ClrFacade.GetDefaultEncoding(); + public Encoding Encoding + { + get + { + return _encoding; + } + + set + { + EncodingConversion.WarnIfObsolete(this, value); + _encoding = value; + } + } + + private Encoding _encoding = ClrFacade.GetDefaultEncoding(); #endregion Command Line Parameters diff --git a/src/System.Management.Automation/namespaces/FileSystemProvider.cs b/src/System.Management.Automation/namespaces/FileSystemProvider.cs index 6c91b806dfa..eab04cb6e40 100644 --- a/src/System.Management.Automation/namespaces/FileSystemProvider.cs +++ b/src/System.Management.Automation/namespaces/FileSystemProvider.cs @@ -6744,7 +6744,7 @@ public IContentReader GetContentReader(string path) /// public object GetContentReaderDynamicParameters(string path) { - return new FileSystemContentReaderDynamicParameters(); + return new FileSystemContentReaderDynamicParameters(this); } /// @@ -6878,7 +6878,7 @@ public IContentWriter GetContentWriter(string path) /// public object GetContentWriterDynamicParameters(string path) { - return new FileSystemContentWriterDynamicParameters(); + return new FileSystemContentWriterDynamicParameters(this); } /// @@ -7593,6 +7593,13 @@ public SwitchParameter System /// public class FileSystemContentDynamicParametersBase { + internal FileSystemContentDynamicParametersBase(FileSystemProvider provider) + { + _provider = provider; + } + + private FileSystemProvider _provider; + /// /// Gets or sets the encoding method used when /// reading data from the file. @@ -7610,6 +7617,10 @@ public Encoding Encoding set { + if (value == System.Text.Encoding.UTF7) + { + _provider.WriteWarning(PathUtilsStrings.Utf7EncodingObsolete); + } _encoding = value; // If an encoding was explicitly set, be sure to capture that. WasStreamTypeSpecified = true; @@ -7659,6 +7670,8 @@ public class FileSystemClearContentDynamicParameters /// public class FileSystemContentWriterDynamicParameters : FileSystemContentDynamicParametersBase { + internal FileSystemContentWriterDynamicParameters(FileSystemProvider provider) : base(provider) { } + /// /// False to add a newline to the end of the output string, true if not. /// @@ -7684,6 +7697,8 @@ public SwitchParameter NoNewline /// public class FileSystemContentReaderDynamicParameters : FileSystemContentDynamicParametersBase { + internal FileSystemContentReaderDynamicParameters(FileSystemProvider provider) : base (provider) { } + /// /// Gets or sets the delimiter to use when reading the file. Custom delimiters /// may not be used when the file is opened with a "Byte" encoding. diff --git a/src/System.Management.Automation/resources/PathUtilsStrings.resx b/src/System.Management.Automation/resources/PathUtilsStrings.resx index 16fb037a4d5..217f2522ac8 100644 --- a/src/System.Management.Automation/resources/PathUtilsStrings.resx +++ b/src/System.Management.Automation/resources/PathUtilsStrings.resx @@ -117,6 +117,9 @@ System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + Encoding 'UTF-7' is obsolete, please use UTF-8. + File {0} already exists and {1} was specified. diff --git a/src/System.Management.Automation/utils/EncodingUtils.cs b/src/System.Management.Automation/utils/EncodingUtils.cs index 8206b5cf8a3..6825a259dae 100644 --- a/src/System.Management.Automation/utils/EncodingUtils.cs +++ b/src/System.Management.Automation/utils/EncodingUtils.cs @@ -63,6 +63,12 @@ internal static Encoding Convert(Cmdlet cmdlet, string encoding) Encoding foundEncoding; if (encodingMap.TryGetValue(encoding, out foundEncoding)) { + // Write a warning if using utf7 as it is obsolete in .NET5 + if (string.Compare(encoding, Utf7, StringComparison.OrdinalIgnoreCase) == 0) + { + cmdlet.WriteWarning(PathUtilsStrings.Utf7EncodingObsolete); + } + return foundEncoding; } @@ -81,6 +87,19 @@ internal static Encoding Convert(Cmdlet cmdlet, string encoding) return null; } + + /// + /// Warn if the encoding has been designated as obsolete. + /// + /// A cmdlet instance which is used to emit the warning. + /// The encoding to check for obsolescence. + internal static void WarnIfObsolete(Cmdlet cmdlet, Encoding encoding) + { + if (encoding == System.Text.Encoding.UTF7) + { + cmdlet.WriteWarning(PathUtilsStrings.Utf7EncodingObsolete); + } + } } /// diff --git a/test/powershell/engine/Basic/Encoding.Tests.ps1 b/test/powershell/engine/Basic/Encoding.Tests.ps1 index 2569f8619be..dc1a0b15ba2 100644 --- a/test/powershell/engine/Basic/Encoding.Tests.ps1 +++ b/test/powershell/engine/Basic/Encoding.Tests.ps1 @@ -99,4 +99,30 @@ Describe "File encoding tests" -Tag CI { (Get-Content $testFile -AsByteStream) -join "-" | Should -BeExactly $expectedBytes } } + + Context "Using encoding utf7 results in a warning" { + BeforeAll { + $expectedString = "Encoding 'UTF-7' is obsolete, please use UTF-8." + $testCases = @( + @{ Command = 'Add-Content'; Script = { "test" | Add-Content -Encoding utf7 -Path TESTDRIVE:/file 3>TESTDRIVE:/warning } } + @{ Command = 'Export-CliXml'; Script = { "test" | Export-Clixml -Path TESTDRIVE:/file.ps1xml -Encoding utf7 3>TESTDRIVE:/warning } } + @{ Command = 'Export-Csv'; Script = { "test" | Export-Csv -Path TESTDRIVE:/export.csv -Encoding utf7 3>TESTDRIVE:/warning } } + @{ Command = 'Format-Hex'; Script = { "test" | Format-Hex -Encoding utf7 > TESTDRIVE:/output 3>TESTDRIVE:/warning } } + @{ Command = 'Get-Content'; Script = { "output" > TESTDRIVE:/input; $null = Get-Content -Path TESTDRIVE:/input -Encoding utf7 3>TESTDRIVE:/warning } } + @{ Command = 'Import-Csv'; Script = { "test" | Export-Csv -Path TESTDRIVE:/output.csv; $null = Import-Csv -Path TESTDRIVE:/output.csv -Encoding utf7 3>TESTDRIVE:/warning } } + @{ Command = 'Out-File'; Script = { "test" | Out-File -Path TESTDRIVE:/output.txt -Encoding utf7 3>TESTDRIVE:/warning } } + @{ Command = 'Select-String'; Script = { "aa" | Select-String -pattern bb -Encoding utf7 3>TESTDRIVE:/warning } } + @{ Command = 'Set-Content'; Script = { "aa" | Set-Content -Path TESTDRIVE:/output.txt -Encoding utf7 3>TESTDRIVE:/warning } } + ) + } + BeforeEach { + Remove-Item TESTDRIVE:/* -force -ErrorAction Ignore + } + It "' has a warning when '-Encoding utf7' is used" -TestCases $testCases { + param ($command, $script) + & $script + $observed = Get-Content TESTDRIVE:/warning + $observed | Should -BeExactly $expectedString + } + } } From 6c96f250e60de5908d6778775677a7f09ddf2295 Mon Sep 17 00:00:00 2001 From: Christopher Yeleighton Date: Tue, 18 Aug 2020 07:22:29 +0200 Subject: [PATCH 03/40] Add a precheck for git to build.psm1 (#13227) --- build.psm1 | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/build.psm1 b/build.psm1 index dda6cc723de..9e28edfe323 100644 --- a/build.psm1 +++ b/build.psm1 @@ -345,8 +345,14 @@ function Start-PSBuild { # Add .NET CLI tools to PATH Find-Dotnet + # Verify we have git in place to do the build, and abort if the precheck failed + $precheck = precheck 'git' "Build dependency 'git' not found in PATH. See " + if (-not $precheck) { + return + } + # Verify we have .NET SDK in place to do the build, and abort if the precheck failed - $precheck = precheck 'dotnet' "Build dependency 'dotnet' not found in PATH. Run Start-PSBootstrap. Also see: https://dotnet.github.io/getting-started/" + $precheck = precheck 'dotnet' "Build dependency 'dotnet' not found in PATH. Run Start-PSBootstrap. Also see " if (-not $precheck) { return } From 904e5511789f0a8375c23c9a1ee59918be0a82a1 Mon Sep 17 00:00:00 2001 From: "dependabot-preview[bot]" <27856297+dependabot-preview[bot]@users.noreply.github.com> Date: Tue, 18 Aug 2020 10:22:42 +0500 Subject: [PATCH 04/40] Bump Markdig.Signed from 0.20.0 to 0.21.1 (#13463) Bumps [Markdig.Signed](https://github.com/lunet-io/markdig) from 0.20.0 to 0.21.1. - [Release notes](https://github.com/lunet-io/markdig/releases) - [Changelog](https://github.com/lunet-io/markdig/blob/master/changelog.md) - [Commits](https://github.com/lunet-io/markdig/compare/0.20.0...0.21.1) Signed-off-by: dependabot-preview[bot] Co-authored-by: dependabot-preview[bot] <27856297+dependabot-preview[bot]@users.noreply.github.com> --- .../Microsoft.PowerShell.MarkdownRender.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Microsoft.PowerShell.MarkdownRender/Microsoft.PowerShell.MarkdownRender.csproj b/src/Microsoft.PowerShell.MarkdownRender/Microsoft.PowerShell.MarkdownRender.csproj index 6cc2b02c660..af8bd52e2a0 100644 --- a/src/Microsoft.PowerShell.MarkdownRender/Microsoft.PowerShell.MarkdownRender.csproj +++ b/src/Microsoft.PowerShell.MarkdownRender/Microsoft.PowerShell.MarkdownRender.csproj @@ -9,7 +9,7 @@ - + From 1e940f55b1f265c9640d622937383208e13a849b Mon Sep 17 00:00:00 2001 From: Aditya Patwardhan Date: Tue, 18 Aug 2020 15:47:56 -0700 Subject: [PATCH 05/40] A few fixes to the release pipeline (#13473) --- .../azureDevOps/templates/release-ReleaseToNuGet.yml | 7 ++++--- .../azureDevOps/templates/release-UpdateDepsJson.yml | 7 +++++-- 2 files changed, 9 insertions(+), 5 deletions(-) diff --git a/tools/releaseBuild/azureDevOps/templates/release-ReleaseToNuGet.yml b/tools/releaseBuild/azureDevOps/templates/release-ReleaseToNuGet.yml index dd8404f5dce..a77b0203b4f 100644 --- a/tools/releaseBuild/azureDevOps/templates/release-ReleaseToNuGet.yml +++ b/tools/releaseBuild/azureDevOps/templates/release-ReleaseToNuGet.yml @@ -8,20 +8,21 @@ steps: - pwsh: | #Exclude all global tool packages. Their names start with 'PowerShell.' - Copy-Item "$ENV:PIPELINE_WORKSPACE/releasePipeline/finalResults/*.nupkg" -Destination "$(Pipeline.Workspace)/release" -Exclude "PowerShell.*.nupkg" -Force + $null = New-Item -ItemType Directory -Path "$(Pipeline.Workspace)/release" + Copy-Item "$ENV:PIPELINE_WORKSPACE/releasePipeline/finalResults/*.nupkg" -Destination "$(Pipeline.Workspace)/release" -Exclude "PowerShell.*.nupkg" -Force -Verbose $releaseVersion = Get-Content "$ENV:PIPELINE_WORKSPACE/releasePipeline/metadata/release.json" | ConvertFrom-Json | Select-Object -ExpandProperty 'ReleaseVersion' $globalToolPath = "$ENV:PIPELINE_WORKSPACE/releasePipeline/finalResults/PowerShell.$releaseVersion.nupkg" ### -WhatIf to make sure we do not release global tool. Remove -WhatIf when the PowerShell name reservation is done. Copy-Item $globalToolPath -Destination "$(Pipeline.Workspace)/release" -WhatIf - Get-ChildItem "$(Pipeline.Workspace)" + Get-ChildItem "$(Pipeline.Workspace)/release" -recurse displayName: Download and capture nupkgs - task: NuGetCommand@2 displayName: 'NuGet push' inputs: command: push - packagesToPush: '$(Agent.ReleaseDirectory)/*.nupkg' + packagesToPush: '$(Pipeline.Workspace)/release/*.nupkg' nuGetFeedType: external publishFeedCredentials: PowerShellNuGetOrgPush diff --git a/tools/releaseBuild/azureDevOps/templates/release-UpdateDepsJson.yml b/tools/releaseBuild/azureDevOps/templates/release-UpdateDepsJson.yml index 8c2b94dae12..0d2f0df315e 100644 --- a/tools/releaseBuild/azureDevOps/templates/release-UpdateDepsJson.yml +++ b/tools/releaseBuild/azureDevOps/templates/release-UpdateDepsJson.yml @@ -20,16 +20,18 @@ jobs: throw "Unexpected fileName: $fileName" } - $vstsCommand = "vso[task.setvariable variable=ContainerName]$fileName" + $vstsCommand = "vso[task.setvariable variable=BlobPrefix]$fileName" + Write-Verbose -Verbose $vstsCommand Write-Host "##$vstsCommand" displayName: Determine container name - pwsh: | - $zipFile = (Get-Item "$ENV:PIPELINE_WORKSPACE/releasePipeline/finalResults/PowerShell*-winx64.zip") + $zipFile = (Get-Item "$ENV:PIPELINE_WORKSPACE/releasePipeline/finalResults/PowerShell*-win-x64.zip") Expand-Archive -Path $zipFile -Destination "$ENV:PIPELINE_WORKSPACE/expanded" $pwshDepsFile = Get-Item "$ENV:PIPELINE_WORKSPACE/expanded/pwsh.deps.json" $vstsCommand = "vso[task.setvariable variable=FileToUpload]$pwshDepsFile" + Write-Verbose -Verbose $vstsCommand Write-Host "##$vstsCommand" displayName: Determine file to upload @@ -41,3 +43,4 @@ jobs: Destination: AzureBlob storage: '$(StorageAccount)' ContainerName: ps-deps-json + blobPrefix: '$(BlobPrefix)' From ac5f5f9f221014540ed81dc190c810efe3e520a1 Mon Sep 17 00:00:00 2001 From: Paul Higinbotham Date: Wed, 19 Aug 2020 09:05:25 -0700 Subject: [PATCH 06/40] Disable WMF link invocation test (#13479) --- test/powershell/Installer/WindowsInstaller.Tests.ps1 | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/test/powershell/Installer/WindowsInstaller.Tests.ps1 b/test/powershell/Installer/WindowsInstaller.Tests.ps1 index d1ce05e8f23..76cca8151de 100644 --- a/test/powershell/Installer/WindowsInstaller.Tests.ps1 +++ b/test/powershell/Installer/WindowsInstaller.Tests.ps1 @@ -21,7 +21,8 @@ Describe "Windows Installer" -Tags "Scenario" { ## Running 'Invoke-WebRequest' with WMF download URLs has been failing intermittently, ## because sometimes the URLs lead to a 'this download is no longer available' page. ## We use a retry logic here. Retry for 5 times with 1 second interval. - It "Pre-Requisistes link for '' is reachable: " -TestCases $linkCheckTestCases -Skip:$skipTest { + # It "Pre-Requisistes link for '' is reachable: " -TestCases $linkCheckTestCases -Skip:$skipTest { + It "Pre-Requisistes link for '' is reachable: " -TestCases $linkCheckTestCases -Pending { param ($Url) foreach ($i in 1..5) { From 1a0a5db069277f08064ca3209d423c5197e8de33 Mon Sep 17 00:00:00 2001 From: xtqqczze <45661989+xtqqczze@users.noreply.github.com> Date: Wed, 19 Aug 2020 17:15:07 +0100 Subject: [PATCH 07/40] Remove redundant delegate creation (#13441) --- .../utility/FormatAndOutput/out-printer/PrinterLineOutput.cs | 2 +- .../commands/utility/ImplicitRemotingCommands.cs | 2 +- .../commands/utility/ShowCommand/ShowCommand.cs | 4 ++-- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/out-printer/PrinterLineOutput.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/out-printer/PrinterLineOutput.cs index 5616a7fa436..e38a22ac98c 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/out-printer/PrinterLineOutput.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/out-printer/PrinterLineOutput.cs @@ -131,7 +131,7 @@ private void DoPrint() } // set up the callback mechanism - pd.PrintPage += new PrintPageEventHandler(this.pd_PrintPage); + pd.PrintPage += this.pd_PrintPage; // start printing pd.Print(); diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ImplicitRemotingCommands.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ImplicitRemotingCommands.cs index 9198250dd75..2171dd66aec 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ImplicitRemotingCommands.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ImplicitRemotingCommands.cs @@ -1682,7 +1682,7 @@ private PowerShell BuildPowerShellForGetCommand() powerShell.AddParameter("ArgumentList", this.ArgumentList); powerShell.Runspace = Session.Runspace; - powerShell.RemotePowerShell.HostCallReceived += new EventHandler>(HandleHostCallReceived); + powerShell.RemotePowerShell.HostCallReceived += HandleHostCallReceived; return powerShell; } diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowCommand/ShowCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowCommand/ShowCommand.cs index f4788fd89bc..d9556753fb1 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowCommand/ShowCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowCommand/ShowCommand.cs @@ -278,8 +278,8 @@ private void RunScriptSilentlyAndWithErrorHookup(string script) // errors are not created here, because there is a field for it used in the final pop up PSDataCollection output = new PSDataCollection(); - output.DataAdded += new EventHandler(this.Output_DataAdded); - _errors.DataAdded += new EventHandler(this.Error_DataAdded); + output.DataAdded += this.Output_DataAdded; + _errors.DataAdded += this.Error_DataAdded; System.Management.Automation.PowerShell ps = System.Management.Automation.PowerShell.Create(RunspaceMode.CurrentRunspace); ps.Streams.Error = _errors; From d67649c300dd98d7b00461501b148c186437122f Mon Sep 17 00:00:00 2001 From: Steve Lee Date: Wed, 19 Aug 2020 09:31:38 -0700 Subject: [PATCH 08/40] Fix `$?` to not be `$false` when native command writes to `stderr` (#13395) --- src/System.Management.Automation/engine/MshCommandRuntime.cs | 3 ++- .../Scripting/NativeExecution/NativeCommandProcessor.Tests.ps1 | 2 +- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/src/System.Management.Automation/engine/MshCommandRuntime.cs b/src/System.Management.Automation/engine/MshCommandRuntime.cs index eea82e1ab65..314bb27d1b9 100644 --- a/src/System.Management.Automation/engine/MshCommandRuntime.cs +++ b/src/System.Management.Automation/engine/MshCommandRuntime.cs @@ -2825,7 +2825,6 @@ internal void _WriteErrorSkipAllowCheck(ErrorRecord errorRecord, ActionPreferenc Severity.Warning); } - this.PipelineProcessor.ExecutionFailed = true; if (LogPipelineExecutionDetail) { this.PipelineProcessor.LogExecutionError(_thisCommand.MyInvocation, errorRecord); @@ -2833,6 +2832,8 @@ internal void _WriteErrorSkipAllowCheck(ErrorRecord errorRecord, ActionPreferenc if (!(ExperimentalFeature.IsEnabled("PSNotApplyErrorActionToStderr") && isNativeError)) { + this.PipelineProcessor.ExecutionFailed = true; + ActionPreference preference = ErrorAction; if (actionPreference.HasValue) { diff --git a/test/powershell/Language/Scripting/NativeExecution/NativeCommandProcessor.Tests.ps1 b/test/powershell/Language/Scripting/NativeExecution/NativeCommandProcessor.Tests.ps1 index e582f55a044..13724556036 100644 --- a/test/powershell/Language/Scripting/NativeExecution/NativeCommandProcessor.Tests.ps1 +++ b/test/powershell/Language/Scripting/NativeExecution/NativeCommandProcessor.Tests.ps1 @@ -142,7 +142,7 @@ Describe "Native Command Processor" -tags "Feature" { } It '$ErrorActionPreference does not apply to redirected stderr output' -Skip:(!$EnabledExperimentalFeatures.Contains('PSNotApplyErrorActionToStderr')) { - pwsh -noprofile -command '$ErrorActionPreference = ''Stop''; testexe -stderr stop 2>$null; ''hello''; $error' | Should -BeExactly 'hello' + pwsh -noprofile -command '$ErrorActionPreference = ''Stop''; testexe -stderr stop 2>$null; ''hello''; $error; $?' | Should -BeExactly 'hello','True' } } From 98dbaefcd6846680c88b255467f442f95e74abea Mon Sep 17 00:00:00 2001 From: Dongbo Wang Date: Wed, 19 Aug 2020 10:48:14 -0700 Subject: [PATCH 09/40] Optimize 'GetSystemLockdownPolicy' for non-lockdown scenarios (#13438) --- .../security/wldpNativeMethods.cs | 42 +++++-------------- 1 file changed, 11 insertions(+), 31 deletions(-) diff --git a/src/System.Management.Automation/security/wldpNativeMethods.cs b/src/System.Management.Automation/security/wldpNativeMethods.cs index 608503b932f..e9665f4dfa8 100644 --- a/src/System.Management.Automation/security/wldpNativeMethods.cs +++ b/src/System.Management.Automation/security/wldpNativeMethods.cs @@ -48,16 +48,23 @@ private SystemPolicy() /// An EnforcementMode that describes the system policy. public static SystemEnforcementMode GetSystemLockdownPolicy() { - if (s_allowDebugOverridePolicy || (s_systemLockdownPolicy == null)) + if (s_systemLockdownPolicy == null) { lock (s_systemLockdownPolicyLock) { - if (s_allowDebugOverridePolicy || (s_systemLockdownPolicy == null)) + if (s_systemLockdownPolicy == null) { - s_systemLockdownPolicy = GetLockdownPolicy(null, null); + s_systemLockdownPolicy = GetLockdownPolicy(path: null, handle: null); } } } + else if (s_allowDebugOverridePolicy) + { + lock (s_systemLockdownPolicyLock) + { + s_systemLockdownPolicy = GetDebugLockdownPolicy(path: null); + } + } return s_systemLockdownPolicy.Value; } @@ -357,34 +364,7 @@ private static SystemEnforcementMode GetDebugLockdownPolicy(string path) return SystemEnforcementMode.None; } - using (RegistryKey hklm = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Default)) - { - using (RegistryKey wldpPolicy = hklm.OpenSubKey("SYSTEM\\CurrentControlSet\\Control\\CI\\TRSData")) - { - if (wldpPolicy != null) - { - object exclusionPathsKey = wldpPolicy.GetValue("TestPath"); - - wldpPolicy.Close(); - hklm.Close(); - - if (exclusionPathsKey != null) - { - string[] exclusionPaths = (string[])exclusionPathsKey; - foreach (string exclusionPath in exclusionPaths) - { - if (path.IndexOf(exclusionPath, StringComparison.OrdinalIgnoreCase) >= 0) - { - return SystemEnforcementMode.None; - } - } - } - } - } - } - - // No explicit debug allowance for the file, so return the system policy if there - // is one. + // No explicit debug allowance for the file, so return the system policy if there is one. return s_systemLockdownPolicy.GetValueOrDefault(SystemEnforcementMode.None); } From 10fdfc4ac6351119d615ec807e64707b219d4570 Mon Sep 17 00:00:00 2001 From: Aditya Patwardhan Date: Wed, 19 Aug 2020 13:12:16 -0700 Subject: [PATCH 10/40] Create the folder before copying the global tools (#13476) --- tools/releaseBuild/azureDevOps/templates/nuget.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tools/releaseBuild/azureDevOps/templates/nuget.yml b/tools/releaseBuild/azureDevOps/templates/nuget.yml index 5a18354b91e..138050f5c60 100644 --- a/tools/releaseBuild/azureDevOps/templates/nuget.yml +++ b/tools/releaseBuild/azureDevOps/templates/nuget.yml @@ -164,9 +164,9 @@ jobs: artifactPath: '$(System.ArtifactsDirectory)\signed' - powershell: | - if (-not (Test-Path "$(System.ArtifactsDirectory)\signed")) + if (-not (Test-Path "$(System.ArtifactsDirectory)\signed\globaltool")) { - $null = New-Item -Path "$(System.ArtifactsDirectory)\signed\globaltool" -ItemType Directory + $null = New-Item -Path "$(System.ArtifactsDirectory)\signed\globaltool" -ItemType Directory -Force } Move-Item -Path "$(System.ArtifactsDirectory)\signed\PowerShell.*" -Destination "$(System.ArtifactsDirectory)\signed\globaltool" -Force From fc4c9cbfd716f975b202afb36afd0176c5af9bbb Mon Sep 17 00:00:00 2001 From: Dongbo Wang Date: Thu, 20 Aug 2020 17:41:44 -0700 Subject: [PATCH 11/40] Initial work of the subsystem plugin model (for minimal powershell) (#13186) --- .../PowerShellCore_format_ps1xml.cs | 22 ++ .../CommandCompletion/CompletionAnalysis.cs | 95 +++-- .../ExperimentalFeature.cs | 3 + .../engine/InitialSessionState.cs | 7 + .../CommandPrediction/CommandPrediction.cs | 170 +++++++++ .../CommandPrediction/ICommandPredictor.cs | 163 +++++++++ .../Subsystem/Commands/GetSubsystemCommand.cs | 54 +++ .../engine/Subsystem/ISubsystem.cs | 62 ++++ .../engine/Subsystem/SubsystemInfo.cs | 346 ++++++++++++++++++ .../engine/Subsystem/SubsystemManager.cs | 282 ++++++++++++++ .../engine/Utils.cs | 30 ++ .../resources/SubsystemStrings.resx | 156 ++++++++ .../engine/Help/HelpSystem.Tests.ps1 | 3 +- test/xUnit/csharp/test_Prediction.cs | 193 ++++++++++ test/xUnit/csharp/test_Subsystem.cs | 189 ++++++++++ tools/packaging/packaging.psm1 | 35 +- 16 files changed, 1776 insertions(+), 34 deletions(-) create mode 100644 src/System.Management.Automation/engine/Subsystem/CommandPrediction/CommandPrediction.cs create mode 100644 src/System.Management.Automation/engine/Subsystem/CommandPrediction/ICommandPredictor.cs create mode 100644 src/System.Management.Automation/engine/Subsystem/Commands/GetSubsystemCommand.cs create mode 100644 src/System.Management.Automation/engine/Subsystem/ISubsystem.cs create mode 100644 src/System.Management.Automation/engine/Subsystem/SubsystemInfo.cs create mode 100644 src/System.Management.Automation/engine/Subsystem/SubsystemManager.cs create mode 100644 src/System.Management.Automation/resources/SubsystemStrings.resx create mode 100644 test/xUnit/csharp/test_Prediction.cs create mode 100644 test/xUnit/csharp/test_Subsystem.cs diff --git a/src/System.Management.Automation/FormatAndOutput/DefaultFormatters/PowerShellCore_format_ps1xml.cs b/src/System.Management.Automation/FormatAndOutput/DefaultFormatters/PowerShellCore_format_ps1xml.cs index b7d8f46b4b8..5729605fe9a 100644 --- a/src/System.Management.Automation/FormatAndOutput/DefaultFormatters/PowerShellCore_format_ps1xml.cs +++ b/src/System.Management.Automation/FormatAndOutput/DefaultFormatters/PowerShellCore_format_ps1xml.cs @@ -133,6 +133,10 @@ internal static IEnumerable GetFormatData() "System.Management.Automation.PSDriveInfo", ViewsOf_System_Management_Automation_PSDriveInfo()); + yield return new ExtendedTypeDefinition( + "System.Management.Automation.Subsystem.SubsystemInfo", + ViewsOf_System_Management_Automation_Subsystem_SubsystemInfo()); + yield return new ExtendedTypeDefinition( "System.Management.Automation.ShellVariable", ViewsOf_System_Management_Automation_ShellVariable()); @@ -728,6 +732,24 @@ private static IEnumerable ViewsOf_System_Management_Autom .EndList()); } + private static IEnumerable ViewsOf_System_Management_Automation_Subsystem_SubsystemInfo() + { + yield return new FormatViewDefinition( + "System.Management.Automation.Subsystem.SubsystemInfo", + TableControl.Create() + .AddHeader(Alignment.Left, width: 17, label: "Kind") + .AddHeader(Alignment.Left, width: 15, label: "SubsystemType") + .AddHeader(Alignment.Right, width: 12, label: "IsRegistered") + .AddHeader(Alignment.Left, label: "Implementations") + .StartRowDefinition() + .AddPropertyColumn("Kind") + .AddScriptBlockColumn("$_.SubsystemType.Name") + .AddPropertyColumn("IsRegistered") + .AddPropertyColumn("Implementations") + .EndRowDefinition() + .EndTable()); + } + private static IEnumerable ViewsOf_System_Management_Automation_ShellVariable() { yield return new FormatViewDefinition("ShellVariable", diff --git a/src/System.Management.Automation/engine/CommandCompletion/CompletionAnalysis.cs b/src/System.Management.Automation/engine/CommandCompletion/CompletionAnalysis.cs index ed0c1309cc1..db32f5de184 100644 --- a/src/System.Management.Automation/engine/CommandCompletion/CompletionAnalysis.cs +++ b/src/System.Management.Automation/engine/CommandCompletion/CompletionAnalysis.cs @@ -1,6 +1,7 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. +using System; using System.Collections; using System.Collections.Generic; using System.Linq; @@ -94,26 +95,32 @@ private static bool IsCursorOutsideOfExtent(IScriptPosition cursor, IScriptExten return cursor.Offset < extent.StartOffset || cursor.Offset > extent.EndOffset; } - internal CompletionContext CreateCompletionContext(PowerShell powerShell) + internal readonly struct AstAnalysisContext { - var typeInferenceContext = new TypeInferenceContext(powerShell); - return InitializeCompletionContext(typeInferenceContext); - } + internal AstAnalysisContext(Token tokenAtCursor, Token tokenBeforeCursor, List relatedAsts, int replacementIndex) + { + TokenAtCursor = tokenAtCursor; + TokenBeforeCursor = tokenBeforeCursor; + RelatedAsts = relatedAsts; + ReplacementIndex = replacementIndex; + } - internal CompletionContext CreateCompletionContext(TypeInferenceContext typeInferenceContext) - { - return InitializeCompletionContext(typeInferenceContext); + internal readonly Token TokenAtCursor; + internal readonly Token TokenBeforeCursor; + internal readonly List RelatedAsts; + internal readonly int ReplacementIndex; } - private CompletionContext InitializeCompletionContext(TypeInferenceContext typeInferenceContext) + internal static AstAnalysisContext ExtractAstContext(Ast inputAst, Token[] inputTokens, IScriptPosition cursor) { + bool adjustLineAndColumn = false; + IScriptPosition positionForAstSearch = cursor; + Token tokenBeforeCursor = null; - IScriptPosition positionForAstSearch = _cursorPosition; - var adjustLineAndColumn = false; - var tokenAtCursor = InterstingTokenAtCursorOrDefault(_tokens, _cursorPosition); + Token tokenAtCursor = InterstingTokenAtCursorOrDefault(inputTokens, cursor); if (tokenAtCursor == null) { - tokenBeforeCursor = InterstingTokenBeforeCursorOrDefault(_tokens, _cursorPosition); + tokenBeforeCursor = InterstingTokenBeforeCursorOrDefault(inputTokens, cursor); if (tokenBeforeCursor != null) { positionForAstSearch = tokenBeforeCursor.Extent.EndScriptPosition; @@ -125,30 +132,52 @@ private CompletionContext InitializeCompletionContext(TypeInferenceContext typeI var stringExpandableToken = tokenAtCursor as StringExpandableToken; if (stringExpandableToken?.NestedTokens != null) { - tokenAtCursor = InterstingTokenAtCursorOrDefault(stringExpandableToken.NestedTokens, _cursorPosition) ?? stringExpandableToken; + tokenAtCursor = InterstingTokenAtCursorOrDefault(stringExpandableToken.NestedTokens, cursor) ?? stringExpandableToken; } } - var asts = AstSearcher.FindAll(_ast, ast => IsCursorWithinOrJustAfterExtent(positionForAstSearch, ast.Extent), searchNestedScriptBlocks: true).ToList(); + int replacementIndex = adjustLineAndColumn ? cursor.Offset : 0; + List relatedAsts = AstSearcher.FindAll( + inputAst, + ast => IsCursorWithinOrJustAfterExtent(positionForAstSearch, ast.Extent), + searchNestedScriptBlocks: true).ToList(); Diagnostics.Assert(tokenAtCursor == null || tokenBeforeCursor == null, "Only one of these tokens can be non-null"); + return new AstAnalysisContext(tokenAtCursor, tokenBeforeCursor, relatedAsts, replacementIndex); + } + + internal CompletionContext CreateCompletionContext(PowerShell powerShell) + { + var typeInferenceContext = new TypeInferenceContext(powerShell); + return InitializeCompletionContext(typeInferenceContext); + } + + internal CompletionContext CreateCompletionContext(TypeInferenceContext typeInferenceContext) + { + return InitializeCompletionContext(typeInferenceContext); + } + + private CompletionContext InitializeCompletionContext(TypeInferenceContext typeInferenceContext) + { + var astContext = ExtractAstContext(_ast, _tokens, _cursorPosition); + if (typeInferenceContext.CurrentTypeDefinitionAst == null) { - typeInferenceContext.CurrentTypeDefinitionAst = Ast.GetAncestorTypeDefinitionAst(asts.Last()); + typeInferenceContext.CurrentTypeDefinitionAst = Ast.GetAncestorTypeDefinitionAst(astContext.RelatedAsts.Last()); } ExecutionContext executionContext = typeInferenceContext.ExecutionContext; return new CompletionContext { - TokenAtCursor = tokenAtCursor, - TokenBeforeCursor = tokenBeforeCursor, - CursorPosition = _cursorPosition, - RelatedAsts = asts, Options = _options, + CursorPosition = _cursorPosition, + TokenAtCursor = astContext.TokenAtCursor, + TokenBeforeCursor = astContext.TokenBeforeCursor, + RelatedAsts = astContext.RelatedAsts, + ReplacementIndex = astContext.ReplacementIndex, ExecutionContext = executionContext, - ReplacementIndex = adjustLineAndColumn ? _cursorPosition.Offset : 0, TypeInferenceContext = typeInferenceContext, Helper = typeInferenceContext.Helper, CustomArgumentCompleters = executionContext.CustomArgumentCompleters, @@ -156,14 +185,32 @@ private CompletionContext InitializeCompletionContext(TypeInferenceContext typeI }; } - private static Token InterstingTokenAtCursorOrDefault(IEnumerable tokens, IScriptPosition cursorPosition) + private static Token InterstingTokenAtCursorOrDefault(IReadOnlyList tokens, IScriptPosition cursorPosition) { - return tokens.LastOrDefault(token => IsCursorWithinOrJustAfterExtent(cursorPosition, token.Extent) && IsInterestingToken(token)); + for (int i = tokens.Count - 1; i >= 0; --i) + { + Token token = tokens[i]; + if (IsCursorWithinOrJustAfterExtent(cursorPosition, token.Extent) && IsInterestingToken(token)) + { + return token; + } + } + + return null; } - private static Token InterstingTokenBeforeCursorOrDefault(IEnumerable tokens, IScriptPosition cursorPosition) + private static Token InterstingTokenBeforeCursorOrDefault(IReadOnlyList tokens, IScriptPosition cursorPosition) { - return tokens.LastOrDefault(token => IsCursorAfterExtent(cursorPosition, token.Extent) && IsInterestingToken(token)); + for (int i = tokens.Count - 1; i >= 0; --i) + { + Token token = tokens[i]; + if (IsCursorAfterExtent(cursorPosition, token.Extent) && IsInterestingToken(token)) + { + return token; + } + } + + return null; } private static Ast GetLastAstAtCursor(ScriptBlockAst scriptBlockAst, IScriptPosition cursorPosition) diff --git a/src/System.Management.Automation/engine/ExperimentalFeature/ExperimentalFeature.cs b/src/System.Management.Automation/engine/ExperimentalFeature/ExperimentalFeature.cs index e44ea07962c..603ff2f34b0 100644 --- a/src/System.Management.Automation/engine/ExperimentalFeature/ExperimentalFeature.cs +++ b/src/System.Management.Automation/engine/ExperimentalFeature/ExperimentalFeature.cs @@ -126,6 +126,9 @@ static ExperimentalFeature() new ExperimentalFeature( name: "PSNotApplyErrorActionToStderr", description: "Don't have $ErrorActionPreference affect stderr output"), + new ExperimentalFeature( + name: "PSSubsystemPluginModel", + description: "A plugin model for registering and un-registering PowerShell subsystems"), }; EngineExperimentalFeatures = new ReadOnlyCollection(engineFeatures); diff --git a/src/System.Management.Automation/engine/InitialSessionState.cs b/src/System.Management.Automation/engine/InitialSessionState.cs index 0d2e1274aa6..2a4f10d9fc4 100644 --- a/src/System.Management.Automation/engine/InitialSessionState.cs +++ b/src/System.Management.Automation/engine/InitialSessionState.cs @@ -5392,6 +5392,12 @@ private static void InitializeCoreCmdletsAndProviders( { "Out-LineOutput", new SessionStateCmdletEntry("Out-LineOutput", typeof(OutLineOutputCommand), helpFile) }, { "Format-Default", new SessionStateCmdletEntry("Format-Default", typeof(FormatDefaultCommand), helpFile) }, }; + + if (ExperimentalFeature.IsEnabled("PSSubsystemPluginModel")) + { + cmdlets.Add("Get-Subsystem", new SessionStateCmdletEntry("Get-Subsystem", typeof(Subsystem.GetSubsystemCommand), helpFile)); + } + foreach (var val in cmdlets.Values) { val.SetPSSnapIn(psSnapInInfo); @@ -5408,6 +5414,7 @@ private static void InitializeCoreCmdletsAndProviders( { "Function", new SessionStateProviderEntry("Function", typeof(FunctionProvider), helpFile) }, { "Variable", new SessionStateProviderEntry("Variable", typeof(VariableProvider), helpFile) }, }; + foreach (var val in providers.Values) { val.SetPSSnapIn(psSnapInInfo); diff --git a/src/System.Management.Automation/engine/Subsystem/CommandPrediction/CommandPrediction.cs b/src/System.Management.Automation/engine/Subsystem/CommandPrediction/CommandPrediction.cs new file mode 100644 index 00000000000..f77072ea376 --- /dev/null +++ b/src/System.Management.Automation/engine/Subsystem/CommandPrediction/CommandPrediction.cs @@ -0,0 +1,170 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +#nullable enable + +using System; +using System.Collections.Generic; +using System.Management.Automation.Internal; +using System.Management.Automation.Language; +using System.Threading; +using System.Threading.Tasks; + +namespace System.Management.Automation.Subsystem +{ + /// + /// The class represents the prediction result from a predictor. + /// + public sealed class PredictionResult + { + /// + /// Gets the Id of the predictor. + /// + public Guid Id { get; } + + /// + /// Gets the name of the predictor. + /// + public string Name { get; } + + /// + /// Gets the suggestions. + /// + public IReadOnlyList Suggestions { get; } + + internal PredictionResult(Guid id, string name, List suggestions) + { + Id = id; + Name = name; + Suggestions = suggestions; + } + } + + /// + /// Provides a set of possible predictions for given input. + /// + public static class CommandPrediction + { + /// + /// Collect the predictive suggestions from registered predictors using the default timeout. + /// + /// The object from parsing the current command line input. + /// The objects from parsing the current command line input. + /// A list of objects. + public static Task?> PredictInput(Ast ast, Token[] astTokens) + { + return PredictInput(ast, astTokens, millisecondsTimeout: 20); + } + + /// + /// Collect the predictive suggestions from registered predictors using the specified timeout. + /// + /// The object from parsing the current command line input. + /// The objects from parsing the current command line input. + /// The milliseconds to timeout. + /// A list of objects. + public static async Task?> PredictInput(Ast ast, Token[] astTokens, int millisecondsTimeout) + { + Requires.Condition(millisecondsTimeout > 0, nameof(millisecondsTimeout)); + + var predictors = SubsystemManager.GetSubsystems(); + if (predictors.Count == 0) + { + return null; + } + + var context = new PredictionContext(ast, astTokens); + var tasks = new Task[predictors.Count]; + using var cancellationSource = new CancellationTokenSource(); + + for (int i = 0; i < predictors.Count; i++) + { + ICommandPredictor predictor = predictors[i]; + + tasks[i] = Task.Factory.StartNew( + state => { + var predictor = (ICommandPredictor)state!; + List? texts = predictor.GetSuggestion(context, cancellationSource.Token); + return texts?.Count > 0 ? new PredictionResult(predictor.Id, predictor.Name, texts) : null; + }, + predictor, + cancellationSource.Token, + TaskCreationOptions.DenyChildAttach, + TaskScheduler.Default); + } + + await Task.WhenAny( + Task.WhenAll(tasks), + Task.Delay(millisecondsTimeout, cancellationSource.Token)).ConfigureAwait(false); + cancellationSource.Cancel(); + + var results = new List(predictors.Count); + foreach (Task task in tasks) + { + if (task.IsCompletedSuccessfully) + { + PredictionResult? result = task.Result; + if (result != null) + { + results.Add(result); + } + } + } + + return results; + } + + /// + /// Allow registered predictors to do early processing when a command line is accepted. + /// + /// History command lines provided as references for prediction. + public static void OnCommandLineAccepted(IReadOnlyList history) + { + Requires.NotNull(history, nameof(history)); + + var predictors = SubsystemManager.GetSubsystems(); + if (predictors.Count == 0) + { + return; + } + + foreach (ICommandPredictor predictor in predictors) + { + if (predictor.SupportEarlyProcessing) + { + ThreadPool.QueueUserWorkItem( + state => state.StartEarlyProcessing(history), + predictor, + preferLocal: false); + } + } + } + + /// + /// Send feedback to predictors about their last suggestions. + /// + /// The identifier of the predictor whose prediction result was accepted. + /// The accepted suggestion text. + public static void OnSuggestionAccepted(Guid predictorId, string suggestionText) + { + Requires.NotNullOrEmpty(suggestionText, nameof(suggestionText)); + + var predictors = SubsystemManager.GetSubsystems(); + if (predictors.Count == 0) + { + return; + } + + foreach (ICommandPredictor predictor in predictors) + { + if (predictor.AcceptFeedback && predictor.Id == predictorId) + { + ThreadPool.QueueUserWorkItem( + state => state.OnSuggestionAccepted(suggestionText), + predictor, + preferLocal: false); + } + } + } + } +} diff --git a/src/System.Management.Automation/engine/Subsystem/CommandPrediction/ICommandPredictor.cs b/src/System.Management.Automation/engine/Subsystem/CommandPrediction/ICommandPredictor.cs new file mode 100644 index 00000000000..0edd768cf89 --- /dev/null +++ b/src/System.Management.Automation/engine/Subsystem/CommandPrediction/ICommandPredictor.cs @@ -0,0 +1,163 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +#nullable enable + +using System; +using System.Collections.Generic; +using System.Management.Automation.Internal; +using System.Management.Automation.Language; +using System.Threading; + +namespace System.Management.Automation.Subsystem +{ + /// + /// Interface for implementing a predictor plugin. + /// + public interface ICommandPredictor : ISubsystem + { + /// + /// Default implementation. No function is required for a predictor. + /// + Dictionary? ISubsystem.FunctionsToDefine => null; + + /// + /// Default implementation for `ISubsystem.Kind`. + /// + SubsystemKind ISubsystem.Kind => SubsystemKind.CommandPredictor; + + /// + /// Gets a value indicating whether the predictor supports early processing. + /// + bool SupportEarlyProcessing { get; } + + /// + /// Gets a value indicating whether the predictor accepts feedback about the previous suggestion. + /// + bool AcceptFeedback { get; } + + /// + /// A command line was accepted to execute. + /// The predictor can start processing early as needed with the latest history. + /// + /// History command lines provided as references for prediction. + void StartEarlyProcessing(IReadOnlyList history); + + /// + /// The suggestion given by the predictor was accepted. + /// + /// The accepted suggestion text. + void OnSuggestionAccepted(string acceptedSuggestion); + + /// + /// Get the predictive suggestions. + /// + /// The object to be used for prediction. + /// The cancellation token to cancel the prediction. + /// A list of predictive suggestions. + List? GetSuggestion(PredictionContext context, CancellationToken cancellationToken); + } + + /// + /// Context information about the user input. + /// + public class PredictionContext + { + /// + /// Gets the abstract syntax tree (AST) generated from parsing the user input. + /// + public Ast InputAst { get; } + + /// + /// Gets the tokens generated from parsing the user input. + /// + public IReadOnlyList InputTokens { get; } + + /// + /// Gets the cursor position, which is assumed always at the end of the input line. + /// + public IScriptPosition CursorPosition { get; } + + /// + /// Gets the token at the cursor. + /// + public Token? TokenAtCursor { get; } + + /// + /// Gets all ASTs that are related to the cursor position, + /// which is assumed always at the end of the input line. + /// + public IReadOnlyList RelatedAsts { get; } + + /// + /// Initializes a new instance of the class from the AST and tokens that represent the user input. + /// + /// The object from parsing the current command line input. + /// The objects from parsing the current command line input. + public PredictionContext(Ast inputAst, Token[] inputTokens) + { + Requires.NotNull(inputAst, nameof(inputAst)); + Requires.NotNull(inputTokens, nameof(inputTokens)); + + var cursor = inputAst.Extent.EndScriptPosition; + var astContext = CompletionAnalysis.ExtractAstContext(inputAst, inputTokens, cursor); + + InputAst = inputAst; + InputTokens = inputTokens; + CursorPosition = cursor; + TokenAtCursor = astContext.TokenAtCursor; + RelatedAsts = astContext.RelatedAsts; + } + + /// + /// Creates a context instance from the user input line. + /// + /// The user input. + /// A object. + public static PredictionContext Create(string input) + { + Requires.NotNullOrEmpty(input, nameof(input)); + + Ast ast = Parser.ParseInput(input, out Token[] tokens, out _); + return new PredictionContext(ast, tokens); + } + } + + /// + /// The class represents a predictive suggestion generated by a predictor. + /// + public sealed class PredictiveSuggestion + { + /// + /// Gets the suggestion. + /// + public string SuggestionText { get; } + + /// + /// Gets the tooltip of the suggestion. + /// + public string? ToolTip { get; } + + /// + /// Initializes a new instance of the class. + /// + /// The predictive suggestion text. + public PredictiveSuggestion(string suggestion) + : this(suggestion, toolTip: null) + { + } + + /// + /// Initializes a new instance of the class. + /// + /// The predictive suggestion text. + /// The tooltip of the suggestion. + public PredictiveSuggestion(string suggestion, string? toolTip) + { + Requires.NotNullOrEmpty(suggestion, nameof(suggestion)); + + SuggestionText = suggestion; + ToolTip = toolTip; + } + } +} diff --git a/src/System.Management.Automation/engine/Subsystem/Commands/GetSubsystemCommand.cs b/src/System.Management.Automation/engine/Subsystem/Commands/GetSubsystemCommand.cs new file mode 100644 index 00000000000..666cf9c5568 --- /dev/null +++ b/src/System.Management.Automation/engine/Subsystem/Commands/GetSubsystemCommand.cs @@ -0,0 +1,54 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +#nullable enable + +namespace System.Management.Automation.Subsystem +{ + /// + /// Implementation of 'Get-Subsystem' cmdlet. + /// + [Experimental("PSSubsystemPluginModel", ExperimentAction.Show)] + [Cmdlet(VerbsCommon.Get, "Subsystem", DefaultParameterSetName = AllSet)] + [OutputType(typeof(SubsystemInfo))] + public sealed class GetSubsystemCommand : PSCmdlet + { + private const string AllSet = "GetAllSet"; + private const string TypeSet = "GetByTypeSet"; + private const string KindSet = "GetByKindSet"; + + /// + /// Gets or sets a concrete subsystem kind. + /// + [Parameter(Mandatory = true, ParameterSetName = KindSet, ValueFromPipeline = true)] + public SubsystemKind Kind { get; set; } + + /// + /// Gets or sets the interface or abstract class type of a concrete subsystem. + /// + [Parameter(Mandatory = true, ParameterSetName = TypeSet, ValueFromPipeline = true)] + public Type? SubsystemType { get; set; } + + /// + /// ProcessRecord implementation. + /// + protected override void ProcessRecord() + { + switch (ParameterSetName) + { + case AllSet: + WriteObject(SubsystemManager.GetAllSubsystemInfo()); + break; + case KindSet: + WriteObject(SubsystemManager.GetSubsystemInfo(Kind)); + break; + case TypeSet: + WriteObject(SubsystemManager.GetSubsystemInfo(SubsystemType!)); + break; + + default: + throw new InvalidOperationException("New parameter set is added but the switch statement is not updated."); + } + } + } +} diff --git a/src/System.Management.Automation/engine/Subsystem/ISubsystem.cs b/src/System.Management.Automation/engine/Subsystem/ISubsystem.cs new file mode 100644 index 00000000000..e19f37f06c7 --- /dev/null +++ b/src/System.Management.Automation/engine/Subsystem/ISubsystem.cs @@ -0,0 +1,62 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +#nullable enable + +using System; +using System.Collections.Generic; + +namespace System.Management.Automation.Subsystem +{ + /// + /// Define the kinds of subsystems. + /// + public enum SubsystemKind + { + /// + /// Component that provides predictive suggestions to commandline input. + /// + CommandPredictor = 1, + } + + /// + /// Define the base interface to implement a subsystem. + /// The API contracts for specific subsystems are defined within the specific interfaces/abstract classes that implements this interface. + /// + /// + /// There are two purposes to have the internal member `Kind` declared in 'ISubsystem': + /// 1. Make the mapping from an `ISubsystem` implementation to the `SubsystemKind` easy; + /// 2. Make sure a user cannot directly implement 'ISubsystem', but have to derive from one of the concrete subsystem interface or abstract class. + /// + /// The internal member needs to have a default implementation defined by the specific subsystem interfaces or abstract class, + /// because it should be the same for a specific kind of subsystem. + /// + public interface ISubsystem + { + /// + /// Gets the unique identifier for a subsystem implementation. + /// + Guid Id { get; } + + /// + /// Gets the name of a subsystem implementation. + /// + string Name { get; } + + /// + /// Gets the description of a subsystem implementation. + /// + string Description { get; } + + /// + /// Gets a dictionary that contains the functions to be defined at the global scope of a PowerShell session. + /// Key: function name; Value: function script. + /// + Dictionary? FunctionsToDefine { get; } + + /// + /// Gets the subsystem kind. + /// + internal SubsystemKind Kind { get; } + } +} diff --git a/src/System.Management.Automation/engine/Subsystem/SubsystemInfo.cs b/src/System.Management.Automation/engine/Subsystem/SubsystemInfo.cs new file mode 100644 index 00000000000..c12eedde397 --- /dev/null +++ b/src/System.Management.Automation/engine/Subsystem/SubsystemInfo.cs @@ -0,0 +1,346 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +#nullable enable + +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Management.Automation.Internal; + +namespace System.Management.Automation.Subsystem +{ + /// + /// Class used to represent the metadata and state of a subsystem. + /// + public abstract class SubsystemInfo + { + #region "Metadata of a Subsystem (public)" + + /// + /// The kind of a concrete subsystem. + /// + public SubsystemKind Kind { get; private set; } + + /// + /// The type of a concrete subsystem. + /// + public Type SubsystemType { get; private set; } + + /// + /// Indicate whether the subsystem allows to unregister an implementation. + /// + public bool AllowUnregistration { get; private set; } + + /// + /// Indicate whether the subsystem allows to have multiple implementations registered. + /// + public bool AllowMultipleRegistration { get; private set; } + + /// + /// Gets the names of the required cmdlets that have to be implemented by the subsystem implementation. + /// + public ReadOnlyCollection RequiredCmdlets { get; private set; } + + /// + /// Gets the names of the required functions that have to be implemented by the subsystem implementation. + /// + public ReadOnlyCollection RequiredFunctions { get; private set; } + + // /// + // /// A subsystem may depend on or more other subsystems. + // /// Maybe add a 'DependsOn' member? + // /// This can be validated when registering a subsystem implementation, + // /// to make sure its prerequisites have already been registered. + // /// + // public ReadOnlyCollection DependsOn { get; private set; } + + #endregion + + #region "State of a Subsystem (public)" + + /// + /// Indicate whether there is any implementation registered to the subsystem. + /// + public bool IsRegistered => _cachedImplInfos.Count > 0; + + /// + /// Get the information about the registered implementations. + /// + public ReadOnlyCollection Implementations => _cachedImplInfos; + + #endregion + + #region "private/internal instance members" + + private protected readonly object _syncObj; + private protected ReadOnlyCollection _cachedImplInfos; + + private protected SubsystemInfo(SubsystemKind kind, Type subsystemType) + { + _syncObj = new object(); + _cachedImplInfos = Utils.EmptyReadOnlyCollection(); + + Kind = kind; + SubsystemType = subsystemType; + AllowUnregistration = false; + AllowMultipleRegistration = false; + RequiredCmdlets = Utils.EmptyReadOnlyCollection(); + RequiredFunctions = Utils.EmptyReadOnlyCollection(); + } + + private protected abstract void AddImplementation(ISubsystem rawImpl); + private protected abstract ISubsystem RemoveImplementation(Guid id); + + internal void RegisterImplementation(ISubsystem impl) + { + AddImplementation(impl); + } + + internal ISubsystem UnregisterImplementation(Guid id) + { + return RemoveImplementation(id); + } + + #endregion + + #region "Static factory overloads" + + internal static SubsystemInfo Create(SubsystemKind kind) + where TConcreteSubsystem : class, ISubsystem + { + return new SubsystemInfoImpl(kind); + } + + internal static SubsystemInfo Create( + SubsystemKind kind, + bool allowUnregistration, + bool allowMultipleRegistration) where TConcreteSubsystem : class, ISubsystem + { + return new SubsystemInfoImpl(kind) + { + AllowUnregistration = allowUnregistration, + AllowMultipleRegistration = allowMultipleRegistration, + }; + } + + internal static SubsystemInfo Create( + SubsystemKind kind, + bool allowUnregistration, + bool allowMultipleRegistration, + ReadOnlyCollection requiredCmdlets, + ReadOnlyCollection requiredFunctions) where TConcreteSubsystem : class, ISubsystem + { + if (allowMultipleRegistration && + (requiredCmdlets.Count > 0 || requiredFunctions.Count > 0)) + { + throw new ArgumentException( + StringUtil.Format( + SubsystemStrings.InvalidSubsystemInfo, + kind.ToString())); + } + + return new SubsystemInfoImpl(kind) + { + AllowUnregistration = allowUnregistration, + AllowMultipleRegistration = allowMultipleRegistration, + RequiredCmdlets = requiredCmdlets, + RequiredFunctions = requiredFunctions, + }; + } + + #endregion + + #region "ImplementationInfo" + + /// + /// Information about an implementation of a subsystem. + /// + public class ImplementationInfo + { + internal ImplementationInfo(ISubsystem implementation) + { + Id = implementation.Id; + Kind = implementation.Kind; + Name = implementation.Name; + Description = implementation.Description; + ImplementationType = implementation.GetType(); + } + + /// + /// Gets the unique identifier for a subsystem implementation. + /// + public Guid Id { get; } + + /// + /// Gets the kind of subsystem. + /// + public SubsystemKind Kind { get; } + + /// + /// Gets the name of a subsystem implementation. + /// + public string Name { get; } + + /// + /// Gets the description of a subsystem implementation. + /// + public string Description { get; } + + /// + /// Gets the implementation type. + /// + public Type ImplementationType { get; } + } + + #endregion + } + + internal sealed class SubsystemInfoImpl : SubsystemInfo + where TConcreteSubsystem : class, ISubsystem + { + private ReadOnlyCollection _registeredImpls; + + internal SubsystemInfoImpl(SubsystemKind kind) + : base(kind, typeof(TConcreteSubsystem)) + { + _registeredImpls = Utils.EmptyReadOnlyCollection(); + } + + /// + /// The 'add' and 'remove' operations are implemented in a way to optimize the 'reading' operation, + /// so that reading is lock-free and allocation-free, at the cost of O(n) copy in 'add' and 'remove' + /// ('n' is the number of registered implementations). + /// + /// + /// In the subsystem scenario, registration operations will be minimum, and in most cases, the registered + /// implementation will never be unregistered, so optimization for reading is more important. + /// + private protected override void AddImplementation(ISubsystem rawImpl) + { + lock (_syncObj) + { + var impl = (TConcreteSubsystem)rawImpl; + + if (_registeredImpls.Count == 0) + { + _registeredImpls = new ReadOnlyCollection(new[] { impl }); + _cachedImplInfos = new ReadOnlyCollection(new[] { new ImplementationInfo(impl) }); + return; + } + + if (!AllowMultipleRegistration) + { + throw new InvalidOperationException( + StringUtil.Format( + SubsystemStrings.MultipleRegistrationNotAllowed, + Kind.ToString())); + } + + foreach (TConcreteSubsystem item in _registeredImpls) + { + if (item.Id == impl.Id) + { + throw new InvalidOperationException( + StringUtil.Format( + SubsystemStrings.ImplementationAlreadyRegistered, + impl.Id, + Kind.ToString())); + } + } + + var list = new List(_registeredImpls.Count + 1); + list.AddRange(_registeredImpls); + list.Add(impl); + + _registeredImpls = new ReadOnlyCollection(list); + _cachedImplInfos = new ReadOnlyCollection(list.ConvertAll(s => new ImplementationInfo(s))); + } + } + + /// + /// The 'add' and 'remove' operations are implemented in a way to optimize the 'reading' operation, + /// so that reading is lock-free and allocation-free, at the cost of O(n) copy in 'add' and 'remove' + /// ('n' is the number of registered implementations). + /// + /// + /// In the subsystem scenario, registration operations will be minimum, and in most cases, the registered + /// implementation will never be unregistered, so optimization for reading is more important. + /// + private protected override ISubsystem RemoveImplementation(Guid id) + { + if (!AllowUnregistration) + { + throw new InvalidOperationException( + StringUtil.Format( + SubsystemStrings.UnregistrationNotAllowed, + Kind.ToString())); + } + + lock (_syncObj) + { + if (_registeredImpls.Count == 0) + { + throw new InvalidOperationException( + StringUtil.Format( + SubsystemStrings.NoImplementationRegistered, + Kind.ToString())); + } + + int index = -1; + for (int i = 0; i < _registeredImpls.Count; i++) + { + if (_registeredImpls[i].Id == id) + { + index = i; + break; + } + } + + if (index == -1) + { + throw new InvalidOperationException( + StringUtil.Format( + SubsystemStrings.ImplementationNotFound, + id.ToString())); + } + + ISubsystem target = _registeredImpls[index]; + if (_registeredImpls.Count == 1) + { + _registeredImpls = Utils.EmptyReadOnlyCollection(); + _cachedImplInfos = Utils.EmptyReadOnlyCollection(); + } + else + { + var list = new List(_registeredImpls.Count - 1); + for (int i = 0; i < _registeredImpls.Count; i++) + { + if (index == i) + { + continue; + } + + list.Add(_registeredImpls[i]); + } + + _registeredImpls = new ReadOnlyCollection(list); + _cachedImplInfos = new ReadOnlyCollection(list.ConvertAll(s => new ImplementationInfo(s))); + } + + return target; + } + } + + internal TConcreteSubsystem? GetImplementation() + { + var localRef = _registeredImpls; + return localRef.Count > 0 ? localRef[localRef.Count - 1] : null; + } + + internal ReadOnlyCollection GetAllImplementations() + { + return _registeredImpls; + } + } +} diff --git a/src/System.Management.Automation/engine/Subsystem/SubsystemManager.cs b/src/System.Management.Automation/engine/Subsystem/SubsystemManager.cs new file mode 100644 index 00000000000..1e32436e6da --- /dev/null +++ b/src/System.Management.Automation/engine/Subsystem/SubsystemManager.cs @@ -0,0 +1,282 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +#nullable enable + +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.Management.Automation.Internal; + +namespace System.Management.Automation.Subsystem +{ + /// + /// Class used to manage subsystems. + /// + public static class SubsystemManager + { + private static readonly ReadOnlyCollection s_subsystems; + private static readonly ReadOnlyDictionary s_subSystemTypeMap; + private static readonly ReadOnlyDictionary s_subSystemKindMap; + + static SubsystemManager() + { + var subsystems = new SubsystemInfo[] + { + SubsystemInfo.Create( + SubsystemKind.CommandPredictor, + allowUnregistration: true, + allowMultipleRegistration: true), + }; + + var subSystemTypeMap = new Dictionary(subsystems.Length); + var subSystemKindMap = new Dictionary(subsystems.Length); + + foreach (var subsystem in subsystems) + { + subSystemTypeMap.Add(subsystem.SubsystemType, subsystem); + subSystemKindMap.Add(subsystem.Kind, subsystem); + } + + s_subsystems = new ReadOnlyCollection(subsystems); + s_subSystemTypeMap = new ReadOnlyDictionary(subSystemTypeMap); + s_subSystemKindMap = new ReadOnlyDictionary(subSystemKindMap); + } + + #region internal - Retrieve subsystem proxy object + + /// + /// Get the proxy object registered for a specific subsystem. + /// Return null when the given subsystem is not registered. + /// + /// + /// Design point: + /// The implemnentation proxy object is not supposed to expose to users. + /// Users shouldn't depend on a implementation proxy object directly, but instead should depend on PowerShell APIs. + /// + /// Example: if a user want to use prediction functionality, he/she should use the PowerShell prediction API instead of + /// directly interacting with the implementation proxy object of `IPrediction`. + /// + /// The concrete subsystem base type. + /// The most recently registered implmentation object of the concrete subsystem. + internal static TConcreteSubsystem? GetSubsystem() + where TConcreteSubsystem : class, ISubsystem + { + if (s_subSystemTypeMap.TryGetValue(typeof(TConcreteSubsystem), out SubsystemInfo? subsystemInfo)) + { + var subsystemInfoImpl = (SubsystemInfoImpl)subsystemInfo; + return subsystemInfoImpl.GetImplementation(); + } + + throw new ArgumentException( + StringUtil.Format( + SubsystemStrings.SubsystemTypeUnknown, + typeof(TConcreteSubsystem).FullName)); + } + + /// + /// Get all the proxy objects registered for a specific subsystem. + /// Return an empty collection when the given subsystem is not registered. + /// + /// The concrete subsystem base type. + /// A readonly collection of all implmentation objects registered for the concrete subsystem. + internal static ReadOnlyCollection GetSubsystems() + where TConcreteSubsystem : class, ISubsystem + { + if (s_subSystemTypeMap.TryGetValue(typeof(TConcreteSubsystem), out SubsystemInfo? subsystemInfo)) + { + var subsystemInfoImpl = (SubsystemInfoImpl)subsystemInfo; + return subsystemInfoImpl.GetAllImplementations(); + } + + throw new ArgumentException( + StringUtil.Format( + SubsystemStrings.SubsystemTypeUnknown, + typeof(TConcreteSubsystem).FullName)); + } + + #endregion + + #region public - Subsystem metadata + + /// + /// Get the information about all subsystems. + /// + /// A readonly collection of all objects. + public static ReadOnlyCollection GetAllSubsystemInfo() + { + return s_subsystems; + } + + /// + /// Get the information about a subsystem by the subsystem type. + /// + /// The base type of a specific concrete subsystem. + /// The object that represents the concrete subsystem. + public static SubsystemInfo GetSubsystemInfo(Type subsystemType) + { + Requires.NotNull(subsystemType, nameof(subsystemType)); + + if (s_subSystemTypeMap.TryGetValue(subsystemType, out SubsystemInfo? subsystemInfo)) + { + return subsystemInfo; + } + + throw new ArgumentException( + StringUtil.Format( + SubsystemStrings.SubsystemTypeUnknown, + subsystemType.FullName)); + } + + /// + /// Get the information about a subsystem by the subsystem kind. + /// + /// A specific . + /// The object that represents the concrete subsystem. + public static SubsystemInfo GetSubsystemInfo(SubsystemKind kind) + { + if (s_subSystemKindMap.TryGetValue(kind, out SubsystemInfo? subsystemInfo)) + { + return subsystemInfo; + } + + throw new ArgumentException( + StringUtil.Format( + SubsystemStrings.SubsystemKindUnknown, + kind.ToString())); + } + + #endregion + + #region public - Subsystem registration + + /// + /// Subsystem registration. + /// + /// The concrete subsystem base type. + /// The implementation type of that concrete subsystem. + /// An instance of the implementation. + public static void RegisterSubsystem(TImplementation proxy) + where TConcreteSubsystem : class, ISubsystem + where TImplementation : class, TConcreteSubsystem + { + Requires.NotNull(proxy, nameof(proxy)); + + RegisterSubsystem(GetSubsystemInfo(typeof(TConcreteSubsystem)), proxy); + } + + /// + /// Register an implementation for a subsystem. + /// + /// The target of the registration. + /// An instance of the implementation. + public static void RegisterSubsystem(SubsystemKind kind, ISubsystem proxy) + { + Requires.NotNull(proxy, nameof(proxy)); + + if (kind != proxy.Kind) + { + throw new ArgumentException( + StringUtil.Format( + SubsystemStrings.ImplementationMismatch, + proxy.Kind.ToString(), + kind.ToString()), + nameof(proxy)); + } + + RegisterSubsystem(GetSubsystemInfo(kind), proxy); + } + + private static void RegisterSubsystem(SubsystemInfo subsystemInfo, ISubsystem proxy) + { + if (proxy.Id == Guid.Empty) + { + throw new ArgumentException( + StringUtil.Format( + SubsystemStrings.EmptyImplementationId, + subsystemInfo.Kind.ToString()), + nameof(proxy)); + } + + if (string.IsNullOrEmpty(proxy.Name)) + { + throw new ArgumentException( + StringUtil.Format( + SubsystemStrings.NullOrEmptyImplementationName, + subsystemInfo.Kind.ToString()), + nameof(proxy)); + } + + if (string.IsNullOrEmpty(proxy.Description)) + { + throw new ArgumentException( + StringUtil.Format( + SubsystemStrings.NullOrEmptyImplementationDescription, + subsystemInfo.Kind.ToString()), + nameof(proxy)); + } + + if (subsystemInfo.RequiredCmdlets.Any() || subsystemInfo.RequiredFunctions.Any()) + { + // Process 'proxy.CmdletImplementationAssembly' and 'proxy.FunctionsToDefine' + // Functions are added to global scope. + // Cmdlets are loaded in a way like a snapin, making the 'Source' of the cmdlets to be 'Microsoft.PowerShell.Core'. + // + // For example, let's say the Job adapter is made a subsystem, then all `*-Job` cmdlets will be moved out of S.M.A + // into a subsystem implementation DLL. After registration, all `*-Job` cmdlets should be back in the + // 'Microsoft.PowerShell.Core' namespace to keep backward compatibility. + // + // Both cmdlets and functions are added to the default InitialSessionState used for creating a new Runspace, + // so the subsystem works for all subsequent new runspaces after it's registered. + // Take the Job adapter subsystem as an instance again, so when creating another Runspace after the registration, + // all '*-Job' cmdlets should be available in the 'Microsoft.PowerShell.Core' namespace by default. + } + + subsystemInfo.RegisterImplementation(proxy); + } + + #endregion + + #region public - Subsystem unregistration + + /// + /// Subsystem unregistration. + /// Throw 'InvalidOperationException' when called for subsystems that cannot be unregistered. + /// + /// The base type of the target concrete subsystem of the un-registration. + /// The Id of the implementation to be unregistered. + public static void UnregisterSubsystem(Guid id) + where TConcreteSubsystem : class, ISubsystem + { + UnregisterSubsystem(GetSubsystemInfo(typeof(TConcreteSubsystem)), id); + } + + /// + /// Subsystem unregistration. + /// Throw 'InvalidOperationException' when called for subsystems that cannot be unregistered. + /// + /// The target of the un-registration. + /// The Id of the implementation to be unregistered. + public static void UnregisterSubsystem(SubsystemKind kind, Guid id) + { + UnregisterSubsystem(GetSubsystemInfo(kind), id); + } + + private static void UnregisterSubsystem(SubsystemInfo subsystemInfo, Guid id) + { + if (subsystemInfo.RequiredCmdlets.Any() || subsystemInfo.RequiredFunctions.Any()) + { + throw new NotSupportedException("NotSupported yet: unregister subsystem that introduced new cmdlets/functions."); + } + + ISubsystem impl = subsystemInfo.UnregisterImplementation(id); + if (impl is IDisposable disposable) + { + disposable.Dispose(); + } + } + + #endregion + } +} diff --git a/src/System.Management.Automation/engine/Utils.cs b/src/System.Management.Automation/engine/Utils.cs index b3d62c4b06f..bce78b3543d 100644 --- a/src/System.Management.Automation/engine/Utils.cs +++ b/src/System.Management.Automation/engine/Utils.cs @@ -2278,4 +2278,34 @@ internal ReadOnlyBag(HashSet hashset) /// internal static readonly ReadOnlyBag Empty = new ReadOnlyBag(new HashSet(capacity: 0)); } + + /// + /// Helper class for simple argument validations. + /// + internal static class Requires + { + internal static void NotNull(object value, string paramName) + { + if (value == null) + { + throw new ArgumentNullException(paramName); + } + } + + internal static void NotNullOrEmpty(string value, string paramName) + { + if (string.IsNullOrEmpty(value)) + { + throw new ArgumentNullException(paramName); + } + } + + internal static void Condition([DoesNotReturnIf(false)] bool precondition, string paramName) + { + if (!precondition) + { + throw new ArgumentException(paramName); + } + } + } } diff --git a/src/System.Management.Automation/resources/SubsystemStrings.resx b/src/System.Management.Automation/resources/SubsystemStrings.resx new file mode 100644 index 00000000000..a2819da8682 --- /dev/null +++ b/src/System.Management.Automation/resources/SubsystemStrings.resx @@ -0,0 +1,156 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + The subsystem '{0}' does not allow more than one implementation to be registered. + + + The implementation with Id '{0}' was already registered for the subsystem '{1}'. + + + The subsystem '{0}' does not allow the unregistration of an implementation. + + + No implementation was registered for the subsystem '{0}'. + + + A registered implementation with the Id '{0}' was not found. + + + The specified subsystem type '{0}' is unknown. + + + The specified subsystem kind '{0}' is unknown. + + + The specified implementation instance implements the subsystem '{0}', which does not match the target subsystem '{1}'. + + + The declared metadata for subsystem kind '{0}' is invalid. A subsystem that requires cmdlets or functions to be defined cannot allow multiple registrations because that would result in one implementation overwriting the commands defined by another implementation. + + + The 'Id' property of an implementation for the subsystem '{0}' cannot be an empty GUID. + + + The 'Name' property of an implementation for the subsystem '{0}' cannot be null or an empty string. + + + The 'Description' property of an implementation for the subsystem '{0}' cannot be null or an empty string. + + diff --git a/test/powershell/engine/Help/HelpSystem.Tests.ps1 b/test/powershell/engine/Help/HelpSystem.Tests.ps1 index 80d6a46b709..d3c508fe40a 100644 --- a/test/powershell/engine/Help/HelpSystem.Tests.ps1 +++ b/test/powershell/engine/Help/HelpSystem.Tests.ps1 @@ -15,7 +15,8 @@ $script:cmdletsToSkip = @( "Enable-PSRemoting", "Get-ExperimentalFeature", "Enable-ExperimentalFeature", - "Disable-ExperimentalFeature" + "Disable-ExperimentalFeature", + "Get-Subsystem" ) function UpdateHelpFromLocalContentPath { diff --git a/test/xUnit/csharp/test_Prediction.cs b/test/xUnit/csharp/test_Prediction.cs new file mode 100644 index 00000000000..4d67c850f6d --- /dev/null +++ b/test/xUnit/csharp/test_Prediction.cs @@ -0,0 +1,193 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Collections.Generic; +using System.Management.Automation.Language; +using System.Management.Automation.Subsystem; +using System.Threading; +using Xunit; + +namespace PSTests.Sequential +{ + public class MyPredictor : ICommandPredictor + { + private readonly Guid _id; + private readonly string _name, _description; + private readonly bool _delay; + + public List History { get; } + + public List AcceptedSuggestions { get; } + + public static readonly MyPredictor SlowPredictor; + + public static readonly MyPredictor FastPredictor; + + static MyPredictor() + { + SlowPredictor = new MyPredictor( + Guid.NewGuid(), + "Test Predictor #1", + "Description for #1 predictor.", + delay: true); + + FastPredictor = new MyPredictor( + Guid.NewGuid(), + "Test Predictor #2", + "Description for #2 predictor.", + delay: false); + } + + private MyPredictor(Guid id, string name, string description, bool delay) + { + _id = id; + _name = name; + _description = description; + _delay = delay; + + History = new List(); + AcceptedSuggestions = new List(); + } + + public Guid Id => _id; + + public string Name => _name; + + public string Description => _description; + + bool ICommandPredictor.SupportEarlyProcessing => true; + + bool ICommandPredictor.AcceptFeedback => true; + + public void StartEarlyProcessing(IReadOnlyList history) + { + History.AddRange(history); + } + + public void OnSuggestionAccepted(string acceptedSuggestion) + { + AcceptedSuggestions.Add(acceptedSuggestion); + } + + public List GetSuggestion(PredictionContext context, CancellationToken cancellationToken) + { + if (_delay) + { + // The delay is exaggerated to make the test reliable. + // xUnit must spin up a lot tasks, which makes the test unreliable when the time difference between 'delay' and 'timeout' is small. + Thread.Sleep(2000); + } + + // You can get the user input from the AST. + var userInput = context.InputAst.Extent.Text; + return new List { + new PredictiveSuggestion($"{userInput} TEST-1 from {Name}"), + new PredictiveSuggestion($"{userInput} TeSt-2 from {Name}"), + }; + } + } + + public static class CommandPredictionTests + { + [Fact] + public static void PredictInput() + { + MyPredictor slow = MyPredictor.SlowPredictor; + MyPredictor fast = MyPredictor.FastPredictor; + Ast ast = Parser.ParseInput("Hello world", out Token[] tokens, out _); + + // Returns null when no predictor implementation registered + List results = CommandPrediction.PredictInput(ast, tokens).Result; + Assert.Null(results); + + try + { + // Register 2 predictor implementations + SubsystemManager.RegisterSubsystem(slow); + SubsystemManager.RegisterSubsystem(SubsystemKind.CommandPredictor, fast); + + // Expect the results from 'fast' predictor only b/c the 'slow' one + // cannot finish before the specified timeout. + // The specified timeout is exaggerated to make the test reliable. + // xUnit must spin up a lot tasks, which makes the test unreliable when the time difference between 'delay' and 'timeout' is small. + results = CommandPrediction.PredictInput(ast, tokens, millisecondsTimeout: 1000).Result; + Assert.Single(results); + + PredictionResult res = results[0]; + Assert.Equal(fast.Id, res.Id); + Assert.Equal(2, res.Suggestions.Count); + Assert.Equal($"Hello world TEST-1 from {fast.Name}", res.Suggestions[0].SuggestionText); + Assert.Equal($"Hello world TeSt-2 from {fast.Name}", res.Suggestions[1].SuggestionText); + + // Expect the results from both 'slow' and 'fast' predictors + // Same here -- the specified timeout is exaggerated to make the test reliable. + // xUnit must spin up a lot tasks, which makes the test unreliable when the time difference between 'delay' and 'timeout' is small. + results = CommandPrediction.PredictInput(ast, tokens, millisecondsTimeout: 4000).Result; + Assert.Equal(2, results.Count); + + PredictionResult res1 = results[0]; + Assert.Equal(slow.Id, res1.Id); + Assert.Equal(2, res1.Suggestions.Count); + Assert.Equal($"Hello world TEST-1 from {slow.Name}", res1.Suggestions[0].SuggestionText); + Assert.Equal($"Hello world TeSt-2 from {slow.Name}", res1.Suggestions[1].SuggestionText); + + PredictionResult res2 = results[1]; + Assert.Equal(fast.Id, res2.Id); + Assert.Equal(2, res2.Suggestions.Count); + Assert.Equal($"Hello world TEST-1 from {fast.Name}", res2.Suggestions[0].SuggestionText); + Assert.Equal($"Hello world TeSt-2 from {fast.Name}", res2.Suggestions[1].SuggestionText); + } + finally + { + SubsystemManager.UnregisterSubsystem(slow.Id); + SubsystemManager.UnregisterSubsystem(SubsystemKind.CommandPredictor, fast.Id); + } + } + + [Fact] + public static void Feedback() + { + MyPredictor slow = MyPredictor.SlowPredictor; + MyPredictor fast = MyPredictor.FastPredictor; + + try + { + // Register 2 predictor implementations + SubsystemManager.RegisterSubsystem(slow); + SubsystemManager.RegisterSubsystem(SubsystemKind.CommandPredictor, fast); + + var history = new[] { "hello", "world" }; + var ids = new HashSet { slow.Id, fast.Id }; + + CommandPrediction.OnCommandLineAccepted(history); + CommandPrediction.OnSuggestionAccepted(slow.Id, "Yeah"); + + // The calls to 'StartEarlyProcessing' and 'OnSuggestionAccepted' are queued in thread pool, + // so we wait a bit to make sure the calls are done. + while (slow.History.Count == 0 || slow.AcceptedSuggestions.Count == 0) + { + Thread.Sleep(10); + } + + Assert.Equal(2, slow.History.Count); + Assert.Equal(history[0], slow.History[0]); + Assert.Equal(history[1], slow.History[1]); + + Assert.Equal(2, fast.History.Count); + Assert.Equal(history[0], fast.History[0]); + Assert.Equal(history[1], fast.History[1]); + + Assert.Single(slow.AcceptedSuggestions); + Assert.Equal("Yeah", slow.AcceptedSuggestions[0]); + + Assert.Empty(fast.AcceptedSuggestions); + } + finally + { + SubsystemManager.UnregisterSubsystem(slow.Id); + SubsystemManager.UnregisterSubsystem(SubsystemKind.CommandPredictor, fast.Id); + } + } + } +} diff --git a/test/xUnit/csharp/test_Subsystem.cs b/test/xUnit/csharp/test_Subsystem.cs new file mode 100644 index 00000000000..a45ebc116b5 --- /dev/null +++ b/test/xUnit/csharp/test_Subsystem.cs @@ -0,0 +1,189 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Collections.ObjectModel; +using System.Management.Automation.Subsystem; +using System.Threading; +using Xunit; + +namespace PSTests.Sequential +{ + public static class SubsystemTests + { + private static readonly MyPredictor predictor1, predictor2; + + static SubsystemTests() + { + predictor1 = MyPredictor.FastPredictor; + predictor2 = MyPredictor.SlowPredictor; + } + + // This method needs to be updated when there are more than 1 subsystem defined. + private static void VerifySubsystemMetadata(SubsystemInfo ssInfo) + { + Assert.Equal(SubsystemKind.CommandPredictor, ssInfo.Kind); + Assert.Equal(typeof(ICommandPredictor), ssInfo.SubsystemType); + Assert.True(ssInfo.AllowUnregistration); + Assert.True(ssInfo.AllowMultipleRegistration); + Assert.Empty(ssInfo.RequiredCmdlets); + Assert.Empty(ssInfo.RequiredFunctions); + } + + [Fact] + public static void GetSubsystemInfo() + { + SubsystemInfo ssInfo = SubsystemManager.GetSubsystemInfo(typeof(ICommandPredictor)); + + VerifySubsystemMetadata(ssInfo); + Assert.False(ssInfo.IsRegistered); + Assert.Empty(ssInfo.Implementations); + + SubsystemInfo ssInfo2 = SubsystemManager.GetSubsystemInfo(SubsystemKind.CommandPredictor); + Assert.Same(ssInfo2, ssInfo); + + ReadOnlyCollection ssInfos = SubsystemManager.GetAllSubsystemInfo(); + Assert.Single(ssInfos); + Assert.Same(ssInfos[0], ssInfo); + + ICommandPredictor impl = SubsystemManager.GetSubsystem(); + Assert.Null(impl); + ReadOnlyCollection impls = SubsystemManager.GetSubsystems(); + Assert.Empty(impls); + } + + [Fact] + public static void RegisterSubsystem() + { + try + { + Assert.Throws( + paramName: "proxy", + () => SubsystemManager.RegisterSubsystem(null)); + Assert.Throws( + paramName: "proxy", + () => SubsystemManager.RegisterSubsystem(SubsystemKind.CommandPredictor, null)); + Assert.Throws( + paramName: "proxy", + () => SubsystemManager.RegisterSubsystem((SubsystemKind)0, predictor1)); + + // Register 'predictor1' + SubsystemManager.RegisterSubsystem(predictor1); + + // Now validate the SubsystemInfo of the 'ICommandPredictor' subsystem + SubsystemInfo ssInfo = SubsystemManager.GetSubsystemInfo(typeof(ICommandPredictor)); + VerifySubsystemMetadata(ssInfo); + Assert.True(ssInfo.IsRegistered); + Assert.Single(ssInfo.Implementations); + + // Now validate the 'ImplementationInfo' + var implInfo = ssInfo.Implementations[0]; + Assert.Equal(predictor1.Id, implInfo.Id); + Assert.Equal(predictor1.Name, implInfo.Name); + Assert.Equal(predictor1.Description, implInfo.Description); + Assert.Equal(SubsystemKind.CommandPredictor, implInfo.Kind); + Assert.Same(typeof(MyPredictor), implInfo.ImplementationType); + + // Now validate the all-subsystem-info collection. + ReadOnlyCollection ssInfos = SubsystemManager.GetAllSubsystemInfo(); + Assert.Single(ssInfos); + Assert.Same(ssInfos[0], ssInfo); + + // Now validate the subsystem implementation itself. + ICommandPredictor impl = SubsystemManager.GetSubsystem(); + Assert.Same(impl, predictor1); + Assert.Null(impl.FunctionsToDefine); + Assert.Equal(SubsystemKind.CommandPredictor, impl.Kind); + + var predCxt = PredictionContext.Create("Hello world"); + var results = impl.GetSuggestion(predCxt, CancellationToken.None); + Assert.Equal($"Hello world TEST-1 from {impl.Name}", results[0].SuggestionText); + Assert.Equal($"Hello world TeSt-2 from {impl.Name}", results[1].SuggestionText); + + // Now validate the all-subsystem-implementation collection. + ReadOnlyCollection impls = SubsystemManager.GetSubsystems(); + Assert.Single(impls); + Assert.Same(predictor1, impls[0]); + + // Register 'predictor2' + SubsystemManager.RegisterSubsystem(SubsystemKind.CommandPredictor, predictor2); + + // Now validate the SubsystemInfo of the 'ICommandPredictor' subsystem + VerifySubsystemMetadata(ssInfo); + Assert.True(ssInfo.IsRegistered); + Assert.Equal(2, ssInfo.Implementations.Count); + + // Now validate the new 'ImplementationInfo' + implInfo = ssInfo.Implementations[1]; + Assert.Equal(predictor2.Id, implInfo.Id); + Assert.Equal(predictor2.Name, implInfo.Name); + Assert.Equal(predictor2.Description, implInfo.Description); + Assert.Equal(SubsystemKind.CommandPredictor, implInfo.Kind); + Assert.Same(typeof(MyPredictor), implInfo.ImplementationType); + + // Now validate the new subsystem implementation. + impl = SubsystemManager.GetSubsystem(); + Assert.Same(impl, predictor2); + + // Now validate the all-subsystem-implementation collection. + impls = SubsystemManager.GetSubsystems(); + Assert.Equal(2, impls.Count); + Assert.Same(predictor1, impls[0]); + Assert.Same(predictor2, impls[1]); + } + finally + { + SubsystemManager.UnregisterSubsystem(predictor1.Id); + SubsystemManager.UnregisterSubsystem(SubsystemKind.CommandPredictor, predictor2.Id); + } + } + + [Fact] + public static void UnregisterSubsystem() + { + // Exception expected when no implementation is registered + Assert.Throws(() => SubsystemManager.UnregisterSubsystem(predictor1.Id)); + + SubsystemManager.RegisterSubsystem(predictor1); + SubsystemManager.RegisterSubsystem(SubsystemKind.CommandPredictor, predictor2); + + // Exception is expected when specified id cannot be found + Assert.Throws(() => SubsystemManager.UnregisterSubsystem(Guid.NewGuid())); + + // Unregister 'predictor1' + SubsystemManager.UnregisterSubsystem(predictor1.Id); + + SubsystemInfo ssInfo = SubsystemManager.GetSubsystemInfo(SubsystemKind.CommandPredictor); + VerifySubsystemMetadata(ssInfo); + Assert.True(ssInfo.IsRegistered); + Assert.Single(ssInfo.Implementations); + + var implInfo = ssInfo.Implementations[0]; + Assert.Equal(predictor2.Id, implInfo.Id); + Assert.Equal(predictor2.Name, implInfo.Name); + Assert.Equal(predictor2.Description, implInfo.Description); + Assert.Equal(SubsystemKind.CommandPredictor, implInfo.Kind); + Assert.Same(typeof(MyPredictor), implInfo.ImplementationType); + + ICommandPredictor impl = SubsystemManager.GetSubsystem(); + Assert.Same(impl, predictor2); + + ReadOnlyCollection impls = SubsystemManager.GetSubsystems(); + Assert.Single(impls); + Assert.Same(predictor2, impls[0]); + + // Unregister 'predictor2' + SubsystemManager.UnregisterSubsystem(SubsystemKind.CommandPredictor, predictor2.Id); + + VerifySubsystemMetadata(ssInfo); + Assert.False(ssInfo.IsRegistered); + Assert.Empty(ssInfo.Implementations); + + impl = SubsystemManager.GetSubsystem(); + Assert.Null(impl); + + impls = SubsystemManager.GetSubsystems(); + Assert.Empty(impls); + } + } +} diff --git a/tools/packaging/packaging.psm1 b/tools/packaging/packaging.psm1 index 6740cb0afa4..664f5455553 100644 --- a/tools/packaging/packaging.psm1 +++ b/tools/packaging/packaging.psm1 @@ -2325,46 +2325,63 @@ function CleanupGeneratedSourceCode '[System.Runtime.CompilerServices.IsReadOnlyAttribute]' '[System.Runtime.CompilerServices.NullableContextAttribute(' '[System.Runtime.CompilerServices.NullableAttribute((byte)0)]' + '[System.Runtime.CompilerServices.NullableAttribute(new byte[]{ (byte)2, (byte)1, (byte)1})]' + '[System.Runtime.CompilerServices.AsyncStateMachineAttribute' ) $patternsToReplace = @( @{ - ApplyTo = "Microsoft.PowerShell.Commands.Utility" + ApplyTo = @("Microsoft.PowerShell.Commands.Utility") Pattern = "[System.Runtime.CompilerServices.IsReadOnlyAttribute]ref Microsoft.PowerShell.Commands.JsonObject.ConvertToJsonContext" Replacement = "in Microsoft.PowerShell.Commands.JsonObject.ConvertToJsonContext" }, @{ - ApplyTo = "Microsoft.PowerShell.Commands.Utility" + ApplyTo = @("Microsoft.PowerShell.Commands.Utility") Pattern = "public partial struct ConvertToJsonContext" Replacement = "public readonly struct ConvertToJsonContext" }, @{ - ApplyTo = "Microsoft.PowerShell.Commands.Utility" + ApplyTo = @("Microsoft.PowerShell.Commands.Utility") Pattern = "Unable to resolve assembly 'Assembly(Name=Newtonsoft.Json" Replacement = "// Unable to resolve assembly 'Assembly(Name=Newtonsoft.Json" }, @{ - ApplyTo = "System.Management.Automation" + ApplyTo = @("System.Management.Automation") Pattern = "Unable to resolve assembly 'Assembly(Name=System.Security.Principal.Windows" Replacement = "// Unable to resolve assembly 'Assembly(Name=System.Security.Principal.Windows" }, @{ - ApplyTo = "System.Management.Automation" + ApplyTo = @("System.Management.Automation") Pattern = "Unable to resolve assembly 'Assembly(Name=Microsoft.Management.Infrastructure" Replacement = "// Unable to resolve assembly 'Assembly(Name=Microsoft.Management.Infrastructure" }, @{ - ApplyTo = "System.Management.Automation" + ApplyTo = @("System.Management.Automation") Pattern = "Unable to resolve assembly 'Assembly(Name=System.Security.AccessControl" Replacement = "// Unable to resolve assembly 'Assembly(Name=System.Security.AccessControl" }, @{ - ApplyTo = "Microsoft.PowerShell.ConsoleHost" + ApplyTo = @("System.Management.Automation") + Pattern = "[System.Runtime.CompilerServices.NullableAttribute(new byte[]{ (byte)1, (byte)2, (byte)1})]" + Replacement = "/* [System.Runtime.CompilerServices.NullableAttribute(new byte[]{ (byte)1, (byte)2, (byte)1})] */ " + }, + @{ + ApplyTo = @("System.Management.Automation") + Pattern = "[System.Runtime.CompilerServices.NullableAttribute(new byte[]{ (byte)2, (byte)1})]" + Replacement = "/* [System.Runtime.CompilerServices.NullableAttribute(new byte[]{ (byte)2, (byte)1})] */ " + }, + @{ + ApplyTo = @("System.Management.Automation") + Pattern = "[System.Runtime.CompilerServices.CompilerGeneratedAttribute, System.Runtime.CompilerServices.NullableContextAttribute((byte)2)]" + Replacement = "/* [System.Runtime.CompilerServices.CompilerGeneratedAttribute, System.Runtime.CompilerServices.NullableContextAttribute((byte)2)] */ " + }, + @{ + ApplyTo = @("System.Management.Automation", "Microsoft.PowerShell.ConsoleHost") Pattern = "[System.Runtime.CompilerServices.NullableAttribute((byte)2)]" Replacement = "/* [System.Runtime.CompilerServices.NullableAttribute((byte)2)] */" }, @{ - ApplyTo = "Microsoft.PowerShell.ConsoleHost" + ApplyTo = @("System.Management.Automation", "Microsoft.PowerShell.ConsoleHost") Pattern = "[System.Runtime.CompilerServices.NullableAttribute((byte)1)]" Replacement = "/* [System.Runtime.CompilerServices.NullableAttribute((byte)1)] */" } @@ -2378,7 +2395,7 @@ function CleanupGeneratedSourceCode $lineWasProcessed = $false foreach ($patternToReplace in $patternsToReplace) { - if ($assemblyName -eq $patternToReplace.ApplyTo -and $line.Contains($patternToReplace.Pattern)) { + if ($assemblyName -in $patternToReplace.ApplyTo -and $line.Contains($patternToReplace.Pattern)) { $line = $line.Replace($patternToReplace.Pattern, $patternToReplace.Replacement) $lineWasProcessed = $true break From 5f9d2846f7143b113febfb96516e6c06033d4167 Mon Sep 17 00:00:00 2001 From: Dongbo Wang Date: Thu, 20 Aug 2020 23:30:42 -0700 Subject: [PATCH 12/40] Change `Add-Type -OutputType` to not support `ConsoleApplication` and `WindowsApplication` (#13440) --- .../commands/utility/AddType.cs | 23 ++++++++++++++----- .../resources/AddTypeStrings.resx | 3 +++ .../Add-Type.Tests.ps1 | 8 +++++++ 3 files changed, 28 insertions(+), 6 deletions(-) diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/AddType.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/AddType.cs index 4f7185a7e85..54a841c5f43 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/AddType.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/AddType.cs @@ -551,7 +551,21 @@ protected override void BeginProcessing() { ThrowTerminatingError( new ErrorRecord( - new PSNotSupportedException(AddTypeStrings.CannotDefineNewType), "CannotDefineNewType", ErrorCategory.PermissionDenied, null)); + new PSNotSupportedException(AddTypeStrings.CannotDefineNewType), + nameof(AddTypeStrings.CannotDefineNewType), + ErrorCategory.PermissionDenied, + targetObject: null)); + } + + // 'ConsoleApplication' and 'WindowsApplication' types are currently not working in .NET Core + if (OutputType != OutputAssemblyType.Library) + { + ThrowTerminatingError( + new ErrorRecord( + new PSNotSupportedException(AddTypeStrings.AssemblyTypeNotSupported), + nameof(AddTypeStrings.AssemblyTypeNotSupported), + ErrorCategory.NotImplemented, + targetObject: OutputType)); } } @@ -890,12 +904,9 @@ private OutputKind OutputAssemblyTypeToOutputKind(OutputAssemblyType outputType) { case OutputAssemblyType.Library: return OutputKind.DynamicallyLinkedLibrary; - case OutputAssemblyType.ConsoleApplication: - return OutputKind.ConsoleApplication; - case OutputAssemblyType.WindowsApplication: - return OutputKind.WindowsApplication; + default: - throw new ArgumentOutOfRangeException(nameof(outputType)); + throw PSTraceSource.NewNotSupportedException(); } } diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/AddTypeStrings.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/AddTypeStrings.resx index ba570831de8..75ba47072d2 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/resources/AddTypeStrings.resx +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/AddTypeStrings.resx @@ -165,4 +165,7 @@ The specified reference assembly '{0}' is unnecessary and ignored. + + Both the assembly types 'ConsoleApplication' and 'WindowsApplication' are not currently supported. + diff --git a/test/powershell/Modules/Microsoft.PowerShell.Utility/Add-Type.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Utility/Add-Type.Tests.ps1 index ab2b94a6b58..b818dc64012 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Utility/Add-Type.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Utility/Add-Type.Tests.ps1 @@ -246,4 +246,12 @@ public class AttributeTest$guid : PSCmdlet param ($assemblyName, $errorid) { Add-Type -AssemblyName $assemblyName } | Should -Throw -ErrorId $errorid } + + It "Throw terminating error when '-OutputType' is ''" -TestCases @( + @{ outputType = 'ConsoleApplication' } + @{ outputType = 'WindowsApplication' } + ) { + param($outputType) + { Add-Type -TypeDefinition "Hello" -OutputType $outputType } | Should -Throw -ErrorId 'AssemblyTypeNotSupported,Microsoft.PowerShell.Commands.AddTypeCommand' + } } From ff2143d07b69c5340a3ca9c6b4ad9aff76895f14 Mon Sep 17 00:00:00 2001 From: "dependabot-preview[bot]" <27856297+dependabot-preview[bot]@users.noreply.github.com> Date: Fri, 21 Aug 2020 08:53:58 -0700 Subject: [PATCH 13/40] Bump Microsoft.NET.Test.Sdk from 16.7.0 to 16.7.1 (#13492) Bumps [Microsoft.NET.Test.Sdk](https://github.com/microsoft/vstest) from 16.7.0 to 16.7.1. - [Release notes](https://github.com/microsoft/vstest/releases) - [Commits](https://github.com/microsoft/vstest/compare/v16.7.0...v16.7.1) Signed-off-by: dependabot-preview[bot] Co-authored-by: dependabot-preview[bot] <27856297+dependabot-preview[bot]@users.noreply.github.com> --- test/xUnit/xUnit.tests.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/xUnit/xUnit.tests.csproj b/test/xUnit/xUnit.tests.csproj index 4c8db7a118e..1dd68b6ae8e 100644 --- a/test/xUnit/xUnit.tests.csproj +++ b/test/xUnit/xUnit.tests.csproj @@ -27,7 +27,7 @@ - + From 44bb5861cb2e8ee60ca4d251c8dbfb25c500f029 Mon Sep 17 00:00:00 2001 From: Dongbo Wang Date: Fri, 21 Aug 2020 10:28:16 -0700 Subject: [PATCH 14/40] Avoid multiple enumerations of an `IEnumerable` instance in `Compiler.cs` (#13491) --- .../engine/parser/Compiler.cs | 32 ++++++++++++++++--- 1 file changed, 27 insertions(+), 5 deletions(-) diff --git a/src/System.Management.Automation/engine/parser/Compiler.cs b/src/System.Management.Automation/engine/parser/Compiler.cs index 3a25e8c5d98..642bd1e1dc3 100644 --- a/src/System.Management.Automation/engine/parser/Compiler.cs +++ b/src/System.Management.Automation/engine/parser/Compiler.cs @@ -949,9 +949,20 @@ internal Expression CompileExpressionOperand(ExpressionAst exprAst) return result; } - private IEnumerable CompileInvocationArguments(IEnumerable arguments) + private IEnumerable CompileInvocationArguments(IReadOnlyList arguments) { - return arguments == null ? Array.Empty() : arguments.Select(CompileExpressionOperand); + if (arguments is null || arguments.Count == 0) + { + return Array.Empty(); + } + + var result = new Expression[arguments.Count]; + for (int i = 0; i < result.Length; i++) + { + result[i] = CompileExpressionOperand(arguments[i]); + } + + return result; } internal Expression ReduceAssignment(ISupportsAssignment left, TokenKind tokenKind, Expression right) @@ -6669,9 +6680,20 @@ private IEnumerable GetArgumentExprs(Compiler compiler) return _argExprTemps; } - return InvokeMemberExpressionAst.Arguments == null - ? Array.Empty() - : InvokeMemberExpressionAst.Arguments.Select(compiler.Compile).ToArray(); + ReadOnlyCollection arguments = InvokeMemberExpressionAst.Arguments; + + if (arguments is null || arguments.Count == 0) + { + return Array.Empty(); + } + + var result = new Expression[arguments.Count]; + for (int i = 0; i < result.Length; i++) + { + result[i] = compiler.Compile(arguments[i]); + } + + return result; } public Expression GetValue(Compiler compiler, List exprs, List temps) From 213e5b7857df4cb30bd1395791fb20f9b1672632 Mon Sep 17 00:00:00 2001 From: Robert Holt Date: Fri, 21 Aug 2020 10:37:42 -0700 Subject: [PATCH 15/40] Suppress `UTF-7` obsolete warnings (#13484) --- .../namespaces/FileSystemProvider.cs | 2 ++ src/System.Management.Automation/utils/EncodingUtils.cs | 2 ++ 2 files changed, 4 insertions(+) diff --git a/src/System.Management.Automation/namespaces/FileSystemProvider.cs b/src/System.Management.Automation/namespaces/FileSystemProvider.cs index eab04cb6e40..c1a539fb3ac 100644 --- a/src/System.Management.Automation/namespaces/FileSystemProvider.cs +++ b/src/System.Management.Automation/namespaces/FileSystemProvider.cs @@ -7617,7 +7617,9 @@ public Encoding Encoding set { +#pragma warning disable 612, 618 if (value == System.Text.Encoding.UTF7) +#pragma warning restore 612, 618 { _provider.WriteWarning(PathUtilsStrings.Utf7EncodingObsolete); } diff --git a/src/System.Management.Automation/utils/EncodingUtils.cs b/src/System.Management.Automation/utils/EncodingUtils.cs index 6825a259dae..abbe4a569f6 100644 --- a/src/System.Management.Automation/utils/EncodingUtils.cs +++ b/src/System.Management.Automation/utils/EncodingUtils.cs @@ -95,7 +95,9 @@ internal static Encoding Convert(Cmdlet cmdlet, string encoding) /// The encoding to check for obsolescence. internal static void WarnIfObsolete(Cmdlet cmdlet, Encoding encoding) { +#pragma warning disable 612, 618 if (encoding == System.Text.Encoding.UTF7) +#pragma warning restore 612, 618 { cmdlet.WriteWarning(PathUtilsStrings.Utf7EncodingObsolete); } From 6615fa3df606154647d839c09c66022c413a0c69 Mon Sep 17 00:00:00 2001 From: Dongbo Wang Date: Fri, 21 Aug 2020 11:59:30 -0700 Subject: [PATCH 16/40] Fix test hooks for `CommandLineParameterParser` (#13459) --- .../host/msh/CommandLineParameterParser.cs | 21 ++++++++++++++----- .../host/msh/ConsoleHost.cs | 7 +++++++ test/xUnit/csharp/test_CommandLineParser.cs | 6 +++--- 3 files changed, 26 insertions(+), 8 deletions(-) diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/CommandLineParameterParser.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/CommandLineParameterParser.cs index 11de41ce95f..f51a6c94410 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/CommandLineParameterParser.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/CommandLineParameterParser.cs @@ -169,7 +169,7 @@ internal static int MaxNameLength() return maxLength - Path.GetTempPath().Length; } - internal bool? TestHookConsoleInputRedirected; + internal bool? InputRedirectedTestHook; private static readonly string[] s_validParameters = { "sta", @@ -209,6 +209,7 @@ internal CommandLineParameterParser() } #region Internal properties + internal bool AbortStartup { get @@ -245,6 +246,17 @@ internal bool WasInitialCommandEncoded } } +#if !UNIX + internal ProcessWindowStyle? WindowStyle + { + get + { + AssertArgumentsParsed(); + return _windowStyle; + } + } +#endif + internal bool ShowBanner { get @@ -846,9 +858,7 @@ private void ParseHelper(string[] args) try { - ProcessWindowStyle style = (ProcessWindowStyle)LanguagePrimitives.ConvertTo( - args[i], typeof(ProcessWindowStyle), CultureInfo.InvariantCulture); - ConsoleControl.SetConsoleMode(style); + _windowStyle = LanguagePrimitives.ConvertTo(args[i]); } catch (PSInvalidCastException e) { @@ -1234,7 +1244,7 @@ private bool ParseCommand(string[] args, ref int i, bool noexitSeen, bool isEnco return false; } - if (TestHookConsoleInputRedirected.HasValue ? !TestHookConsoleInputRedirected.Value : !Console.IsInputRedirected) + if (InputRedirectedTestHook.HasValue ? !InputRedirectedTestHook.Value : !Console.IsInputRedirected) { SetCommandLineError(CommandLineParameterParserStrings.StdinNotRedirected, showHelp: true); return false; @@ -1340,6 +1350,7 @@ private bool CollectArgs(string[] args, ref int i) private string? _workingDirectory; #if !UNIX + private ProcessWindowStyle? _windowStyle; private bool _removeWorkingDirectoryTrailingCharacter = false; #endif } diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHost.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHost.cs index cf73f2ebeaa..fb269cb57e1 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHost.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHost.cs @@ -271,6 +271,13 @@ internal static void ParseCommandLine(string[] args) { s_cpp.Parse(args); +#if !UNIX + if (s_cpp.WindowStyle.HasValue) + { + ConsoleControl.SetConsoleMode(s_cpp.WindowStyle.Value); + } +#endif + if (s_cpp.SettingsFile is not null) { PowerShellConfig.Instance.SetSystemConfigFilePath(s_cpp.SettingsFile); diff --git a/test/xUnit/csharp/test_CommandLineParser.cs b/test/xUnit/csharp/test_CommandLineParser.cs index d4b722b7f4a..0e15659bf3a 100644 --- a/test/xUnit/csharp/test_CommandLineParser.cs +++ b/test/xUnit/csharp/test_CommandLineParser.cs @@ -475,7 +475,7 @@ public static void TestParameter_Command_With_Dash_And_Not_ConsoleInputRedirecte { var cpp = new CommandLineParameterParser(); - cpp.TestHookConsoleInputRedirected = false; + cpp.InputRedirectedTestHook = false; cpp.Parse(commandLine); @@ -512,7 +512,7 @@ public static void TestParameter_Command_With_Dash_And_ConsoleInputRedirected(pa { var cpp = new CommandLineParameterParser(); - cpp.TestHookConsoleInputRedirected = true; + cpp.InputRedirectedTestHook = true; cpp.Parse(commandLine); @@ -855,7 +855,7 @@ public static void TestParameter_EncodedCommand_With_Dash_And_ConsoleInputRedire { var cpp = new CommandLineParameterParser(); - cpp.TestHookConsoleInputRedirected = true; + cpp.InputRedirectedTestHook = true; cpp.Parse(commandLine); From 3594ac60c790cc5d3b39ea0d956cc8ee8985d0c8 Mon Sep 17 00:00:00 2001 From: xtqqczze <45661989+xtqqczze@users.noreply.github.com> Date: Mon, 24 Aug 2020 05:10:54 +0100 Subject: [PATCH 17/40] Add StringUtil.Format overload to avoid unnecessary allocations (#13408) * Rename parameters to correspond to string.Format * Add addtional overload to avoid allocations at call sites --- .../utils/StringUtil.cs | 27 +++++++------------ 1 file changed, 9 insertions(+), 18 deletions(-) diff --git a/src/System.Management.Automation/utils/StringUtil.cs b/src/System.Management.Automation/utils/StringUtil.cs index 9a95407df76..0b74385d335 100644 --- a/src/System.Management.Automation/utils/StringUtil.cs +++ b/src/System.Management.Automation/utils/StringUtil.cs @@ -11,26 +11,17 @@ namespace System.Management.Automation.Internal internal static class StringUtil { - internal static - string - Format(string formatSpec, object o) - { - return string.Format(System.Globalization.CultureInfo.CurrentCulture, formatSpec, o); - } + internal static string Format(string format, object arg0) + => string.Format(Globalization.CultureInfo.CurrentCulture, format, arg0); - internal static - string - Format(string formatSpec, object o1, object o2) - { - return string.Format(System.Globalization.CultureInfo.CurrentCulture, formatSpec, o1, o2); - } + internal static string Format(string format, object arg0, object arg1) + => string.Format(Globalization.CultureInfo.CurrentCulture, format, arg0, arg1); - internal static - string - Format(string formatSpec, params object[] o) - { - return string.Format(System.Globalization.CultureInfo.CurrentCulture, formatSpec, o); - } + internal static string Format(string format, object arg0, object arg1, object arg2) + => string.Format(Globalization.CultureInfo.CurrentCulture, format, arg0, arg1, arg2); + + internal static string Format(string format, params object[] args) + => string.Format(Globalization.CultureInfo.CurrentCulture, format, args); internal static string From 16f0b74187d7ab6da0f73ba207bc3a9a2a86f1b9 Mon Sep 17 00:00:00 2001 From: xtqqczze <45661989+xtqqczze@users.noreply.github.com> Date: Tue, 25 Aug 2020 19:29:26 +0100 Subject: [PATCH 18/40] Cleanup: Remove redundant empty lines (#13404) --- .../PdhHelper.cs | 1 - .../commands/management/Computer.cs | 1 - .../commands/management/Process.cs | 1 - .../commands/utility/ConsoleColorCmdlet.cs | 3 - .../commands/utility/ConvertTo-Html.cs | 1 - .../commands/utility/CsvCommands.cs | 1 - .../commands/utility/CustomSerialization.cs | 1 - .../commands/utility/GetHostCmdlet.cs | 1 - .../commands/utility/Measure-Object.cs | 1 - .../commands/utility/ReadConsoleCmdlet.cs | 3 - .../commands/utility/Var.cs | 1 - .../host/msh/ConsoleControl.cs | 23 ----- .../host/msh/ConsoleHost.cs | 7 -- .../host/msh/ConsoleHostRawUserInterface.cs | 18 ---- .../host/msh/ConsoleHostUserInterface.cs | 20 ----- .../msh/ConsoleHostUserInterfaceProgress.cs | 3 - .../msh/ConsoleHostUserInterfacePrompt.cs | 2 - ...ConsoleHostUserInterfacePromptForChoice.cs | 1 - .../msh/ConsoleHostUserInterfaceSecurity.cs | 2 - .../host/msh/ConsoleShell.cs | 1 - .../host/msh/Executor.cs | 2 - .../host/msh/PendingProgress.cs | 17 ---- .../host/msh/ProgressNode.cs | 14 --- .../host/msh/ProgressPane.cs | 6 -- .../host/msh/Serialization.cs | 4 - .../host/msh/StartTranscriptCmdlet.cs | 4 - .../host/msh/StopTranscriptCmdlet.cs | 2 - .../security/CertificateProvider.cs | 13 --- src/Microsoft.WSMan.Management/CredSSP.cs | 1 - src/Microsoft.WSMan.Management/Interop.cs | 2 - .../InvokeWSManAction.cs | 1 - .../NewWSManSession.cs | 1 - src/Microsoft.WSMan.Management/PingWSMan.cs | 1 - .../WSManConnections.cs | 1 - .../WSManInstance.cs | 10 --- .../WSManSessionOption.cs | 1 - .../engine/ComInterop/ComMethodDesc.cs | 1 - .../engine/ComInterop/ComTypeDesc.cs | 1 - .../engine/ComInterop/IDispatchComObject.cs | 1 - .../engine/ComInterop/UnknownArgBuilder.cs | 1 - .../engine/ComInterop/VarEnumSelector.cs | 1 - .../engine/CommandBase.cs | 1 - .../engine/InformationRecord.cs | 1 - .../engine/ProgressRecord.cs | 14 --- .../engine/ScopedItemSearcher.cs | 1 - .../engine/SessionState.cs | 1 - .../engine/SessionStateScope.cs | 1 - .../engine/hostifaces/ChoiceDescription.cs | 5 -- .../engine/hostifaces/DefaultHost.cs | 6 -- .../engine/hostifaces/FieldDescription.cs | 14 --- .../engine/hostifaces/History.cs | 12 --- .../InternalHostRawUserInterface.cs | 15 ---- .../hostifaces/InternalHostUserInterface.cs | 15 ---- .../engine/hostifaces/MshHost.cs | 14 --- .../hostifaces/MshHostRawUserInterface.cs | 90 ------------------- .../engine/hostifaces/MshHostUserInterface.cs | 1 - .../engine/hostifaces/RunspaceInit.cs | 1 - .../internalHostuserInterfacesecurity.cs | 2 - .../engine/remoting/client/Job.cs | 1 - .../WireDataFormat/RemoteSessionCapability.cs | 1 - .../server/serverremotesessionstatemachine.cs | 4 - .../namespaces/CoreCommandContext.cs | 1 - .../utils/HostInterfacesExceptions.cs | 12 --- 63 files changed, 390 deletions(-) diff --git a/src/Microsoft.PowerShell.Commands.Diagnostics/PdhHelper.cs b/src/Microsoft.PowerShell.Commands.Diagnostics/PdhHelper.cs index 130a7f41804..d0ffb1d579d 100644 --- a/src/Microsoft.PowerShell.Commands.Diagnostics/PdhHelper.cs +++ b/src/Microsoft.PowerShell.Commands.Diagnostics/PdhHelper.cs @@ -431,7 +431,6 @@ public void Dispose() /// /// /// - private void ReadPdhMultiString(ref IntPtr strNative, Int32 strSize, ref StringCollection strColl) { Debug.Assert(strSize >= 2); diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/Computer.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/Computer.cs index 5d2513a47ae..7cb9e6856c1 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/Computer.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/Computer.cs @@ -1272,7 +1272,6 @@ private void ProcessWSManProtocol(object[] flags) /// workgroup computer. Use this command to rename domain workstations and local /// machines only. It cannot be used to rename Domain Controllers. /// - [Cmdlet(VerbsCommon.Rename, "Computer", SupportsShouldProcess = true, HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2097054", RemotingCapability = RemotingCapability.SupportedByCommand)] public class RenameComputerCommand : PSCmdlet diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/Process.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/Process.cs index c20ef98a80d..b825266e6ef 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/Process.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/Process.cs @@ -545,7 +545,6 @@ public SwitchParameter IncludeUserName /// /// To display the modules of a process. /// - [Parameter(ParameterSetName = NameParameterSet)] [Parameter(ParameterSetName = IdParameterSet)] [Parameter(ParameterSetName = InputObjectParameterSet)] diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ConsoleColorCmdlet.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ConsoleColorCmdlet.cs index 250b00422d6..bb6a35746c6 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ConsoleColorCmdlet.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ConsoleColorCmdlet.cs @@ -10,7 +10,6 @@ namespace Microsoft.PowerShell.Commands /// /// Base class for a variety of commandlets that take color parameters. /// - public class ConsoleColorCmdlet : PSCmdlet { @@ -26,7 +25,6 @@ public ConsoleColorCmdlet() /// The -ForegroundColor parameter. /// /// - [Parameter] public ConsoleColor @@ -60,7 +58,6 @@ public ConsoleColorCmdlet() /// /// /// - [Parameter] public ConsoleColor diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ConvertTo-Html.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ConvertTo-Html.cs index b0c3ff27f35..4ca99f45ae2 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ConvertTo-Html.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ConvertTo-Html.cs @@ -18,7 +18,6 @@ namespace Microsoft.PowerShell.Commands /// /// Class comment. /// - [Cmdlet(VerbsData.ConvertTo, "Html", DefaultParameterSetName = "Page", HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2096595", RemotingCapability = RemotingCapability.None)] public sealed diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/CsvCommands.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/CsvCommands.cs index dab4a4b3340..bea8b55d7c1 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/CsvCommands.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/CsvCommands.cs @@ -43,7 +43,6 @@ public abstract class BaseCsvWritingCommand : PSCmdlet /// Abstract Property - Input Object which is written in Csv format. /// Derived as Different Attributes.In ConvertTo-CSV, This is a positional parameter. Export-CSV not a Positional behaviour. /// - public abstract PSObject InputObject { get; set; } /// diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/CustomSerialization.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/CustomSerialization.cs index 465ef91f037..2c85a64cf18 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/CustomSerialization.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/CustomSerialization.cs @@ -1104,7 +1104,6 @@ private void WriteObjectString( /// Name of property. Pass null for item. /// Object to be written. /// Serialization information about source. - private void WriteOnePrimitiveKnownType( XmlWriter writer, string property, object source, TypeSerializationInfo entry) { diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetHostCmdlet.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetHostCmdlet.cs index 76718bfde3f..444e085591f 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetHostCmdlet.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetHostCmdlet.cs @@ -10,7 +10,6 @@ namespace Microsoft.PowerShell.Commands /// /// Writes the PSHost object to the success stream. /// - [Cmdlet(VerbsCommon.Get, "Host", HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2097110", RemotingCapability = RemotingCapability.None)] [OutputType(typeof(System.Management.Automation.Host.PSHost))] public diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Measure-Object.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Measure-Object.cs index 67a9e43c3b9..230f985c19e 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Measure-Object.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Measure-Object.cs @@ -198,7 +198,6 @@ public V EnsureEntry(string key) /// to maintain two sets of MeasureInfo and constantly checking /// what mode we're in. /// - [SuppressMessage("Microsoft.Performance", "CA1812:AvoidUninstantiatedInternalClasses")] private class Statistics { diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ReadConsoleCmdlet.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ReadConsoleCmdlet.cs index f0cab039424..997bae76554 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ReadConsoleCmdlet.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ReadConsoleCmdlet.cs @@ -16,7 +16,6 @@ namespace Microsoft.PowerShell.Commands /// /// Retrieves input from the host virtual console and writes it to the pipeline output. /// - [Cmdlet(VerbsCommunications.Read, "Host", DefaultParameterSetName = "AsString", HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2096610")] [OutputType(typeof(string), typeof(SecureString))] public sealed class ReadHostCommand : PSCmdlet @@ -24,7 +23,6 @@ public sealed class ReadHostCommand : PSCmdlet /// /// Constructs a new instance. /// - public ReadHostCommand() { @@ -36,7 +34,6 @@ public sealed class ReadHostCommand : PSCmdlet /// /// The objects to display on the host before collecting input. /// - [Parameter(Position = 0, ValueFromRemainingArguments = true)] [AllowNull] public diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Var.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Var.cs index 6739dbb38e5..fd121fc5fb2 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Var.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Var.cs @@ -14,7 +14,6 @@ namespace Microsoft.PowerShell.Commands /// Base class for all variable commands. /// Because -Scope is defined in VariableCommandBase, all derived commands must implement -Scope. /// - public abstract class VariableCommandBase : PSCmdlet { #region Parameters diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleControl.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleControl.cs index 6159e349497..0403fdf41f9 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleControl.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleControl.cs @@ -44,7 +44,6 @@ namespace Microsoft.PowerShell /// Class ConsoleControl is used to wrap the various win32 console APIs 1:1 (i.e. at a low level, without attempting to be a /// "true" object-oriented library. /// - internal static class ConsoleControl { #if !UNIX @@ -481,7 +480,6 @@ internal static void SetConsoleMode(ProcessWindowStyle style) /// /// Types of control ConsoleBreakSignals received by break Win32Handler delegates. /// - internal enum ConsoleBreakSignal : uint { // These correspond to the CRTL_XXX_EVENT #defines in public/sdk/inc/wincon.h @@ -511,7 +509,6 @@ internal enum ConsoleBreakSignal : uint /// /// If Win32's SetConsoleCtrlHandler fails /// - internal static void AddBreakHandler(BreakHandler handlerDelegate) { bool result = NativeMethods.SetConsoleCtrlHandler(handlerDelegate, true); @@ -532,7 +529,6 @@ internal static void AddBreakHandler(BreakHandler handlerDelegate) /// /// If Win32's SetConsoleCtrlHandler fails /// - internal static void RemoveBreakHandler() { bool result = NativeMethods.SetConsoleCtrlHandler(null, false); @@ -657,7 +653,6 @@ internal enum ConsoleModes : uint /// /// If Win32's GetConsoleMode fails /// - internal static ConsoleModes GetMode(ConsoleHandle consoleHandle) { Dbg.Assert(!consoleHandle.IsInvalid, "consoleHandle is not valid"); @@ -690,7 +685,6 @@ internal static ConsoleModes GetMode(ConsoleHandle consoleHandle) /// /// If Win32's SetConsoleMode fails /// - internal static void SetMode(ConsoleHandle consoleHandle, ConsoleModes mode) { Dbg.Assert(!consoleHandle.IsInvalid, "consoleHandle is not valid"); @@ -740,7 +734,6 @@ internal static void SetMode(ConsoleHandle consoleHandle, ConsoleModes mode) /// /// If Win32's ReadConsole fails /// - internal static string ReadConsole( ConsoleHandle consoleHandle, int initialContentLength, @@ -813,7 +806,6 @@ internal static string ReadConsole( /// /// If Win32's ReadConsoleInput fails /// - internal static int ReadConsoleInput(ConsoleHandle consoleHandle, ref INPUT_RECORD[] buffer) { Dbg.Assert(!consoleHandle.IsInvalid, "ConsoleHandle is not valid"); @@ -853,7 +845,6 @@ internal static int ReadConsoleInput(ConsoleHandle consoleHandle, ref INPUT_RECO /// /// If Win32's PeekConsoleInput fails /// - internal static int PeekConsoleInput ( ConsoleHandle consoleHandle, @@ -895,7 +886,6 @@ ref INPUT_RECORD[] buffer /// /// If Win32's GetNumberOfConsoleInputEvents fails /// - internal static int GetNumberOfConsoleInputEvents(ConsoleHandle consoleHandle) { Dbg.Assert(!consoleHandle.IsInvalid, "ConsoleHandle is not valid"); @@ -989,7 +979,6 @@ internal static CONSOLE_SCREEN_BUFFER_INFO GetConsoleScreenBufferInfo(ConsoleHan /// /// If Win32's SetConsoleScreenBufferSize fails /// - internal static void SetConsoleScreenBufferSize(ConsoleHandle consoleHandle, Size newSize) { Dbg.Assert(!consoleHandle.IsInvalid, "ConsoleHandle is not valid"); @@ -1078,7 +1067,6 @@ internal static WORD ColorToWORD(ConsoleColor foreground, ConsoleColor backgroun /// /// If it is illegal to write to the output buffer /// - internal static void WriteConsoleOutput(ConsoleHandle consoleHandle, Coordinates origin, BufferCell[,] contents) { Dbg.Assert(!consoleHandle.IsInvalid, "ConsoleHandle is not valid"); @@ -1705,7 +1693,6 @@ private static void WriteConsoleOutputPlain(ConsoleHandle consoleHandle, Coordin /// /// If there is not enough memory to complete calls to Win32's ReadConsoleOutput /// - internal static void ReadConsoleOutput ( ConsoleHandle consoleHandle, @@ -2379,7 +2366,6 @@ Coordinates origin /// /// If Win32's ScrollConsoleScreenBuffer fails /// - internal static void ScrollConsoleScreenBuffer ( ConsoleHandle consoleHandle, @@ -2430,7 +2416,6 @@ internal static void ScrollConsoleScreenBuffer /// /// If Win32's SetConsoleWindowInfo fails /// - internal static void SetConsoleWindowInfo(ConsoleHandle consoleHandle, bool absolute, SMALL_RECT windowInfo) { Dbg.Assert(!consoleHandle.IsInvalid, "ConsoleHandle is not valid"); @@ -2460,7 +2445,6 @@ internal static void SetConsoleWindowInfo(ConsoleHandle consoleHandle, bool abso /// /// If Win32's GetLargestConsoleWindowSize fails /// - internal static Size GetLargestConsoleWindowSize(ConsoleHandle consoleHandle) { Dbg.Assert(!consoleHandle.IsInvalid, "ConsoleHandle is not valid"); @@ -2490,7 +2474,6 @@ internal static Size GetLargestConsoleWindowSize(ConsoleHandle consoleHandle) /// /// If Win32's GetConsoleTitle fails /// - internal static string GetConsoleWindowTitle() { const int MaxWindowTitleLength = 1024; @@ -2522,7 +2505,6 @@ internal static string GetConsoleWindowTitle() /// /// If Win32's SetConsoleTitle fails /// - internal static void SetConsoleWindowTitle(string consoleTitle) { bool result = NativeMethods.SetConsoleTitle(consoleTitle); @@ -2643,7 +2625,6 @@ private static void WriteConsole(ConsoleHandle consoleHandle, ReadOnlySpan /// /// if the Win32's SetConsoleTextAttribute fails /// - internal static void SetConsoleTextAttribute(ConsoleHandle consoleHandle, WORD attribute) { Dbg.Assert(!consoleHandle.IsInvalid, "ConsoleHandle is not valid"); @@ -2849,7 +2830,6 @@ internal static bool IsCJKOutputCodePage(out uint codePage) /// /// If Win32's SetConsoleCursorPosition fails /// - internal static void SetConsoleCursorPosition(ConsoleHandle consoleHandle, Coordinates cursorPosition) { Dbg.Assert(!consoleHandle.IsInvalid, "ConsoleHandle is not valid"); @@ -2884,7 +2864,6 @@ internal static void SetConsoleCursorPosition(ConsoleHandle consoleHandle, Coord /// /// If Win32's GetConsoleCursorInfo fails /// - internal static CONSOLE_CURSOR_INFO GetConsoleCursorInfo(ConsoleHandle consoleHandle) { Dbg.Assert(!consoleHandle.IsInvalid, "ConsoleHandle is not valid"); @@ -2939,7 +2918,6 @@ internal static CONSOLE_FONT_INFO_EX GetConsoleFontInfo(ConsoleHandle consoleHan /// /// If Win32's SetConsoleCursorInfo fails /// - internal static void SetConsoleCursorInfo(ConsoleHandle consoleHandle, CONSOLE_CURSOR_INFO cursorInfo) { Dbg.Assert(!consoleHandle.IsInvalid, "ConsoleHandle is not valid"); @@ -3002,7 +2980,6 @@ internal static void MimicKeyPress(INPUT[] inputs) /// /// Class to hold the Native Methods used in this file enclosing class. /// - internal static class NativeMethods { internal static readonly IntPtr INVALID_HANDLE_VALUE = new IntPtr(-1); // WinBase.h diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHost.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHost.cs index fb269cb57e1..5522f419300 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHost.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHost.cs @@ -401,7 +401,6 @@ private static bool BreakIntoDebugger() /// executing instance is stopped. /// /// - private static void SpinUpBreakHandlerThread(bool shouldEndSession) { ConsoleHost host = ConsoleHost.SingletonInstance; @@ -533,7 +532,6 @@ internal static ConsoleHost SingletonInstance /// /// /// - public override string Name { get @@ -550,7 +548,6 @@ public override string Name /// /// /// - public override System.Version Version { get @@ -565,7 +562,6 @@ public override System.Version Version /// /// /// - public override System.Guid InstanceId { get; } = Guid.NewGuid(); /// @@ -1621,7 +1617,6 @@ private bool LoadPSReadline() /// Opens and Initializes the Host's sole Runspace. Processes the startup scripts and runs any command passed on the /// command line. /// - private void DoCreateRunspace(string initialCommand, bool skipProfiles, bool staMode, string configurationName, Collection initialCommandArgs) { Dbg.Assert(_runspaceRef == null, "runspace should be null"); @@ -2009,7 +2004,6 @@ private void RunProfile(string profileFileName, Executor exec) /// /// /// - internal static string EscapeSingleQuotes(string str) { // worst case we have to escape every character, so capacity is twice as large as input length @@ -2347,7 +2341,6 @@ internal static void RunNewInputLoop(ConsoleHost parent, bool isNested) /// /// when there is no instanceStack.Count == 0 /// - internal static bool ExitCurrentLoop() { if (s_instanceStack.Count == 0) diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostRawUserInterface.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostRawUserInterface.cs index 91aceef2fbd..dbf1ec61587 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostRawUserInterface.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostRawUserInterface.cs @@ -22,7 +22,6 @@ namespace Microsoft.PowerShell /// /// Implementation of RawConsole for powershell. /// - internal sealed class ConsoleHostRawUserInterface : System.Management.Automation.Host.PSHostRawUserInterface { @@ -31,7 +30,6 @@ class ConsoleHostRawUserInterface : System.Management.Automation.Host.PSHostRawU /// /// If obtaining the buffer's foreground and background color failed /// - internal ConsoleHostRawUserInterface(ConsoleHostUserInterface mshConsole) : base() { @@ -78,7 +76,6 @@ class ConsoleHostRawUserInterface : System.Management.Automation.Host.PSHostRawU /// OR /// Win32's SetConsoleTextAttribute /// - public override ConsoleColor ForegroundColor @@ -129,7 +126,6 @@ public override /// OR /// Win32's SetConsoleTextAttribute /// - public override ConsoleColor BackgroundColor @@ -222,7 +218,6 @@ public override /// OR /// Win32's SetConsoleCursorInfo failed /// - public override int CursorSize @@ -278,7 +273,6 @@ public override /// OR /// Win32's SetConsoleWindowInfo failed /// - public override Coordinates WindowPosition @@ -345,7 +339,6 @@ public override /// OR /// Win32's SetConsoleScreenBufferSize failed /// - public override Size BufferSize @@ -398,7 +391,6 @@ public override /// OR /// Win32's SetConsoleWindowInfo failed /// - public override Size WindowSize @@ -519,7 +511,6 @@ public override /// /// If obtaining information about the buffer failed /// - public override Size MaxWindowSize @@ -543,7 +534,6 @@ public override /// OR /// Win32's GetLargestConsoleWindowSize failed /// - public override Size MaxPhysicalWindowSize @@ -602,7 +592,6 @@ private static void CacheKeyEvent(ConsoleControl.KEY_EVENT_RECORD input, ref Con /// OR /// Win32's ReadConsoleInput failed /// - public override KeyInfo ReadKey(ReadKeyOptions options) @@ -730,7 +719,6 @@ private static /// OR /// Win32's FlushConsoleInputBuffer failed /// - public override void FlushInputBuffer() @@ -752,7 +740,6 @@ public override /// OR /// Win32's PeekConsoleInput failed /// - public override bool KeyAvailable @@ -873,7 +860,6 @@ public override string WindowTitle /// OR /// there is not enough memory to complete calls to Win32's WriteConsoleOutput /// - public override void SetBufferContents(Coordinates origin, BufferCell[,] contents) @@ -1084,7 +1070,6 @@ public override /// OR /// there is not enough memory to complete calls to Win32's ReadConsoleOutput /// - public override BufferCell[,] GetBufferContents(Rectangle region) { @@ -1208,7 +1193,6 @@ BufferCell fill /// /// If Win32's WideCharToMultiByte fails /// - public override int LengthInBufferCells(string s) { @@ -1224,7 +1208,6 @@ int LengthInBufferCells(string s) /// /// If Win32's WideCharToMultiByte fails /// - public override int LengthInBufferCells(string s, int offset) { @@ -1244,7 +1227,6 @@ int LengthInBufferCells(string s, int offset) /// /// If Win32's WideCharToMultiByte fails /// - public override int LengthInBufferCells(char c) { diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterface.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterface.cs index de043bf36ec..b48af7eabbe 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterface.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterface.cs @@ -54,7 +54,6 @@ internal partial class ConsoleHostUserInterface : System.Management.Automation.H /// /// /// - internal ConsoleHostUserInterface(ConsoleHost parent) { Dbg.Assert(parent != null, "parent may not be null"); @@ -93,7 +92,6 @@ internal ConsoleHostUserInterface(ConsoleHost parent) /// /// /// - public override PSHostRawUserInterface RawUI { get @@ -131,7 +129,6 @@ public override PSHostRawUserInterface RawUI /// /// True if command completion is currently running. /// - internal bool IsCommandCompletionRunning { get @@ -144,13 +141,11 @@ internal bool IsCommandCompletionRunning /// /// True if the Read* functions should read from the stdin stream instead of from the win32 console. /// - internal bool ReadFromStdin { get; set; } /// /// True if the host shouldn't write out prompts. /// - internal bool NoPrompt { get; set; } #region Line-oriented interaction @@ -168,7 +163,6 @@ internal bool IsCommandCompletionRunning /// OR /// Win32's SetConsoleCursorPosition failed /// - public override string ReadLine() { HandleThrowOnReadAndPrompt(); @@ -193,7 +187,6 @@ public override string ReadLine() /// /// If Ctrl-C is entered by user /// - public override SecureString ReadLineAsSecureString() { HandleThrowOnReadAndPrompt(); @@ -245,7 +238,6 @@ public override SecureString ReadLineAsSecureString() /// /// If Ctrl-C is entered by user /// - private object ReadLineSafe(bool isSecureString, char? printToken) { // Don't lock (instanceLock) in here -- the caller needs to do that... @@ -439,7 +431,6 @@ private object ReadLineSafe(bool isSecureString, char? printToken) /// OR /// Win32's SetConsoleCursorPosition failed /// - private void WritePrintToken( string printToken, ref Coordinates originalCursorPosition) @@ -476,7 +467,6 @@ private void WritePrintToken( /// OR /// Win32's SetConsoleCursorPosition failed /// - private void WriteBackSpace(Coordinates originalCursorPosition) { Coordinates cursorPosition = _rawui.CursorPosition; @@ -678,7 +668,6 @@ private void WriteLineToConsole() /// OR /// Win32's WriteConsole fails /// - public override void Write(string value) { WriteImpl(value, newLine: false); @@ -749,7 +738,6 @@ private void WriteImpl(string value, bool newLine) /// OR /// Win32's WriteConsole fails /// - public override void Write(ConsoleColor foregroundColor, ConsoleColor backgroundColor, string value) { Write(foregroundColor, backgroundColor, value, newLine: false); @@ -861,7 +849,6 @@ public override void WriteLine() /// A list of strings representing the text broken into "lines" each of which are guaranteed not to exceed /// maxWidthInBufferCells. /// - internal List WrapText(string text, int maxWidthInBufferCells) { List result = new List(); @@ -953,7 +940,6 @@ internal List WrapText(string text, int maxWidthInBufferCells) /// /// Struct used by WrapText. /// - [Flags] internal enum WordFlags { @@ -988,7 +974,6 @@ internal struct Word /// This can be made faster by, instead of creating little strings for each word, creating indices of the start and end /// range of a word. That would reduce the string allocations. /// - internal List ChopTextIntoWords(string text, int maxWidthInBufferCells) { List result = new List(); @@ -1096,7 +1081,6 @@ internal List ChopTextIntoWords(string text, int maxWidthInBufferCells) /// /// The list into which the words will be added. /// - internal void AddWord(string text, int startIndex, int endIndex, int maxWidthInBufferCells, bool isWhitespace, ref List result) { @@ -1235,7 +1219,6 @@ public override void WriteInformation(InformationRecord record) /// OR /// Win32's WriteConsole fails /// - public override void WriteVerboseLine(string message) { // don't lock here as WriteLine is already protected. @@ -1273,7 +1256,6 @@ public override void WriteVerboseLine(string message) /// OR /// Win32's WriteConsole fails /// - public override void WriteWarningLine(string message) { // don't lock here as WriteLine is already protected. @@ -1297,7 +1279,6 @@ public override void WriteWarningLine(string message) /// /// Invoked by CommandBase.WriteProgress to display a progress record. /// - public override void WriteProgress(Int64 sourceId, ProgressRecord record) { if (record == null) @@ -1436,7 +1417,6 @@ internal enum ReadLineResult /// OR /// Win32's SetConsoleCursorPosition failed /// - internal string ReadLine(bool endOnTab, string initialContent, out ReadLineResult result, bool calledFromPipeline, bool transcribeResult) { result = ReadLineResult.endedOnEnter; diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterfaceProgress.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterfaceProgress.cs index ffc5735f35f..75954bddca8 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterfaceProgress.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterfaceProgress.cs @@ -16,7 +16,6 @@ class ConsoleHostUserInterface : System.Management.Automation.Host.PSHostUserInt /// Called at the end of a prompt loop to take down any progress display that might have appeared and purge any /// outstanding progress activity state. /// - internal void ResetProgress() @@ -55,7 +54,6 @@ class ConsoleHostUserInterface : System.Management.Automation.Host.PSHostUserInt /// Invoked by ConsoleHostUserInterface.WriteProgress to update the set of outstanding activities for which /// ProgressRecords have been received. /// - private void HandleIncomingProgressRecord(Int64 sourceId, ProgressRecord record) @@ -101,7 +99,6 @@ class ConsoleHostUserInterface : System.Management.Automation.Host.PSHostUserInt /// /// TimerCallback for '_progPaneUpdateTimer' to update 'progPaneUpdateFlag' /// - private void ProgressPaneUpdateTimerElapsed(object sender) diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterfacePrompt.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterfacePrompt.cs index 0afe5f987d8..cd7c7c90e67 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterfacePrompt.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterfacePrompt.cs @@ -87,7 +87,6 @@ private static /// If the converting the user input to the prompt field type fails unless it is caused by /// OverflowException or FormatException /// - public override Dictionary Prompt(string caption, string message, Collection descriptions) @@ -475,7 +474,6 @@ private PromptCommonInputErrors PromptTryConvertTo(Type fieldType, bool isFromRe /// /// /// - private string PromptCommandMode(string input, FieldDescription desc, out bool inputDone) { Dbg.Assert(input != null && input.StartsWith(PromptCommandPrefix, StringComparison.OrdinalIgnoreCase), diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterfacePromptForChoice.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterfacePromptForChoice.cs index 0dfe3f63739..b22845c2d56 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterfacePromptForChoice.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterfacePromptForChoice.cs @@ -39,7 +39,6 @@ internal partial class ConsoleHostUserInterface : PSHostUserInterface, IHostUISu /// /// when prompt is canceled by, for example, Ctrl-c. /// - public override int PromptForChoice(string caption, string message, Collection choices, int defaultChoice) { HandleThrowOnReadAndPrompt(); diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterfaceSecurity.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterfaceSecurity.cs index 6926f685795..7f34c789fc7 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterfaceSecurity.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterfaceSecurity.cs @@ -29,7 +29,6 @@ class ConsoleHostUserInterface : System.Management.Automation.Host.PSHostUserInt /// Message to be displayed. /// Caption for the message. /// PSCredential object. - public override PSCredential PromptForCredential( string caption, string message, @@ -54,7 +53,6 @@ public override PSCredential PromptForCredential( /// What type of creds can be supplied by the user. /// Options that control the cred gathering UI behavior. /// PSCredential object, or null if input was cancelled (or if reading from stdin and stdin at EOF). - public override PSCredential PromptForCredential( string caption, string message, diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleShell.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleShell.cs index ce03133c0f6..11dd276a52d 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleShell.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleShell.cs @@ -12,7 +12,6 @@ namespace Microsoft.PowerShell /// This class provides an entry point which is called by minishell's main /// to transfer control to Msh console host implementation. /// - public static class ConsoleShell { /// Entry point in to ConsoleShell. This method is called by main of minishell. diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/Executor.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/Executor.cs index 24b48837005..e5b3ba9f41d 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/Executor.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/Executor.cs @@ -24,7 +24,6 @@ namespace Microsoft.PowerShell /// The class' instance methods manage a single pipeline. The class' static methods track the outstanding instances to /// ensure that only one instance is 'active' (and therefore cancellable) at a time. /// - internal class Executor { [Flags] @@ -527,7 +526,6 @@ internal string ExecuteCommandAndGetResultAsString(string command, out Exception /// The Nullable`bool representation of the first result object returned, or null if an exception was thrown or no /// objects were returned by the command. /// - internal bool? ExecuteCommandAndGetResultAsBool(string command) { Exception unused = null; diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/PendingProgress.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/PendingProgress.cs index 2ca795447d0..153f99b1b20 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/PendingProgress.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/PendingProgress.cs @@ -24,7 +24,6 @@ namespace Microsoft.PowerShell /// This class uses lots of nearly identical helper functions to recursively traverse the tree. If I weren't so pressed /// for time, I would see if generic methods could be used to collapse the number of traversers. /// - internal class PendingProgress { @@ -42,7 +41,6 @@ class PendingProgress /// The ProgressRecord received that will either update the status of an activity which we are already tracking, or /// represent a new activity that we need to track. /// - internal void Update(Int64 sourceId, ProgressRecord record) @@ -179,7 +177,6 @@ class PendingProgress /// /// Index into the list of the node to be removed. /// - private void RemoveNode(ArrayList nodes, int indexToRemove) @@ -255,7 +252,6 @@ class PendingProgress /// /// Node to be added. /// - private void AddNode(ArrayList nodes, ProgressNode nodeToAdd) @@ -356,7 +352,6 @@ internal override /// /// Convenience overload. /// - private ProgressNode FindNodeById(Int64 sourceId, int activityId) @@ -427,7 +422,6 @@ internal override /// /// The found node, or null if no suitable node was located. /// - private ProgressNode FindNodeById(Int64 sourceId, int activityId, out ArrayList listWhereFound, out int indexWhereFound) @@ -465,7 +459,6 @@ internal override /// /// The found node, or null if no suitable node was located. /// - private ProgressNode FindOldestNodeOfGivenStyle(ArrayList nodes, int oldestSoFar, ProgressNode.RenderStyle style) @@ -530,7 +523,6 @@ internal override /// /// All nodes are aged every time a new ProgressRecord is received. /// - private void AgeNodesAndResetStyle() @@ -561,7 +553,6 @@ internal override /// /// An array of strings containing the textual representation of the outstanding progress activities. /// - internal string[] Render(int maxWidth, int maxHeight, PSHostRawUserInterface rawUI) @@ -631,7 +622,6 @@ internal override /// /// The PSHostRawUserInterface used to gauge string widths in the rendering. /// - private void RenderHelper(ArrayList strings, ArrayList nodes, int indentation, int maxWidth, PSHostRawUserInterface rawUI) @@ -708,7 +698,6 @@ internal override /// /// /// - private int TallyHeight(PSHostRawUserInterface rawUi, int maxHeight, int maxWidth) { HeightTallyer ht = new HeightTallyer(rawUi, maxHeight, maxWidth); @@ -724,7 +713,6 @@ private int TallyHeight(PSHostRawUserInterface rawUi, int maxHeight, int maxWidt /// /// /// - private bool AllNodesHaveGivenStyle(ArrayList nodes, ProgressNode.RenderStyle style) @@ -759,7 +747,6 @@ private int TallyHeight(PSHostRawUserInterface rawUi, int maxHeight, int maxWidt /// /// Debugging code. NodeVisitor that counts up the number of nodes in the tree. /// - private class CountingNodeVisitor : NodeVisitor @@ -783,7 +770,6 @@ internal override /// /// The number of nodes in the tree. /// - private int CountNodes() @@ -823,7 +809,6 @@ internal override /// false to indicate that all of the nodes are compressed to a given level, but that the rendering still can't fit /// within the constraint. /// - private bool CompressToFitHelper( @@ -894,7 +879,6 @@ internal override /// The number of nodes that were made invisible during the compression. /// /// - private int CompressToFit(PSHostRawUserInterface rawUi, int maxHeight, int maxWidth) @@ -983,7 +967,6 @@ class NodeVisitor /// /// true to continue visiting nodes, false if not. /// - internal abstract bool Visit(ProgressNode node, ArrayList listWhereFound, int indexWhereFound); diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ProgressNode.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ProgressNode.cs index 35066c0bf09..92fc1316240 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ProgressNode.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ProgressNode.cs @@ -15,7 +15,6 @@ namespace Microsoft.PowerShell /// ProgressNode is an augmentation of the ProgressRecord type that adds extra fields for the purposes of tracking /// outstanding activities received by the host, and rendering them in the console. /// - internal class ProgressNode : ProgressRecord @@ -23,7 +22,6 @@ namespace Microsoft.PowerShell /// /// Indicates the various layouts for rendering a particular node. Each style is progressively less terse. /// - internal enum RenderStyle @@ -47,7 +45,6 @@ namespace Microsoft.PowerShell /// /// Constructs an instance from a ProgressRecord. /// - internal ProgressNode(Int64 sourceId, ProgressRecord record) : @@ -80,7 +77,6 @@ namespace Microsoft.PowerShell /// /// The PSHostRawUserInterface used to gauge string widths in the rendering. /// - internal void Render(ArrayList strCollection, int indentation, int maxWidth, PSHostRawUserInterface rawUI) @@ -130,7 +126,6 @@ namespace Microsoft.PowerShell /// /// Indicate if the full StatusDescription and CurrentOperation should be displayed. /// - private void RenderFull(ArrayList strCollection, int indentation, int maxWidth, PSHostRawUserInterface rawUI, bool isFullPlus) @@ -240,7 +235,6 @@ private static void RenderFullDescription(string description, string indent, int /// /// The PSHostRawUserInterface used to gauge string widths in the rendering. /// - private void RenderCompact(ArrayList strCollection, int indentation, int maxWidth, PSHostRawUserInterface rawUI) @@ -309,7 +303,6 @@ private static void RenderFullDescription(string description, string indent, int /// /// The PSHostRawUserInterface used to gauge string widths in the rendering. /// - private void RenderMinimal(ArrayList strCollection, int indentation, int maxWidth, PSHostRawUserInterface rawUI) @@ -347,7 +340,6 @@ private static void RenderFullDescription(string description, string indent, int /// /// The nodes that have this node as their parent. /// - internal ArrayList Children; @@ -362,7 +354,6 @@ private static void RenderFullDescription(string description, string indent, int /// space. The rendering of nodes can be progressively "compressed" into a more terse format, or not rendered at all in /// order to fit as many nodes as possible in the available space. The oldest nodes are compressed or skipped first. /// - internal int Age; @@ -370,7 +361,6 @@ private static void RenderFullDescription(string description, string indent, int /// /// The style in which this node should be rendered. /// - internal RenderStyle Style = RenderStyle.FullPlus; @@ -378,7 +368,6 @@ private static void RenderFullDescription(string description, string indent, int /// /// Identifies the source of the progress record. /// - internal Int64 SourceId; @@ -387,7 +376,6 @@ private static void RenderFullDescription(string description, string indent, int /// The number of vertical BufferCells that are required to render the node in its current style. /// /// - internal int LinesRequiredMethod(PSHostRawUserInterface rawUi, int maxWidth) { Dbg.Assert(this.RecordType != ProgressRecordType.Completed, "should never render completed records"); @@ -421,7 +409,6 @@ internal int LinesRequiredMethod(PSHostRawUserInterface rawUi, int maxWidth) /// The number of vertical BufferCells that are required to render the node in the Full style. /// /// - private int LinesRequiredInFullStyleMethod(PSHostRawUserInterface rawUi, int maxWidth, bool isFullPlus) { // Since the fields of this instance could have been changed, we compute this on-the-fly. @@ -479,7 +466,6 @@ private int LinesRequiredInFullStyleMethod(PSHostRawUserInterface rawUi, int max /// The number of vertical BufferCells that are required to render the node in the Compact style. /// /// - private int LinesRequiredInCompactStyle diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ProgressPane.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ProgressPane.cs index 55dba38d6b4..f65beebd542 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ProgressPane.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ProgressPane.cs @@ -13,7 +13,6 @@ namespace Microsoft.PowerShell /// progress updates are shown. /// /// - internal class ProgressPane { @@ -23,7 +22,6 @@ class ProgressPane /// /// An implementation of the PSHostRawUserInterface with which the pane will be shown and hidden. /// - internal ProgressPane(ConsoleHostUserInterface ui) { @@ -39,7 +37,6 @@ class ProgressPane /// true if the pane is visible, false if not. /// /// - internal bool IsShowing @@ -54,7 +51,6 @@ class ProgressPane /// Shows the pane in the screen buffer. Saves off the content of the region of the buffer that will be overwritten so /// that it can be restored again. /// - internal void Show() @@ -140,7 +136,6 @@ class ProgressPane /// Hides the pane by restoring the saved contents of the region of the buffer that the pane occupies. If the pane is /// not showing, then does nothing. /// - internal void Hide() @@ -164,7 +159,6 @@ class ProgressPane /// /// A PendingProgress instance that represents the outstanding activities that should be shown. /// - internal void Show(PendingProgress pendingProgress) diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/Serialization.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/Serialization.cs index 696b95ca049..5340a3950d7 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/Serialization.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/Serialization.cs @@ -14,26 +14,22 @@ namespace Microsoft.PowerShell /// Wraps Hitesh's xml serializer in such a way that it will select the proper serializer based on the data /// format. /// - internal class Serialization { /// /// Describes the format of the data streamed between minishells, e.g. the allowed arguments to the minishell /// -outputformat and -inputformat command line parameters. /// - internal enum DataFormat { /// /// Text format -- i.e. stream text just as out-default would display it. /// - Text = 0, /// /// XML-serialized format. /// - XML = 1, /// diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/StartTranscriptCmdlet.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/StartTranscriptCmdlet.cs index 1587f91d3f9..3f413df76ef 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/StartTranscriptCmdlet.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/StartTranscriptCmdlet.cs @@ -12,7 +12,6 @@ namespace Microsoft.PowerShell.Commands /// /// Implements the start-transcript cmdlet. /// - [Cmdlet(VerbsLifecycle.Start, "Transcript", SupportsShouldProcess = true, DefaultParameterSetName = "ByPath", HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2096485")] [OutputType(typeof(string))] public sealed class StartTranscriptCommand : PSCmdlet @@ -23,7 +22,6 @@ public sealed class StartTranscriptCommand : PSCmdlet /// Documents/PowerShell_transcript.YYYYMMDDmmss.txt. /// /// - [Parameter(Position = 0, ParameterSetName = "ByPath")] [ValidateNotNullOrEmpty] public string Path @@ -77,7 +75,6 @@ public string OutputDirectory /// Describes the current state of the activity. /// /// - [Parameter] public SwitchParameter Append { @@ -99,7 +96,6 @@ public SwitchParameter Append /// /// The read-only attribute will not be replaced when the transcript is done. /// - [Parameter()] public SwitchParameter Force { diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/StopTranscriptCmdlet.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/StopTranscriptCmdlet.cs index 9fae35ac83e..48b392f98e7 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/StopTranscriptCmdlet.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/StopTranscriptCmdlet.cs @@ -10,7 +10,6 @@ namespace Microsoft.PowerShell.Commands /// /// Implements the stop-transcript cmdlet. /// - [Cmdlet(VerbsLifecycle.Stop, "Transcript", HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2096798")] [OutputType(typeof(string))] public sealed class StopTranscriptCommand : PSCmdlet @@ -18,7 +17,6 @@ public sealed class StopTranscriptCommand : PSCmdlet /// /// Starts the transcription. /// - protected override void BeginProcessing() diff --git a/src/Microsoft.PowerShell.Security/security/CertificateProvider.cs b/src/Microsoft.PowerShell.Security/security/CertificateProvider.cs index d0a589bb1cb..ff66e7c9932 100644 --- a/src/Microsoft.PowerShell.Security/security/CertificateProvider.cs +++ b/src/Microsoft.PowerShell.Security/security/CertificateProvider.cs @@ -469,7 +469,6 @@ public void FreeCert(IntPtr certContext) /// /// Native IntPtr store handle. /// - public IntPtr StoreHandle { get @@ -503,7 +502,6 @@ public string StoreName /// /// True if a real store is open. /// - public bool Valid { get @@ -701,7 +699,6 @@ public CertificateProvider() /// path is null or empty. /// destination is null or empty. /// - protected override void RemoveItem( string path, bool recurse) @@ -808,7 +805,6 @@ protected override object RemoveItemDynamicParameters(string path, bool recurse) /// path is null or empty. /// destination is null or empty. /// - protected override void MoveItem( string path, string destination) @@ -1620,7 +1616,6 @@ private static string[] GetPathElements(string path) /// /// Key prov info. /// No return. - [SuppressMessage("Microsoft.Usage", "CA1806:DoNotIgnoreMethodResults", MessageId = "System.Management.Automation.Security.NativeMethods.NCryptSetProperty(System.IntPtr,System.String,System.Void*,System.Int32,System.Int32)")] [SuppressMessage("Microsoft.Usage", "CA1806:DoNotIgnoreMethodResults", MessageId = "System.Management.Automation.Security.NativeMethods.NCryptFreeObject(System.IntPtr)")] private void DoDeleteKey(IntPtr pProvInfo) @@ -1749,7 +1744,6 @@ private void DoDeleteKey(IntPtr pProvInfo) /// Boolean to specify whether or not to delete private key. /// Source path. /// No return. - private void RemoveCertStore(string storeName, bool fDeleteKey, string sourcePath) { // if recurse is true, remove every cert in the store @@ -1847,7 +1841,6 @@ private void RemoveCertItem(X509Certificate2 cert, bool fDeleteKey, bool fMachin /// Machine context or user. /// Source path. /// No return. - [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1806:DoNotIgnoreMethodResults")] private void DoRemove(X509Certificate2 cert, bool fDeleteKey, bool fMachine, string sourcePath) { @@ -3085,7 +3078,6 @@ public struct EnhancedKeyUsageRepresentation /// /// Constructor of an EnhancedKeyUsageRepresentation. /// - [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Oid")] public EnhancedKeyUsageRepresentation(string inputFriendlyName, string inputOid) @@ -3154,14 +3146,12 @@ public override string ToString() /// /// Class for SendAsTrustedIssuer. /// - [SuppressMessage("Microsoft.Design", "CA1053:StaticHolderTypesShouldNotHaveConstructors")] public sealed class SendAsTrustedIssuerProperty { /// /// Get property of SendAsTrustedIssuer. /// - [SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")] public static bool ReadSendAsTrustedIssuerProperty(X509Certificate2 cert) { @@ -3197,7 +3187,6 @@ public static bool ReadSendAsTrustedIssuerProperty(X509Certificate2 cert) /// /// Set property of SendAsTrustedIssuer. /// - [SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")] public static void WriteSendAsTrustedIssuerProperty(X509Certificate2 cert, string certPath, bool addProperty) { @@ -3311,7 +3300,6 @@ private static string[] GetPathElements(string path) /// /// Class for ekulist. /// - public sealed class EnhancedKeyUsageProperty { private List _ekuList = new List(); @@ -3355,7 +3343,6 @@ public EnhancedKeyUsageProperty(X509Certificate2 cert) /// /// Class for DNSNameList. /// - public sealed class DnsNameProperty { private List _dnsList = new List(); diff --git a/src/Microsoft.WSMan.Management/CredSSP.cs b/src/Microsoft.WSMan.Management/CredSSP.cs index 52c4f4e921d..f81e6447ce7 100644 --- a/src/Microsoft.WSMan.Management/CredSSP.cs +++ b/src/Microsoft.WSMan.Management/CredSSP.cs @@ -97,7 +97,6 @@ internal IWSManSession CreateWSManSession() /// the server, hence allowing the user to perform management operations that /// access a second hop. /// - [Cmdlet(VerbsLifecycle.Disable, "WSManCredSSP", HelpUri = "https://go.microsoft.com/fwlink/?LinkId=2096628")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Cred")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "SSP")] diff --git a/src/Microsoft.WSMan.Management/Interop.cs b/src/Microsoft.WSMan.Management/Interop.cs index 7df5d16fc93..6e813ef17e1 100644 --- a/src/Microsoft.WSMan.Management/Interop.cs +++ b/src/Microsoft.WSMan.Management/Interop.cs @@ -23,7 +23,6 @@ namespace Microsoft.WSMan.Management #region WsManEnumFlags /// _WSManEnumFlags enumeration. - [SuppressMessage("Microsoft.Design", "CA1027:MarkEnumsWithFlags")] [TypeLibType((short)0)] public enum WSManEnumFlags @@ -926,7 +925,6 @@ public interface IWSManSession /// /// /// - [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "URI")] [SuppressMessage("Microsoft.Design", "CA1054:UriParametersShouldNotBeStrings", MessageId = "0#")] [DispId(5)] diff --git a/src/Microsoft.WSMan.Management/InvokeWSManAction.cs b/src/Microsoft.WSMan.Management/InvokeWSManAction.cs index 71f8ae4c84d..7c217b0ea9a 100644 --- a/src/Microsoft.WSMan.Management/InvokeWSManAction.cs +++ b/src/Microsoft.WSMan.Management/InvokeWSManAction.cs @@ -23,7 +23,6 @@ namespace Microsoft.WSMan.Management /// Invoke-WSManAction -Action StartService -ResourceURI wmicimv2/Win32_Service /// -SelectorSet {Name=Spooler} /// - [Cmdlet(VerbsLifecycle.Invoke, "WSManAction", DefaultParameterSetName = "URI", HelpUri = "https://go.microsoft.com/fwlink/?LinkId=2096843")] public class InvokeWSManActionCommand : AuthenticatingWSManCommand, IDisposable { diff --git a/src/Microsoft.WSMan.Management/NewWSManSession.cs b/src/Microsoft.WSMan.Management/NewWSManSession.cs index b2d6719e7e9..2bb367aeecc 100644 --- a/src/Microsoft.WSMan.Management/NewWSManSession.cs +++ b/src/Microsoft.WSMan.Management/NewWSManSession.cs @@ -25,7 +25,6 @@ namespace Microsoft.WSMan.Management /// Invoke-WSManAction /// Connect-WSMan. /// - [Cmdlet(VerbsCommon.New, "WSManSessionOption", HelpUri = "https://go.microsoft.com/fwlink/?LinkId=2096845")] public class NewWSManSessionOptionCommand : PSCmdlet { diff --git a/src/Microsoft.WSMan.Management/PingWSMan.cs b/src/Microsoft.WSMan.Management/PingWSMan.cs index 9581eaabc33..47ca6ef738b 100644 --- a/src/Microsoft.WSMan.Management/PingWSMan.cs +++ b/src/Microsoft.WSMan.Management/PingWSMan.cs @@ -22,7 +22,6 @@ namespace Microsoft.WSMan.Management /// Issues an operation against the remote machine to ensure that the wsman /// service is running. /// - [Cmdlet(VerbsDiagnostic.Test, "WSMan", HelpUri = "https://go.microsoft.com/fwlink/?LinkId=2097114")] public class TestWSManCommand : AuthenticatingWSManCommand, IDisposable { diff --git a/src/Microsoft.WSMan.Management/WSManConnections.cs b/src/Microsoft.WSMan.Management/WSManConnections.cs index 4aeb283b81f..6d6c5f6bc0e 100644 --- a/src/Microsoft.WSMan.Management/WSManConnections.cs +++ b/src/Microsoft.WSMan.Management/WSManConnections.cs @@ -288,7 +288,6 @@ protected override void BeginProcessing() /// is the local computer. Type the fully qualified domain name, NETBIOS name or /// IP address to indicate the remote host(s) /// - [Cmdlet(VerbsCommunications.Disconnect, "WSMan", HelpUri = "https://go.microsoft.com/fwlink/?LinkId=2096839")] public class DisconnectWSManCommand : PSCmdlet, IDisposable { diff --git a/src/Microsoft.WSMan.Management/WSManInstance.cs b/src/Microsoft.WSMan.Management/WSManInstance.cs index 5a3d6b74f7f..ca299f1c085 100644 --- a/src/Microsoft.WSMan.Management/WSManInstance.cs +++ b/src/Microsoft.WSMan.Management/WSManInstance.cs @@ -28,7 +28,6 @@ namespace Microsoft.WSMan.Management /// Invoke-WSManAction -Action StartService -ResourceURI wmicimv2/Win32_Service /// -SelectorSet {Name=Spooler} /// - [Cmdlet(VerbsCommon.Get, "WSManInstance", DefaultParameterSetName = "GetInstance", HelpUri = "https://go.microsoft.com/fwlink/?LinkId=2096627")] public class GetWSManInstanceCommand : AuthenticatingWSManCommand, IDisposable { @@ -102,7 +101,6 @@ public string ComputerName /// remote machine. The format of this string is: /// transport://server:port/Prefix. /// - [Parameter( ParameterSetName = "GetInstance")] [Parameter( @@ -143,7 +141,6 @@ public Uri Dialect /// Switch indicates list all instances of a management resource. Equivalent to /// WSManagement Enumerate. /// - [Parameter(Mandatory = true, ParameterSetName = "Enumerate")] public SwitchParameter Enumerate @@ -181,7 +178,6 @@ public string Filter /// Specifies a section inside the instance that is to be updated or retrieved /// for the given operation. /// - [Parameter(ParameterSetName = "GetInstance")] [ValidateNotNullOrEmpty] public string Fragment @@ -242,7 +238,6 @@ public Int32 Port /// associated instances. This can only be used when specifying the Dialect as /// Association. /// - [Parameter(ParameterSetName = "Enumerate")] public SwitchParameter Associations { @@ -754,7 +749,6 @@ public string Fragment /// request. These are similar to switches used in command line shells in that /// they are service-specific. /// - [Parameter] [SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] [Alias("os")] @@ -788,7 +782,6 @@ public Int32 Port /// The following is the definition of the input parameter "ResourceURI". /// URI of the resource class/instance representation. /// - [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "URI")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Resourceuri")] @@ -1077,7 +1070,6 @@ public Uri ConnectionURI /// request. These are similar to switches used in command line shells in that /// they are service-specific. /// - [Parameter] [SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] [Alias("os")] @@ -1111,7 +1103,6 @@ public Int32 Port /// The following is the definition of the input parameter "ResourceURI". /// URI of the resource class/instance representation. /// - [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "URI")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Resourceuri")] @@ -1275,7 +1266,6 @@ protected override void ProcessRecord() /// Creates an instance of a management resource identified by the resource URI /// using specified ValueSet or input File. /// - [Cmdlet(VerbsCommon.New, "WSManInstance", DefaultParameterSetName = "ComputerName", HelpUri = "https://go.microsoft.com/fwlink/?LinkId=2096933")] public class NewWSManInstanceCommand : AuthenticatingWSManCommand, IDisposable { diff --git a/src/Microsoft.WSMan.Runtime/WSManSessionOption.cs b/src/Microsoft.WSMan.Runtime/WSManSessionOption.cs index 014cc03c8ec..d8681a54618 100644 --- a/src/Microsoft.WSMan.Runtime/WSManSessionOption.cs +++ b/src/Microsoft.WSMan.Runtime/WSManSessionOption.cs @@ -23,7 +23,6 @@ namespace Microsoft.WSMan.Management /// /// Session option class. /// - public sealed class SessionOption { /// diff --git a/src/System.Management.Automation/engine/ComInterop/ComMethodDesc.cs b/src/System.Management.Automation/engine/ComInterop/ComMethodDesc.cs index 1f16d9c90ef..35b4c9fa25d 100644 --- a/src/System.Management.Automation/engine/ComInterop/ComMethodDesc.cs +++ b/src/System.Management.Automation/engine/ComInterop/ComMethodDesc.cs @@ -31,7 +31,6 @@ internal ComMethodDesc(string name, int dispId, INVOKEKIND invkind) internal ComMethodDesc(ITypeInfo typeInfo, FUNCDESC funcDesc) : this(funcDesc.memid) { - InvokeKind = funcDesc.invkind; string[] rgNames = new string[1 + funcDesc.cParams]; diff --git a/src/System.Management.Automation/engine/ComInterop/ComTypeDesc.cs b/src/System.Management.Automation/engine/ComInterop/ComTypeDesc.cs index 85af47ca9d6..92e9ea8ed6f 100644 --- a/src/System.Management.Automation/engine/ComInterop/ComTypeDesc.cs +++ b/src/System.Management.Automation/engine/ComInterop/ComTypeDesc.cs @@ -25,7 +25,6 @@ internal ComTypeDesc(ITypeInfo typeInfo, ComTypeLibDesc typeLibDesc) TypeLib = typeLibDesc; } - internal static ComTypeDesc FromITypeInfo(ITypeInfo typeInfo, TYPEATTR typeAttr) { switch (typeAttr.typekind) diff --git a/src/System.Management.Automation/engine/ComInterop/IDispatchComObject.cs b/src/System.Management.Automation/engine/ComInterop/IDispatchComObject.cs index aa297ecb487..bf4c3f021f0 100644 --- a/src/System.Management.Automation/engine/ComInterop/IDispatchComObject.cs +++ b/src/System.Management.Automation/engine/ComInterop/IDispatchComObject.cs @@ -73,7 +73,6 @@ namespace System.Management.Automation.ComInterop /// just find and invoke the multicast delegate corresponding to the invoked /// dispid. /// - internal sealed class IDispatchComObject : ComObject, IDynamicMetaObjectProvider { private ComTypeDesc _comTypeDesc; diff --git a/src/System.Management.Automation/engine/ComInterop/UnknownArgBuilder.cs b/src/System.Management.Automation/engine/ComInterop/UnknownArgBuilder.cs index f7aa95df6e9..cf97a976a80 100644 --- a/src/System.Management.Automation/engine/ComInterop/UnknownArgBuilder.cs +++ b/src/System.Management.Automation/engine/ComInterop/UnknownArgBuilder.cs @@ -48,7 +48,6 @@ internal override Expression MarshalToRef(Expression parameter) ); } - internal override Expression UnmarshalFromRef(Expression value) { // value == IntPtr.Zero ? null : Marshal.GetObjectForIUnknown(value); diff --git a/src/System.Management.Automation/engine/ComInterop/VarEnumSelector.cs b/src/System.Management.Automation/engine/ComInterop/VarEnumSelector.cs index c7d3f139ae9..9c5ea9e9900 100644 --- a/src/System.Management.Automation/engine/ComInterop/VarEnumSelector.cs +++ b/src/System.Management.Automation/engine/ComInterop/VarEnumSelector.cs @@ -245,7 +245,6 @@ private static void CheckForAmbiguousMatch(Type argumentType, List comp typeNames += typeName; } - throw Error.AmbiguousConversion(argumentType.Name, typeNames); } diff --git a/src/System.Management.Automation/engine/CommandBase.cs b/src/System.Management.Automation/engine/CommandBase.cs index 720a93ab85d..b2019ec90dd 100644 --- a/src/System.Management.Automation/engine/CommandBase.cs +++ b/src/System.Management.Automation/engine/CommandBase.cs @@ -543,7 +543,6 @@ public object GetVariableValue(string name) } /// - public object GetVariableValue(string name, object defaultValue) { using (PSTransactionManager.GetEngineProtectionScope()) diff --git a/src/System.Management.Automation/engine/InformationRecord.cs b/src/System.Management.Automation/engine/InformationRecord.cs index 81a9789bb81..b9513e30d87 100644 --- a/src/System.Management.Automation/engine/InformationRecord.cs +++ b/src/System.Management.Automation/engine/InformationRecord.cs @@ -14,7 +14,6 @@ namespace System.Management.Automation /// which, according to host or user preference, forwards that information on to the host for rendering to the user. /// /// - [DataContract()] public class InformationRecord { diff --git a/src/System.Management.Automation/engine/ProgressRecord.cs b/src/System.Management.Automation/engine/ProgressRecord.cs index f040e24e416..346290f189f 100644 --- a/src/System.Management.Automation/engine/ProgressRecord.cs +++ b/src/System.Management.Automation/engine/ProgressRecord.cs @@ -15,7 +15,6 @@ namespace System.Management.Automation /// which, according to user preference, forwards that information on to the host for rendering to the user. /// /// - [DataContract()] public class ProgressRecord @@ -35,7 +34,6 @@ class ProgressRecord /// /// A description of the status of the activity. /// - public ProgressRecord(int activityId, string activity, string statusDescription) { @@ -81,7 +79,6 @@ internal ProgressRecord(ProgressRecord other) /// Gets the Id of the activity to which this record corresponds. Used as a 'key' for the /// linking of subordinate activities. /// - public int ActivityId @@ -107,7 +104,6 @@ internal ProgressRecord(ProgressRecord other) /// shell so that a script can set that variable, and have all subsequent calls to WriteProgress (the API) be /// subordinate to the "current parent id".--> /// - public int ParentActivityId @@ -135,7 +131,6 @@ internal ProgressRecord(ProgressRecord other) /// States the overall intent of whats being accomplished, such as "Recursively removing item c:\temp." Typically /// displayed in conjunction with a progress bar. /// - public string Activity @@ -159,7 +154,6 @@ internal ProgressRecord(ProgressRecord other) /// /// Gets and sets the current status of the operation, e.g., "35 of 50 items Copied." or "95% completed." or "100 files purged." /// - public string StatusDescription @@ -185,7 +179,6 @@ internal ProgressRecord(ProgressRecord other) /// below its associated progress bar, e.g., "deleting file foo.bar" /// Set to null or empty in the case a sub-activity will be used to show the current operation. /// - public string CurrentOperation @@ -207,7 +200,6 @@ internal ProgressRecord(ProgressRecord other) /// Gets and sets the estimate of the percentage of total work for the activity that is completed. Typically displayed as a progress bar. /// Set to a negative value to indicate that the percentage completed should not be displayed. /// - public int PercentComplete @@ -241,7 +233,6 @@ internal ProgressRecord(ProgressRecord other) /// /// A value less than 0 means "don't display a time remaining." /// - public int SecondsRemaining @@ -262,7 +253,6 @@ internal ProgressRecord(ProgressRecord other) /// /// Gets and sets the type of record represented by this instance. /// - public ProgressRecordType RecordType @@ -291,7 +281,6 @@ internal ProgressRecord(ProgressRecord other) /// a, b, c, d, e, f, and g are the values of ParentActivityId, ActivityId, Activity, StatusDescription, /// CurrentOperation, PercentComplete, SecondsRemaining and RecordType properties. /// - public override string ToString() @@ -520,7 +509,6 @@ internal PSObject ToPSObjectForRemoting() /// /// Defines two types of progress record that refer to the beginning (or middle) and end of an operation. /// - public enum ProgressRecordType { @@ -539,7 +527,6 @@ enum ProgressRecordType /// Finally, when the host receives a 'completed' record /// for that activity, it will remove the progress indicator. /// - Processing, /// @@ -550,7 +537,6 @@ enum ProgressRecordType /// ProgressRecordType.Completed exactly once, in the last call /// to WriteProgress. /// - Completed } } diff --git a/src/System.Management.Automation/engine/ScopedItemSearcher.cs b/src/System.Management.Automation/engine/ScopedItemSearcher.cs index 4d5f2f1107f..a68b93694b9 100644 --- a/src/System.Management.Automation/engine/ScopedItemSearcher.cs +++ b/src/System.Management.Automation/engine/ScopedItemSearcher.cs @@ -111,7 +111,6 @@ public bool MoveNext() /// /// Gets the current scoped item. /// - T IEnumerator.Current { get diff --git a/src/System.Management.Automation/engine/SessionState.cs b/src/System.Management.Automation/engine/SessionState.cs index f011a87a2aa..64e06a81744 100644 --- a/src/System.Management.Automation/engine/SessionState.cs +++ b/src/System.Management.Automation/engine/SessionState.cs @@ -18,7 +18,6 @@ namespace System.Management.Automation /// /// Holds the state of a Monad Shell session. /// - [SuppressMessage("Microsoft.Maintainability", "CA1506:AvoidExcessiveClassCoupling", Justification = "This is a bridge class between internal classes and a public interface. It requires this much coupling.")] internal sealed partial class SessionStateInternal { diff --git a/src/System.Management.Automation/engine/SessionStateScope.cs b/src/System.Management.Automation/engine/SessionStateScope.cs index 54b7a40e1f2..6fd1749ba30 100644 --- a/src/System.Management.Automation/engine/SessionStateScope.cs +++ b/src/System.Management.Automation/engine/SessionStateScope.cs @@ -1852,7 +1852,6 @@ private Dictionary GetAllScopeFunctions() /// table. The entries in this table are automatically propagated /// to new scopes. /// - private readonly Dictionary> _allScopeCmdlets = new Dictionary>(StringComparer.OrdinalIgnoreCase); /// diff --git a/src/System.Management.Automation/engine/hostifaces/ChoiceDescription.cs b/src/System.Management.Automation/engine/hostifaces/ChoiceDescription.cs index 9fca84d4a33..94c47816c0d 100644 --- a/src/System.Management.Automation/engine/hostifaces/ChoiceDescription.cs +++ b/src/System.Management.Automation/engine/hostifaces/ChoiceDescription.cs @@ -9,7 +9,6 @@ namespace System.Management.Automation.Host /// Provides a description of a choice for use by . /// /// - public sealed class ChoiceDescription { @@ -29,7 +28,6 @@ class ChoiceDescription /// /// is null or empty. /// - public ChoiceDescription(string label) { @@ -59,7 +57,6 @@ class ChoiceDescription /// /// is null. /// - public ChoiceDescription(string label, string helpMessage) { @@ -92,7 +89,6 @@ class ChoiceDescription /// /// For examples, a choice named "Yes to All" might have "Yes to &All" as it's label. /// - public string Label @@ -115,7 +111,6 @@ class ChoiceDescription /// This should be a few sentences to describe the field, suitable for presentation as a tool tip. /// Avoid placing including formatting characters such as newline and tab. /// - public string HelpMessage diff --git a/src/System.Management.Automation/engine/hostifaces/DefaultHost.cs b/src/System.Management.Automation/engine/hostifaces/DefaultHost.cs index 1542ab865f7..e49bafd28da 100644 --- a/src/System.Management.Automation/engine/hostifaces/DefaultHost.cs +++ b/src/System.Management.Automation/engine/hostifaces/DefaultHost.cs @@ -14,7 +14,6 @@ namespace Microsoft.PowerShell /// This is the default host implementing PSHost offering minimal host capabilities. /// Runspace is the primary user of this class. /// - internal class DefaultHost : PSHost { #region ctor @@ -25,7 +24,6 @@ internal class DefaultHost : PSHost /// Current culture for this host. /// Current UI culture for this host. /// - internal DefaultHost(CultureInfo currentCulture, CultureInfo currentUICulture) { CurrentCulture = currentCulture; @@ -70,7 +68,6 @@ internal DefaultHost(CultureInfo currentCulture, CultureInfo currentUICulture) /// /// /// - public override void SetShouldExit(int exitCode) @@ -85,7 +82,6 @@ public override /// /// On calling this method /// - public override void EnterNestedPrompt() @@ -112,7 +108,6 @@ public override /// /// /// - public override void NotifyBeginApplication() @@ -125,7 +120,6 @@ public override /// /// /// - public override void NotifyEndApplication() diff --git a/src/System.Management.Automation/engine/hostifaces/FieldDescription.cs b/src/System.Management.Automation/engine/hostifaces/FieldDescription.cs index 545440a1574..0af791ed829 100644 --- a/src/System.Management.Automation/engine/hostifaces/FieldDescription.cs +++ b/src/System.Management.Automation/engine/hostifaces/FieldDescription.cs @@ -22,7 +22,6 @@ namespace System.Management.Automation.Host /// It is permitted to subclass /// but there is no established scenario for doing this, nor has it been tested. /// - public class FieldDescription { @@ -35,7 +34,6 @@ public class /// /// is null or empty. /// - public FieldDescription(string name) { @@ -69,7 +67,6 @@ public string Name /// /// If is null. /// - public void SetParameterType(System.Type parameterType) @@ -96,7 +93,6 @@ public string Name /// /// - public string ParameterTypeName @@ -123,7 +119,6 @@ public string Name /// /// - public string ParameterTypeFullName @@ -151,7 +146,6 @@ public string Name /// If not already set by a call to , /// will be used as the type. /// - public string ParameterAssemblyFullName @@ -189,7 +183,6 @@ public string Name /// /// If no label is set, then the empty string is returned. /// - public string Label @@ -222,7 +215,6 @@ public string Name /// This should be a few sentences to describe the field, suitable for presentation as a tool tip. /// Avoid placing including formatting characters such as newline and tab. /// - public string HelpMessage @@ -248,7 +240,6 @@ public string Name /// /// Gets and sets whether a value must be supplied for this field. /// - public bool IsMandatory @@ -274,7 +265,6 @@ public string Name /// can make use of the object in its presentation of the fields prompt. /// /// - public PSObject DefaultValue @@ -297,7 +287,6 @@ public string Name /// is being called from the MSH engine, this will contain the set of prompting attributes that are attached to a /// cmdlet parameter declaration. /// - public Collection Attributes @@ -312,7 +301,6 @@ public string Name /// /// If is null. /// - internal void SetParameterTypeName(string nameOfType) @@ -332,7 +320,6 @@ public string Name /// /// If is null. /// - internal void SetParameterTypeFullName(string fullNameOfType) @@ -352,7 +339,6 @@ public string Name /// /// If is null. /// - internal void SetParameterAssemblyFullName(string fullNameOfAssembly) diff --git a/src/System.Management.Automation/engine/hostifaces/History.cs b/src/System.Management.Automation/engine/hostifaces/History.cs index a88692a91e7..278f15aceee 100644 --- a/src/System.Management.Automation/engine/hostifaces/History.cs +++ b/src/System.Management.Automation/engine/hostifaces/History.cs @@ -109,7 +109,6 @@ public override string ToString() /// /// Cleared status of an entry. /// - internal bool Cleared { get; set; } = false; /// @@ -167,7 +166,6 @@ internal class History /// /// Constructs history store. /// - internal History(ExecutionContext context) { // Create history size variable. Add ValidateRangeAttribute to @@ -586,7 +584,6 @@ internal void ClearEntry(long id) /// gets the total number of entries added /// ///count of total entries added. - internal int Buffercapacity() { return _capacity; @@ -1586,7 +1583,6 @@ private static /// /// This Class implements the Clear History cmdlet /// - [Cmdlet(VerbsCommon.Clear, "History", SupportsShouldProcess = true, DefaultParameterSetName = "IDParameter", HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2096691")] public class ClearHistoryCommand : PSCmdlet { @@ -1616,13 +1612,11 @@ public int[] Id /// /// Id of a history entry. /// - private int[] _id; /// /// Command line name of an entry in the session history. /// - [Parameter(ParameterSetName = "CommandLineParameter", HelpMessage = "Specifies the name of a command in the session history")] [ValidateNotNullOrEmpty()] [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] @@ -1642,7 +1636,6 @@ public string[] CommandLine /// /// Commandline parameter. /// - private string[] _commandline = null; /// @@ -1677,7 +1670,6 @@ public int Count /// /// Specifies whether new entries to be cleared or the default old ones. /// - [Parameter(Mandatory = false, HelpMessage = "Specifies whether new entries to be cleared or the default old ones.")] public SwitchParameter Newest { @@ -1695,7 +1687,6 @@ public SwitchParameter Newest /// /// Switch parameter on the history entries. /// - private SwitchParameter _newest; #endregion Command Line Parameters @@ -1703,7 +1694,6 @@ public SwitchParameter Newest /// /// Overriding Begin Processing. /// - protected override void BeginProcessing() { _history = ((LocalRunspace)Context.CurrentRunspace).History; @@ -1712,7 +1702,6 @@ protected override void BeginProcessing() /// /// Overriding Process Record. /// - protected override void ProcessRecord() { // case statement to identify the parameter set @@ -1915,7 +1904,6 @@ private void ClearHistoryByCmdLine() /// Order of the entries. /// Nothing. /// - private void ClearHistoryEntries(long id, int count, string cmdline, SwitchParameter newest) { // if cmdline is null,use default parameter set notion. diff --git a/src/System.Management.Automation/engine/hostifaces/InternalHostRawUserInterface.cs b/src/System.Management.Automation/engine/hostifaces/InternalHostRawUserInterface.cs index d182ef6302a..156d6d58dc8 100644 --- a/src/System.Management.Automation/engine/hostifaces/InternalHostRawUserInterface.cs +++ b/src/System.Management.Automation/engine/hostifaces/InternalHostRawUserInterface.cs @@ -78,7 +78,6 @@ public override /// if the RawUI property of the external host is null, possibly because the PSHostRawUserInterface is not /// implemented by the external host /// - public override ConsoleColor BackgroundColor @@ -114,7 +113,6 @@ public override /// if the RawUI property of the external host is null, possibly because the PSHostRawUserInterface is not /// implemented by the external host /// - public override Coordinates CursorPosition @@ -150,7 +148,6 @@ public override /// if the RawUI property of the external host is null, possibly because the PSHostRawUserInterface is not /// implemented by the external host /// - public override Coordinates WindowPosition @@ -186,7 +183,6 @@ public override /// if the RawUI property of the external host is null, possibly because the PSHostRawUserInterface is not /// implemented by the external host /// - public override int CursorSize @@ -222,7 +218,6 @@ public override /// if the RawUI property of the external host is null, possibly because the PSHostRawUserInterface is not /// implemented by the external host /// - public override Size BufferSize @@ -258,7 +253,6 @@ public override /// if the RawUI property of the external host is null, possibly because the PSHostRawUserInterface is not /// implemented by the external host /// - public override Size WindowSize @@ -294,7 +288,6 @@ public override /// if the RawUI property of the external host is null, possibly because the PSHostRawUserInterface is not /// implemented by the external host /// - public override Size MaxWindowSize @@ -320,7 +313,6 @@ public override /// if the RawUI property of the external host is null, possibly because the PSHostRawUserInterface is not /// implemented by the external host /// - public override Size MaxPhysicalWindowSize @@ -348,7 +340,6 @@ public override /// if the RawUI property of the external host is null, possibly because the PSHostRawUserInterface is not /// implemented by the external host /// - public override KeyInfo ReadKey(ReadKeyOptions options) @@ -386,7 +377,6 @@ public override /// if the RawUI property of the external host is null, possibly because the PSHostRawUserInterface is not /// implemented by the external host /// - public override void FlushInputBuffer() @@ -407,7 +397,6 @@ public override /// if the RawUI property of the external host is null, possibly because the PSHostRawUserInterface is not /// implemented by the external host /// - public override bool KeyAvailable @@ -433,7 +422,6 @@ public override /// if the RawUI property of the external host is null, possibly because the PSHostRawUserInterface is not /// implemented by the external host /// - public override string WindowTitle @@ -495,7 +483,6 @@ public override /// if the RawUI property of the external host is null, possibly because the PSHostRawUserInterface is not /// implemented by the external host /// - public override void SetBufferContents(Rectangle r, BufferCell fill) @@ -517,7 +504,6 @@ public override /// if the RawUI property of the external host is null, possibly because the PSHostRawUserInterface is not /// implemented by the external host /// - public override BufferCell[,] GetBufferContents(Rectangle r) @@ -545,7 +531,6 @@ public override /// if the RawUI property of the external host is null, possibly because the PSHostRawUserInterface is not /// implemented by the external host /// - public override void ScrollBufferContents diff --git a/src/System.Management.Automation/engine/hostifaces/InternalHostUserInterface.cs b/src/System.Management.Automation/engine/hostifaces/InternalHostUserInterface.cs index 8432b4432d0..8aa5956e8a8 100644 --- a/src/System.Management.Automation/engine/hostifaces/InternalHostUserInterface.cs +++ b/src/System.Management.Automation/engine/hostifaces/InternalHostUserInterface.cs @@ -67,7 +67,6 @@ class InternalHostUserInterface : PSHostUserInterface, IHostUISupportsMultipleCh /// /// /// - public override System.Management.Automation.Host.PSHostRawUserInterface RawUI @@ -127,7 +126,6 @@ public override /// if the UI property of the external host is null, possibly because the PSHostUserInterface is not /// implemented by the external host. /// - public override SecureString ReadLineAsSecureString() @@ -168,7 +166,6 @@ public override /// if is not null and the UI property of the external host is null, /// possibly because the PSHostUserInterface is not implemented by the external host /// - public override void Write(string value) @@ -199,7 +196,6 @@ public override /// if is not null and the UI property of the external host is null, /// possibly because the PSHostUserInterface is not implemented by the external host /// - public override void Write(ConsoleColor foregroundColor, ConsoleColor backgroundColor, string value) @@ -226,7 +222,6 @@ public override /// if the UI property of the external host is null, possibly because the PSHostUserInterface is not /// implemented by the external host /// - public override void WriteLine() @@ -248,7 +243,6 @@ public override /// if is not null and the UI property of the external host is null, /// possibly because the PSHostUserInterface is not implemented by the external host /// - public override void WriteLine(string value) @@ -296,7 +290,6 @@ public override /// if is not null and the UI property of the external host is null, /// possibly because the PSHostUserInterface is not implemented by the external host /// - public override void WriteLine(ConsoleColor foregroundColor, ConsoleColor backgroundColor, string value) @@ -321,7 +314,6 @@ public override /// if is not null and the UI property of the external host is null, /// possibly because the PSHostUserInterface is not implemented by the external host /// - public override void WriteDebugLine(string message) @@ -369,7 +361,6 @@ internal void WriteDebugInfoBuffers(DebugRecord record) /// /// If the debug preference is not a valid ActionPreference value. /// - internal void WriteDebugLine(string message, ref ActionPreference preference) @@ -469,7 +460,6 @@ internal PSInformationalBuffers GetInformationalMessageBuffers() /// Preference setting which determines the behaviour. This is by-ref and will be modified based upon what the user /// types. (e.g. YesToAll will change Inquire => NotifyContinue) /// - private bool DebugShouldContinue(string message, ref ActionPreference actionPreference) @@ -539,7 +529,6 @@ internal PSInformationalBuffers GetInformationalMessageBuffers() /// if is not null and the UI property of the external host is null, /// possibly because the PSHostUserInterface is not implemented by the external host /// - public override void WriteProgress(Int64 sourceId, ProgressRecord record) @@ -570,7 +559,6 @@ public override /// if is not null and the UI property of the external host is null, /// possibly because the PSHostUserInterface is not implemented by the external host /// - public override void WriteVerboseLine(string message) @@ -616,7 +604,6 @@ internal void WriteVerboseInfoBuffers(VerboseRecord record) /// if is not null and the UI property of the external host is null, /// possibly because the PSHostUserInterface is not implemented by the external host /// - public override void WriteWarningLine(string message) { if (message == null) @@ -725,7 +712,6 @@ internal static bool IsSecuritySensitiveType(string typeName) /// if the UI property of the external host is null, /// possibly because the PSHostUserInterface is not implemented by the external host /// - public override Dictionary Prompt(string caption, string message, Collection descriptions) @@ -779,7 +765,6 @@ public override /// if the UI property of the external host is null, /// possibly because the PSHostUserInterface is not implemented by the external host /// - public override int PromptForChoice(string caption, string message, Collection choices, int defaultChoice) diff --git a/src/System.Management.Automation/engine/hostifaces/MshHost.cs b/src/System.Management.Automation/engine/hostifaces/MshHost.cs index 0c5ef87436f..64d8f1170f2 100644 --- a/src/System.Management.Automation/engine/hostifaces/MshHost.cs +++ b/src/System.Management.Automation/engine/hostifaces/MshHost.cs @@ -34,7 +34,6 @@ namespace System.Management.Automation.Host /// /// /// - public abstract class PSHost { /// @@ -47,7 +46,6 @@ public abstract class PSHost /// /// Protected constructor which does nothing. Provided per .Net design guidelines section 4.3.1. /// - protected PSHost() { // do nothing @@ -70,7 +68,6 @@ protected PSHost() /// if ($Host.Name -ieq "ConsoleHost") { write-host "I'm running in the Console Host" } /// /// - public abstract string Name { get; @@ -87,7 +84,6 @@ public abstract string Name /// /// The version number of the hosting application. /// - public abstract System.Version Version { get; @@ -97,7 +93,6 @@ public abstract System.Version Version /// Gets a GUID that uniquely identifies this instance of the host. The value should remain invariant for the lifetime of /// this instance. /// - public abstract System.Guid InstanceId { get; @@ -118,7 +113,6 @@ public abstract System.Guid InstanceId /// implementation of PSHostUserInterface for this application. As an alternative, /// for simple scenarios, just returning null is sufficient. /// - public abstract System.Management.Automation.Host.PSHostUserInterface UI { get; @@ -134,7 +128,6 @@ public abstract System.Management.Automation.Host.PSHostUserInterface UI /// The runspace will set the thread current culture to this value each time it starts a pipeline. Thus, cmdlets are /// encouraged to use Thread.CurrentThread.CurrentCulture. /// - public abstract System.Globalization.CultureInfo CurrentCulture { get; @@ -148,7 +141,6 @@ public abstract System.Globalization.CultureInfo CurrentCulture /// /// A CultureInfo object representing the host's current UI culture. Returning null is not allowed. /// - public abstract System.Globalization.CultureInfo CurrentUICulture { get; @@ -167,7 +159,6 @@ public abstract System.Globalization.CultureInfo CurrentUICulture /// The exit code accompanying the exit keyword. Typically, after exiting a runspace, a host will also terminate. The /// exitCode parameter can be used to set the host's process exit code. /// - public abstract void SetShouldExit(int exitCode); /// @@ -188,7 +179,6 @@ public abstract System.Globalization.CultureInfo CurrentUICulture /// evaluates other commands. It does not create a truly new engine instance with new session state.--> /// /// - public abstract void EnterNestedPrompt(); /// @@ -204,7 +194,6 @@ public abstract System.Globalization.CultureInfo CurrentUICulture /// If the UI Property returns a null, the engine should not call this method. /// /// - public abstract void ExitNestedPrompt(); /// @@ -230,7 +219,6 @@ public abstract System.Globalization.CultureInfo CurrentUICulture /// change will not be visible to the host if the host is in another process. Therefore, the implementation of /// get for this property should always return a unique instance. /// - public virtual PSObject PrivateData { get @@ -270,14 +258,12 @@ public virtual PSObject PrivateData /// NotifyBeginApplication. /// /// - public abstract void NotifyBeginApplication(); /// /// Called by the engine to notify the host that the execution of a legacy command has completed. /// /// - public abstract void NotifyEndApplication(); /// diff --git a/src/System.Management.Automation/engine/hostifaces/MshHostRawUserInterface.cs b/src/System.Management.Automation/engine/hostifaces/MshHostRawUserInterface.cs index 79f4bcff66a..f4c3aedfb69 100644 --- a/src/System.Management.Automation/engine/hostifaces/MshHostRawUserInterface.cs +++ b/src/System.Management.Automation/engine/hostifaces/MshHostRawUserInterface.cs @@ -15,7 +15,6 @@ namespace System.Management.Automation.Host /// /// Represents an (x,y) coordinate pair. /// - public struct Coordinates { @@ -68,7 +67,6 @@ public int Y /// /// "a,b" where a and b are the values of the X and Y properties. /// - public override string ToString() @@ -86,7 +84,6 @@ public override /// True if is Coordinates and its X and Y values are the same as those of this instance, /// false if not. /// - public override bool Equals(object obj) @@ -107,7 +104,6 @@ public override /// /// Hash code for this instance. /// - public override int GetHashCode() @@ -173,7 +169,6 @@ public override /// /// true if the respective X and Y values are the same, false otherwise. /// - public static bool operator ==(Coordinates first, Coordinates second) @@ -195,7 +190,6 @@ public static /// /// true if any of the respective either X or Y field is not the same, false otherwise. /// - public static bool operator !=(Coordinates first, Coordinates second) @@ -207,7 +201,6 @@ public static /// /// Represents a width and height pair. /// - public struct Size { @@ -260,7 +253,6 @@ public int Height /// /// "a,b" where a and b are the values of the Width and Height properties. /// - public override string ToString() @@ -278,7 +270,6 @@ public override /// True if is Size and its Width and Height values are the same as those of this instance, /// false if not. /// - public override bool Equals(object obj) @@ -302,7 +293,6 @@ public override /// consider Width the high-order part of a 64-bit in, and /// Height the lower order half. Then use the int64.GetHashCode.--> /// - public override int GetHashCode() @@ -368,7 +358,6 @@ public override /// /// true if the respective Width and Height fields are the same, false otherwise. /// - public static bool operator ==(Size first, Size second) @@ -390,7 +379,6 @@ public static /// /// true if any of the respective Width and Height fields are not the same, false otherwise. /// - public static bool operator !=(Size first, Size second) @@ -403,7 +391,6 @@ public static /// Governs the behavior of /// and /// - [Flags] public enum @@ -412,32 +399,27 @@ public static /// /// Allow Ctrl-C to be processed as a keystroke, as opposed to causing a break event. /// - AllowCtrlC = 0x0001, /// /// Do not display the character for the key in the window when pressed. /// - NoEcho = 0x0002, /// /// Include key down events. Either one of IncludeKeyDown and IncludeKeyUp or both must be specified. /// - IncludeKeyDown = 0x0004, /// /// Include key up events. Either one of IncludeKeyDown and IncludeKeyUp or both must be specified. /// - IncludeKeyUp = 0x0008 } /// /// Defines the states of Control Key. /// - [Flags] public enum ControlKeyStates @@ -445,62 +427,52 @@ enum ControlKeyStates /// /// The right alt key is pressed. /// - RightAltPressed = 0x0001, /// /// The left alt key is pressed. /// - LeftAltPressed = 0x0002, /// /// The right ctrl key is pressed. /// - RightCtrlPressed = 0x0004, /// /// The left ctrl key is pressed. /// - LeftCtrlPressed = 0x0008, /// /// The shift key is pressed. /// - ShiftPressed = 0x0010, /// /// The numlock light is on. /// - NumLockOn = 0x0020, /// /// The scrolllock light is on. /// - ScrollLockOn = 0x0040, /// /// The capslock light is on. /// - CapsLockOn = 0x0080, /// /// The key is enhanced. /// - EnhancedKey = 0x0100 } /// /// Represents information of a keystroke. /// - public struct KeyInfo { @@ -516,7 +488,6 @@ struct KeyInfo /// /// Gets and set device-independent key. /// - public int VirtualKeyCode { get { return virtualKeyCode; } @@ -527,7 +498,6 @@ public int VirtualKeyCode /// /// Gets and set unicode Character of the key. /// - public char Character { get { return character; } @@ -538,7 +508,6 @@ public char Character /// /// State of the control keys. /// - public ControlKeyStates ControlKeyState { get { return controlKeyState; } @@ -549,7 +518,6 @@ public ControlKeyStates ControlKeyState /// /// Gets and set the status of whether this instance is generated by a key pressed or released. /// - public bool KeyDown { get { return keyDown; } @@ -573,7 +541,6 @@ public bool KeyDown /// /// Whether the key is pressed or released /// - public KeyInfo ( @@ -595,7 +562,6 @@ bool keyDown /// /// "a,b,c,d" where a, b, c, and d are the values of the VirtualKeyCode, Character, ControlKeyState, and KeyDown properties. /// - public override string ToString() @@ -612,7 +578,6 @@ public override /// True if is KeyInfo and its VirtualKeyCode, Character, ControlKeyState, and KeyDown values are the /// same as those of this instance, false if not. /// - public override bool Equals(object obj) @@ -637,7 +602,6 @@ public override /// VirtualKeyCode the lower-order nibbles of a 32-bit int, /// Then use the UInt32.GetHashCode.--> /// - public override int GetHashCode() @@ -672,7 +636,6 @@ public override /// are the same, false otherwise. /// /// - public static bool operator ==(KeyInfo first, KeyInfo second) @@ -697,7 +660,6 @@ public static /// are the different, false otherwise. /// /// - public static bool operator !=(KeyInfo first, KeyInfo second) @@ -711,7 +673,6 @@ public static /// /// - public struct Rectangle { @@ -727,7 +688,6 @@ struct Rectangle /// /// Gets and sets the left side of the rectangle. /// - public int Left { get { return left; } @@ -738,7 +698,6 @@ public int Left /// /// Gets and sets the top of the rectangle. /// - public int Top { get { return top; } @@ -749,7 +708,6 @@ public int Top /// /// Gets and sets the right side of the rectangle. /// - public int Right { get { return right; } @@ -760,7 +718,6 @@ public int Right /// /// Gets and sets the bottom of the rectangle. /// - public int Bottom { get { return bottom; } @@ -787,7 +744,6 @@ public int Bottom /// is less than ; /// is less than /// - public Rectangle(int left, int top, int right, int bottom) { @@ -824,7 +780,6 @@ public int Bottom /// The Coordinates of the lower right corner of the Rectangle /// /// - public Rectangle(Coordinates upperLeft, Coordinates lowerRight) : this(upperLeft.X, upperLeft.Y, lowerRight.X, lowerRight.Y) @@ -837,7 +792,6 @@ public int Bottom /// /// "a,b ; c,d" where a, b, c, and d are values of the Left, Top, Right, and Bottom properties. /// - public override string ToString() @@ -855,7 +809,6 @@ public override /// True if is Rectangle and its Left, Top, Right, and Bottom values are the same as those of this instance, /// false if not. /// - public override bool Equals(object obj) @@ -879,7 +832,6 @@ public override /// (Left XOR Right) the lower order half. Then use the int64.GetHashCode.--> /// /// - public override int GetHashCode() @@ -948,7 +900,6 @@ public override /// /// true if the respective Top, Left, Bottom, and Right fields are the same, false otherwise. /// - public static bool operator ==(Rectangle first, Rectangle second) @@ -972,7 +923,6 @@ public static /// true if any of the respective Top, Left, Bottom, and Right fields are not the same, false otherwise. /// /// - public static bool operator !=(Rectangle first, Rectangle second) @@ -984,7 +934,6 @@ public static /// /// Represents a character, a foregroundColor color, and background color. /// - public struct BufferCell { @@ -1000,7 +949,6 @@ struct BufferCell /// /// Gets and sets the character value. /// - public char Character { get { return character; } @@ -1014,7 +962,6 @@ public char Character /// /// Gets and sets the foreground color. /// - public ConsoleColor ForegroundColor { get { return foregroundColor; } @@ -1025,7 +972,6 @@ public ConsoleColor ForegroundColor /// /// Gets and sets the background color. /// - public ConsoleColor BackgroundColor { get { return backgroundColor; } @@ -1036,7 +982,6 @@ public ConsoleColor BackgroundColor /// /// Gets and sets the type value. /// - public BufferCellType BufferCellType { get { return bufferCellType; } @@ -1060,7 +1005,6 @@ public BufferCellType BufferCellType /// /// The type of this BufferCell object /// - public BufferCell(char character, ConsoleColor foreground, ConsoleColor background, BufferCellType bufferCellType) { @@ -1076,7 +1020,6 @@ public BufferCellType BufferCellType /// /// "'a' b c d" where a, b, c, and d are the values of the Character, ForegroundColor, BackgroundColor, and Type properties. /// - public override string ToString() @@ -1094,7 +1037,6 @@ public override /// True if is BufferCell and its Character, ForegroundColor, BackgroundColor, and BufferCellType values /// are the same as those of this instance, false if not. /// - public override bool Equals(object obj) @@ -1118,7 +1060,6 @@ public override /// Hash code for this instance. /// /// - public override int GetHashCode() @@ -1148,7 +1089,6 @@ public override /// /// true if the respective Character, ForegroundColor, BackgroundColor, and BufferCellType values are the same, false otherwise. /// - public static bool operator ==(BufferCell first, BufferCell second) @@ -1174,7 +1114,6 @@ public static /// true if any of the respective Character, ForegroundColor, BackgroundColor, and BufferCellType values are not the same, /// false otherwise. /// - public static bool operator !=(BufferCell first, BufferCell second) @@ -1189,26 +1128,22 @@ public static /// Defines three types of BufferCells to accommodate for hosts that use up to two cells /// to display a character in some languages such as Chinese and Japanese. /// - public enum BufferCellType { /// /// Character occupies one BufferCell. /// - Complete, /// /// Character occupies two BufferCells and this is the leading one. /// - Leading, /// /// Preceded by a Leading BufferCell. /// - Trailing } @@ -1227,14 +1162,12 @@ public enum /// /// /// - public abstract class PSHostRawUserInterface { /// /// Protected constructor which does nothing. Provided per .Net design guidelines section 4.3.1. /// - protected PSHostRawUserInterface() { @@ -1250,7 +1183,6 @@ class PSHostRawUserInterface /// other properties that take structs (e.g. -Position, -Size), I anticipate that the more common use-case for color /// is to just change the foreground color.--> /// - public abstract ConsoleColor ForegroundColor @@ -1264,7 +1196,6 @@ public abstract /// the screen buffer can have a separate background color. /// /// - public abstract ConsoleColor BackgroundColor @@ -1288,7 +1219,6 @@ public abstract /// /// /// - public abstract Coordinates CursorPosition @@ -1305,7 +1235,6 @@ public abstract /// /// /// - public abstract Coordinates WindowPosition @@ -1318,7 +1247,6 @@ public abstract /// Gets or sets the cursor size as a percentage 0..100. /// /// - public abstract int CursorSize @@ -1335,7 +1263,6 @@ public abstract /// /// /// - public abstract Size BufferSize @@ -1353,7 +1280,6 @@ public abstract /// /// /// - public abstract Size WindowSize @@ -1378,7 +1304,6 @@ public abstract /// /// /// - public abstract Size MaxWindowSize @@ -1400,7 +1325,6 @@ public abstract /// /// /// - public abstract Size MaxPhysicalWindowSize @@ -1424,7 +1348,6 @@ public abstract /// /// /// - public KeyInfo ReadKey() @@ -1457,7 +1380,6 @@ public abstract /// /// /// - public abstract KeyInfo ReadKey(ReadKeyOptions options); @@ -1468,7 +1390,6 @@ public abstract /// /// /// - public abstract void FlushInputBuffer(); @@ -1482,7 +1403,6 @@ public abstract /// /// /// - public abstract bool KeyAvailable @@ -1493,7 +1413,6 @@ public abstract /// /// Gets or sets the titlebar text of the current view window. /// - public abstract string WindowTitle @@ -1521,7 +1440,6 @@ public abstract /// /// /// - public abstract void SetBufferContents(Coordinates origin, BufferCell[,] contents); @@ -1566,7 +1484,6 @@ public abstract /// /// /// - public abstract void SetBufferContents(Rectangle rectangle, BufferCell fill); @@ -1605,7 +1522,6 @@ public abstract /// /// /// - public abstract BufferCell[,] GetBufferContents(Rectangle rectangle); @@ -1636,7 +1552,6 @@ public abstract /// /// /// - public abstract void ScrollBufferContents @@ -1670,7 +1585,6 @@ BufferCell fill /// /// /// - public virtual int LengthInBufferCells @@ -1710,7 +1624,6 @@ int offset /// /// /// - public virtual int LengthInBufferCells @@ -1743,7 +1656,6 @@ string source /// /// /// - public virtual int LengthInBufferCells @@ -1912,7 +1824,6 @@ char source /// /// /// - public BufferCell[,] NewBufferCellArray(int width, int height, BufferCell contents) @@ -1994,7 +1905,6 @@ char source /// /// /// - public BufferCell[,] NewBufferCellArray(Size size, BufferCell contents) diff --git a/src/System.Management.Automation/engine/hostifaces/MshHostUserInterface.cs b/src/System.Management.Automation/engine/hostifaces/MshHostUserInterface.cs index d30a1f4089b..f40a8350a1e 100644 --- a/src/System.Management.Automation/engine/hostifaces/MshHostUserInterface.cs +++ b/src/System.Management.Automation/engine/hostifaces/MshHostUserInterface.cs @@ -23,7 +23,6 @@ namespace System.Management.Automation.Host /// /// /// - public abstract class PSHostUserInterface { /// diff --git a/src/System.Management.Automation/engine/hostifaces/RunspaceInit.cs b/src/System.Management.Automation/engine/hostifaces/RunspaceInit.cs index 04dc65baac2..34244c3db83 100644 --- a/src/System.Management.Automation/engine/hostifaces/RunspaceInit.cs +++ b/src/System.Management.Automation/engine/hostifaces/RunspaceInit.cs @@ -9,7 +9,6 @@ namespace System.Management.Automation.Runspaces /// /// Runspace class for local runspace. /// - internal sealed partial class LocalRunspace : RunspaceBase { diff --git a/src/System.Management.Automation/engine/hostifaces/internalHostuserInterfacesecurity.cs b/src/System.Management.Automation/engine/hostifaces/internalHostuserInterfacesecurity.cs index f5155fd7c13..0aeb89197f1 100644 --- a/src/System.Management.Automation/engine/hostifaces/internalHostuserInterfacesecurity.cs +++ b/src/System.Management.Automation/engine/hostifaces/internalHostuserInterfacesecurity.cs @@ -14,7 +14,6 @@ class InternalHostUserInterface : PSHostUserInterface /// /// See base class. /// - public override PSCredential PromptForCredential @@ -34,7 +33,6 @@ string targetName /// /// See base class. /// - public override PSCredential PromptForCredential diff --git a/src/System.Management.Automation/engine/remoting/client/Job.cs b/src/System.Management.Automation/engine/remoting/client/Job.cs index 6db4da1670c..775886e18c6 100644 --- a/src/System.Management.Automation/engine/remoting/client/Job.cs +++ b/src/System.Management.Automation/engine/remoting/client/Job.cs @@ -2316,7 +2316,6 @@ internal bool HideComputerName /// /// Checks the status of remote command execution. /// - [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] private void SetStatusMessage() { diff --git a/src/System.Management.Automation/engine/remoting/common/WireDataFormat/RemoteSessionCapability.cs b/src/System.Management.Automation/engine/remoting/common/WireDataFormat/RemoteSessionCapability.cs index bc5d47c8a83..86f43cbcc42 100644 --- a/src/System.Management.Automation/engine/remoting/common/WireDataFormat/RemoteSessionCapability.cs +++ b/src/System.Management.Automation/engine/remoting/common/WireDataFormat/RemoteSessionCapability.cs @@ -174,7 +174,6 @@ internal class HostDefaultData /// /// Data. /// - #region DO NOT REMOVE OR RENAME THESE FIELDS - it will break remoting compatibility with Windows PowerShell private Dictionary data; diff --git a/src/System.Management.Automation/engine/remoting/server/serverremotesessionstatemachine.cs b/src/System.Management.Automation/engine/remoting/server/serverremotesessionstatemachine.cs index b943444dd0a..9a77d2a86bd 100644 --- a/src/System.Management.Automation/engine/remoting/server/serverremotesessionstatemachine.cs +++ b/src/System.Management.Automation/engine/remoting/server/serverremotesessionstatemachine.cs @@ -346,7 +346,6 @@ private void DoNegotiationPending(object sender, RemoteSessionStateMachineEventA /// If the parameter is not NegotiationReceived event or it does not hold the /// client negotiation packet. /// - private void DoNegotiationReceived(object sender, RemoteSessionStateMachineEventArgs fsmEventArg) { using (s_trace.TraceEventHandlers()) @@ -386,7 +385,6 @@ private void DoNegotiationReceived(object sender, RemoteSessionStateMachineEvent /// /// If the parameter is null. /// - private void DoNegotiationSending(object sender, RemoteSessionStateMachineEventArgs fsmEventArg) { if (fsmEventArg == null) @@ -413,7 +411,6 @@ private void DoNegotiationSending(object sender, RemoteSessionStateMachineEventA /// /// If the parameter is null. /// - private void DoNegotiationCompleted(object sender, RemoteSessionStateMachineEventArgs fsmEventArg) { using (s_trace.TraceEventHandlers()) @@ -441,7 +438,6 @@ private void DoNegotiationCompleted(object sender, RemoteSessionStateMachineEven /// /// If the parameter is null. /// - private void DoEstablished(object sender, RemoteSessionStateMachineEventArgs fsmEventArg) { using (s_trace.TraceEventHandlers()) diff --git a/src/System.Management.Automation/namespaces/CoreCommandContext.cs b/src/System.Management.Automation/namespaces/CoreCommandContext.cs index 34cdb0d68b7..0bf72583c32 100644 --- a/src/System.Management.Automation/namespaces/CoreCommandContext.cs +++ b/src/System.Management.Automation/namespaces/CoreCommandContext.cs @@ -250,7 +250,6 @@ internal CmdletProviderContext( /// /// If is null. /// - internal CmdletProviderContext( CmdletProviderContext contextToCopyFrom) { diff --git a/src/System.Management.Automation/utils/HostInterfacesExceptions.cs b/src/System.Management.Automation/utils/HostInterfacesExceptions.cs index c67fcd7e1b7..dab2568a2f7 100644 --- a/src/System.Management.Automation/utils/HostInterfacesExceptions.cs +++ b/src/System.Management.Automation/utils/HostInterfacesExceptions.cs @@ -10,7 +10,6 @@ namespace System.Management.Automation.Host /// Defines the exception thrown when the Host cannot complete an operation /// such as checking whether there is any input available. /// - [Serializable] public class HostException : RuntimeException @@ -19,7 +18,6 @@ class HostException : RuntimeException /// /// Initializes a new instance of the HostException class. /// - public HostException() : base( StringUtil.Format(HostInterfaceExceptionsStrings.DefaultCtorMessageTemplate, typeof(HostException).FullName)) @@ -33,7 +31,6 @@ class HostException : RuntimeException /// /// The error message that explains the reason for the exception. /// - public HostException(string message) : base(message) { @@ -52,7 +49,6 @@ class HostException : RuntimeException /// parameter is not a null reference, the current exception is raised in a catch /// block that handles the inner exception. /// - public HostException(string message, Exception innerException) : base(message, innerException) @@ -82,7 +78,6 @@ class HostException : RuntimeException /// /// Intentionally public, third-party hosts can call this /// - public HostException(string message, Exception innerException, string errorId, ErrorCategory errorCategory) : base(message, innerException) @@ -101,7 +96,6 @@ class HostException : RuntimeException /// /// The contextual information about the source or destination. /// - protected HostException(SerializationInfo info, StreamingContext context) : base(info, context) @@ -121,7 +115,6 @@ private void SetDefaultErrorRecord() /// /// Defines the exception thrown when an error occurs from prompting for a command parameter. /// - [Serializable] public class PromptingException : HostException @@ -130,7 +123,6 @@ class PromptingException : HostException /// /// Initializes a new instance of the PromptingException class. /// - public PromptingException() : base(StringUtil.Format(HostInterfaceExceptionsStrings.DefaultCtorMessageTemplate, typeof(PromptingException).FullName)) { @@ -143,7 +135,6 @@ class PromptingException : HostException /// /// The error message that explains the reason for the exception. /// - public PromptingException(string message) : base(message) { @@ -162,7 +153,6 @@ class PromptingException : HostException /// parameter is not a null reference, the current exception is raised in a catch /// block that handles the inner exception. /// - public PromptingException(string message, Exception innerException) : base(message, innerException) @@ -192,7 +182,6 @@ class PromptingException : HostException /// /// Intentionally public, third-party hosts can call this /// - public PromptingException(string message, Exception innerException, string errorId, ErrorCategory errorCategory) : base(message, innerException, errorId, errorCategory) @@ -209,7 +198,6 @@ class PromptingException : HostException /// /// The contextual information about the source or destination. /// - protected PromptingException(SerializationInfo info, StreamingContext context) : base(info, context) From 840884a4e374ccf7da2e199a9306ba3007d60f76 Mon Sep 17 00:00:00 2001 From: jackerr3 Date: Tue, 25 Aug 2020 15:21:33 -0600 Subject: [PATCH 19/40] Remove `ZapDisable` if statement from `build.psm1` to prevent `InvalidOperation` error (#13350) --- build.psm1 | 4 ---- 1 file changed, 4 deletions(-) diff --git a/build.psm1 b/build.psm1 index 9e28edfe323..0b99a020ec2 100644 --- a/build.psm1 +++ b/build.psm1 @@ -2009,10 +2009,6 @@ function Start-DevPowerShell { { Remove-Item env:DEVPATH } - - if ($ZapDisable) { - Remove-Item env:COMPLUS_ZapDisable - } } } From 126d94218a4766b61e00d9103dbee872151babc3 Mon Sep 17 00:00:00 2001 From: The Dumb Date: Tue, 25 Aug 2020 23:35:43 +0200 Subject: [PATCH 20/40] Use field if property does not exist for `ObRoot` (#13375) --- .../remoting/common/RunspaceConnectionInfo.cs | 21 ++++++++++++++++++- 1 file changed, 20 insertions(+), 1 deletion(-) diff --git a/src/System.Management.Automation/engine/remoting/common/RunspaceConnectionInfo.cs b/src/System.Management.Automation/engine/remoting/common/RunspaceConnectionInfo.cs index 7f46151a857..c134cde53cc 100644 --- a/src/System.Management.Automation/engine/remoting/common/RunspaceConnectionInfo.cs +++ b/src/System.Management.Automation/engine/remoting/common/RunspaceConnectionInfo.cs @@ -3443,7 +3443,26 @@ private void GetContainerPropertiesInternal() // if (RuntimeId == Guid.Empty) { - ContainerObRoot = (string)computeSystemPropertiesType.GetProperty("ObRoot").GetValue(computeSystemPropertiesHandle); + // Since Hyper-V changed this from a property to a field, we can optimize for newest Windows to see if it's a field, + // otherwise we fall back to old code to be compatible with older versions of Windows + var obRootFieldInfo = computeSystemPropertiesType.GetField("ObRoot"); + if (obRootFieldInfo != null) + { + ContainerObRoot = obRootFieldInfo.GetValue(computeSystemPropertiesHandle) as string; + } + else + { + var obRootPropertyInfo = computeSystemPropertiesType.GetProperty("ObRoot"); + if (obRootPropertyInfo != null) + { + ContainerObRoot = obRootPropertyInfo.GetValue(computeSystemPropertiesHandle) as string; + } + } + + if (ContainerObRoot == null) + { + throw new PSInvalidOperationException(RemotingErrorIdStrings.CannotGetHostInteropTypes); + } } } } From 74c743d279a91c9494ea7a7baa879cd1c31228ac Mon Sep 17 00:00:00 2001 From: Steve Lee Date: Thu, 27 Aug 2020 00:08:52 -0700 Subject: [PATCH 21/40] Change `PSNativePSPathResolution` to not be Experimental (#13522) --- .../ExperimentalFeature.cs | 3 - .../engine/NativeCommandParameterBinder.cs | 79 ++++++++----------- .../NativeCommandArguments.Tests.ps1 | 11 +-- 3 files changed, 36 insertions(+), 57 deletions(-) diff --git a/src/System.Management.Automation/engine/ExperimentalFeature/ExperimentalFeature.cs b/src/System.Management.Automation/engine/ExperimentalFeature/ExperimentalFeature.cs index 603ff2f34b0..8f24333e27e 100644 --- a/src/System.Management.Automation/engine/ExperimentalFeature/ExperimentalFeature.cs +++ b/src/System.Management.Automation/engine/ExperimentalFeature/ExperimentalFeature.cs @@ -120,9 +120,6 @@ static ExperimentalFeature() new ExperimentalFeature( name: "PSCultureInvariantReplaceOperator", description: "Use culture invariant to-string convertor for lval in replace operator"), - new ExperimentalFeature( - name: "PSNativePSPathResolution", - description: "Convert PSPath to filesystem path, if possible, for native commands"), new ExperimentalFeature( name: "PSNotApplyErrorActionToStderr", description: "Don't have $ErrorActionPreference affect stderr output"), diff --git a/src/System.Management.Automation/engine/NativeCommandParameterBinder.cs b/src/System.Management.Automation/engine/NativeCommandParameterBinder.cs index 0091596a443..6d987334922 100644 --- a/src/System.Management.Automation/engine/NativeCommandParameterBinder.cs +++ b/src/System.Management.Automation/engine/NativeCommandParameterBinder.cs @@ -122,14 +122,6 @@ internal void BindParameters(Collection parameters) break; } - // Prior to PSNativePSPathResolution experimental feature, a single quote worked the same as a double quote - // so if the feature is not enabled, we treat any quotes as double quotes. When this feature is no longer - // experimental, this code here needs to be removed. - if (!ExperimentalFeature.IsEnabled("PSNativePSPathResolution") && stringConstantType == StringConstantType.SingleQuoted) - { - stringConstantType = StringConstantType.DoubleQuoted; - } - AppendOneNativeArgument(Context, argValue, arrayLiteralAst, sawVerbatimArgumentMarker, stringConstantType); } } @@ -362,58 +354,55 @@ private void PossiblyGlobArg(string arg, StringConstantType stringConstantType) /// Resolved PSPath if applicable otherwise the original path internal static string ResolvePath(string path, ExecutionContext context) { - if (ExperimentalFeature.IsEnabled("PSNativePSPathResolution")) - { #if !UNIX - // on Windows, we need to expand ~ to point to user's home path - if (string.Equals(path, "~", StringComparison.Ordinal) || path.StartsWith(TildeDirectorySeparator, StringComparison.Ordinal) || path.StartsWith(TildeAltDirectorySeparator, StringComparison.Ordinal)) + // on Windows, we need to expand ~ to point to user's home path + if (string.Equals(path, "~", StringComparison.Ordinal) || path.StartsWith(TildeDirectorySeparator, StringComparison.Ordinal) || path.StartsWith(TildeAltDirectorySeparator, StringComparison.Ordinal)) + { + try { - try - { - ProviderInfo fileSystemProvider = context.EngineSessionState.GetSingleProvider(FileSystemProvider.ProviderName); - return new StringBuilder(fileSystemProvider.Home) - .Append(path.Substring(1)) - .Replace(Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar) - .ToString(); - } - catch - { - return path; - } + ProviderInfo fileSystemProvider = context.EngineSessionState.GetSingleProvider(FileSystemProvider.ProviderName); + return new StringBuilder(fileSystemProvider.Home) + .Append(path.Substring(1)) + .Replace(Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar) + .ToString(); } + catch + { + return path; + } + } - // check if the driveName is an actual disk drive on Windows, if so, no expansion - if (path.Length >= 2 && path[1] == ':') + // check if the driveName is an actual disk drive on Windows, if so, no expansion + if (path.Length >= 2 && path[1] == ':') + { + foreach (var drive in DriveInfo.GetDrives()) { - foreach (var drive in DriveInfo.GetDrives()) + if (drive.Name.StartsWith(new string(path[0], 1), StringComparison.OrdinalIgnoreCase)) { - if (drive.Name.StartsWith(new string(path[0], 1), StringComparison.OrdinalIgnoreCase)) - { - return path; - } + return path; } } + } #endif - if (path.Contains(':')) + if (path.Contains(':')) + { + LocationGlobber globber = new LocationGlobber(context.SessionState); + try { - LocationGlobber globber = new LocationGlobber(context.SessionState); - try - { - ProviderInfo providerInfo; + ProviderInfo providerInfo; - // replace the argument with resolved path if it's a filesystem path - string pspath = globber.GetProviderPath(path, out providerInfo); - if (string.Equals(providerInfo.Name, FileSystemProvider.ProviderName, StringComparison.OrdinalIgnoreCase)) - { - path = pspath; - } - } - catch + // replace the argument with resolved path if it's a filesystem path + string pspath = globber.GetProviderPath(path, out providerInfo); + if (string.Equals(providerInfo.Name, FileSystemProvider.ProviderName, StringComparison.OrdinalIgnoreCase)) { - // if it's not a provider path, do nothing + path = pspath; } } + catch + { + // if it's not a provider path, do nothing + } } return path; diff --git a/test/powershell/Language/Scripting/NativeExecution/NativeCommandArguments.Tests.ps1 b/test/powershell/Language/Scripting/NativeExecution/NativeCommandArguments.Tests.ps1 index c5b5a5f66dd..4848cd34b95 100644 --- a/test/powershell/Language/Scripting/NativeExecution/NativeCommandArguments.Tests.ps1 +++ b/test/powershell/Language/Scripting/NativeExecution/NativeCommandArguments.Tests.ps1 @@ -67,11 +67,6 @@ Describe "Native Command Arguments" -tags "CI" { Describe 'PSPath to native commands' { BeforeAll { - $featureEnabled = $EnabledExperimentalFeatures.Contains('PSNativePSPathResolution') - $originalDefaultParameterValues = $PSDefaultParameterValues.Clone() - - $PSDefaultParameterValues["it:skip"] = (-not $featureEnabled) - if ($IsWindows) { $cmd = "cmd" $cmdArg1 = "/c" @@ -95,8 +90,6 @@ Describe 'PSPath to native commands' { } AfterAll { - $global:PSDefaultParameterValues = $originalDefaultParameterValues - Remove-Item -Path "env:/test var" Remove-Item -Path $filePath Remove-PSDrive -Name $complexDriveName @@ -144,10 +137,10 @@ Describe 'PSPath to native commands' { It 'Relative PSPath works' { New-Item -Path $testdrive -Name TestFolder -ItemType Directory -ErrorAction Stop - $pwd = Get-Location + $cwd = Get-Location Set-Content -Path (Join-Path -Path $testdrive -ChildPath 'TestFolder' -AdditionalChildPath 'test.txt') -Value 'hello' Set-Location -Path (Join-Path -Path $testdrive -ChildPath 'TestFolder') - Set-Location -Path $pwd + Set-Location -Path $cwd $out = & $cmd $cmdArg1 $cmdArg2 "TestDrive:test.txt" $LASTEXITCODE | Should -Be 0 $out | Should -BeExactly 'Hello' From cb8165eeef384ed3adb76969c3d12e5f41e3c8cf Mon Sep 17 00:00:00 2001 From: Aditya Patwardhan Date: Thu, 27 Aug 2020 10:11:01 -0700 Subject: [PATCH 22/40] Move `PSNullConditionalOperators` feature out of experimental (#13529) --- .../ExperimentalFeature.cs | 3 - .../engine/parser/tokenizer.cs | 2 +- .../TabCompletion/TabCompletion.Tests.ps1 | 5 +- .../Operators/NullConditional.Tests.ps1 | 74 ------------------- .../Language/Parser/Parsing.Tests.ps1 | 43 +++-------- test/tools/TestMetadata.json | 4 - 6 files changed, 15 insertions(+), 116 deletions(-) diff --git a/src/System.Management.Automation/engine/ExperimentalFeature/ExperimentalFeature.cs b/src/System.Management.Automation/engine/ExperimentalFeature/ExperimentalFeature.cs index 8f24333e27e..ebb47e9be72 100644 --- a/src/System.Management.Automation/engine/ExperimentalFeature/ExperimentalFeature.cs +++ b/src/System.Management.Automation/engine/ExperimentalFeature/ExperimentalFeature.cs @@ -114,9 +114,6 @@ static ExperimentalFeature() name: "PSUnixFileStat", description: "Provide unix permission information for files and directories"), #endif - new ExperimentalFeature( - name: "PSNullConditionalOperators", - description: "Support the null conditional member access operators in PowerShell language"), new ExperimentalFeature( name: "PSCultureInvariantReplaceOperator", description: "Use culture invariant to-string convertor for lval in replace operator"), diff --git a/src/System.Management.Automation/engine/parser/tokenizer.cs b/src/System.Management.Automation/engine/parser/tokenizer.cs index 5fdd4ac4633..f896aeda376 100644 --- a/src/System.Management.Automation/engine/parser/tokenizer.cs +++ b/src/System.Management.Automation/engine/parser/tokenizer.cs @@ -4243,7 +4243,7 @@ internal Token GetMemberAccessOperator(bool allowLBracket) return NewToken(TokenKind.LBracket); } - if (ExperimentalFeature.IsEnabled("PSNullConditionalOperators") && c == '?') + if (c == '?') { _tokenStart = _currentIndex; SkipChar(); diff --git a/test/powershell/Host/TabCompletion/TabCompletion.Tests.ps1 b/test/powershell/Host/TabCompletion/TabCompletion.Tests.ps1 index b8b1cc607a5..c42f30e510a 100644 --- a/test/powershell/Host/TabCompletion/TabCompletion.Tests.ps1 +++ b/test/powershell/Host/TabCompletion/TabCompletion.Tests.ps1 @@ -3,7 +3,6 @@ Describe "TabCompletion" -Tags CI { BeforeAll { $separator = [System.IO.Path]::DirectorySeparatorChar - $nullConditionalFeatureDisabled = -not $EnabledExperimentalFeatures.Contains('PSNullConditionalOperators') } It 'Should complete Command' { @@ -34,12 +33,12 @@ Describe "TabCompletion" -Tags CI { $res.CompletionMatches[0].CompletionText | Should -BeExactly 'ToString(' } - It 'Should complete dotnet method with null conditional operator' -Skip:$nullConditionalFeatureDisabled { + It 'Should complete dotnet method with null conditional operator' { $res = TabExpansion2 -inputScript '(1)?.ToSt' -cursorColumn '(1)?.ToSt'.Length $res.CompletionMatches[0].CompletionText | Should -BeExactly 'ToString(' } - It 'Should complete dotnet method with null conditional operator without first letter' -Skip:$nullConditionalFeatureDisabled { + It 'Should complete dotnet method with null conditional operator without first letter' { $res = TabExpansion2 -inputScript '(1)?.' -cursorColumn '(1)?.'.Length $res.CompletionMatches[0].CompletionText | Should -BeExactly 'CompareTo(' } diff --git a/test/powershell/Language/Operators/NullConditional.Tests.ps1 b/test/powershell/Language/Operators/NullConditional.Tests.ps1 index 5c2c65e4ad9..237b4d8c987 100644 --- a/test/powershell/Language/Operators/NullConditional.Tests.ps1 +++ b/test/powershell/Language/Operators/NullConditional.Tests.ps1 @@ -260,31 +260,6 @@ Describe 'NullCoalesceOperations' -Tags 'CI' { Describe 'NullConditionalMemberAccess' -Tag 'CI' { - BeforeAll { - $skipTest = -not $EnabledExperimentalFeatures.Contains('PSNullConditionalOperators') - - if ($skipTest) { - Write-Verbose "Test Suite Skipped. The test suite requires the experimental feature 'PSNullConditionalOperators' to be enabled." -Verbose - $originalDefaultParameterValues = $PSDefaultParameterValues.Clone() - $PSDefaultParameterValues["it:skip"] = $true - } - - function ExecuteTestIfFeatureIsEnabled([string] $TestContet) - { - if ($skipTest) { - Set-ItResult -Skipped -Because "PSNullConditionalOperators feature is disabled" - } else { - Invoke-Expression $testContent - } - } - } - - AfterAll { - if ($skipTest) { - $global:PSDefaultParameterValues = $originalDefaultParameterValues - } - } - Context '?. operator tests' { BeforeAll { $psObj = [psobject]::new() @@ -302,8 +277,6 @@ Describe 'NullConditionalMemberAccess' -Tag 'CI' { } It 'Can get member value of a non-null variable' { - - $testContent = @' ${psObj}?.name | Should -BeExactly 'value' ${array}?.length | Should -Be 3 ${hash}?.a | Should -Be 1 @@ -311,81 +284,50 @@ Describe 'NullConditionalMemberAccess' -Tag 'CI' { (Get-Item $TestDrive)?.EnumerateFiles()?.Name | Should -BeExactly 'testfile.txt' [int32]::MaxValue?.ToString() | Should -BeExactly '2147483647' -'@ - - ExecuteTestIfFeatureIsEnabled -TestContent $testContent } It 'Can get null when variable is null' { - $testContent = @' ${nonExistent}?.name | Should -BeNullOrEmpty ${nonExistent}?.MyMethod() | Should -BeNullOrEmpty (get-process -Name doesnotexist -ErrorAction SilentlyContinue)?.Id | Should -BeNullOrEmpty -'@ - - ExecuteTestIfFeatureIsEnabled -TestContent $testContent } It 'Use ?. operator multiple times in statement' { - $testContent = @' ${psObj}?.name?.nonExistent | Should -BeNullOrEmpty ${psObj}?.nonExistent?.nonExistent | Should -BeNullOrEmpty ${nonExistent}?.nonExistent?.nonExistent | Should -BeNullOrEmpty ${psObj}?.nested?.name | Should -BeExactly 'valuenested' ${psObj}?.nestedMethod?.GetHello() | Should -BeExactly 'hello' -'@ - - ExecuteTestIfFeatureIsEnabled -TestContent $testContent } It 'Use ?. on a dynamic method name' { - $testContent = @' $methodName = 'ToLongDateString' (Get-Date '11/11/2019')?.$methodName() | Should -BeExactly 'Monday, November 11, 2019' ${doesNotExist}?.$methodName() | Should -BeNullOrEmpty -'@ - - ExecuteTestIfFeatureIsEnabled -TestContent $testContent } It 'Use ?. on a dynamic method name that does not exist' { - $testContent = @' $methodName = 'DoesNotExist' { (Get-Date '11/11/2019')?.$methodName() } | Should -Throw -ErrorId 'MethodNotFound' -'@ - - ExecuteTestIfFeatureIsEnabled -TestContent $testContent } It 'Use ?. on a dynamic method name that does not exist' { - $testContent = @' $methodName = $null { (Get-Date '11/11/2019')?.$methodName() } | Should -Throw -ErrorId 'MethodNotFound' -'@ - - ExecuteTestIfFeatureIsEnabled -TestContent $testContent } It 'Use ?. on a dynamic property name' { - $testContent = @' $propName = 'SI' (Get-Process -Id $PID)?.$propName | Should -Be (Get-Process -id $PID).SessionId ${doesNotExist}?.$propName() | Should -BeNullOrEmpty -'@ - - ExecuteTestIfFeatureIsEnabled -TestContent $testContent } It 'Should throw error when method does not exist' { - $testContent = @' { ${psObj}?.nestedMethod?.NonExistent() } | Should -Throw -ErrorId 'MethodNotFound' -'@ - - ExecuteTestIfFeatureIsEnabled -TestContent $testContent } } @@ -401,46 +343,30 @@ Describe 'NullConditionalMemberAccess' -Tag 'CI' { } It 'Can index can call properties' { - $testContent = @' ${array}?[0] | Should -Be 1 ${array}?[0,1] | Should -Be @(1,2) ${array}?[0..2] | Should -Be @(1,2,3) ${array}?[-2] | Should -Be 2 ${hash}?['a'] | Should -Be 1 -'@ - - ExecuteTestIfFeatureIsEnabled -TestContent $testContent } It 'Indexing in null items should be null' { - $testContent = @' ${doesnotExist}?[0] | Should -BeNullOrEmpty ${doesnotExist}?[0,1] | Should -BeNullOrEmpty ${doesnotExist}?[0..2] | Should -BeNullOrEmpty ${doesnotExist}?[-2] | Should -BeNullOrEmpty ${doesnotExist}?['a'] | Should -BeNullOrEmpty -'@ - - ExecuteTestIfFeatureIsEnabled -TestContent $testContent } It 'Can call methods on indexed items' { - $testContent = @' ${dateArray}?[0]?.ToLongDateString() | Should -BeExactly 'Friday, November 1, 2019' -'@ - - ExecuteTestIfFeatureIsEnabled -TestContent $testContent } It 'Calling a method on nonexistent item give null' { - $testContent = @' ${dateArray}?[1234]?.ToLongDateString() | Should -BeNullOrEmpty ${doesNotExist}?[0]?.MyGetMethod() | Should -BeNullOrEmpty -'@ - - ExecuteTestIfFeatureIsEnabled -TestContent $testContent } } } diff --git a/test/powershell/Language/Parser/Parsing.Tests.ps1 b/test/powershell/Language/Parser/Parsing.Tests.ps1 index 9f213ecf14c..c764830954b 100644 --- a/test/powershell/Language/Parser/Parsing.Tests.ps1 +++ b/test/powershell/Language/Parser/Parsing.Tests.ps1 @@ -279,37 +279,18 @@ Describe 'null coalescing statement parsing' -Tag "CI" { } Describe 'null conditional member access statement parsing' -Tag 'CI' { - BeforeAll { - $skipTest = -not $EnabledExperimentalFeatures.Contains('PSNullConditionalOperators') - - if ($skipTest) { - Write-Verbose "Test Suite Skipped. The test suite requires the experimental feature 'PSNullConditionalOperators' to be enabled." -Verbose - $originalDefaultParameterValues = $PSDefaultParameterValues.Clone() - $PSDefaultParameterValues["it:skip"] = $true - } - } - - AfterAll { - if ($skipTest) { - $global:PSDefaultParameterValues = $originalDefaultParameterValues - } - } - - # We need to add this check as parsing on script block is done before an `It` is called. - if (-not $skipTest) { - ShouldBeParseError '[datetime]?::now' ExpectedValueExpression, UnexpectedToken 11, 11 - ShouldBeParseError '$x ?.name' ExpectedValueExpression, UnexpectedToken 4, 4 - ShouldBeParseError 'Get-Date ?.ToString()' ExpectedExpression 20 - ShouldBeParseError '${x}?.' MissingPropertyName 6 - ShouldBeParseError '${x}?.name = "value"' InvalidLeftHandSide 0 - - ShouldBeParseError '[datetime]?[0]' MissingTypename, ExpectedValueExpression, UnexpectedToken 12, 11, 11 - ShouldBeParseError '${x} ?[1]' MissingTypename, ExpectedValueExpression, UnexpectedToken 7, 6, 6 - ShouldBeParseError '${x}?[]' MissingArrayIndexExpression 6 - ShouldBeParseError '${x}?[-]' MissingExpressionAfterOperator 7 - ShouldBeParseError '${x}?[ ]' MissingArrayIndexExpression 6 - ShouldBeParseError '${x}?[0] = 1' InvalidLeftHandSide 0 - } + ShouldBeParseError '[datetime]?::now' ExpectedValueExpression, UnexpectedToken 11, 11 + ShouldBeParseError '$x ?.name' ExpectedValueExpression, UnexpectedToken 4, 4 + ShouldBeParseError 'Get-Date ?.ToString()' ExpectedExpression 20 + ShouldBeParseError '${x}?.' MissingPropertyName 6 + ShouldBeParseError '${x}?.name = "value"' InvalidLeftHandSide 0 + + ShouldBeParseError '[datetime]?[0]' MissingTypename, ExpectedValueExpression, UnexpectedToken 12, 11, 11 + ShouldBeParseError '${x} ?[1]' MissingTypename, ExpectedValueExpression, UnexpectedToken 7, 6, 6 + ShouldBeParseError '${x}?[]' MissingArrayIndexExpression 6 + ShouldBeParseError '${x}?[-]' MissingExpressionAfterOperator 7 + ShouldBeParseError '${x}?[ ]' MissingArrayIndexExpression 6 + ShouldBeParseError '${x}?[0] = 1' InvalidLeftHandSide 0 } Describe 'splatting parsing' -Tags "CI" { diff --git a/test/tools/TestMetadata.json b/test/tools/TestMetadata.json index db65e6ec212..66dc8572d37 100644 --- a/test/tools/TestMetadata.json +++ b/test/tools/TestMetadata.json @@ -1,10 +1,6 @@ { "ExperimentalFeatures": { "ExpTest.FeatureOne": [ "test/powershell/engine/ExperimentalFeature/ExperimentalFeature.Basic.Tests.ps1" ], - "PSNullConditionalOperators": [ - "test/powershell/Language/Operators/NullConditional.Tests.ps1", - "test/powershell/Language/Parser/Parsing.Tests.ps1", - "test/powershell/Host/TabCompletion/TabCompletion.Tests.ps1" ], "PSCultureInvariantReplaceOperator": [ "test/powershell/Language/Operators/ReplaceOperator.Tests.ps1" ], "Microsoft.PowerShell.Utility.PSManageBreakpointsInRunspace": [ "test/powershell/Modules/Microsoft.PowerShell.Utility/RunspaceBreakpointManagement.Tests.ps1" ] } From 78d0d0e3065d946a1f17cc97cf29b94c12ce9c9f Mon Sep 17 00:00:00 2001 From: xtqqczze <45661989+xtqqczze@users.noreply.github.com> Date: Thu, 27 Aug 2020 18:27:24 +0100 Subject: [PATCH 23/40] Use `uint` instead of `long` for `PDH` constants (#13502) --- .../PdhHelper.cs | 178 +++++++++--------- 1 file changed, 89 insertions(+), 89 deletions(-) diff --git a/src/Microsoft.PowerShell.Commands.Diagnostics/PdhHelper.cs b/src/Microsoft.PowerShell.Commands.Diagnostics/PdhHelper.cs index d0ffb1d579d..1e703d66219 100644 --- a/src/Microsoft.PowerShell.Commands.Diagnostics/PdhHelper.cs +++ b/src/Microsoft.PowerShell.Commands.Diagnostics/PdhHelper.cs @@ -17,92 +17,92 @@ namespace Microsoft.Powershell.Commands.GetCounter.PdhNative { internal static class PdhResults { - public const long PDH_CSTATUS_VALID_DATA = 0x0L; - public const long PDH_CSTATUS_NEW_DATA = 0x1L; - public const long PDH_CSTATUS_NO_MACHINE = 0x800007D0L; - public const long PDH_CSTATUS_NO_INSTANCE = 0x800007D1L; - public const long PDH_MORE_DATA = 0x800007D2L; - public const long PDH_CSTATUS_ITEM_NOT_VALIDATED = 0x800007D3L; - public const long PDH_RETRY = 0x800007D4L; - public const long PDH_NO_DATA = 0x800007D5L; - public const long PDH_CALC_NEGATIVE_DENOMINATOR = 0x800007D6L; - public const long PDH_CALC_NEGATIVE_TIMEBASE = 0x800007D7L; - public const long PDH_CALC_NEGATIVE_VALUE = 0x800007D8L; - public const long PDH_DIALOG_CANCELLED = 0x800007D9L; - public const long PDH_END_OF_LOG_FILE = 0x800007DAL; - public const long PDH_ASYNC_QUERY_TIMEOUT = 0x800007DBL; - public const long PDH_CANNOT_SET_DEFAULT_REALTIME_DATASOURCE = 0x800007DCL; - public const long PDH_UNABLE_MAP_NAME_FILES = 0x80000BD5L; - public const long PDH_PLA_VALIDATION_WARNING = 0x80000BF3L; - public const long PDH_CSTATUS_NO_OBJECT = 0xC0000BB8L; - public const long PDH_CSTATUS_NO_COUNTER = 0xC0000BB9L; - public const long PDH_CSTATUS_INVALID_DATA = 0xC0000BBAL; - public const long PDH_MEMORY_ALLOCATION_FAILURE = 0xC0000BBBL; - public const long PDH_INVALID_HANDLE = 0xC0000BBCL; - public const long PDH_INVALID_ARGUMENT = 0xC0000BBDL; - public const long PDH_FUNCTION_NOT_FOUND = 0xC0000BBEL; - public const long PDH_CSTATUS_NO_COUNTERNAME = 0xC0000BBFL; - public const long PDH_CSTATUS_BAD_COUNTERNAME = 0xC0000BC0L; - public const long PDH_INVALID_BUFFER = 0xC0000BC1L; - public const long PDH_INSUFFICIENT_BUFFER = 0xC0000BC2L; - public const long PDH_CANNOT_CONNECT_MACHINE = 0xC0000BC3L; - public const long PDH_INVALID_PATH = 0xC0000BC4L; - public const long PDH_INVALID_INSTANCE = 0xC0000BC5L; - public const long PDH_INVALID_DATA = 0xC0000BC6L; - public const long PDH_NO_DIALOG_DATA = 0xC0000BC7L; - public const long PDH_CANNOT_READ_NAME_STRINGS = 0xC0000BC8L; - public const long PDH_LOG_FILE_CREATE_ERROR = 0xC0000BC9L; - public const long PDH_LOG_FILE_OPEN_ERROR = 0xC0000BCAL; - public const long PDH_LOG_TYPE_NOT_FOUND = 0xC0000BCBL; - public const long PDH_NO_MORE_DATA = 0xC0000BCCL; - public const long PDH_ENTRY_NOT_IN_LOG_FILE = 0xC0000BCDL; - public const long PDH_DATA_SOURCE_IS_LOG_FILE = 0xC0000BCEL; - public const long PDH_DATA_SOURCE_IS_REAL_TIME = 0xC0000BCFL; - public const long PDH_UNABLE_READ_LOG_HEADER = 0xC0000BD0L; - public const long PDH_FILE_NOT_FOUND = 0xC0000BD1L; - public const long PDH_FILE_ALREADY_EXISTS = 0xC0000BD2L; - public const long PDH_NOT_IMPLEMENTED = 0xC0000BD3L; - public const long PDH_STRING_NOT_FOUND = 0xC0000BD4L; - public const long PDH_UNKNOWN_LOG_FORMAT = 0xC0000BD6L; - public const long PDH_UNKNOWN_LOGSVC_COMMAND = 0xC0000BD7L; - public const long PDH_LOGSVC_QUERY_NOT_FOUND = 0xC0000BD8L; - public const long PDH_LOGSVC_NOT_OPENED = 0xC0000BD9L; - public const long PDH_WBEM_ERROR = 0xC0000BDAL; - public const long PDH_ACCESS_DENIED = 0xC0000BDBL; - public const long PDH_LOG_FILE_TOO_SMALL = 0xC0000BDCL; - public const long PDH_INVALID_DATASOURCE = 0xC0000BDDL; - public const long PDH_INVALID_SQLDB = 0xC0000BDEL; - public const long PDH_NO_COUNTERS = 0xC0000BDFL; - public const long PDH_SQL_ALLOC_FAILED = 0xC0000BE0L; - public const long PDH_SQL_ALLOCCON_FAILED = 0xC0000BE1L; - public const long PDH_SQL_EXEC_DIRECT_FAILED = 0xC0000BE2L; - public const long PDH_SQL_FETCH_FAILED = 0xC0000BE3L; - public const long PDH_SQL_ROWCOUNT_FAILED = 0xC0000BE4L; - public const long PDH_SQL_MORE_RESULTS_FAILED = 0xC0000BE5L; - public const long PDH_SQL_CONNECT_FAILED = 0xC0000BE6L; - public const long PDH_SQL_BIND_FAILED = 0xC0000BE7L; - public const long PDH_CANNOT_CONNECT_WMI_SERVER = 0xC0000BE8L; - public const long PDH_PLA_COLLECTION_ALREADY_RUNNING = 0xC0000BE9L; - public const long PDH_PLA_ERROR_SCHEDULE_OVERLAP = 0xC0000BEAL; - public const long PDH_PLA_COLLECTION_NOT_FOUND = 0xC0000BEBL; - public const long PDH_PLA_ERROR_SCHEDULE_ELAPSED = 0xC0000BECL; - public const long PDH_PLA_ERROR_NOSTART = 0xC0000BEDL; - public const long PDH_PLA_ERROR_ALREADY_EXISTS = 0xC0000BEEL; - public const long PDH_PLA_ERROR_TYPE_MISMATCH = 0xC0000BEFL; - public const long PDH_PLA_ERROR_FILEPATH = 0xC0000BF0L; - public const long PDH_PLA_SERVICE_ERROR = 0xC0000BF1L; - public const long PDH_PLA_VALIDATION_ERROR = 0xC0000BF2L; - public const long PDH_PLA_ERROR_NAME_TOO_LONG = 0xC0000BF4L; - public const long PDH_INVALID_SQL_LOG_FORMAT = 0xC0000BF5L; - public const long PDH_COUNTER_ALREADY_IN_QUERY = 0xC0000BF6L; - public const long PDH_BINARY_LOG_CORRUPT = 0xC0000BF7L; - public const long PDH_LOG_SAMPLE_TOO_SMALL = 0xC0000BF8L; - public const long PDH_OS_LATER_VERSION = 0xC0000BF9L; - public const long PDH_OS_EARLIER_VERSION = 0xC0000BFAL; - public const long PDH_INCORRECT_APPEND_TIME = 0xC0000BFBL; - public const long PDH_UNMATCHED_APPEND_COUNTER = 0xC0000BFCL; - public const long PDH_SQL_ALTER_DETAIL_FAILED = 0xC0000BFDL; - public const long PDH_QUERY_PERF_DATA_TIMEOUT = 0xC0000BFEL; + public const uint PDH_CSTATUS_VALID_DATA = 0x0; + public const uint PDH_CSTATUS_NEW_DATA = 0x1; + public const uint PDH_CSTATUS_NO_MACHINE = 0x800007D0; + public const uint PDH_CSTATUS_NO_INSTANCE = 0x800007D1; + public const uint PDH_MORE_DATA = 0x800007D2; + public const uint PDH_CSTATUS_ITEM_NOT_VALIDATED = 0x800007D3; + public const uint PDH_RETRY = 0x800007D4; + public const uint PDH_NO_DATA = 0x800007D5; + public const uint PDH_CALC_NEGATIVE_DENOMINATOR = 0x800007D6; + public const uint PDH_CALC_NEGATIVE_TIMEBASE = 0x800007D7; + public const uint PDH_CALC_NEGATIVE_VALUE = 0x800007D8; + public const uint PDH_DIALOG_CANCELLED = 0x800007D9; + public const uint PDH_END_OF_LOG_FILE = 0x800007DA; + public const uint PDH_ASYNC_QUERY_TIMEOUT = 0x800007DB; + public const uint PDH_CANNOT_SET_DEFAULT_REALTIME_DATASOURCE = 0x800007DC; + public const uint PDH_UNABLE_MAP_NAME_FILES = 0x80000BD5; + public const uint PDH_PLA_VALIDATION_WARNING = 0x80000BF3; + public const uint PDH_CSTATUS_NO_OBJECT = 0xC0000BB8; + public const uint PDH_CSTATUS_NO_COUNTER = 0xC0000BB9; + public const uint PDH_CSTATUS_INVALID_DATA = 0xC0000BBA; + public const uint PDH_MEMORY_ALLOCATION_FAILURE = 0xC0000BBB; + public const uint PDH_INVALID_HANDLE = 0xC0000BBC; + public const uint PDH_INVALID_ARGUMENT = 0xC0000BBD; + public const uint PDH_FUNCTION_NOT_FOUND = 0xC0000BBE; + public const uint PDH_CSTATUS_NO_COUNTERNAME = 0xC0000BBF; + public const uint PDH_CSTATUS_BAD_COUNTERNAME = 0xC0000BC0; + public const uint PDH_INVALID_BUFFER = 0xC0000BC1; + public const uint PDH_INSUFFICIENT_BUFFER = 0xC0000BC2; + public const uint PDH_CANNOT_CONNECT_MACHINE = 0xC0000BC3; + public const uint PDH_INVALID_PATH = 0xC0000BC4; + public const uint PDH_INVALID_INSTANCE = 0xC0000BC5; + public const uint PDH_INVALID_DATA = 0xC0000BC6; + public const uint PDH_NO_DIALOG_DATA = 0xC0000BC7; + public const uint PDH_CANNOT_READ_NAME_STRINGS = 0xC0000BC8; + public const uint PDH_LOG_FILE_CREATE_ERROR = 0xC0000BC9; + public const uint PDH_LOG_FILE_OPEN_ERROR = 0xC0000BCA; + public const uint PDH_LOG_TYPE_NOT_FOUND = 0xC0000BCB; + public const uint PDH_NO_MORE_DATA = 0xC0000BCC; + public const uint PDH_ENTRY_NOT_IN_LOG_FILE = 0xC0000BCD; + public const uint PDH_DATA_SOURCE_IS_LOG_FILE = 0xC0000BCE; + public const uint PDH_DATA_SOURCE_IS_REAL_TIME = 0xC0000BCF; + public const uint PDH_UNABLE_READ_LOG_HEADER = 0xC0000BD0; + public const uint PDH_FILE_NOT_FOUND = 0xC0000BD1; + public const uint PDH_FILE_ALREADY_EXISTS = 0xC0000BD2; + public const uint PDH_NOT_IMPLEMENTED = 0xC0000BD3; + public const uint PDH_STRING_NOT_FOUND = 0xC0000BD4; + public const uint PDH_UNKNOWN_LOG_FORMAT = 0xC0000BD6; + public const uint PDH_UNKNOWN_LOGSVC_COMMAND = 0xC0000BD7; + public const uint PDH_LOGSVC_QUERY_NOT_FOUND = 0xC0000BD8; + public const uint PDH_LOGSVC_NOT_OPENED = 0xC0000BD9; + public const uint PDH_WBEM_ERROR = 0xC0000BDA; + public const uint PDH_ACCESS_DENIED = 0xC0000BDB; + public const uint PDH_LOG_FILE_TOO_SMALL = 0xC0000BDC; + public const uint PDH_INVALID_DATASOURCE = 0xC0000BDD; + public const uint PDH_INVALID_SQLDB = 0xC0000BDE; + public const uint PDH_NO_COUNTERS = 0xC0000BDF; + public const uint PDH_SQL_ALLOC_FAILED = 0xC0000BE0; + public const uint PDH_SQL_ALLOCCON_FAILED = 0xC0000BE1; + public const uint PDH_SQL_EXEC_DIRECT_FAILED = 0xC0000BE2; + public const uint PDH_SQL_FETCH_FAILED = 0xC0000BE3; + public const uint PDH_SQL_ROWCOUNT_FAILED = 0xC0000BE4; + public const uint PDH_SQL_MORE_RESULTS_FAILED = 0xC0000BE5; + public const uint PDH_SQL_CONNECT_FAILED = 0xC0000BE6; + public const uint PDH_SQL_BIND_FAILED = 0xC0000BE7; + public const uint PDH_CANNOT_CONNECT_WMI_SERVER = 0xC0000BE8; + public const uint PDH_PLA_COLLECTION_ALREADY_RUNNING = 0xC0000BE9; + public const uint PDH_PLA_ERROR_SCHEDULE_OVERLAP = 0xC0000BEA; + public const uint PDH_PLA_COLLECTION_NOT_FOUND = 0xC0000BEB; + public const uint PDH_PLA_ERROR_SCHEDULE_ELAPSED = 0xC0000BEC; + public const uint PDH_PLA_ERROR_NOSTART = 0xC0000BED; + public const uint PDH_PLA_ERROR_ALREADY_EXISTS = 0xC0000BEE; + public const uint PDH_PLA_ERROR_TYPE_MISMATCH = 0xC0000BEF; + public const uint PDH_PLA_ERROR_FILEPATH = 0xC0000BF0; + public const uint PDH_PLA_SERVICE_ERROR = 0xC0000BF1; + public const uint PDH_PLA_VALIDATION_ERROR = 0xC0000BF2; + public const uint PDH_PLA_ERROR_NAME_TOO_LONG = 0xC0000BF4; + public const uint PDH_INVALID_SQL_LOG_FORMAT = 0xC0000BF5; + public const uint PDH_COUNTER_ALREADY_IN_QUERY = 0xC0000BF6; + public const uint PDH_BINARY_LOG_CORRUPT = 0xC0000BF7; + public const uint PDH_LOG_SAMPLE_TOO_SMALL = 0xC0000BF8; + public const uint PDH_OS_LATER_VERSION = 0xC0000BF9; + public const uint PDH_OS_EARLIER_VERSION = 0xC0000BFA; + public const uint PDH_INCORRECT_APPEND_TIME = 0xC0000BFB; + public const uint PDH_UNMATCHED_APPEND_COUNTER = 0xC0000BFC; + public const uint PDH_SQL_ALTER_DETAIL_FAILED = 0xC0000BFD; + public const uint PDH_QUERY_PERF_DATA_TIMEOUT = 0xC0000BFE; } internal static class PerfDetail @@ -967,7 +967,7 @@ public uint TranslateLocalCounterPath(string englishPath, out string localizedPa } catch (Exception) { - return (uint)PdhResults.PDH_INVALID_PATH; + return PdhResults.PDH_INVALID_PATH; } } else if (regString.ToLowerInvariant() == lowerEngObjectName) @@ -978,7 +978,7 @@ public uint TranslateLocalCounterPath(string englishPath, out string localizedPa } catch (Exception) { - return (uint)PdhResults.PDH_INVALID_PATH; + return PdhResults.PDH_INVALID_PATH; } } @@ -990,7 +990,7 @@ public uint TranslateLocalCounterPath(string englishPath, out string localizedPa if (counterIndex == -1 || objIndex == -1) { - return (uint)PdhResults.PDH_INVALID_PATH; + return PdhResults.PDH_INVALID_PATH; } // Now, call retrieve the localized names of the object and the counter by index: From 4e2b6e9540c1946d22664149f0331447ac0bf797 Mon Sep 17 00:00:00 2001 From: Ilya Date: Thu, 27 Aug 2020 23:51:19 +0500 Subject: [PATCH 24/40] Process reparse points for Microsoft Store applications (#13481) --- .../engine/NativeCommandProcessor.cs | 49 ++++++++++++++++--- .../namespaces/FileSystemProvider.cs | 25 ++++++---- 2 files changed, 57 insertions(+), 17 deletions(-) diff --git a/src/System.Management.Automation/engine/NativeCommandProcessor.cs b/src/System.Management.Automation/engine/NativeCommandProcessor.cs index 3a12dab6295..05b316f0de0 100644 --- a/src/System.Management.Automation/engine/NativeCommandProcessor.cs +++ b/src/System.Management.Automation/engine/NativeCommandProcessor.cs @@ -10,7 +10,6 @@ using System.Collections; using System.Threading; using System.Management.Automation.Internal; -using System.Management.Automation.Runspaces; using System.Xml; using System.Runtime.InteropServices; using Dbg = System.Management.Automation.Diagnostics; @@ -222,6 +221,29 @@ private string Path } } + /// + /// Gets true if Path is Console Application. + /// + private bool IsConsoleApplication => !IsWindowsApplication; + + /// + /// Gets true if Path is Windows Application. + /// + private bool IsWindowsApplication + { + get + { + if (!_isWindowsApplication.HasValue) + { + _isWindowsApplication = CheckIfWindowsApplication(Path); + } + + return _isWindowsApplication.Value; + } + } + + private bool? _isWindowsApplication; + #endregion ctor/native command properties #region parameter binder @@ -476,7 +498,7 @@ private void InitNativeProcess() bool notDone = true; if (!string.IsNullOrEmpty(executable)) { - if (IsConsoleApplication(executable)) + if (CheckIfConsoleApplication(executable)) { // Allocate a console if there isn't one attached already... ConsoleVisibility.AllocateHiddenConsole(); @@ -532,7 +554,7 @@ private void InitNativeProcess() _isRunningInBackground = true; if (startInfo.UseShellExecute == false) { - _isRunningInBackground = IsWindowsApplication(_nativeProcess.StartInfo.FileName); + _isRunningInBackground = IsWindowsApplication; } } @@ -935,9 +957,9 @@ private static void KillChildProcesses(int parentId, ProcessWithParentId[] curre /// /// /// - private static bool IsConsoleApplication(string fileName) + private static bool CheckIfConsoleApplication(string fileName) { - return !IsWindowsApplication(fileName); + return !CheckIfWindowsApplication(fileName); } /// @@ -946,10 +968,22 @@ private static bool IsConsoleApplication(string fileName) /// /// [ArchitectureSensitive] - private static bool IsWindowsApplication(string fileName) + private static bool CheckIfWindowsApplication(string fileName) { +#if UNIX + return false; +#else if (!Platform.IsWindowsDesktop) { return false; } + // SHGetFileInfo() does not understand reparse points and returns 0 ("non exe or error") + // so we are trying to get a real path before. + // It is a workaround for Microsoft Store applications. + string realPath = Microsoft.PowerShell.Commands.InternalSymbolicLinkLinkCodeMethods.WinInternalGetTarget(fileName); + if (realPath is not null) + { + fileName = realPath; + } + SHFILEINFO shinfo = new SHFILEINFO(); IntPtr type = SHGetFileInfo(fileName, 0, ref shinfo, (uint)Marshal.SizeOf(shinfo), SHGFI_EXETYPE); @@ -968,6 +1002,7 @@ private static bool IsWindowsApplication(string fileName) // anything else - is a windows program... return true; } +#endif } #endregion checkForConsoleApplication @@ -1266,7 +1301,7 @@ private void CalculateIORedirection(out bool redirectOutput, out bool redirectEr redirectOutput = true; redirectError = true; } - else if (Platform.IsWindowsDesktop && IsConsoleApplication(this.Path)) + else if (Platform.IsWindowsDesktop && IsConsoleApplication) { // On Windows desktops, if the command to run is a console application, // then allocate a console if there isn't one attached already... diff --git a/src/System.Management.Automation/namespaces/FileSystemProvider.cs b/src/System.Management.Automation/namespaces/FileSystemProvider.cs index c1a539fb3ac..e4567a96b31 100644 --- a/src/System.Management.Automation/namespaces/FileSystemProvider.cs +++ b/src/System.Management.Automation/namespaces/FileSystemProvider.cs @@ -8073,16 +8073,7 @@ public static string GetTarget(PSObject instance) if (instance.BaseObject is FileSystemInfo fileSysInfo) { #if !UNIX - // We set accessMode parameter to zero because documentation says: - // If this parameter is zero, the application can query certain metadata - // such as file, directory, or device attributes without accessing - // that file or device, even if GENERIC_READ access would have been denied. - using (SafeFileHandle handle = OpenReparsePoint(fileSysInfo.FullName, FileDesiredAccess.GenericZero)) - { - string linkTarget = WinInternalGetTarget(handle); - - return linkTarget; - } + return WinInternalGetTarget(fileSysInfo.FullName); #else return UnixInternalGetTarget(fileSysInfo.FullName); #endif @@ -8382,6 +8373,19 @@ internal static bool WinIsHardLink(ref IntPtr handle) return succeeded && (handleInfo.NumberOfLinks > 1); } +#if !UNIX + internal static string WinInternalGetTarget(string path) + { + // We set accessMode parameter to zero because documentation says: + // If this parameter is zero, the application can query certain metadata + // such as file, directory, or device attributes without accessing + // that file or device, even if GENERIC_READ access would have been denied. + using (SafeFileHandle handle = OpenReparsePoint(path, FileDesiredAccess.GenericZero)) + { + return WinInternalGetTarget(handle); + } + } + [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2001:AvoidCallingProblematicMethods")] private static string WinInternalGetTarget(SafeFileHandle handle) { @@ -8456,6 +8460,7 @@ private static string WinInternalGetTarget(SafeFileHandle handle) Marshal.FreeHGlobal(outBuffer); } } +#endif internal static bool CreateJunction(string path, string target) { From 3b83a686a1f1b8811dc0480e2b671a2577333ceb Mon Sep 17 00:00:00 2001 From: Ilya Date: Sat, 29 Aug 2020 00:03:30 +0500 Subject: [PATCH 25/40] Add null check for args in CommandLineParser (#13451) --- .../host/msh/CommandLineParameterParser.cs | 8 ++++++++ .../resources/CommandLineParameterParserStrings.resx | 3 +++ test/xUnit/csharp/test_CommandLineParser.cs | 9 +++++++++ 3 files changed, 20 insertions(+) diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/CommandLineParameterParser.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/CommandLineParameterParser.cs index f51a6c94410..55b0f1182c3 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/CommandLineParameterParser.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/CommandLineParameterParser.cs @@ -712,6 +712,14 @@ internal void Parse(string[] args) throw new InvalidOperationException("This instance has already been used. Create a new instance."); } + for (int i = 0; i < args.Length; i++) + { + if (args[i] is null) + { + throw new ArgumentNullException(nameof(args), CommandLineParameterParserStrings.NullElementInArgs); + } + } + // Indicates that we've called this method on this instance, and that when it's done, the state variables // will reflect the parse. _dirty = true; diff --git a/src/Microsoft.PowerShell.ConsoleHost/resources/CommandLineParameterParserStrings.resx b/src/Microsoft.PowerShell.ConsoleHost/resources/CommandLineParameterParserStrings.resx index 9703420c254..ab893b91a0a 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/resources/CommandLineParameterParserStrings.resx +++ b/src/Microsoft.PowerShell.ConsoleHost/resources/CommandLineParameterParserStrings.resx @@ -219,4 +219,7 @@ Valid formats are: Parameter -STA is not supported on this platform. + + The specified arguments must not contain null elements. + diff --git a/test/xUnit/csharp/test_CommandLineParser.cs b/test/xUnit/csharp/test_CommandLineParser.cs index 0e15659bf3a..6644b5daef8 100644 --- a/test/xUnit/csharp/test_CommandLineParser.cs +++ b/test/xUnit/csharp/test_CommandLineParser.cs @@ -65,6 +65,15 @@ public static void Test_Throws_On_Reuse() Assert.Throws(() => cpp.Parse(new string[0])); } + [Theory] + [InlineData("arg1", null, "arg3")] + public static void Test_ARGS_With_Null(params string[] commandLine) + { + var cpp = new CommandLineParameterParser(); + + Assert.Throws(() => cpp.Parse(commandLine)); + } + [Theory] [InlineData("noexistfilename")] public static void TestDefaultParameterIsFileName_Not_Exist(params string[] commandLine) From 83079f6397fe40b3b21ebf5276eeebbfe8bf5a0a Mon Sep 17 00:00:00 2001 From: xtqqczze <45661989+xtqqczze@users.noreply.github.com> Date: Sat, 29 Aug 2020 07:21:28 +0100 Subject: [PATCH 26/40] Reformat StringUtil (#13509) --- .../utils/StringUtil.cs | 33 +++++++++---------- 1 file changed, 15 insertions(+), 18 deletions(-) diff --git a/src/System.Management.Automation/utils/StringUtil.cs b/src/System.Management.Automation/utils/StringUtil.cs index 0b74385d335..c84b3f5e9fe 100644 --- a/src/System.Management.Automation/utils/StringUtil.cs +++ b/src/System.Management.Automation/utils/StringUtil.cs @@ -1,6 +1,7 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. +using System.Globalization; using System.Management.Automation.Host; using System.Threading; @@ -8,24 +9,21 @@ namespace System.Management.Automation.Internal { - internal static - class StringUtil + internal static class StringUtil { internal static string Format(string format, object arg0) - => string.Format(Globalization.CultureInfo.CurrentCulture, format, arg0); + => string.Format(CultureInfo.CurrentCulture, format, arg0); internal static string Format(string format, object arg0, object arg1) - => string.Format(Globalization.CultureInfo.CurrentCulture, format, arg0, arg1); + => string.Format(CultureInfo.CurrentCulture, format, arg0, arg1); internal static string Format(string format, object arg0, object arg1, object arg2) - => string.Format(Globalization.CultureInfo.CurrentCulture, format, arg0, arg1, arg2); + => string.Format(CultureInfo.CurrentCulture, format, arg0, arg1, arg2); internal static string Format(string format, params object[] args) - => string.Format(Globalization.CultureInfo.CurrentCulture, format, args); + => string.Format(CultureInfo.CurrentCulture, format, args); - internal static - string - TruncateToBufferCellWidth(PSHostRawUserInterface rawUI, string toTruncate, int maxWidthInBufferCells) + internal static string TruncateToBufferCellWidth(PSHostRawUserInterface rawUI, string toTruncate, int maxWidthInBufferCells) { Dbg.Assert(rawUI != null, "need a reference"); Dbg.Assert(maxWidthInBufferCells >= 0, "maxWidthInBufferCells must be positive"); @@ -58,19 +56,19 @@ internal static // Typical padding is at most a screen's width, any more than that and we won't bother caching. private const int IndentCacheMax = 120; - private static readonly string[] IndentCache = new string[IndentCacheMax]; + private static readonly string[] s_indentCache = new string[IndentCacheMax]; internal static string Padding(int countOfSpaces) { if (countOfSpaces >= IndentCacheMax) return new string(' ', countOfSpaces); - var result = IndentCache[countOfSpaces]; + var result = s_indentCache[countOfSpaces]; if (result == null) { - Interlocked.CompareExchange(ref IndentCache[countOfSpaces], new string(' ', countOfSpaces), null); - result = IndentCache[countOfSpaces]; + Interlocked.CompareExchange(ref s_indentCache[countOfSpaces], new string(' ', countOfSpaces), null); + result = s_indentCache[countOfSpaces]; } return result; @@ -78,23 +76,22 @@ internal static string Padding(int countOfSpaces) private const int DashCacheMax = 120; - private static readonly string[] DashCache = new string[DashCacheMax]; + private static readonly string[] s_dashCache = new string[DashCacheMax]; internal static string DashPadding(int count) { if (count >= DashCacheMax) return new string('-', count); - var result = DashCache[count]; + var result = s_dashCache[count]; if (result == null) { - Interlocked.CompareExchange(ref DashCache[count], new string('-', count), null); - result = DashCache[count]; + Interlocked.CompareExchange(ref s_dashCache[count], new string('-', count), null); + result = s_dashCache[count]; } return result; } } } - From 3543491909f7448f363dc7971d6a7cd96970ee05 Mon Sep 17 00:00:00 2001 From: Aditya Patwardhan Date: Sat, 29 Aug 2020 12:27:50 -0700 Subject: [PATCH 27/40] Change stage dependency for docker release stage in release pipeline (#13512) --- tools/releaseBuild/azureDevOps/releasePipeline.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tools/releaseBuild/azureDevOps/releasePipeline.yml b/tools/releaseBuild/azureDevOps/releasePipeline.yml index c9a0bc8d9e1..9c752a179d9 100644 --- a/tools/releaseBuild/azureDevOps/releasePipeline.yml +++ b/tools/releaseBuild/azureDevOps/releasePipeline.yml @@ -198,7 +198,7 @@ stages: - stage: ReleaseDocker displayName: Release Docker dependsOn: - - StartDocker + - GitHubManualTasks jobs: - deployment: ReleaseDocker displayName: Release Docker From 6a37eb9313077f726c4bca7902466a1f5a6a3f44 Mon Sep 17 00:00:00 2001 From: Robert Holt Date: Mon, 31 Aug 2020 10:38:05 -0700 Subject: [PATCH 28/40] Update to .NET 5 preview 8 (#13530) --- DotnetRuntimeMetadata.json | 8 ++++---- assets/files.wxs | 8 ++++---- global.json | 2 +- .../FilterRules/FilterRuleExtensions.cs | 4 ++++ .../Microsoft.PowerShell.GraphicalHost.csproj | 4 +++- ...soft.PowerShell.Commands.Management.csproj | 2 +- .../commands/management/Process.cs | 2 ++ ...crosoft.PowerShell.Commands.Utility.csproj | 4 ++-- .../host/msh/ConsoleControl.cs | 2 ++ .../host/msh/ConsoleHostUserInterface.cs | 2 ++ ...crosoft.PowerShell.CoreCLR.Eventing.csproj | 2 +- .../Microsoft.PowerShell.SDK.csproj | 8 ++++---- .../Microsoft.WSMan.Management.csproj | 2 +- .../System.Management.Automation.csproj | 20 +++++++++---------- .../WireDataFormat/RemoteSessionCapability.cs | 2 ++ .../namespaces/FileSystemProvider.cs | 6 +++--- .../utils/EncodingUtils.cs | 8 +++++--- .../powershell-win-core.csproj | 20 +++++-------------- test/tools/TestService/TestService.csproj | 2 +- test/tools/WebListener/WebListener.csproj | 4 ++-- ...crosoft.PowerShell.Commands.Utility.csproj | 2 +- .../System.Management.Automation.csproj | 4 ++-- 22 files changed, 62 insertions(+), 56 deletions(-) diff --git a/DotnetRuntimeMetadata.json b/DotnetRuntimeMetadata.json index ffd8f438071..119291dccc5 100644 --- a/DotnetRuntimeMetadata.json +++ b/DotnetRuntimeMetadata.json @@ -1,8 +1,8 @@ { "sdk": { - "channel": "release/5.0.1xx-preview7", - "packageVersionPattern": "5.0.0-preview.7", - "sdkImageVersion": "5.0.100-preview.7", - "nextChannel": "net5/preview7" + "channel": "release/5.0.1xx-preview8", + "packageVersionPattern": "5.0.0-preview.8", + "sdkImageVersion": "5.0.100-preview.8", + "nextChannel": "net5/preview8" } } diff --git a/assets/files.wxs b/assets/files.wxs index 5d7b42ca97e..a5d09c2604b 100644 --- a/assets/files.wxs +++ b/assets/files.wxs @@ -3105,12 +3105,12 @@ - - - + + + @@ -4112,8 +4112,8 @@ - + diff --git a/global.json b/global.json index 8255d028e95..fe1d9f915f6 100644 --- a/global.json +++ b/global.json @@ -1,5 +1,5 @@ { "sdk": { - "version": "5.0.100-preview.7.20366.15" + "version": "5.0.100-preview.8.20417.9" } } diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/FilterRuleExtensions.cs b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/FilterRuleExtensions.cs index cb0a79de775..4a09321edb2 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/FilterRuleExtensions.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/FilterRuleExtensions.cs @@ -40,10 +40,14 @@ public static FilterRule DeepCopy(this FilterRule rule) FilterRule copy = null; try { +#pragma warning disable MSLIB0003 formatter.Serialize(ms, rule); +#pragma warning restore MSLIB0003 ms.Position = 0; +#pragma warning disable MSLIB0003 copy = (FilterRule)formatter.Deserialize(ms); +#pragma warning restore MSLIB0003 } finally { diff --git a/src/Microsoft.Management.UI.Internal/Microsoft.PowerShell.GraphicalHost.csproj b/src/Microsoft.Management.UI.Internal/Microsoft.PowerShell.GraphicalHost.csproj index 466511d6d22..72eb8d6572f 100644 --- a/src/Microsoft.Management.UI.Internal/Microsoft.PowerShell.GraphicalHost.csproj +++ b/src/Microsoft.Management.UI.Internal/Microsoft.PowerShell.GraphicalHost.csproj @@ -1,4 +1,4 @@ - + Assembly containing WPF code for Out-GridView, HelpWindow, and Show-Command @@ -6,6 +6,8 @@ Microsoft.Management.UI.Internal Microsoft.PowerShell.GraphicalHost True + Windows + 7.0 diff --git a/src/Microsoft.PowerShell.Commands.Management/Microsoft.PowerShell.Commands.Management.csproj b/src/Microsoft.PowerShell.Commands.Management/Microsoft.PowerShell.Commands.Management.csproj index 67a70166185..4b04038e4af 100644 --- a/src/Microsoft.PowerShell.Commands.Management/Microsoft.PowerShell.Commands.Management.csproj +++ b/src/Microsoft.PowerShell.Commands.Management/Microsoft.PowerShell.Commands.Management.csproj @@ -47,7 +47,7 @@ - + diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/Process.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/Process.cs index b825266e6ef..b05ce1e0e69 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/Process.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/Process.cs @@ -784,8 +784,10 @@ private static string RetrieveProcessUserName(Process process) // The buffer length must be +1, last position is for a null string terminator. int userNameLength = 257; int domainNameLength = 16; +#pragma warning disable CA2014 Span userNameStr = stackalloc char[userNameLength]; Span domainNameStr = stackalloc char[domainNameLength]; +#pragma warning restore CA2014 Win32Native.SID_NAME_USE accountType; // userNameLength and domainNameLength will be set to actual lengths. diff --git a/src/Microsoft.PowerShell.Commands.Utility/Microsoft.PowerShell.Commands.Utility.csproj b/src/Microsoft.PowerShell.Commands.Utility/Microsoft.PowerShell.Commands.Utility.csproj index efdd37f4223..8225e03452d 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/Microsoft.PowerShell.Commands.Utility.csproj +++ b/src/Microsoft.PowerShell.Commands.Utility/Microsoft.PowerShell.Commands.Utility.csproj @@ -32,8 +32,8 @@ - - + + diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleControl.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleControl.cs index 0403fdf41f9..1fec13c464e 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleControl.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleControl.cs @@ -2576,7 +2576,9 @@ internal static void WriteConsole(ConsoleHandle consoleHandle, ReadOnlySpan outBufferLine = stackalloc char[outBuffer.Length + endOfLineLength]; +#pragma warning restore CA2014 outBuffer.CopyTo(outBufferLine); endOfLine.CopyTo(outBufferLine.Slice(outBufferLine.Length - endOfLineLength)); WriteConsole(consoleHandle, outBufferLine); diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterface.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterface.cs index b48af7eabbe..2d494cf701c 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterface.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterface.cs @@ -305,7 +305,9 @@ private object ReadLineSafe(bool isSecureString, char? printToken) ConsoleKeyInfo keyInfo = Console.ReadKey(true); #else const int CharactersToRead = 1; +#pragma warning disable CA2014 Span inputBuffer = stackalloc char[CharactersToRead + 1]; +#pragma warning restore CA2014 string key = ConsoleControl.ReadConsole(handle, initialContentLength: 0, inputBuffer, charactersToRead: CharactersToRead, endOnTab: false, out _); #endif diff --git a/src/Microsoft.PowerShell.CoreCLR.Eventing/Microsoft.PowerShell.CoreCLR.Eventing.csproj b/src/Microsoft.PowerShell.CoreCLR.Eventing/Microsoft.PowerShell.CoreCLR.Eventing.csproj index 6a0944359a0..09bb1c95a9a 100644 --- a/src/Microsoft.PowerShell.CoreCLR.Eventing/Microsoft.PowerShell.CoreCLR.Eventing.csproj +++ b/src/Microsoft.PowerShell.CoreCLR.Eventing/Microsoft.PowerShell.CoreCLR.Eventing.csproj @@ -8,7 +8,7 @@ - + diff --git a/src/Microsoft.PowerShell.SDK/Microsoft.PowerShell.SDK.csproj b/src/Microsoft.PowerShell.SDK/Microsoft.PowerShell.SDK.csproj index 45ed6de5124..6798baf83a3 100644 --- a/src/Microsoft.PowerShell.SDK/Microsoft.PowerShell.SDK.csproj +++ b/src/Microsoft.PowerShell.SDK/Microsoft.PowerShell.SDK.csproj @@ -18,9 +18,9 @@ - - - + + + @@ -30,7 +30,7 @@ - + diff --git a/src/Microsoft.WSMan.Management/Microsoft.WSMan.Management.csproj b/src/Microsoft.WSMan.Management/Microsoft.WSMan.Management.csproj index fd826ae01af..a63b2596315 100644 --- a/src/Microsoft.WSMan.Management/Microsoft.WSMan.Management.csproj +++ b/src/Microsoft.WSMan.Management/Microsoft.WSMan.Management.csproj @@ -9,7 +9,7 @@ - + diff --git a/src/System.Management.Automation/System.Management.Automation.csproj b/src/System.Management.Automation/System.Management.Automation.csproj index ae6bd145a5f..e0d81d95088 100644 --- a/src/System.Management.Automation/System.Management.Automation.csproj +++ b/src/System.Management.Automation/System.Management.Automation.csproj @@ -16,16 +16,16 @@ - - - - - - - - - - + + + + + + + + + + diff --git a/src/System.Management.Automation/engine/remoting/common/WireDataFormat/RemoteSessionCapability.cs b/src/System.Management.Automation/engine/remoting/common/WireDataFormat/RemoteSessionCapability.cs index 86f43cbcc42..3c631c0f4ae 100644 --- a/src/System.Management.Automation/engine/remoting/common/WireDataFormat/RemoteSessionCapability.cs +++ b/src/System.Management.Automation/engine/remoting/common/WireDataFormat/RemoteSessionCapability.cs @@ -107,7 +107,9 @@ internal static byte[] GetCurrentTimeZoneInByteFormat() BinaryFormatter formatter = new BinaryFormatter(); using (MemoryStream stream = new MemoryStream()) { +#pragma warning disable MSLIB0003 formatter.Serialize(stream, TimeZoneInfo.Local); +#pragma warning restore MSLIB0003 stream.Seek(0, SeekOrigin.Begin); byte[] result = new byte[stream.Length]; stream.Read(result, 0, (int)stream.Length); diff --git a/src/System.Management.Automation/namespaces/FileSystemProvider.cs b/src/System.Management.Automation/namespaces/FileSystemProvider.cs index e4567a96b31..b548e4b9195 100644 --- a/src/System.Management.Automation/namespaces/FileSystemProvider.cs +++ b/src/System.Management.Automation/namespaces/FileSystemProvider.cs @@ -7617,9 +7617,9 @@ public Encoding Encoding set { -#pragma warning disable 612, 618 - if (value == System.Text.Encoding.UTF7) -#pragma warning restore 612, 618 + // Check for UTF-7 by checking for code page 65000 + // See: https://docs.microsoft.com/en-us/dotnet/core/compatibility/corefx#utf-7-code-paths-are-obsolete + if (value != null && value.CodePage == 65000) { _provider.WriteWarning(PathUtilsStrings.Utf7EncodingObsolete); } diff --git a/src/System.Management.Automation/utils/EncodingUtils.cs b/src/System.Management.Automation/utils/EncodingUtils.cs index abbe4a569f6..366d749441e 100644 --- a/src/System.Management.Automation/utils/EncodingUtils.cs +++ b/src/System.Management.Automation/utils/EncodingUtils.cs @@ -38,7 +38,9 @@ internal static class EncodingConversion { Default, ClrFacade.GetDefaultEncoding() }, { OEM, ClrFacade.GetOEMEncoding() }, { Unicode, System.Text.Encoding.Unicode }, +#pragma warning disable MSLIB0001 { Utf7, System.Text.Encoding.UTF7 }, +#pragma warning restore MSLIB0001 { Utf8, ClrFacade.GetDefaultEncoding() }, { Utf8Bom, System.Text.Encoding.UTF8 }, { Utf8NoBom, ClrFacade.GetDefaultEncoding() }, @@ -95,9 +97,9 @@ internal static Encoding Convert(Cmdlet cmdlet, string encoding) /// The encoding to check for obsolescence. internal static void WarnIfObsolete(Cmdlet cmdlet, Encoding encoding) { -#pragma warning disable 612, 618 - if (encoding == System.Text.Encoding.UTF7) -#pragma warning restore 612, 618 + // Check for UTF-7 by checking for code page 65000 + // See: https://docs.microsoft.com/en-us/dotnet/core/compatibility/corefx#utf-7-code-paths-are-obsolete + if (encoding != null && encoding.CodePage == 65000) { cmdlet.WriteWarning(PathUtilsStrings.Utf7EncodingObsolete); } diff --git a/src/powershell-win-core/powershell-win-core.csproj b/src/powershell-win-core/powershell-win-core.csproj index f2c31f6ff22..16f625827d4 100644 --- a/src/powershell-win-core/powershell-win-core.csproj +++ b/src/powershell-win-core/powershell-win-core.csproj @@ -11,23 +11,11 @@ win7-x86;win7-x64 Microsoft.PowerShell ..\..\assets\pwsh.manifest + Windows + 7.0 - - - Microsoft.NET.Sdk.WindowsDesktop - - - - - - - - - - true - true - + @@ -64,4 +52,6 @@ + + diff --git a/test/tools/TestService/TestService.csproj b/test/tools/TestService/TestService.csproj index 93950793985..97d0c463760 100644 --- a/test/tools/TestService/TestService.csproj +++ b/test/tools/TestService/TestService.csproj @@ -12,7 +12,7 @@ - + diff --git a/test/tools/WebListener/WebListener.csproj b/test/tools/WebListener/WebListener.csproj index 2948ec0696d..f9b93fa7756 100644 --- a/test/tools/WebListener/WebListener.csproj +++ b/test/tools/WebListener/WebListener.csproj @@ -7,8 +7,8 @@ - - + + diff --git a/tools/packaging/projects/reference/Microsoft.PowerShell.Commands.Utility/Microsoft.PowerShell.Commands.Utility.csproj b/tools/packaging/projects/reference/Microsoft.PowerShell.Commands.Utility/Microsoft.PowerShell.Commands.Utility.csproj index 46738ca931f..7630af87df9 100644 --- a/tools/packaging/projects/reference/Microsoft.PowerShell.Commands.Utility/Microsoft.PowerShell.Commands.Utility.csproj +++ b/tools/packaging/projects/reference/Microsoft.PowerShell.Commands.Utility/Microsoft.PowerShell.Commands.Utility.csproj @@ -14,6 +14,6 @@ - + diff --git a/tools/packaging/projects/reference/System.Management.Automation/System.Management.Automation.csproj b/tools/packaging/projects/reference/System.Management.Automation/System.Management.Automation.csproj index 8c5dcc0bb7e..6e5dc7b458b 100644 --- a/tools/packaging/projects/reference/System.Management.Automation/System.Management.Automation.csproj +++ b/tools/packaging/projects/reference/System.Management.Automation/System.Management.Automation.csproj @@ -9,7 +9,7 @@ - - + + From 8f37cced709168f313a00b2e3ee7088495bbcd7a Mon Sep 17 00:00:00 2001 From: xtqqczze <45661989+xtqqczze@users.noreply.github.com> Date: Mon, 31 Aug 2020 19:39:00 +0100 Subject: [PATCH 29/40] Cleanup: remove duplicate words in comments (#13539) --- .../commands/management/Navigation.cs | 2 +- .../commands/utility/ReadConsoleCmdlet.cs | 4 ++-- .../host/msh/ConsoleControl.cs | 2 +- src/Microsoft.WSMan.Management/InvokeWSManAction.cs | 2 +- src/Microsoft.WSMan.Management/WSManInstance.cs | 8 ++++---- .../CoreCLR/CorePsPlatform.cs | 4 ++-- .../DscSupport/CimDSCParser.cs | 2 +- .../common/DisplayDatabase/typeDataManager.cs | 4 ++-- src/System.Management.Automation/engine/AliasInfo.cs | 2 +- .../engine/CmdletParameterBinderController.cs | 2 +- .../engine/DataStoreAdapter.cs | 2 +- .../engine/Modules/ModuleCmdletBase.cs | 4 ++-- src/System.Management.Automation/engine/MshMemberInfo.cs | 2 +- .../engine/MshObjectTypeDescriptor.cs | 4 ++-- .../engine/NativeCommandProcessor.cs | 2 +- .../engine/hostifaces/History.cs | 2 +- .../engine/hostifaces/PowerShell.cs | 2 +- .../engine/remoting/commands/ConnectPSSession.cs | 2 +- .../remoting/common/WireDataFormat/EncodeAndDecode.cs | 2 +- .../engine/remoting/common/fragmentor.cs | 2 +- .../engine/remoting/server/ServerRunspacePoolDriver.cs | 2 +- .../help/CommandHelpProvider.cs | 2 +- .../namespaces/FileSystemProvider.cs | 2 +- src/System.Management.Automation/utils/IObjectWriter.cs | 2 +- src/System.Management.Automation/utils/MshTraceSource.cs | 2 +- src/System.Management.Automation/utils/ObjectStream.cs | 4 ++-- src/System.Management.Automation/utils/ObjectWriter.cs | 2 +- .../utils/StructuredTraceSource.cs | 2 +- 28 files changed, 37 insertions(+), 37 deletions(-) diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/Navigation.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/Navigation.cs index 4389f657f69..dc003cc7562 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/Navigation.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/Navigation.cs @@ -654,7 +654,7 @@ public string Path } /// - /// Gets or sets the path path property, when bound from the pipeline. + /// Gets or sets the path property, when bound from the pipeline. /// [Parameter(ParameterSetName = LiteralPathParameterSet, Mandatory = true, ValueFromPipeline = false, ValueFromPipelineByPropertyName = true)] diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ReadConsoleCmdlet.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ReadConsoleCmdlet.cs index 997bae76554..2eb71f1ca5d 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ReadConsoleCmdlet.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ReadConsoleCmdlet.cs @@ -52,7 +52,7 @@ public sealed class ReadHostCommand : PSCmdlet } /// - /// Gets or sets to no echo the input as is is typed. If set then the cmdlet returns a secure string. + /// Gets or sets to no echo the input as is typed. If set then the cmdlet returns a secure string. /// [Parameter(ParameterSetName = "AsSecureString")] public @@ -71,7 +71,7 @@ public sealed class ReadHostCommand : PSCmdlet } /// - /// Gets or sets whether the console will echo the input as is is typed. If set then the cmdlet returns a regular string. + /// Gets or sets whether the console will echo the input as is typed. If set then the cmdlet returns a regular string. /// [Parameter(ParameterSetName = "AsString")] public diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleControl.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleControl.cs index 1fec13c464e..26bdc72a851 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleControl.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleControl.cs @@ -447,7 +447,7 @@ internal enum KeyboardFlag : uint /// /// The window to show... /// The command to do. - /// True it it was successful. + /// True if it was successful. [DllImport("user32.dll")] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool ShowWindow(IntPtr hWnd, Int32 nCmdShow); diff --git a/src/Microsoft.WSMan.Management/InvokeWSManAction.cs b/src/Microsoft.WSMan.Management/InvokeWSManAction.cs index 7c217b0ea9a..1472a26f016 100644 --- a/src/Microsoft.WSMan.Management/InvokeWSManAction.cs +++ b/src/Microsoft.WSMan.Management/InvokeWSManAction.cs @@ -156,7 +156,7 @@ public Int32 Port /// /// The following is the definition of the input parameter "SelectorSet". /// SelectorSet is a hash table which helps in identify an instance of the - /// management resource if there are are more than 1 instance of the resource + /// management resource if there are more than 1 instance of the resource /// class. /// [Parameter(Position = 2, diff --git a/src/Microsoft.WSMan.Management/WSManInstance.cs b/src/Microsoft.WSMan.Management/WSManInstance.cs index ca299f1c085..fa96cacf780 100644 --- a/src/Microsoft.WSMan.Management/WSManInstance.cs +++ b/src/Microsoft.WSMan.Management/WSManInstance.cs @@ -306,7 +306,7 @@ public string ReturnType /// /// The following is the definition of the input parameter "SelectorSet". /// SelectorSet is a hash table which helps in identify an instance of the - /// management resource if there are are more than 1 instance of the resource + /// management resource if there are more than 1 instance of the resource /// class. /// [Parameter( @@ -800,7 +800,7 @@ public Uri ResourceURI /// /// The following is the definition of the input parameter "SelectorSet". /// SelectorSet is a hash table which helps in identify an instance of the - /// management resource if there are are more than 1 instance of the resource + /// management resource if there are more than 1 instance of the resource /// class. /// [Parameter(Position = 1, @@ -1121,7 +1121,7 @@ public Uri ResourceURI /// /// The following is the definition of the input parameter "SelectorSet". /// SelectorSet is a hash table which helps in identify an instance of the - /// management resource if there are are more than 1 instance of the resource + /// management resource if there are more than 1 instance of the resource /// class. /// [Parameter(Position = 1, Mandatory = true, @@ -1398,7 +1398,7 @@ public Uri ResourceURI /// /// The following is the definition of the input parameter "SelectorSet". /// SelectorSet is a hash table which helps in identify an instance of the - /// management resource if there are are more than 1 instance of the resource + /// management resource if there are more than 1 instance of the resource /// class. /// [Parameter(Mandatory = true, Position = 1, diff --git a/src/System.Management.Automation/CoreCLR/CorePsPlatform.cs b/src/System.Management.Automation/CoreCLR/CorePsPlatform.cs index 4e572586c98..df416a3dc2b 100644 --- a/src/System.Management.Automation/CoreCLR/CorePsPlatform.cs +++ b/src/System.Management.Automation/CoreCLR/CorePsPlatform.cs @@ -1159,10 +1159,10 @@ internal struct CommonStatStruct /// This filesystem item is a socket. internal int IsSocket; - /// This filesystem item will run as the the owner if executed. + /// This filesystem item will run as the owner if executed. internal int IsSetUid; - /// This filesystem item will run as the the group if executed. + /// This filesystem item will run as the group if executed. internal int IsSetGid; /// Whether the sticky bit is set on the filesystem item. diff --git a/src/System.Management.Automation/DscSupport/CimDSCParser.cs b/src/System.Management.Automation/DscSupport/CimDSCParser.cs index 58fc81715bb..9bf847757a5 100644 --- a/src/System.Management.Automation/DscSupport/CimDSCParser.cs +++ b/src/System.Management.Automation/DscSupport/CimDSCParser.cs @@ -455,7 +455,7 @@ internal List ParseSchemaMof(string filePath) } /// - /// Make sure that the instance conforms to the the schema. + /// Make sure that the instance conforms to the schema. /// /// internal void ValidateInstanceText(string classText) diff --git a/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/typeDataManager.cs b/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/typeDataManager.cs index 985561670f8..65dd6934682 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/typeDataManager.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/typeDataManager.cs @@ -533,7 +533,7 @@ private static void ProcessBuiltinFormatViewDefinitions( } /// - /// Helper to to add any pre-load intrinsics to the db. + /// Helper to add any pre-load intrinsics to the db. /// /// Db being initialized. private static void AddPreLoadIntrinsics(TypeInfoDataBase db) @@ -542,7 +542,7 @@ private static void AddPreLoadIntrinsics(TypeInfoDataBase db) } /// - /// Helper to to add any post-load intrinsics to the db. + /// Helper to add any post-load intrinsics to the db. /// /// Db being initialized. private static void AddPostLoadIntrinsics(TypeInfoDataBase db) diff --git a/src/System.Management.Automation/engine/AliasInfo.cs b/src/System.Management.Automation/engine/AliasInfo.cs index bd209c6afe8..94acdecf628 100644 --- a/src/System.Management.Automation/engine/AliasInfo.cs +++ b/src/System.Management.Automation/engine/AliasInfo.cs @@ -337,7 +337,7 @@ internal void SetOptions(ScopedItemOptions newOptions, bool force) /// If ResolvedCommand returns null, this property will /// return the name of the command that could not be resolved. /// If ResolvedCommand has not yet been called or was able - /// to resolve the command, this this property will return null. + /// to resolve the command, this property will return null. /// internal string UnresolvedCommandName { get; private set; } diff --git a/src/System.Management.Automation/engine/CmdletParameterBinderController.cs b/src/System.Management.Automation/engine/CmdletParameterBinderController.cs index 4e286302431..a8d9b4b4ff6 100644 --- a/src/System.Management.Automation/engine/CmdletParameterBinderController.cs +++ b/src/System.Management.Automation/engine/CmdletParameterBinderController.cs @@ -551,7 +551,7 @@ private Dictionary GetQualifiedParameter } /// - /// Get the aliases of the the current cmdlet. + /// Get the aliases of the current cmdlet. /// /// private List GetAliasOfCurrentCmdlet() diff --git a/src/System.Management.Automation/engine/DataStoreAdapter.cs b/src/System.Management.Automation/engine/DataStoreAdapter.cs index c7db11bf081..e44a2a3c0b3 100644 --- a/src/System.Management.Automation/engine/DataStoreAdapter.cs +++ b/src/System.Management.Automation/engine/DataStoreAdapter.cs @@ -430,7 +430,7 @@ public PSDriveInfo( /// If null, the current user credential is used. /// /// - /// It indicates if the the created PSDrive would be + /// It indicates if the created PSDrive would be /// persisted across PowerShell sessions. /// /// diff --git a/src/System.Management.Automation/engine/Modules/ModuleCmdletBase.cs b/src/System.Management.Automation/engine/Modules/ModuleCmdletBase.cs index f1f8aaff1f7..29cc066324f 100644 --- a/src/System.Management.Automation/engine/Modules/ModuleCmdletBase.cs +++ b/src/System.Management.Automation/engine/Modules/ModuleCmdletBase.cs @@ -6493,7 +6493,7 @@ private PSModuleInfo AnalyzeScriptFile(string filename, bool force, ExecutionCon /// /// Load a binary module. A binary module is an assembly that should contain cmdlets. /// - /// If true, then then the registered snapins will also be searched when loading. + /// If true, then the registered snapins will also be searched when loading. /// The name of the snapin or assembly to load. /// The path to the assembly to load. /// The assembly to load so no lookup need be done. @@ -6523,7 +6523,7 @@ internal PSModuleInfo LoadBinaryModule(bool trySnapInName, string moduleName, st /// Load a binary module. A binary module is an assembly that should contain cmdlets. /// /// The parent module for which this module is a nested module. - /// If true, then then the registered snapins will also be searched when loading. + /// If true, then the registered snapins will also be searched when loading. /// The name of the snapin or assembly to load. /// The path to the assembly to load. /// The assembly to load so no lookup need be done. diff --git a/src/System.Management.Automation/engine/MshMemberInfo.cs b/src/System.Management.Automation/engine/MshMemberInfo.cs index cb75b1519ce..ab1369822ea 100644 --- a/src/System.Management.Automation/engine/MshMemberInfo.cs +++ b/src/System.Management.Automation/engine/MshMemberInfo.cs @@ -426,7 +426,7 @@ public PSAliasProperty(string name, string referencedMemberName, Type conversion internal PSMemberInfo ReferencedMember => this.LookupMember(ReferencedMemberName); /// - /// Gets the the type to convert the referenced member's value. It might be + /// Gets the type to convert the referenced member's value. It might be /// null when no conversion is done. /// public Type ConversionType { get; private set; } diff --git a/src/System.Management.Automation/engine/MshObjectTypeDescriptor.cs b/src/System.Management.Automation/engine/MshObjectTypeDescriptor.cs index ee54859a1ea..8fe26b1437c 100644 --- a/src/System.Management.Automation/engine/MshObjectTypeDescriptor.cs +++ b/src/System.Management.Automation/engine/MshObjectTypeDescriptor.cs @@ -31,7 +31,7 @@ public class SettingValueExceptionEventArgs : EventArgs public Exception Exception { get; } /// - /// Initializes a new instance of setting the value of of the exception that triggered the associated event. + /// Initializes a new instance of setting the value of the exception that triggered the associated event. /// /// Exception that triggered the associated event. internal SettingValueExceptionEventArgs(Exception exception) @@ -64,7 +64,7 @@ public class GettingValueExceptionEventArgs : EventArgs public Exception Exception { get; } /// - /// Initializes a new instance of setting the value of of the exception that triggered the associated event. + /// Initializes a new instance of setting the value of the exception that triggered the associated event. /// /// Exception that triggered the associated event. internal GettingValueExceptionEventArgs(Exception exception) diff --git a/src/System.Management.Automation/engine/NativeCommandProcessor.cs b/src/System.Management.Automation/engine/NativeCommandProcessor.cs index 05b316f0de0..b9c101edcd4 100644 --- a/src/System.Management.Automation/engine/NativeCommandProcessor.cs +++ b/src/System.Management.Automation/engine/NativeCommandProcessor.cs @@ -1973,7 +1973,7 @@ internal static class ConsoleVisibility /// /// The window to show... /// The command to do. - /// True it it was successful. + /// True if it was successful. [DllImport("user32.dll")] internal static extern bool ShowWindow(IntPtr hWnd, int nCmdShow); diff --git a/src/System.Management.Automation/engine/hostifaces/History.cs b/src/System.Management.Automation/engine/hostifaces/History.cs index 278f15aceee..26496f74ef7 100644 --- a/src/System.Management.Automation/engine/hostifaces/History.cs +++ b/src/System.Management.Automation/engine/hostifaces/History.cs @@ -1413,7 +1413,7 @@ void ProcessRecord() } /// - /// Convert mshObject that has has the properties of an HistoryInfo + /// Convert mshObject that has the properties of an HistoryInfo /// object in to HistoryInfo object. /// /// diff --git a/src/System.Management.Automation/engine/hostifaces/PowerShell.cs b/src/System.Management.Automation/engine/hostifaces/PowerShell.cs index e5015a010a6..12a4ffce7ab 100644 --- a/src/System.Management.Automation/engine/hostifaces/PowerShell.cs +++ b/src/System.Management.Automation/engine/hostifaces/PowerShell.cs @@ -3824,7 +3824,7 @@ public Task StopAsync(AsyncCallback callback, object state) #region Event Handlers /// - /// Handler for state changed changed events for the currently running pipeline. + /// Handler for state changed events for the currently running pipeline. /// /// /// Source of the event. diff --git a/src/System.Management.Automation/engine/remoting/commands/ConnectPSSession.cs b/src/System.Management.Automation/engine/remoting/commands/ConnectPSSession.cs index 5f66afdfac1..c85b88eb26c 100644 --- a/src/System.Management.Automation/engine/remoting/commands/ConnectPSSession.cs +++ b/src/System.Management.Automation/engine/remoting/commands/ConnectPSSession.cs @@ -22,7 +22,7 @@ namespace Microsoft.PowerShell.Commands /// state and returns those PS session objects in the Opened state. One or more /// session objects can be specified for connecting, or a remote computer name can /// be specified and in this case all disconnected remote runspaces found on the - /// remote computer will be be connected and PSSession objects created on the local + /// remote computer will be connected and PSSession objects created on the local /// machine. /// /// The cmdlet can be used in the following ways: diff --git a/src/System.Management.Automation/engine/remoting/common/WireDataFormat/EncodeAndDecode.cs b/src/System.Management.Automation/engine/remoting/common/WireDataFormat/EncodeAndDecode.cs index 85ba02b2e7b..9188263fd54 100644 --- a/src/System.Management.Automation/engine/remoting/common/WireDataFormat/EncodeAndDecode.cs +++ b/src/System.Management.Automation/engine/remoting/common/WireDataFormat/EncodeAndDecode.cs @@ -1541,7 +1541,7 @@ internal static RemoteDataObject GeneratePowerShellStateInfo(PSInvocationStateIn /// /// /// ErrorRecord if exception is of type IContainsErrorRecord - /// Null if if exception is not of type IContainsErrorRecord + /// Null if exception is not of type IContainsErrorRecord /// internal static ErrorRecord GetErrorRecordFromException(Exception exception) { diff --git a/src/System.Management.Automation/engine/remoting/common/fragmentor.cs b/src/System.Management.Automation/engine/remoting/common/fragmentor.cs index 2ebe434ea04..881dc17802a 100644 --- a/src/System.Management.Automation/engine/remoting/common/fragmentor.cs +++ b/src/System.Management.Automation/engine/remoting/common/fragmentor.cs @@ -364,7 +364,7 @@ internal static bool GetIsStartFragment(byte[] fragmentBytes, int startIndex) /// /// /// - /// True if the the E-flag is set in the encoding. Otherwise false. + /// True if the E-flag is set in the encoding. Otherwise false. /// /// /// If fragmentBytes is null. diff --git a/src/System.Management.Automation/engine/remoting/server/ServerRunspacePoolDriver.cs b/src/System.Management.Automation/engine/remoting/server/ServerRunspacePoolDriver.cs index 10814c3ea2b..486383ec4dc 100644 --- a/src/System.Management.Automation/engine/remoting/server/ServerRunspacePoolDriver.cs +++ b/src/System.Management.Automation/engine/remoting/server/ServerRunspacePoolDriver.cs @@ -1115,7 +1115,7 @@ private void HandleGetAvailableRunspacesReceived(object sender, RemoteDataEventA } /// - /// Forces a state reset on a single runspace runspace pool. + /// Forces a state reset on a single runspace pool. /// /// /// diff --git a/src/System.Management.Automation/help/CommandHelpProvider.cs b/src/System.Management.Automation/help/CommandHelpProvider.cs index c460cc6647b..7dd893d2c7c 100644 --- a/src/System.Management.Automation/help/CommandHelpProvider.cs +++ b/src/System.Management.Automation/help/CommandHelpProvider.cs @@ -1244,7 +1244,7 @@ private static bool Match(string target, ICollection patterns) } /// - /// Process helpInfo forwarded over from other other providers, specificly AliasHelpProvider. + /// Process helpInfo forwarded over from other providers, specificly AliasHelpProvider. /// This can return more than 1 helpinfo object. /// /// HelpInfo that is forwarded over. diff --git a/src/System.Management.Automation/namespaces/FileSystemProvider.cs b/src/System.Management.Automation/namespaces/FileSystemProvider.cs index b548e4b9195..141181824e7 100644 --- a/src/System.Management.Automation/namespaces/FileSystemProvider.cs +++ b/src/System.Management.Automation/namespaces/FileSystemProvider.cs @@ -7120,7 +7120,7 @@ private static class NativeMethods /// network resource. /// /// - /// The The netResource structure contains information + /// The netResource structure contains information /// about a network resource. /// /// The password used to get connected to network resource. diff --git a/src/System.Management.Automation/utils/IObjectWriter.cs b/src/System.Management.Automation/utils/IObjectWriter.cs index 5a6afad9514..eaed1ef5e55 100644 --- a/src/System.Management.Automation/utils/IObjectWriter.cs +++ b/src/System.Management.Automation/utils/IObjectWriter.cs @@ -115,7 +115,7 @@ public abstract int MaxCapacity /// /// /// If the enumeration contains elements equal to - /// AutomationNull.Value, they are are ignored. + /// AutomationNull.Value, they are ignored. /// This can cause the return value to be less than the size of /// the collection. /// diff --git a/src/System.Management.Automation/utils/MshTraceSource.cs b/src/System.Management.Automation/utils/MshTraceSource.cs index 9bb0cfbcc3d..946267d2800 100644 --- a/src/System.Management.Automation/utils/MshTraceSource.cs +++ b/src/System.Management.Automation/utils/MshTraceSource.cs @@ -10,7 +10,7 @@ namespace System.Management.Automation { /// /// An PSTraceSource is a representation of a System.Diagnostics.TraceSource instance - /// that is used the the Monad components to produce trace output. + /// that is used in the Monad components to produce trace output. /// /// /// It is permitted to subclass diff --git a/src/System.Management.Automation/utils/ObjectStream.cs b/src/System.Management.Automation/utils/ObjectStream.cs index eccfdfad901..bd3fb0c6a64 100644 --- a/src/System.Management.Automation/utils/ObjectStream.cs +++ b/src/System.Management.Automation/utils/ObjectStream.cs @@ -287,7 +287,7 @@ internal virtual int Write(object value) /// /// /// If the enumeration contains elements equal to - /// AutomationNull.Value, they are are ignored. + /// AutomationNull.Value, they are ignored. /// This can cause the return value to be less than the size of /// the collection. /// @@ -1317,7 +1317,7 @@ internal override object Peek() /// /// /// If the enumeration contains elements equal to - /// AutomationNull.Value, they are are ignored. + /// AutomationNull.Value, they are ignored. /// This can cause the return value to be less than the size of /// the collection. /// diff --git a/src/System.Management.Automation/utils/ObjectWriter.cs b/src/System.Management.Automation/utils/ObjectWriter.cs index d4fe3493b78..f6bf752062e 100644 --- a/src/System.Management.Automation/utils/ObjectWriter.cs +++ b/src/System.Management.Automation/utils/ObjectWriter.cs @@ -164,7 +164,7 @@ public override int Write(object obj) /// /// /// If the enumeration contains elements equal to - /// AutomationNull.Value, they are are ignored. + /// AutomationNull.Value, they are ignored. /// This can cause the return value to be less than the size of /// the collection. /// diff --git a/src/System.Management.Automation/utils/StructuredTraceSource.cs b/src/System.Management.Automation/utils/StructuredTraceSource.cs index c464a27cbaa..88b4cc1a436 100644 --- a/src/System.Management.Automation/utils/StructuredTraceSource.cs +++ b/src/System.Management.Automation/utils/StructuredTraceSource.cs @@ -216,7 +216,7 @@ public enum PSTraceSourceOptions /// /// An PSTraceSource is a representation of a System.Diagnostics.TraceSource instance - /// that is used the the Monad components to produce trace output. + /// that is used in the Monad components to produce trace output. /// /// - diff --git a/src/System.Management.Automation/help/HelpCommands.cs b/src/System.Management.Automation/help/HelpCommands.cs index ca630180fbf..852db86c267 100644 --- a/src/System.Management.Automation/help/HelpCommands.cs +++ b/src/System.Management.Automation/help/HelpCommands.cs @@ -14,8 +14,6 @@ using System.Management.Automation.Internal; using System.Management.Automation.Runspaces; using System.Runtime.InteropServices; -using System.Text; -using Microsoft.PowerShell; #if !UNIX using Microsoft.Win32; #endif @@ -117,21 +115,15 @@ public SwitchParameter Detailed [Parameter(ParameterSetName = "AllUsersView")] public SwitchParameter Full { - private get => _full; - set { - _full = value.ToBool(); - - if (_full) + if (value.ToBool()) { _viewTokenToAdd = HelpView.FullView; } } } - private bool _full; - /// /// Changes the view of HelpObject returned. /// @@ -149,24 +141,15 @@ public SwitchParameter Full [Parameter(ParameterSetName = "Examples", Mandatory = true)] public SwitchParameter Examples { - private get - { - return _examples; - } - set { - _examples = value.ToBool(); - - if (_examples) + if (value.ToBool()) { _viewTokenToAdd = HelpView.ExamplesView; } } } - private bool _examples; - /// /// Parameter name. /// @@ -219,23 +202,6 @@ public SwitchParameter Online private bool _showOnlineHelp; - /// - /// This parameter, if true, will direct get-help cmdlet to - /// display the help content using Microsoft.PowerShell.Pager on alternate screen buffer. - /// - [Parameter] - public SwitchParameter Paged - { - get; - set; - } - - private Microsoft.PowerShell.Pager Pager => _pager ??= new Microsoft.PowerShell.Pager(); - - private Pager _pager; - - private string _multiItemPagerBuffer; - #if !UNIX private GraphicalHostReflectionWrapper graphicalHostReflectionWrapper; private bool showWindow; @@ -370,10 +336,6 @@ protected override void ProcessRecord() { throw PSTraceSource.NewInvalidOperationException(HelpErrors.MultipleOnlineTopicsNotSupported, "Online"); } - else if (Paged && countOfHelpInfos > 1) - { - Pager.Write(_multiItemPagerBuffer); - } // show errors only if there is no wildcard search or VerboseHelpErrors is true. if (((countOfHelpInfos == 0) && (!WildcardPattern.ContainsWildcardCharacters(helpRequest.Target))) @@ -534,7 +496,7 @@ private void GetAndWriteParameterInfo(HelpInfo helpInfo) { foreach (PSObject pInfo in pInfos) { - WriteObjectPaged(pInfo, bufferOutputWhenPaged: false); + WriteObject(pInfo); } } } @@ -635,7 +597,7 @@ private void WriteObjectsOrShowOnlineHelp(HelpInfo helpInfo, bool showFullHelp) { PSObject objectToReturn = TransformView(helpInfo.FullHelp); objectToReturn.IsHelpObject = true; - WriteObjectPaged(objectToReturn, bufferOutputWhenPaged: false); + WriteObject(objectToReturn); } } else @@ -650,92 +612,12 @@ private void WriteObjectsOrShowOnlineHelp(HelpInfo helpInfo, bool showFullHelp) } } - WriteObjectPaged(helpInfo.ShortHelp, bufferOutputWhenPaged: true); + WriteObject(helpInfo.ShortHelp); } } } } - private void WriteObjectPaged(object sendToPipeline, bool bufferOutputWhenPaged) - { - if (Paged) - { - var helpText = GetHelpOutput(); - - if (bufferOutputWhenPaged) - { - // The output from GetHelpOutput has all the item in the output. - // We just need to store it and then write to Pager later. - // No need to append them. - _multiItemPagerBuffer = helpText; - } - else - { - Pager.Write(helpText); - } - } - else - { - WriteObject(sendToPipeline); - } - } - - private string GetHelpOutput() - { - using System.Management.Automation.PowerShell ps = System.Management.Automation.PowerShell.Create(RunspaceMode.CurrentRunspace); - - ps.AddCommand(@"Microsoft.PowerShell.Core\Get-Help"); - - if (!string.IsNullOrEmpty(this.Name)) - { - ps.AddParameter(nameof(this.Name), this.Name); - } - - if (this.Category is not null) - { - ps.AddParameter(nameof(this.Category), this.Category); - } - - if (this.Component is not null) - { - ps.AddParameter(nameof(this.Component), this.Component); - } - - if (this.Functionality is not null) - { - ps.AddParameter(nameof(this.Functionality), this.Functionality); - } - - if (!string.IsNullOrEmpty(this.Path)) - { - ps.AddParameter(nameof(this.Path), this.Path); - } - - if (this.Role is not null) - { - ps.AddParameter(nameof(this.Role), this.Role); - } - - if (this.Examples) - { - ps.AddParameter(nameof(this.Examples), this.Examples); - } - - if (this.Full) - { - ps.AddParameter(nameof(this.Full), this.Full); - } - - if (this.Parameter is not null) - { - ps.AddParameter(nameof(this.Parameter), this.Parameter); - } - - ps.AddCommand(@"Microsoft.PowerShell.Utility\Out-String"); - - return ps.Invoke().FirstOrDefault(); - } - /// /// Opens the Uri. System's default application will be used /// to show the uri. @@ -1006,3 +888,4 @@ Uri result in } } } + From 368c8ff3c3e654cfef525218c73e290b3c6200a2 Mon Sep 17 00:00:00 2001 From: Robert Holt Date: Thu, 3 Sep 2020 18:58:21 +0000 Subject: [PATCH 37/40] Merged PR 12555: Update .NET version to 5.0.0-preview.8.20407.11 Update .NET version to 5.0.0-preview.8.20407.11 --- ...soft.PowerShell.Commands.Management.csproj | 2 +- ...crosoft.PowerShell.Commands.Utility.csproj | 4 ++-- ...crosoft.PowerShell.CoreCLR.Eventing.csproj | 2 +- .../Microsoft.PowerShell.SDK.csproj | 8 ++++---- .../Microsoft.WSMan.Management.csproj | 2 +- .../System.Management.Automation.csproj | 20 +++++++++---------- test/tools/TestService/TestService.csproj | 2 +- test/tools/WebListener/WebListener.csproj | 2 +- ...crosoft.PowerShell.Commands.Utility.csproj | 2 +- .../System.Management.Automation.csproj | 4 ++-- 10 files changed, 24 insertions(+), 24 deletions(-) diff --git a/src/Microsoft.PowerShell.Commands.Management/Microsoft.PowerShell.Commands.Management.csproj b/src/Microsoft.PowerShell.Commands.Management/Microsoft.PowerShell.Commands.Management.csproj index 4b04038e4af..cd399b2340e 100644 --- a/src/Microsoft.PowerShell.Commands.Management/Microsoft.PowerShell.Commands.Management.csproj +++ b/src/Microsoft.PowerShell.Commands.Management/Microsoft.PowerShell.Commands.Management.csproj @@ -47,7 +47,7 @@ - + diff --git a/src/Microsoft.PowerShell.Commands.Utility/Microsoft.PowerShell.Commands.Utility.csproj b/src/Microsoft.PowerShell.Commands.Utility/Microsoft.PowerShell.Commands.Utility.csproj index 8225e03452d..0f59cfd4c53 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/Microsoft.PowerShell.Commands.Utility.csproj +++ b/src/Microsoft.PowerShell.Commands.Utility/Microsoft.PowerShell.Commands.Utility.csproj @@ -32,8 +32,8 @@ - - + + diff --git a/src/Microsoft.PowerShell.CoreCLR.Eventing/Microsoft.PowerShell.CoreCLR.Eventing.csproj b/src/Microsoft.PowerShell.CoreCLR.Eventing/Microsoft.PowerShell.CoreCLR.Eventing.csproj index 09bb1c95a9a..8b8d913c653 100644 --- a/src/Microsoft.PowerShell.CoreCLR.Eventing/Microsoft.PowerShell.CoreCLR.Eventing.csproj +++ b/src/Microsoft.PowerShell.CoreCLR.Eventing/Microsoft.PowerShell.CoreCLR.Eventing.csproj @@ -8,7 +8,7 @@ - + diff --git a/src/Microsoft.PowerShell.SDK/Microsoft.PowerShell.SDK.csproj b/src/Microsoft.PowerShell.SDK/Microsoft.PowerShell.SDK.csproj index 6798baf83a3..cfc2601024d 100644 --- a/src/Microsoft.PowerShell.SDK/Microsoft.PowerShell.SDK.csproj +++ b/src/Microsoft.PowerShell.SDK/Microsoft.PowerShell.SDK.csproj @@ -18,9 +18,9 @@ - - - + + + @@ -30,7 +30,7 @@ - + diff --git a/src/Microsoft.WSMan.Management/Microsoft.WSMan.Management.csproj b/src/Microsoft.WSMan.Management/Microsoft.WSMan.Management.csproj index a63b2596315..e2e13780fd0 100644 --- a/src/Microsoft.WSMan.Management/Microsoft.WSMan.Management.csproj +++ b/src/Microsoft.WSMan.Management/Microsoft.WSMan.Management.csproj @@ -9,7 +9,7 @@ - + diff --git a/src/System.Management.Automation/System.Management.Automation.csproj b/src/System.Management.Automation/System.Management.Automation.csproj index f449e4853b9..c324263e33d 100644 --- a/src/System.Management.Automation/System.Management.Automation.csproj +++ b/src/System.Management.Automation/System.Management.Automation.csproj @@ -16,16 +16,16 @@ - - - - - - - - - - + + + + + + + + + + diff --git a/test/tools/TestService/TestService.csproj b/test/tools/TestService/TestService.csproj index 97d0c463760..d9a782155db 100644 --- a/test/tools/TestService/TestService.csproj +++ b/test/tools/TestService/TestService.csproj @@ -12,7 +12,7 @@ - + diff --git a/test/tools/WebListener/WebListener.csproj b/test/tools/WebListener/WebListener.csproj index f9b93fa7756..ededcf7d80d 100644 --- a/test/tools/WebListener/WebListener.csproj +++ b/test/tools/WebListener/WebListener.csproj @@ -8,7 +8,7 @@ - + diff --git a/tools/packaging/projects/reference/Microsoft.PowerShell.Commands.Utility/Microsoft.PowerShell.Commands.Utility.csproj b/tools/packaging/projects/reference/Microsoft.PowerShell.Commands.Utility/Microsoft.PowerShell.Commands.Utility.csproj index 7630af87df9..50f7158d057 100644 --- a/tools/packaging/projects/reference/Microsoft.PowerShell.Commands.Utility/Microsoft.PowerShell.Commands.Utility.csproj +++ b/tools/packaging/projects/reference/Microsoft.PowerShell.Commands.Utility/Microsoft.PowerShell.Commands.Utility.csproj @@ -14,6 +14,6 @@ - + diff --git a/tools/packaging/projects/reference/System.Management.Automation/System.Management.Automation.csproj b/tools/packaging/projects/reference/System.Management.Automation/System.Management.Automation.csproj index 6e5dc7b458b..f94b69df161 100644 --- a/tools/packaging/projects/reference/System.Management.Automation/System.Management.Automation.csproj +++ b/tools/packaging/projects/reference/System.Management.Automation/System.Management.Automation.csproj @@ -9,7 +9,7 @@ - - + + From dd4bd716c8d6548714c1cf2854c5958500179da5 Mon Sep 17 00:00:00 2001 From: Robert Holt Date: Fri, 4 Sep 2020 22:00:26 +0000 Subject: [PATCH 38/40] Merged PR 12589: Add Microsoft.NET.Test.Sdk dependency Also update xunit dependencies to latest patch. --- test/hosting/hosting.tests.csproj | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/test/hosting/hosting.tests.csproj b/test/hosting/hosting.tests.csproj index 0e459076c28..3a73e139318 100644 --- a/test/hosting/hosting.tests.csproj +++ b/test/hosting/hosting.tests.csproj @@ -15,12 +15,13 @@ - + - + + From bd9185caab361ea13208e2b48f64171192510a81 Mon Sep 17 00:00:00 2001 From: Dongbo Wang Date: Tue, 8 Sep 2020 19:39:58 +0000 Subject: [PATCH 39/40] Merged PR 12600: Update change log for the v7.1.0-preview.7 release Update change log for the v7.1.0-preview.7 release --- .spelling | 10 +++++ CHANGELOG/preview.md | 92 ++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 102 insertions(+) diff --git a/.spelling b/.spelling index 04bf6560484..aa51076c83e 100644 --- a/.spelling +++ b/.spelling @@ -1130,4 +1130,14 @@ ThomasNieto spongemike2 davidseibel HumanEquivalentUnit +hemisphera +tamasvajk +boolean +bitwise +StringUtil +StringUtil.Format +CommandLineParameterParser +jackerr3 +preview.8.20407.11 +pre-check jcotton42 diff --git a/CHANGELOG/preview.md b/CHANGELOG/preview.md index 80031db2bc9..2d83562389a 100644 --- a/CHANGELOG/preview.md +++ b/CHANGELOG/preview.md @@ -1,5 +1,97 @@ # Current preview release +## [7.1.0-preview.7] - 2020-09-08 + +### Breaking Changes + +- Fix `$?` to not be `$false` when native command writes to `stderr` (#13395) + +### Engine Updates and Fixes + +- Initial work of the subsystem plugin model (for minimal powershell) (#13186) +- Optimize `GetSystemLockdownPolicy` for non-lockdown scenarios (#13438) + +### General Cmdlet Updates and Fixes + +- Revert "Add the parameter `-Paged` to `Get-Help` to support paging (#13374)" (#13519) +- Add support for `TLS` 1.3 in Web cmdlets (#13409) (Thanks @iSazonov!) +- Add null check for `args` in `CommandLineParser` (#13451) (Thanks @iSazonov!) +- Process reparse points for Microsoft Store applications (#13481) (Thanks @iSazonov!) +- Move `PSNullConditionalOperators` feature out of experimental (#13529) +- Move `PSNativePSPathResolution` feature out of Experimental (#13522) +- Use field if property does not exist for `ObRoot` when using PowerShell Direct to container (#13375) (Thanks @hemisphera!) +- Suppress `UTF-7` obsolete warnings (#13484) +- Avoid multiple enumerations of an `IEnumerable` instance in `Compiler.cs` (#13491) +- Change `Add-Type -OutputType` to not support `ConsoleApplication` and `WindowsApplication` (#13440) +- Create warnings when `UTF-7` is specified as an encoding (#13430) + +### Code Cleanup + +
+ + + +

We thank the following contributors!

+

@xtqqczze, @tamasvajk

+ +
+ +
    +
  • Add single blank line after copyright header (#13486) (Thanks @xtqqczze!)
  • +
  • Use read-only auto-implemented properties (#13507) (Thanks @xtqqczze!)
  • +
  • Use boolean instead of bitwise operators on bool values (#13506) (Thanks @xtqqczze!)
  • +
  • Fix erroneous assert (#13495) (Thanks @tamasvajk!)
  • +
  • Cleanup: remove duplicate words in comments (#13539) (Thanks @xtqqczze!)
  • +
  • Reformat StringUtil (#13509) (Thanks @xtqqczze!)
  • +
  • Use uint instead of long for PDH constants (#13502) (Thanks @xtqqczze!)
  • +
  • Cleanup: Remove redundant empty lines (#13404) (Thanks @xtqqczze!)
  • +
  • Add StringUtil.Format overload to avoid unnecessary allocations (#13408) (Thanks @xtqqczze!)
  • +
  • Fix test hooks for CommandLineParameterParser (#13459)
  • +
  • Remove redundant delegate creation (#13441) (Thanks @xtqqczze!)
  • +
+ +
+ +### Tools + +- vscode: Add `editorconfig` to recommended extensions (#13537) (Thanks @xtqqczze!) +- Remove the out-dated `ZapDisable` related code from `build.psm1` (#13350) (Thanks @jackerr3!) + +### Tests + +- Disable `WMF` download link validation test (#13479) + +### Build and Packaging Improvements + +
+ + + +

We thank the following contributors!

+

@yecril71pl

+ +
+ +
    +
  • Add Microsoft.NET.Test.Sdk dependency (Internal 12589)
  • +
  • Update .NET NuGet package version to 5.0.0-preview.8.20407.11 (Internal 12555)
  • +
  • Update to .NET 5 preview 8 (#13530)
  • +
  • Change stage dependency for docker release stage in release pipeline (#13512)
  • +
  • Bump Microsoft.NET.Test.Sdk from 16.7.0 to 16.7.1 (#13492)
  • +
  • Create the folder before copying the global tools (#13476)
  • +
  • A few fixes to the release pipeline (#13473)
  • +
  • Bump Markdig.Signed from 0.20.0 to 0.21.1 (#13463)
  • +
  • Add a pre-check for git to build.psm1 (#13227) (Thanks @yecril71pl!)
  • +
+ +
+ +### Documentation and Help Content + +- Update `README` links and `metadata.json` for `7.1.0-preview.6` (#13437) + +[7.1.0-preview.7]: https://github.com/PowerShell/PowerShell/compare/...v7.1.0-preview.7 + ## [7.1.0-preview.6] - 2020-08-17 ### Breaking Changes From 76636448807a07dff7d9649b2dba80fd933ac724 Mon Sep 17 00:00:00 2001 From: Dongbo Wang Date: Tue, 8 Sep 2020 22:34:27 +0000 Subject: [PATCH 40/40] Merged PR 12607: Fix the commit comparing link Fix the commit comparing link --- CHANGELOG/preview.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG/preview.md b/CHANGELOG/preview.md index 2d83562389a..525cea149cf 100644 --- a/CHANGELOG/preview.md +++ b/CHANGELOG/preview.md @@ -90,7 +90,7 @@ - Update `README` links and `metadata.json` for `7.1.0-preview.6` (#13437) -[7.1.0-preview.7]: https://github.com/PowerShell/PowerShell/compare/...v7.1.0-preview.7 +[7.1.0-preview.7]: https://github.com/PowerShell/PowerShell/compare/v7.1.0-preview.6...v7.1.0-preview.7 ## [7.1.0-preview.6] - 2020-08-17