Set StrictMode version 3.0 (#11563)

This commit is contained in:
xtqqczze 2020-02-03 17:44:10 +00:00 committed by GitHub
parent a34d0f3e80
commit 2014ce66c1
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
13 changed files with 77 additions and 58 deletions

View file

@ -16,7 +16,7 @@ param
[ValidateNotNullOrEmpty()] [ValidateNotNullOrEmpty()]
[string] $Path = $PSScriptRoot [string] $Path = $PSScriptRoot
) )
Set-StrictMode -Version Latest Set-StrictMode -Version 3.0
$ErrorActionPreference = 'Stop' $ErrorActionPreference = 'Stop'
function Test-Elevated function Test-Elevated

View file

@ -1,9 +1,12 @@
# Copyright (c) Microsoft Corporation. All rights reserved. # Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. # Licensed under the MIT License.
Set-StrictMode -Version 3.0
# On Unix paths is separated by colon # On Unix paths is separated by colon
# On Windows paths is separated by semicolon # On Windows paths is separated by semicolon
$script:TestModulePathSeparator = [System.IO.Path]::PathSeparator $script:TestModulePathSeparator = [System.IO.Path]::PathSeparator
$script:Options = $null
$dotnetCLIChannel = 'release' $dotnetCLIChannel = 'release'
$dotnetCLIRequiredVersion = $(Get-Content $PSScriptRoot/global.json | ConvertFrom-Json).Sdk.Version $dotnetCLIRequiredVersion = $(Get-Content $PSScriptRoot/global.json | ConvertFrom-Json).Sdk.Version
@ -292,7 +295,7 @@ function Start-PSBuild {
$PSModuleRestore = $true $PSModuleRestore = $true
} }
if ($Runtime -eq "linux-arm" -and -not $environment.IsUbuntu) { if ($Runtime -eq "linux-arm" -and $environment.IsLinux -and -not $environment.IsUbuntu) {
throw "Cross compiling for linux-arm is only supported on Ubuntu environment" throw "Cross compiling for linux-arm is only supported on Ubuntu environment"
} }
@ -499,32 +502,34 @@ Fix steps:
$psVersion = git --git-dir="$PSScriptRoot/.git" describe $psVersion = git --git-dir="$PSScriptRoot/.git" describe
} }
if ($environment.IsRedHatFamily -or $environment.IsDebian) { if ($environment.IsLinux) {
# Symbolic links added here do NOT affect packaging as we do not build on Debian. if ($environment.IsRedHatFamily -or $environment.IsDebian) {
# add two symbolic links to system shared libraries that libmi.so is dependent on to handle # Symbolic links added here do NOT affect packaging as we do not build on Debian.
# platform specific changes. This is the only set of platforms needed for this currently # add two symbolic links to system shared libraries that libmi.so is dependent on to handle
# as Ubuntu has these specific library files in the platform and macOS builds for itself # platform specific changes. This is the only set of platforms needed for this currently
# against the correct versions. # as Ubuntu has these specific library files in the platform and macOS builds for itself
# against the correct versions.
if ($environment.IsDebian10 -or $environment.IsDebian11){ if ($environment.IsDebian10 -or $environment.IsDebian11){
$sslTarget = "/usr/lib/x86_64-linux-gnu/libssl.so.1.1" $sslTarget = "/usr/lib/x86_64-linux-gnu/libssl.so.1.1"
$cryptoTarget = "/usr/lib/x86_64-linux-gnu/libcrypto.so.1.1" $cryptoTarget = "/usr/lib/x86_64-linux-gnu/libcrypto.so.1.1"
} }
elseif ($environment.IsDebian9){ elseif ($environment.IsDebian9){
# NOTE: Debian 8 doesn't need these symlinks # NOTE: Debian 8 doesn't need these symlinks
$sslTarget = "/usr/lib/x86_64-linux-gnu/libssl.so.1.0.2" $sslTarget = "/usr/lib/x86_64-linux-gnu/libssl.so.1.0.2"
$cryptoTarget = "/usr/lib/x86_64-linux-gnu/libcrypto.so.1.0.2" $cryptoTarget = "/usr/lib/x86_64-linux-gnu/libcrypto.so.1.0.2"
} }
else { #IsRedHatFamily else { #IsRedHatFamily
$sslTarget = "/lib64/libssl.so.10" $sslTarget = "/lib64/libssl.so.10"
$cryptoTarget = "/lib64/libcrypto.so.10" $cryptoTarget = "/lib64/libcrypto.so.10"
} }
if ( ! (test-path "$publishPath/libssl.so.1.0.0")) { if ( ! (test-path "$publishPath/libssl.so.1.0.0")) {
$null = New-Item -Force -ItemType SymbolicLink -Target $sslTarget -Path "$publishPath/libssl.so.1.0.0" -ErrorAction Stop $null = New-Item -Force -ItemType SymbolicLink -Target $sslTarget -Path "$publishPath/libssl.so.1.0.0" -ErrorAction Stop
} }
if ( ! (test-path "$publishPath/libcrypto.so.1.0.0")) { if ( ! (test-path "$publishPath/libcrypto.so.1.0.0")) {
$null = New-Item -Force -ItemType SymbolicLink -Target $cryptoTarget -Path "$publishPath/libcrypto.so.1.0.0" -ErrorAction Stop $null = New-Item -Force -ItemType SymbolicLink -Target $cryptoTarget -Path "$publishPath/libcrypto.so.1.0.0" -ErrorAction Stop
}
} }
} }
@ -579,6 +584,7 @@ Fix steps:
function Restore-PSPackage function Restore-PSPackage
{ {
[CmdletBinding()]
param( param(
[ValidateNotNullOrEmpty()] [ValidateNotNullOrEmpty()]
[Parameter()] [Parameter()]
@ -618,7 +624,7 @@ function Restore-PSPackage
$RestoreArguments = @("/property:SDKToUse=$sdkToUse", "--verbosity") $RestoreArguments = @("/property:SDKToUse=$sdkToUse", "--verbosity")
} }
if ($PSCmdlet.MyInvocation.BoundParameters["Verbose"].IsPresent) { if ($VerbosePreference -eq 'Continue') {
$RestoreArguments += "detailed" $RestoreArguments += "detailed"
} else { } else {
$RestoreArguments += "quiet" $RestoreArguments += "quiet"
@ -837,7 +843,7 @@ function Get-PSOptions {
$DefaultToNew $DefaultToNew
) )
if(!$script:Options -and $DefaultToNew.IsPresent) if (!$script:Options -and $DefaultToNew.IsPresent)
{ {
return New-PSOptions return New-PSOptions
} }
@ -876,7 +882,14 @@ function Get-PesterTag {
$fullname = $_.fullname $fullname = $_.fullname
$tok = $err = $null $tok = $err = $null
$ast = [System.Management.Automation.Language.Parser]::ParseFile($FullName, [ref]$tok,[ref]$err) $ast = [System.Management.Automation.Language.Parser]::ParseFile($FullName, [ref]$tok,[ref]$err)
$des = $ast.FindAll({$args[0] -is "System.Management.Automation.Language.CommandAst" -and $args[0].CommandElements[0].Value -eq "Describe"},$true) $des = $ast.FindAll({
$args[0] -is [System.Management.Automation.Language.CommandAst] `
-and $args[0].CommandElements.GetType() -in @(
[System.Management.Automation.Language.StringConstantExpressionAst],
[System.Management.Automation.Language.ExpandableStringExpressionAst]
) `
-and $args[0].CommandElements[0].Value -eq "Describe"
}, $true)
foreach( $describe in $des) { foreach( $describe in $des) {
$elements = $describe.CommandElements $elements = $describe.CommandElements
$lineno = $elements[0].Extent.StartLineNumber $lineno = $elements[0].Extent.StartLineNumber
@ -1079,7 +1092,7 @@ function Start-PSPester {
$publishArgs = @{ } $publishArgs = @{ }
# if we are building for Alpine, we must include the runtime as linux-x64 # if we are building for Alpine, we must include the runtime as linux-x64
# will not build runnable test tools # will not build runnable test tools
if ( $environment.IsAlpine ) { if ( $environment.IsLinux -and $environment.IsAlpine ) {
$publishArgs['runtime'] = 'alpine-x64' $publishArgs['runtime'] = 'alpine-x64'
} }
Publish-PSTestTools @publishArgs | ForEach-Object {Write-Host $_} Publish-PSTestTools @publishArgs | ForEach-Object {Write-Host $_}
@ -1615,7 +1628,7 @@ function Install-Dotnet {
$curl = Get-Command -Name curl -CommandType Application -TotalCount 1 -ErrorAction Stop $curl = Get-Command -Name curl -CommandType Application -TotalCount 1 -ErrorAction Stop
# Uninstall all previous dotnet packages # Uninstall all previous dotnet packages
$uninstallScript = if ($environment.IsUbuntu) { $uninstallScript = if ($environment.IsLinux -and $environment.IsUbuntu) {
"dotnet-uninstall-debian-packages.sh" "dotnet-uninstall-debian-packages.sh"
} elseif ($environment.IsMacOS) { } elseif ($environment.IsMacOS) {
"dotnet-uninstall-pkgs.sh" "dotnet-uninstall-pkgs.sh"
@ -1687,14 +1700,14 @@ function Start-PSBootstrap {
# Note that when it is null, Invoke-Expression (but not &) must be used to interpolate properly # Note that when it is null, Invoke-Expression (but not &) must be used to interpolate properly
$sudo = if (!$NoSudo) { "sudo" } $sudo = if (!$NoSudo) { "sudo" }
if ($BuildLinuxArm -and -not $environment.IsUbuntu) { if ($BuildLinuxArm -and $environment.IsLinux -and -not $environment.IsUbuntu) {
Write-Error "Cross compiling for linux-arm is only supported on Ubuntu environment" Write-Error "Cross compiling for linux-arm is only supported on Ubuntu environment"
return return
} }
# Install ours and .NET's dependencies # Install ours and .NET's dependencies
$Deps = @() $Deps = @()
if ($environment.IsUbuntu) { if ($environment.IsLinux -and $environment.IsUbuntu) {
# Build tools # Build tools
$Deps += "curl", "g++", "cmake", "make" $Deps += "curl", "g++", "cmake", "make"
@ -1724,7 +1737,7 @@ function Start-PSBootstrap {
# change the apt frontend back to the original # change the apt frontend back to the original
$env:DEBIAN_FRONTEND=$originalDebianFrontEnd $env:DEBIAN_FRONTEND=$originalDebianFrontEnd
} }
} elseif ($environment.IsRedHatFamily) { } elseif ($environment.IsLinux -and $environment.IsRedHatFamily) {
# Build tools # Build tools
$Deps += "which", "curl", "gcc-c++", "cmake", "make" $Deps += "which", "curl", "gcc-c++", "cmake", "make"
@ -1748,7 +1761,7 @@ function Start-PSBootstrap {
Start-NativeExecution { Start-NativeExecution {
Invoke-Expression "$baseCommand $Deps" Invoke-Expression "$baseCommand $Deps"
} }
} elseif ($environment.IsSUSEFamily) { } elseif ($environment.IsLinux -and $environment.IsSUSEFamily) {
# Build tools # Build tools
$Deps += "gcc", "cmake", "make" $Deps += "gcc", "cmake", "make"
@ -1784,7 +1797,7 @@ function Start-PSBootstrap {
# Install dependencies # Install dependencies
# ignore exitcode, because they may be already installed # ignore exitcode, because they may be already installed
Start-NativeExecution ([ScriptBlock]::Create("$PackageManager install $Deps")) -IgnoreExitcode Start-NativeExecution ([ScriptBlock]::Create("$PackageManager install $Deps")) -IgnoreExitcode
} elseif ($environment.IsAlpine) { } elseif ($environment.IsLinux -and $environment.IsAlpine) {
$Deps += 'libunwind', 'libcurl', 'bash', 'cmake', 'clang', 'build-base', 'git', 'curl' $Deps += 'libunwind', 'libcurl', 'bash', 'cmake', 'clang', 'build-base', 'git', 'curl'
Start-NativeExecution { Start-NativeExecution {
@ -2105,8 +2118,8 @@ function script:Start-NativeExecution
[switch]$IgnoreExitcode, [switch]$IgnoreExitcode,
[switch]$VerboseOutputOnError [switch]$VerboseOutputOnError
) )
$backupEAP = $script:ErrorActionPreference $backupEAP = $ErrorActionPreference
$script:ErrorActionPreference = "Continue" $ErrorActionPreference = "Continue"
try { try {
if($VerboseOutputOnError.IsPresent) if($VerboseOutputOnError.IsPresent)
{ {
@ -2139,7 +2152,7 @@ function script:Start-NativeExecution
throw "Execution of {$sb} failed with exit code $LASTEXITCODE" throw "Execution of {$sb} failed with exit code $LASTEXITCODE"
} }
} finally { } finally {
$script:ErrorActionPreference = $backupEAP $ErrorActionPreference = $backupEAP
} }
} }

View file

@ -24,7 +24,7 @@ param
[switch] $Unregister [switch] $Unregister
) )
Set-StrictMode -Version Latest Set-StrictMode -Version 3.0
$ErrorActionPreference = 'Stop' $ErrorActionPreference = 'Stop'
function Start-NativeExecution([scriptblock]$sb, [switch]$IgnoreExitcode) function Start-NativeExecution([scriptblock]$sb, [switch]$IgnoreExitcode)

View file

@ -26,7 +26,7 @@ param
$PowerShellHome $PowerShellHome
) )
Set-StrictMode -Version Latest Set-StrictMode -Version 3.0
if (! ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator")) if (! ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator"))
{ {
@ -123,7 +123,7 @@ function Install-PluginEndpoint {
# Install the plugin # # Install the plugin #
# # # #
###################### ######################
if (-not [String]::IsNullOrEmpty($PowerShellHome)) if (-not [String]::IsNullOrEmpty($PowerShellHome))
{ {
$targetPsHome = $PowerShellHome $targetPsHome = $PowerShellHome

View file

@ -2,7 +2,7 @@
# Licensed under the MIT License. # Licensed under the MIT License.
using namespace System.Text using namespace System.Text
Set-StrictMode -Version Latest Set-StrictMode -Version 3.0
$ErrorActionPreference = 'Stop' $ErrorActionPreference = 'Stop'
Import-Module HelpersCommon Import-Module HelpersCommon

View file

@ -131,7 +131,7 @@ Describe "TabCompletion" -Tags CI {
} }
It 'Should complete "Get-Process -Id " with Id and name in tooltip' { It 'Should complete "Get-Process -Id " with Id and name in tooltip' {
Set-StrictMode -Version latest Set-StrictMode -Version 3.0
$cmd = 'Get-Process -Id ' $cmd = 'Get-Process -Id '
[System.Management.Automation.CommandCompletion]$res = TabExpansion2 -inputScript $cmd -cursorColumn $cmd.Length [System.Management.Automation.CommandCompletion]$res = TabExpansion2 -inputScript $cmd -cursorColumn $cmd.Length
$res.CompletionMatches[0].CompletionText -match '^\d+$' | Should -BeTrue $res.CompletionMatches[0].CompletionText -match '^\d+$' | Should -BeTrue

View file

@ -887,7 +887,7 @@ class A
[int] GetX([Foo.Bar]$bar) [int] GetX([Foo.Bar]$bar)
{ {
Set-StrictMode -Version latest Set-StrictMode -Version 3.0
return $bar.x return $bar.x
} }
} }

View file

@ -164,7 +164,7 @@ namespace DotNetInterop
param($Script) param($Script)
try { try {
Set-StrictMode -Version latest Set-StrictMode -Version 3.0
& $Script | Should -Be $null & $Script | Should -Be $null
} finally { } finally {
Set-StrictMode -Off Set-StrictMode -Off
@ -225,7 +225,7 @@ namespace DotNetInterop
It "Get access of an indexer that returns ByRef-like type should fail gracefully in strict mode" { It "Get access of an indexer that returns ByRef-like type should fail gracefully in strict mode" {
try { try {
Set-StrictMode -Version latest Set-StrictMode -Version 3.0
{ $testObj[1] } | Should -Throw -ErrorId "CannotIndexWithByRefLikeReturnType" { $testObj[1] } | Should -Throw -ErrorId "CannotIndexWithByRefLikeReturnType"
} finally { } finally {
Set-StrictMode -Off Set-StrictMode -Off
@ -242,7 +242,7 @@ namespace DotNetInterop
} }
Context "Passing value that is implicitly/explicitly castable to ByRef-like parameter in method invocation" { Context "Passing value that is implicitly/explicitly castable to ByRef-like parameter in method invocation" {
BeforeAll { BeforeAll {
$ps = [powershell]::Create() $ps = [powershell]::Create()
@ -302,7 +302,7 @@ namespace DotNetInterop
It "Return null for getter access of a CodeProperty that returns a ByRef-like type, even in strict mode" { It "Return null for getter access of a CodeProperty that returns a ByRef-like type, even in strict mode" {
$result = $ps.AddScript( $result = $ps.AddScript(
'try { Set-StrictMode -Version latest; $test.TestName } finally { Set-StrictMode -Off }').Invoke() 'try { Set-StrictMode -Version 3.0; $test.TestName } finally { Set-StrictMode -Off }').Invoke()
$ps.Commands.Clear() $ps.Commands.Clear()
$result.Count | Should -Be 1 $result.Count | Should -Be 1
$result[0] | Should -Be $null $result[0] | Should -Be $null

View file

@ -59,7 +59,7 @@ Describe "Validate that the Help function can Run in strict mode" -Tags @('CI')
$help = & { $help = & {
# run in nested scope to keep strict mode from affecting other tests # run in nested scope to keep strict mode from affecting other tests
Set-StrictMode -Version Latest Set-StrictMode -Version 3.0
Help Help
} }
# the help function renders the help content as text so just verify that there is content # the help function renders the help content as text so just verify that there is content

View file

@ -5,7 +5,7 @@
trap {throw $_} trap {throw $_}
# Strict mode FTW. # Strict mode FTW.
Set-StrictMode -Version Latest Set-StrictMode -Version 3.0
# Enable explicit export so that there are no surprises with commands exported from the module. # Enable explicit export so that there are no surprises with commands exported from the module.
Export-ModuleMember Export-ModuleMember

View file

@ -1,7 +1,7 @@
# Copyright (c) Microsoft Corporation. All rights reserved. # Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. # Licensed under the MIT License.
Set-StrictMode -Version Latest Set-StrictMode -Version 3.0
<# <#
os_log notes: os_log notes:
@ -187,7 +187,7 @@ class PSLogItem
hidden static [int] GetMonth([string] $value) hidden static [int] GetMonth([string] $value)
{ {
Set-StrictMode -Version Latest Set-StrictMode -Version 3.0
for ($x = 0; $x -lt [PSLogItem]::monthNames.Count; $x++) for ($x = 0; $x -lt [PSLogItem]::monthNames.Count; $x++)
{ {
[string] $monthName = [PSLogItem]::monthNames[$x] [string] $monthName = [PSLogItem]::monthNames[$x]
@ -201,7 +201,7 @@ class PSLogItem
static [PSLogItem] ConvertSysLog([string] $content, [string] $id, [Nullable[DateTime]] $after) static [PSLogItem] ConvertSysLog([string] $content, [string] $id, [Nullable[DateTime]] $after)
{ {
Set-StrictMode -Version Latest Set-StrictMode -Version 3.0
<# <#
MMM dd HH:MM:SS machinename id[PID]: (commitid:TID:CHANNEL) [EventName] Message MMM dd HH:MM:SS machinename id[PID]: (commitid:TID:CHANNEL) [EventName] Message
Expecting split to return Expecting split to return
@ -339,7 +339,7 @@ class PSLogItem
static [object] ConvertOsLog([string] $content, [string] $id, [Nullable[DateTime]] $after) static [object] ConvertOsLog([string] $content, [string] $id, [Nullable[DateTime]] $after)
{ {
Set-StrictMode -Version Latest Set-StrictMode -Version 3.0
<# <#
Expecting split to return Expecting split to return
0: date 2018-02-07 0: date 2018-02-07

View file

@ -1,6 +1,8 @@
# Copyright (c) Microsoft Corporation. All rights reserved. # Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. # Licensed under the MIT License.
Set-StrictMode -Version 3.0
$ErrorActionPreference = 'continue' $ErrorActionPreference = 'continue'
$repoRoot = Join-Path $PSScriptRoot '..' $repoRoot = Join-Path $PSScriptRoot '..'
$script:administratorsGroupSID = "S-1-5-32-544" $script:administratorsGroupSID = "S-1-5-32-544"
@ -479,7 +481,7 @@ function Invoke-CIFinish
{ {
$null = $artifacts.Add($package) $null = $artifacts.Add($package)
} }
elseif($package -is [pscustomobject] -and $package.msi) elseif($package -is [pscustomobject] -and $package.psobject.Properties['msi'])
{ {
$null = $artifacts.Add($package.msi) $null = $artifacts.Add($package.msi)
$null = $artifacts.Add($package.wixpdb) $null = $artifacts.Add($package.wixpdb)
@ -497,7 +499,7 @@ function Invoke-CIFinish
$packagingTestResult = Invoke-Pester -Script (Join-Path $repoRoot '.\test\packaging\windows\') -PassThru $packagingTestResult = Invoke-Pester -Script (Join-Path $repoRoot '.\test\packaging\windows\') -PassThru
# fail the CI job if the tests failed, or nothing passed # fail the CI job if the tests failed, or nothing passed
if($packagingTestResult.FailedCount -ne 0 -or !$packagingTestResult.PassedCount) if(-not $packagingTestResult -is [pscustomobject] -or $packagingTestResult.FailedCount -ne 0 -or $packagingTestResult.PassedCount -eq 0)
{ {
throw "Packaging tests failed ($($packagingTestResult.FailedCount) failed/$($packagingTestResult.PassedCount) passed)" throw "Packaging tests failed ($($packagingTestResult.FailedCount) failed/$($packagingTestResult.PassedCount) passed)"
} }
@ -579,6 +581,10 @@ function Invoke-LinuxTestsCore
$testResultsNoSudo = "$PWD/TestResultsNoSudo.xml" $testResultsNoSudo = "$PWD/TestResultsNoSudo.xml"
$testResultsSudo = "$PWD/TestResultsSudo.xml" $testResultsSudo = "$PWD/TestResultsSudo.xml"
$testExcludeTag = $ExcludeTag + 'RequireSudoOnUnix' $testExcludeTag = $ExcludeTag + 'RequireSudoOnUnix'
$pesterPassThruNoSudoObject = $null
$pesterPassThruSudoObject = $null
$noSudoResultsWithExpFeatures = $null
$sudoResultsWithExpFeatures = $null
$noSudoPesterParam = @{ $noSudoPesterParam = @{
'BinDir' = $output 'BinDir' = $output

View file

@ -54,7 +54,7 @@ param(
[switch] $Preview [switch] $Preview
) )
Set-StrictMode -Version latest Set-StrictMode -Version 3.0
$ErrorActionPreference = "Stop" $ErrorActionPreference = "Stop"
$IsLinuxEnv = (Get-Variable -Name "IsLinux" -ErrorAction Ignore) -and $IsLinux $IsLinuxEnv = (Get-Variable -Name "IsLinux" -ErrorAction Ignore) -and $IsLinux