diff --git a/Examples/Install-PSDepend.ps1 b/Examples/Install-PSDepend.ps1 index 875b8b8..dfc620a 100644 --- a/Examples/Install-PSDepend.ps1 +++ b/Examples/Install-PSDepend.ps1 @@ -1,4 +1,4 @@ -# No PowerShellGallery? Run this to install PSDepend. +# No PowerShellGallery? Run this to install PSDepend. # Downloads nuget to your ~\ home directory # Creates $Path (and full path to it) # Downloads module to $Path\PSDepend @@ -7,17 +7,17 @@ # Example: .\Install-PSDepend -Path C:\Modules (Installs to C:\Modules\PSDepend) param( [string]$Path ) # Parent folder PSDepend is installed to. Defaults to Profile\WindowsPowerShell\Modules and creates dir if needed -if(-not $Path) { $Path = Join-Path ([Environment]::GetFolderPath('MyDocuments')) 'WindowsPowerShell\Modules' } +if (-not $Path) { $Path = Join-Path ([Environment]::GetFolderPath('MyDocuments')) 'WindowsPowerShell\Modules' } # Bootstrap nuget if we don't have it -if(-not ($NugetPath = (Get-Command 'nuget.exe' -ErrorAction SilentlyContinue).Path)) { +if (-not ($NugetPath = (Get-Command 'nuget.exe' -ErrorAction SilentlyContinue).Path)) { $NugetPath = Join-Path $ENV:USERPROFILE nuget.exe - if(-not (Test-Path $NugetPath)) { Invoke-WebRequest -uri 'https://dist.nuget.org/win-x86-commandline/latest/nuget.exe' -OutFile $NugetPath } + if (-not (Test-Path $NugetPath)) { Invoke-WebRequest -Uri 'https://dist.nuget.org/win-x86-commandline/latest/nuget.exe' -OutFile $NugetPath } } # Bootstrap PSDepend, re-use nuget.exe for the module -if($path) { $null = New-Item $path -ItemType Directory -Force } +if ($path) { $null = New-Item $path -ItemType Directory -Force } $NugetParams = 'install', 'PSDepend', '-Source', 'https://www.powershellgallery.com/api/v2/', - '-ExcludeVersion', '-NonInteractive', '-OutputDirectory', $Path +'-ExcludeVersion', '-NonInteractive', '-OutputDirectory', $Path & $NugetPath @NugetParams Move-Item -Path $NugetPath -Destination "$(Join-Path $Path PSDepend)\nuget.exe" -Force diff --git a/PSDepend/PSDependScripts/Chocolatey.ps1 b/PSDepend/PSDependScripts/Chocolatey.ps1 index b0fb26e..f7af458 100644 --- a/PSDepend/PSDependScripts/Chocolatey.ps1 +++ b/PSDepend/PSDependScripts/Chocolatey.ps1 @@ -84,12 +84,12 @@ function Get-ChocoInstalledPackage { '--local-only' ) $invokeExternalCommandSplat = @{ - Command = 'choco.exe' + Command = 'choco.exe' Arguments = $chocoParams - PassThru = $true + PassThru = $true } $convertFromCsvSplat = @{ - Header = 'Name', 'Version' + Header = 'Name', 'Version' Delimiter = "|" } Invoke-ExternalCommand @invokeExternalCommandSplat | ConvertFrom-Csv @convertFromCsvSplat @@ -118,12 +118,12 @@ function Get-ChocoLatestPackage { } $invokeExternalCommandSplat = @{ - Command = 'choco.exe' + Command = 'choco.exe' Arguments = $chocoParams - PassThru = $true + PassThru = $true } $convertFromCsvSplat = @{ - Header = 'Name', 'Version' + Header = 'Name', 'Version' Delimiter = "|" } Invoke-ExternalCommand @invokeExternalCommandSplat | ConvertFrom-Csv @convertFromCsvSplat @@ -172,7 +172,7 @@ function Invoke-ChocoInstallPackage { } $invokeExternalCommandSplat = @{ - Command = 'choco.exe' + Command = 'choco.exe' Arguments = $chocoParams } Invoke-ExternalCommand @invokeExternalCommandSplat @@ -209,7 +209,8 @@ if (-not (Get-Command -Name 'choco.exe' -ErrorAction SilentlyContinue)) { try { Invoke-WebRequest -UseBasicParsing -Uri $ChocoInstallScriptUrl -OutFile $scriptPath & $scriptPath - } catch { + } + catch { throw "Unable to install Chocolatey from '$scriptUrl'." } } @@ -239,14 +240,15 @@ Write-Verbose "Getting package [$Name] version, if it is installed." $existingVersion = (Get-ChocoInstalledPackage -Name $Name).Version if ($existingVersion) { Write-Verbose "Found package [$Name] installed with version [$existingVersion]." -} else { +} +else { Write-Verbose "Package [$Name] not installed." } # Version latest requested, and equal to current if ($Version -ne 'latest' -and $Version -eq $existingVersion) { Write-Verbose "You have the requested version [$Version] of [$Name]" - if($PSDependAction -contains 'Test') { + if ($PSDependAction -contains 'Test') { return $true } @@ -266,7 +268,8 @@ Write-Verbose "Getting latest package [$Name] version from source [$Source]." $repositoryVersion = (Get-ChocoLatestPackage @repoParams).Version if ($repositoryVersion) { Write-Verbose "Found package [$Name] version [$repositoryVersion] on source [$Source]." -} else { +} +else { Write-Verbose "Package [$Name] not found on source [$Source]. Nothing more can be done." return # cannot continue } @@ -277,7 +280,7 @@ if ( ([System.Version]$repositoryVersion -le [System.Version]$existingVersion) ) { Write-Verbose "You have the latest version of [$Name], with installed version [$existingVersion] and Source version [$repositoryVersion]" - if($PSDependAction -contains 'Test') { + if ($PSDependAction -contains 'Test') { return $true } @@ -300,6 +303,7 @@ if ($PSDependAction -contains 'Install') { } Invoke-ChocoInstallPackage @params -} elseif ($PSDependAction -contains 'Test' -and $PSDependAction.count -eq 1) { +} +elseif ($PSDependAction -contains 'Test' -and $PSDependAction.count -eq 1) { return $false } \ No newline at end of file diff --git a/PSDepend/PSDependScripts/Command.ps1 b/PSDepend/PSDependScripts/Command.ps1 index 720bfe6..33c377b 100644 --- a/PSDepend/PSDependScripts/Command.ps1 +++ b/PSDepend/PSDependScripts/Command.ps1 @@ -46,24 +46,18 @@ param ( Write-Verbose "Executing $($Dependency.count) commands" -foreach($Depend in $Dependency) -{ - foreach($Command in $Depend.Source) - { +foreach ($Depend in $Dependency) { + foreach ($Command in $Depend.Source) { Write-Verbose "Invoking command [$($Dependency.DependencyName)]:`n$Command" $ScriptBlock = [ScriptBlock]::Create($Command) - Try - { + Try { . $ScriptBlock } - Catch - { - if($FailOnError) - { + Catch { + if ($FailOnError) { throw $_ } - else - { + else { Write-Error $_ continue } diff --git a/PSDepend/PSDependScripts/DotnetSdk.ps1 b/PSDepend/PSDependScripts/DotnetSdk.ps1 index 454c4f7..f064408 100644 --- a/PSDepend/PSDependScripts/DotnetSdk.ps1 +++ b/PSDepend/PSDependScripts/DotnetSdk.ps1 @@ -81,7 +81,8 @@ if ($PSDependAction -contains 'Install') { # If the InstallDir is not set, set it to the 'global' path if (!$InstallDir) { $InstallTo = $globalDotnetSdkLocation - } else { + } + else { $InstallTo = $InstallDir } Install-Dotnet -Channel $Channel -Version $Version -InstallDir $InstallTo @@ -93,13 +94,15 @@ if ($PSDependAction -contains 'Import') { # If the InstallDir was specified and the .NET Core SDK exists in it, add it to the path if ($InstallDir -and (Test-Dotnet -Version $Version -InstallDir $InstallDir)) { $env:PATH = "$InstallDir$([IO.Path]::PathSeparator)$env:PATH" - } else { + } + else { # Test if it's in the path already and if it's not check if it's in the 'global' location $dotnetInPath = Get-Command 'dotnet' -ErrorAction SilentlyContinue if (!$dotnetInPath) { if (!(Test-Dotnet -Version $Version -InstallDir $globalDotnetSdkLocation)) { throw ".NET SDK cannot be located. Try installing using PSDepend." - } else { + } + else { $env:PATH = "$globalDotnetSdkLocation$([IO.Path]::PathSeparator)$env:PATH" } } diff --git a/PSDepend/PSDependScripts/FileDownload.ps1 b/PSDepend/PSDependScripts/FileDownload.ps1 index 4d3d134..6e47351 100644 --- a/PSDepend/PSDependScripts/FileDownload.ps1 +++ b/PSDepend/PSDependScripts/FileDownload.ps1 @@ -46,116 +46,98 @@ param( ) function Parse-URLForFile { -[cmdletbinding()] -param($URL) + [cmdletbinding()] + param($URL) # This will need work. Assume leaf is file. If CGI exists in leaf, assume it is after the file $FileName = $URL.split('/')[-1] - if($FileName -match '\?') - { + if ($FileName -match '\?') { $FileName.split('?')[0] } - else - { + else { $FileName } Write-Verbose "Parsed file name [$FileName] from `$URL" } # Extract data from Dependency - $DependencyName = $Dependency.DependencyName - $Name = $Dependency.Name - $Target = $Dependency.Target - $Source = $Dependency.Source - - # Pick the URL - if($Source) - { - $URL = $Source - } - else - { - $URL = $DependencyName - } - Write-Verbose "Using URL: $URL" +$DependencyName = $Dependency.DependencyName +$Name = $Dependency.Name +$Target = $Dependency.Target +$Source = $Dependency.Source + +# Pick the URL +if ($Source) { + $URL = $Source +} +else { + $URL = $DependencyName +} +Write-Verbose "Using URL: $URL" # Act on target path.... - $ToInstall = $False # Anti pattern - $TargetParent = Split-Path $Target -Parent - $PathToAdd = $Target - if( (Test-Path $TargetParent) -and -not (Test-Path $Target)) - { - # They gave us a full path, don't parse the file name, use this! - $Path = $Target - $ToInstall = $True - Write-Verbose "Found parent [$TargetParent], not target [$Target], assuming this is target file path" +$ToInstall = $False # Anti pattern +$TargetParent = Split-Path $Target -Parent +$PathToAdd = $Target +if ( (Test-Path $TargetParent) -and -not (Test-Path $Target)) { + # They gave us a full path, don't parse the file name, use this! + $Path = $Target + $ToInstall = $True + Write-Verbose "Found parent [$TargetParent], not target [$Target], assuming this is target file path" +} +elseif (Test-Path $Target -PathType Leaf) { + # File exists. We should download to temp spot, compare hashes, take action as appropriate. + # For now, skip the file. + Write-Verbose "Skipping existing file [$Target]" + if ($PSDependAction -contains 'Test') { + return $True } - elseif(Test-Path $Target -PathType Leaf) - { - # File exists. We should download to temp spot, compare hashes, take action as appropriate. - # For now, skip the file. - Write-Verbose "Skipping existing file [$Target]" - if($PSDependAction -contains 'Test') - { - return $True - } - $PathToAdd = Split-Path $Target -Parent + $PathToAdd = Split-Path $Target -Parent +} +elseif (-not (Test-Path $Target)) { + # They gave us something that doesn't look like a new container for a new or existing file. Wat? + Write-Error "Could not find target path [$Target]" + if ($PSDependAction -contains 'Test') { + return $False } - elseif(-not (Test-Path $Target)) - { - # They gave us something that doesn't look like a new container for a new or existing file. Wat? - Write-Error "Could not find target path [$Target]" - if($PSDependAction -contains 'Test') - { - return $False - } +} +else { + Write-Verbose "[$Target] is a container, creating path to file" + # We have a target container, now find the name + If ($Name) { + # explicit name + $FileName = $Name } - else - { - Write-Verbose "[$Target] is a container, creating path to file" - # We have a target container, now find the name - If($Name) - { - # explicit name - $FileName = $Name - } - else - { - $FileName = Parse-URLForFile -URL $URL - } - $Path = Join-Path $Target $FileName + else { + $FileName = Parse-URLForFile -URL $URL + } + $Path = Join-Path $Target $FileName - if(Test-Path $Path -PathType Leaf) - { - Write-Verbose "Skipping existing file [$Path]" - if($PSDependAction -contains 'Test') - { - return $True - } - } - else - { - $ToInstall = $True + if (Test-Path $Path -PathType Leaf) { + Write-Verbose "Skipping existing file [$Path]" + if ($PSDependAction -contains 'Test') { + return $True } } - Write-Verbose "Using [$Path] as `$Target" - - #No dependency found, return false if we're testing alone... - if( $PSDependAction -contains 'Test' -and $PSDependAction.count -eq 1) - { - return $False + else { + $ToInstall = $True } - Write-Verbose "Downloading [$URL] to [$Path]" +} +Write-Verbose "Using [$Path] as `$Target" + +#No dependency found, return false if we're testing alone... +if ( $PSDependAction -contains 'Test' -and $PSDependAction.count -eq 1) { + return $False +} +Write-Verbose "Downloading [$URL] to [$Path]" -if($PSDependAction -contains 'Install' -and $ToInstall) -{ +if ($PSDependAction -contains 'Install' -and $ToInstall) { # Future considerations: - # Should we check for existing? And if we find it, still download file, and compare sha256 hash, replace if it does not match? - # We should consider credentials at some point, but PSD1 does not lend itself to securely storing passwords + # Should we check for existing? And if we find it, still download file, and compare sha256 hash, replace if it does not match? + # We should consider credentials at some point, but PSD1 does not lend itself to securely storing passwords Get-WebFile -URL $URL -Path $Path } -if($Dependency.AddToPath) -{ +if ($Dependency.AddToPath) { Write-Verbose "Setting PATH to`n$($PathToAdd, $env:PATH -join ';' | Out-String)" Add-ToItemCollection -Reference Env:\Path -Item $PathToAdd } diff --git a/PSDepend/PSDependScripts/FileSystem.ps1 b/PSDepend/PSDependScripts/FileSystem.ps1 index 5edaf50..0a8a35e 100644 --- a/PSDepend/PSDependScripts/FileSystem.ps1 +++ b/PSDepend/PSDependScripts/FileSystem.ps1 @@ -1,4 +1,4 @@ -<# +<# .SYNOPSIS EXPERIMENTAL: Use Robocopy or Copy-Item for folder and file dependencies, respectively. @@ -72,18 +72,15 @@ param ( ) # Extract data from Dependency - $DependencyName = $Dependency.DependencyName - $Name = $Dependency.Name - $Target = $Dependency.Target - $Sources = @($Dependency.Source) +$DependencyName = $Dependency.DependencyName +$Name = $Dependency.Name +$Target = $Dependency.Target +$Sources = @($Dependency.Source) $TestOutput = @() -foreach($Source in @($Sources)) -{ - if(-not (Test-Path $Source)) - { - if(-not $PSDependAction -like 'Test') - { +foreach ($Source in @($Sources)) { + if (-not (Test-Path $Source)) { + if (-not $PSDependAction -like 'Test') { Write-Error "Skipping $DependencyName, could not find source [$Sources] due to error:" } continue @@ -94,27 +91,22 @@ foreach($Source in @($Sources)) $Target = $ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath($Target) $Source = $ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath($Source) - if($IsContainer) - { + if ($IsContainer) { $Folder = Split-Path $Source -Leaf $Target = Join-Path $Target $Folder - if(-not $ImportPath) {$ImportPath = $Target} + if (-not $ImportPath) { $ImportPath = $Target } # We don't test equality for containers yet - if(Test-Path $Target) - { + if (Test-Path $Target) { $TestOutput += $true } - else - { + else { $TestOutput += $false } - if($PSDependAction -like 'Install') - { + if ($PSDependAction -like 'Install') { # TODO: Add non Windows equivalent... [string[]]$Arguments = "/XO" $Arguments += "/E" - if($Dependency.Parameters.Mirror -eq $True -or $Mirror) - { + if ($Dependency.Parameters.Mirror -eq $True -or $Mirror) { $Arguments += "/PURGE" } @@ -122,75 +114,59 @@ foreach($Source in @($Sources)) ROBOCOPY.exe $Source $Target @Arguments } } - else - { + else { $SourceFolderPath = Split-Path $Source -Parent $SourceFileName = Split-Path $Source -Leaf $TargetFile = Join-Path $Target $SourceFileName $SourceHash = ( Get-Hash $Source ).SHA256 $TargetHash = $null - if(Test-Path $Target -PathType Leaf) - { + if (Test-Path $Target -PathType Leaf) { $TargetHash = ( Get-Hash $Target -ErrorAction SilentlyContinue -WarningAction SilentlyContinue ).SHA256 $TargetPath = $Target } - elseif(Test-Path $TargetFile -PathType Leaf) - { + elseif (Test-Path $TargetFile -PathType Leaf) { $TargetHash = ( Get-Hash $TargetFile -ErrorAction SilentlyContinue -WarningAction SilentlyContinue ).SHA256 $TargetPath = $TargetFile } Write-Verbose "Source [$Source] hash [$SourceHash]`n`tTarget [$TargetPath] hash [$TargetHash]" - if($TargetHash -ne $SourceHash) - { + if ($TargetHash -ne $SourceHash) { Write-Verbose "Hashes do not match" - if($PSDependAction -like 'Install') - { + if ($PSDependAction -like 'Install') { Write-Verbose "Copying file [$Source] to [$Target]" Copy-Item -Path $Source -Destination $Target -Force } - if($PSDependAction -like 'Test' -and $PSDependAction.count -eq 1) - { + if ($PSDependAction -like 'Test' -and $PSDependAction.count -eq 1) { $TestOutput += $false } } - else - { + else { Write-Verbose "Matching hash: [$Source] = [$TargetFile]" - if($PSDependAction -like 'Test' -and $PSDependAction.count -eq 1) - { + if ($PSDependAction -like 'Test' -and $PSDependAction.count -eq 1) { $TestOutput += $True } } } } -if($PSDependAction -like 'Test' -and $PSDependAction.count -eq 1) -{ - if(@($TestOutput) -contains $false -or @($TestOutput) -notcontains $true) - { +if ($PSDependAction -like 'Test' -and $PSDependAction.count -eq 1) { + if (@($TestOutput) -contains $false -or @($TestOutput) -notcontains $true) { return $false } - else - { + else { return $True } } -if($PSDependAction -like 'Import') -{ - if(-not $ImportPath) - { - if(Test-Path $Target -PathType Leaf) - { +if ($PSDependAction -like 'Import') { + if (-not $ImportPath) { + if (Test-Path $Target -PathType Leaf) { $ImportPath = Split-Path $Target -Parent } - elseif(Test-Path $Target -PathType Container) - { + elseif (Test-Path $Target -PathType Container) { $ImportPath = $Target } - else - { + else { Write-Error "Could not import target [$Target], path not found" return } diff --git a/PSDepend/PSDependScripts/Git.ps1 b/PSDepend/PSDependScripts/Git.ps1 index 527588b..6dbb5f0 100644 --- a/PSDepend/PSDependScripts/Git.ps1 +++ b/PSDepend/PSDependScripts/Git.ps1 @@ -75,24 +75,20 @@ param( # Extract data from Dependency $DependencyName = $Dependency.DependencyName $Name = $Dependency.Name -if(-not $Name) -{ +if (-not $Name) { $Name = $DependencyName } #Name is in account/repo format, default to GitHub as source #This likely needs work, and will need to change if GitHub changes valid characters for usernames -if($Name -match "^[a-zA-Z0-9]+/[a-zA-Z0-9_-]+$") -{ +if ($Name -match "^[a-zA-Z0-9]+/[a-zA-Z0-9_-]+$") { $Name = "https://github.com/$Name.git" } $GitName = $Name.trimend('/').split('/')[-1] -replace "\.git$", '' -if($Dependency.Target -and ($Target = (Get-Item $Dependency.Target -ErrorAction SilentlyContinue).FullName)) -{ +if ($Dependency.Target -and ($Target = (Get-Item $Dependency.Target -ErrorAction SilentlyContinue).FullName)) { Write-Debug "Target resolved to $Target" } -else -{ +else { if ($Dependency.Target) { $Target = $ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath($Dependency.Target) Write-Debug "Target $($Dependency.Target) does not exist yet, will be created" @@ -105,71 +101,58 @@ else $RepoPath = Join-Path $Target $GitName $GottaInstall = $True -if(-not (Test-Path $Target) -and $PSDependAction -contains 'Install') -{ +if (-not (Test-Path $Target) -and $PSDependAction -contains 'Install') { Write-Verbose "Creating folder [$Target] for git dependency [$Name]" $null = New-Item $Target -ItemType Directory -Force } -if(-not (Test-Path $RepoPath)) -{ +if (-not (Test-Path $RepoPath)) { # Nothing found, return test output - if( $PSDependAction -contains 'Test' -and $PSDependAction.count -eq 1) - { + if ( $PSDependAction -contains 'Test' -and $PSDependAction.count -eq 1) { return $False } } -else # Target exists -{ +else { # Target exists $GottaTest = $True } -if(-not (Get-Command git -ErrorAction SilentlyContinue)) -{ +if (-not (Get-Command git -ErrorAction SilentlyContinue)) { Write-Error "Git dependency type requires git. Ensure this is in your path, or explicitly specified in $ModuleRoot\PSDepend.Config's GitPath. Skipping [$DependencyName]" } $Version = $Dependency.Version -if(-not $Version) -{ +if (-not $Version) { $Version = 'main' } -if($GottaTest) -{ +if ($GottaTest) { Push-Location Set-Location $RepoPath $Branch = Invoke-ExternalCommand git -Arguments (Write-Output rev-parse --abbrev-ref HEAD) -Passthru $Commit = Invoke-ExternalCommand git -Arguments (Write-Output rev-parse HEAD) -Passthru Pop-Location - if($Version -eq $Branch -or $Version -eq $Commit) - { + if ($Version -eq $Branch -or $Version -eq $Commit) { Write-Verbose "[$RepoPath] exists and is already at version [$Version]" - if($PSDependAction -contains 'Test' -and $PSDependAction.count -eq 1) - { + if ($PSDependAction -contains 'Test' -and $PSDependAction.count -eq 1) { return $true } $GottaInstall = $False } - elseif($PSDependAction -contains 'Test' -and $PSDependAction.count -eq 1) - { + elseif ($PSDependAction -contains 'Test' -and $PSDependAction.count -eq 1) { Write-Verbose "[$RepoPath] exists and is at branch [$Branch], commit [$Commit].`nWe don't currently support moving to the requested version [$Version]" return $false } - else - { + else { Write-Verbose "[$RepoPath] exists and is at branch [$Branch], commit [$Commit].`nWe don't currently support moving to the requested version [$Version]" $GottaInstall = $False } } -if($PSDependAction -notcontains 'Install') -{ +if ($PSDependAction -notcontains 'Install') { return } -if($GottaInstall -and !$ExtractProject) -{ +if ($GottaInstall -and !$ExtractProject) { Push-Location Set-Location $Target Write-Verbose -Message "Cloning dependency [$Name] with git from [$($Target)]" @@ -181,7 +164,7 @@ if($GottaInstall -and !$ExtractProject) Invoke-ExternalCommand git 'checkout', $Version Pop-Location } -elseif($GottaInstall -and $ExtractProject) { +elseif ($GottaInstall -and $ExtractProject) { $OutPath = Join-Path ([System.IO.Path]::GetTempPath()) ([guid]::NewGuid().guid) $RepoFolder = Join-Path -Path $OutPath -ChildPath $GitName @@ -202,20 +185,17 @@ elseif($GottaInstall -and $ExtractProject) { Pop-Location #TODO: Implement test and import PSDependActions. - if(-not (Test-Path $Target)) - { + if (-not (Test-Path $Target)) { $null = New-Item -ItemType Directory -Path $Target -Force } - foreach($Item in $ToCopy) - { + foreach ($Item in $ToCopy) { Write-Verbose "Copy From: $ToCopy To: $Target" Copy-Item -Path $Item -Destination $Target -Force -Confirm:$False -Recurse } Remove-Item $OutPath -Force -Recurse } -if($Dependency.AddToPath) -{ +if ($Dependency.AddToPath) { Write-Verbose "Setting PSModulePath to`n$($Target, $env:PSModulePath -join ';' | Out-String)" Add-ToItemCollection -Reference Env:\PSModulePath -Item (Get-Item $Target).FullName @@ -224,8 +204,7 @@ if($Dependency.AddToPath) } $ToImport = $Target -if($ImportPath) -{ +if ($ImportPath) { $ToImport = $ImportPath } Import-PSDependModule $ToImport diff --git a/PSDepend/PSDependScripts/GitHub.ps1 b/PSDepend/PSDependScripts/GitHub.ps1 index 87285c1..420b63d 100644 --- a/PSDepend/PSDependScripts/GitHub.ps1 +++ b/PSDepend/PSDependScripts/GitHub.ps1 @@ -180,91 +180,73 @@ Write-Verbose -Message "Am I on Windows? [$script:IsWindows]! Am I PS Core? [$sc $DependencyID = $Dependency.DependencyName $DependencyVersion = $Dependency.Version $DependencyTarget = $Dependency.Target -$DependencyName = if ($Dependency.Name) {$Dependency.Name} Else {$DependencyID.Split("/")[1]} +$DependencyName = if ($Dependency.Name) { $Dependency.Name } Else { $DependencyID.Split("/")[1] } # Translate "" to "latest" -if($DependencyVersion -eq "") -{ +if ($DependencyVersion -eq "") { $DependencyVersion = "latest" } # Check if the version that should be used is a version number -if($DependencyVersion -match "^\d+(?:\.\d+)+$") -{ +if ($DependencyVersion -match "^\d+(?:\.\d+)+$") { $DependencyVersion = New-Object "System.Version" $DependencyVersion } if ($script:IsCoreCLR) { $ModuleChildPath = "PowerShell\Modules" } -else -{ +else { $ModuleChildPath = "WindowsPowerShell\Modules" } # Get system installation path -if($script:IsWindows) -{ +if ($script:IsWindows) { $AllUsersPath = Join-Path -Path $env:ProgramFiles -ChildPath $ModuleChildPath } -else -{ +else { $AllUsersPath = [System.Management.Automation.Platform]::SelectProductNameForDirectory('SHARED_MODULES') } # Check if the MyDocuments folder path is accessible -try -{ +try { $MyDocumentsFolderPath = [Environment]::GetFolderPath("MyDocuments") } -catch -{ +catch { $MyDocumentsFolderPath = $null } # Get user installation path -if($script:IsWindows) -{ - if($MyDocumentsFolderPath) - { +if ($script:IsWindows) { + if ($MyDocumentsFolderPath) { $CurrentUserPath = Join-Path -Path $MyDocumentsFolderPath -ChildPath $ModuleChildPath } - else - { + else { $CurrentUserPath = Join-Path -Path $HOME -ChildPath "Documents\$ModuleChildPath" } } -else -{ +else { $CurrentUserPath = [System.Management.Automation.Platform]::SelectProductNameForDirectory('USER_MODULES') } # Set target path -if($DependencyTarget) -{ +if ($DependencyTarget) { # Resolve scope keywords - if($DependencyTarget -Eq "CurrentUser") - { + if ($DependencyTarget -Eq "CurrentUser") { $TargetPath = $CurrentUserPath } - elseif($DependencyTarget -Eq "AllUsers") - { + elseif ($DependencyTarget -Eq "AllUsers") { $TargetPath = $AllUsersPath } - else - { + else { $TargetPath = $DependencyTarget } } -else -{ +else { # Set default target depending on admin permissions - if(($script:IsWindows) -And (([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator"))) - { + if (($script:IsWindows) -And (([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator"))) { $TargetPath = $AllUsersPath } - else - { + else { $TargetPath = $CurrentUserPath } } @@ -284,28 +266,22 @@ $ShouldInstall = $false $RemoteAvailable = $false $URL = $null -if($Module) -{ +if ($Module) { $ModuleExisting = $true } -else -{ +else { $ModuleExisting = $false } -if($ModuleExisting) -{ +if ($ModuleExisting) { Write-Verbose "Found existing module [$DependencyName]" $ExistingVersions = $Module | Select-Object -ExpandProperty "Version" # Check if the version that is should be used is a version number - if($DependencyVersion -match "^\d+(?:\.\d+)+$") - { - :versionslocal foreach($ExistingVersion in $ExistingVersions) - { - switch($ExistingVersion.CompareTo($DependencyVersion)) - { - {@(-1, 1) -contains $_} { + if ($DependencyVersion -match "^\d+(?:\.\d+)+$") { + :versionslocal foreach ($ExistingVersion in $ExistingVersions) { + switch ($ExistingVersion.CompareTo($DependencyVersion)) { + { @(-1, 1) -contains $_ } { Write-Verbose "For [$DependencyName], the version you specified [$DependencyVersion] does not match the already existing version [$ExistingVersion]" $ShouldInstall = $true break @@ -319,49 +295,39 @@ if($ModuleExisting) } } } - else - { + else { # The version that is to be used is probably a GitHub branch name $ShouldInstall = $true } } -else -{ +else { Write-Verbose "Did not find existing module [$DependencyName]" $ShouldInstall = $true } # Skip the case when the version that is to be used already exists -if($ShouldInstall) -{ +if ($ShouldInstall) { # API-fetch the tags on GitHub $GitHubVersion = $null $GitHubTag = $null $Page = 0 - try - { - :nullcheck while($GitHubVersion -Eq $null) - { + try { + :nullcheck while ($GitHubVersion -Eq $null) { $Page++ [Net.ServicePointManager]::SecurityProtocol = [Net.ServicePointManager]::SecurityProtocol -bor [Net.SecurityProtocolType]::Tls12 $GitHubTags = Invoke-RestMethod -Uri "https://api.github.com/repos/$DependencyID/tags?per_page=100&page=$Page" - if($GitHubTags) - { - foreach($GitHubTag in $GitHubTags) - { - if($GitHubTag.name -match "^v?\d+(?:\.\d+)+$" -and ($DependencyVersion -match "^\d+(?:\.\d+)+$" -or $DependencyVersion -eq "latest")) - { - $GitHubVersion = New-Object "System.Version" ($GitHubTag.name -replace '^v','') + if ($GitHubTags) { + foreach ($GitHubTag in $GitHubTags) { + if ($GitHubTag.name -match "^v?\d+(?:\.\d+)+$" -and ($DependencyVersion -match "^\d+(?:\.\d+)+$" -or $DependencyVersion -eq "latest")) { + $GitHubVersion = New-Object "System.Version" ($GitHubTag.name -replace '^v', '') - if($DependencyVersion -Eq "latest") - { + if ($DependencyVersion -Eq "latest") { $DependencyVersion = $GitHubVersion } - switch($DependencyVersion.CompareTo($GitHubVersion)) - { + switch ($DependencyVersion.CompareTo($GitHubVersion)) { -1 { # Version is older compared to the GitHub version, continue searching break @@ -379,32 +345,26 @@ if($ShouldInstall) } } } - else - { + else { break nullcheck } } } - catch - { + catch { # Repository does not seem to exist or a branch is the target $ShouldInstall = $false Write-Warning "Could not find module on GitHub: $_" } - if($RemoteAvailable) - { + if ($RemoteAvailable) { # Use the tag's link $URL = $GitHubTag.zipball_url - if($ExistingVersions) - { - :versionsremote foreach($ExistingVersion in $ExistingVersions) - { + if ($ExistingVersions) { + :versionsremote foreach ($ExistingVersion in $ExistingVersions) { # Because a remote and a local version exist # Prevent a module from getting installed twice - switch($ExistingVersion.CompareTo($GitHubVersion)) - { - {@(-1, 1) -contains $_} { + switch ($ExistingVersion.CompareTo($GitHubVersion)) { + { @(-1, 1) -contains $_ } { Write-Verbose "For [$DependencyName], you have a different version [$ExistingVersion] compared to the version available on GitHub [$GitHubVersion]" break } @@ -418,12 +378,10 @@ if($ShouldInstall) } } } - else - { + else { Write-Verbose "[$DependencyID] has no tags on GitHub or [$DependencyVersion] is a branchname" # Translate version "latest" to "main" - if($DependencyVersion -eq "latest") - { + if ($DependencyVersion -eq "latest") { $DependencyVersion = "main" } @@ -433,38 +391,33 @@ if($ShouldInstall) } } -if ($TargetType -ne 'Exact') -{ +if ($TargetType -ne 'Exact') { $TargetPath = Join-Path $TargetPath $DependencyName } # Install action needs to be wanted and logical -if(($PSDependAction -contains 'Install') -and $ShouldInstall) -{ +if (($PSDependAction -contains 'Install') -and $ShouldInstall) { # Create a temporary directory and download the repository to it $OutPath = Join-Path ([System.IO.Path]::GetTempPath()) ([guid]::NewGuid().guid) New-Item -ItemType Directory -Path $OutPath -Force | Out-Null $OutFile = Join-Path $OutPath "$DependencyVersion.zip" - $PreviousProgressPreference=$ProgressPreference - $ProgressPreference='SilentlyContinue' + $PreviousProgressPreference = $ProgressPreference + $ProgressPreference = 'SilentlyContinue' Invoke-RestMethod -Uri $URL -OutFile $OutFile - $ProgressPreference=$PreviousProgressPreference + $ProgressPreference = $PreviousProgressPreference - if(-not (Test-Path $OutFile)) - { + if (-not (Test-Path $OutFile)) { Write-Error "Could not download [$URL] to [$OutFile]. See error details and verbose output for more information" return } # Extract the zip file - if($script:IsWindows) - { + if ($script:IsWindows) { $ZipFile = (New-Object -com shell.application).NameSpace($OutFile) $ZipDestination = (New-Object -com shell.application).NameSpace($OutPath) $ZipDestination.CopyHere($ZipFile.Items()) } - else - { + else { # If not on Windows "Expand-Archive" should be available as PS version 6 is considered minimum. Expand-Archive $OutFile -DestinationPath $OutPath } @@ -475,30 +428,24 @@ if(($PSDependAction -contains 'Install') -and $ShouldInstall) $OutPath = (Get-ChildItem -Path $OutPath)[0].FullName $OutPath = (Rename-Item -Path $OutPath -NewName $DependencyName -PassThru).FullName - if($ExtractPath) - { + if ($ExtractPath) { # Filter only the contents wanted - [string[]]$ToCopy = foreach($RelativePath in $ExtractPath) - { + [string[]]$ToCopy = foreach ($RelativePath in $ExtractPath) { $AbsolutePath = Join-Path $OutPath $RelativePath - if(-not (Test-Path $AbsolutePath)) - { + if (-not (Test-Path $AbsolutePath)) { Write-Warning "Expected ExtractPath [$RelativePath], did not find at [$AbsolutePath]" } - else - { + else { $AbsolutePath } } } - elseif($ExtractProject) - { + elseif ($ExtractProject) { # Filter only the project contents $ProjectDetails = Get-ProjectDetail -Path $OutPath [string[]]$ToCopy = $ProjectDetails.Path } - else - { + else { # Use the standard download path [string[]]$ToCopy = $OutPath } @@ -506,47 +453,39 @@ if(($PSDependAction -contains 'Install') -and $ShouldInstall) Write-Verbose "Contents that will be copied: $ToCopy" # Copy the contents to their target - if(-not (Test-Path $TargetPath)) - { + if (-not (Test-Path $TargetPath)) { New-Item $TargetPath -ItemType "directory" -Force } $Destination = $null - if($TargetType -eq 'Exact') - { + if ($TargetType -eq 'Exact') { $Destination = $TargetPath } - elseif($DependencyVersion -match "^\d+(?:\.\d+)+$" -and $PSVersionTable.PSVersion -ge '5.0' ) - { + elseif ($DependencyVersion -match "^\d+(?:\.\d+)+$" -and $PSVersionTable.PSVersion -ge '5.0' ) { # For versioned GitHub tags $Destination = Join-Path $TargetPath $DependencyVersion } - elseif(($DependencyVersion -eq "latest") -and ($RemoteAvailable) -and $PSVersionTable.PSVersion -ge '5.0' ) - { + elseif (($DependencyVersion -eq "latest") -and ($RemoteAvailable) -and $PSVersionTable.PSVersion -ge '5.0' ) { # For latest GitHub tags $Destination = Join-Path $TargetPath $GitHubVersion } - elseif($PSVersionTable.PSVersion -ge '5.0' -and $TargetType -eq 'Parallel') - { + elseif ($PSVersionTable.PSVersion -ge '5.0' -and $TargetType -eq 'Parallel') { # For GitHub branches $Destination = Join-Path $TargetPath $DependencyVersion $Destination = Join-Path $Destination $DependencyName } - else - { + else { $Destination = $TargetPath } - if($Force -and (Test-Path -Path $Destination)) - { + if ($Force -and (Test-Path -Path $Destination)) { Remove-Item -Path $Destination -Force -Recurse } Write-Verbose "Copying [$($ToCopy.Count)] items to destination [$Destination] with`nTarget [$TargetPath]`nName [$DependencyName]`nVersion [$DependencyVersion]`nGitHubVersion [$GitHubVersion]" - foreach($Item in $ToCopy) - { + foreach ($Item in $ToCopy) { Copy-Item -Path $Item -Destination $Destination -Force -Recurse } @@ -556,18 +495,15 @@ if(($PSDependAction -contains 'Install') -and $ShouldInstall) } # Conditional import -if($ModuleExisting) -{ +if ($ModuleExisting) { Import-PSDependModule -Name $TargetPath -Action $PSDependAction } -elseif($PSDependAction -contains 'Import') -{ +elseif ($PSDependAction -contains 'Import') { Write-Warning "[$DependencyName] at [$TargetPath] should be imported, but does not exist" } # Return true or false if Test action is wanted -if($PSDependAction -contains 'Test') -{ +if ($PSDependAction -contains 'Test') { return $ModuleExistingMatches } diff --git a/PSDepend/PSDependScripts/Noop.ps1 b/PSDepend/PSDependScripts/Noop.ps1 index 044e100..9057351 100644 --- a/PSDepend/PSDependScripts/Noop.ps1 +++ b/PSDepend/PSDependScripts/Noop.ps1 @@ -26,9 +26,9 @@ param ( Write-Verbose "Starting noop run with $($Dependency.count) sources" [PSCustomObject]@{ - PSBoundParameters = $PSBoundParameters - Dependency= $Dependency + PSBoundParameters = $PSBoundParameters + Dependency = $Dependency DependencyParameters = $Dependency.Parameters - GetVariable = (Get-Variable) - ENV = Get-Childitem ENV: + GetVariable = (Get-Variable) + ENV = Get-ChildItem ENV: } \ No newline at end of file diff --git a/PSDepend/PSDependScripts/Npm.ps1 b/PSDepend/PSDependScripts/Npm.ps1 index 8f8e51b..62faec7 100644 --- a/PSDepend/PSDependScripts/Npm.ps1 +++ b/PSDepend/PSDependScripts/Npm.ps1 @@ -65,54 +65,60 @@ param ( [switch]$Global ) #region Extract Dependency Data - $Name = $Dependency.DependencyName - $Version = $Dependency.Version - $Target = $Dependency.Target - If (-not [string]::IsNullOrEmpty($Target) -and $Target -ne 'global') { - # If the target matches a full path or UNC path, don't modify it; - # Otherwise, assume that its a folder _in the current directory_. - # If no target is specified, it will install to the current directory. - If ($Target -notmatch '(^/|:|\\\\)') { - $Target = "$PWD\$Target" - } - If (-not (Test-Path $Target) -and $PSDependAction -contains 'Install') { - Write-Verbose "Creating folder [$Target] for node module dependency [$Name]" - $null = New-Item -ItemType directory -Path $Target -Force - } +$Name = $Dependency.DependencyName +$Version = $Dependency.Version +$Target = $Dependency.Target +If (-not [string]::IsNullOrEmpty($Target) -and $Target -ne 'global') { + # If the target matches a full path or UNC path, don't modify it; + # Otherwise, assume that its a folder _in the current directory_. + # If no target is specified, it will install to the current directory. + If ($Target -notmatch '(^/|:|\\\\)') { + $Target = "$PWD\$Target" } + If (-not (Test-Path $Target) -and $PSDependAction -contains 'Install') { + Write-Verbose "Creating folder [$Target] for node module dependency [$Name]" + $null = New-Item -ItemType directory -Path $Target -Force + } +} #endregion Extract Dependency Data #region Test Action - If ($PSDependAction -contains 'Test') { - $PackageListArguments = 'ls --json --silent' - If ([string]::IsNullOrEmpty($Target)) { - $InstalledNodeModules = Get-NodeModule - } ElseIf ($Target -eq 'global') { - $InstalledNodeModules = Get-NodeModule -Global - } Else { - Push-Location $Target - $InstalledNodeModules = Get-NodeModule - Pop-Location - } - $InstalledModule = $InstalledNodeModules.$Name - If ($InstalledModule -eq $null) { - return $false - } ElseIf ($Version -ne $null -and $InstalledModule.Version -ne $Version) { - return $false - } Else { - return $true - } +If ($PSDependAction -contains 'Test') { + $PackageListArguments = 'ls --json --silent' + If ([string]::IsNullOrEmpty($Target)) { + $InstalledNodeModules = Get-NodeModule + } + ElseIf ($Target -eq 'global') { + $InstalledNodeModules = Get-NodeModule -Global + } + Else { + Push-Location $Target + $InstalledNodeModules = Get-NodeModule + Pop-Location } + $InstalledModule = $InstalledNodeModules.$Name + If ($InstalledModule -eq $null) { + return $false + } + ElseIf ($Version -ne $null -and $InstalledModule.Version -ne $Version) { + return $false + } + Else { + return $true + } +} #endregion Test Action #region Install Action - If ($PSDependAction -contains 'Install') { - If ([string]::IsNullOrEmpty($Target)) { - $null = Install-NodeModule -PackageName $Name -Version $Version - } ElseIf ($Target -eq 'global') { - $null = Install-NodeModule -PackageName $Name -Version $Version -Global - } Else { - Push-Location $Target - $null = Install-NodeModule -PackageName $Name -Version $Version - Pop-Location - } +If ($PSDependAction -contains 'Install') { + If ([string]::IsNullOrEmpty($Target)) { + $null = Install-NodeModule -PackageName $Name -Version $Version + } + ElseIf ($Target -eq 'global') { + $null = Install-NodeModule -PackageName $Name -Version $Version -Global + } + Else { + Push-Location $Target + $null = Install-NodeModule -PackageName $Name -Version $Version + Pop-Location } +} #endregion Install Action \ No newline at end of file diff --git a/PSDepend/PSDependScripts/Nuget.ps1 b/PSDepend/PSDependScripts/Nuget.ps1 index 64f3bc4..5c4cf3e 100644 --- a/PSDepend/PSDependScripts/Nuget.ps1 +++ b/PSDepend/PSDependScripts/Nuget.ps1 @@ -79,42 +79,35 @@ param( [string]$Name ) # Extract data from Dependency - $DependencyName = $Dependency.DependencyName - if ($null -ne $Dependency.Name) - { - $DependencyName = $Dependency.Name - } +$DependencyName = $Dependency.DependencyName +if ($null -ne $Dependency.Name) { + $DependencyName = $Dependency.Name +} - $Version = $Dependency.Version - if(-not $Version) - { - $Version = 'latest' - } +$Version = $Dependency.Version +if (-not $Version) { + $Version = 'latest' +} - $Source = $Dependency.Source - if(-not $Dependency.Source) - { - $Source = 'https://www.nuget.org/api/v2/' - } +$Source = $Dependency.Source +if (-not $Dependency.Source) { + $Source = 'https://www.nuget.org/api/v2/' +} - # We use target as a proxy for Scope - $Target = $Dependency.Target - if(-not $Dependency.Target) - { - Write-Error "Nuget requires a Dependency Target. Skipping [$DependencyName]" - return - } +# We use target as a proxy for Scope +$Target = $Dependency.Target +if (-not $Dependency.Target) { + Write-Error "Nuget requires a Dependency Target. Skipping [$DependencyName]" + return +} - $Credential = $Dependency.Credential +$Credential = $Dependency.Credential -if(-not (Get-Command Nuget -ErrorAction SilentlyContinue)) -{ - if(Test-PlatformSupport -Type 'Nuget' -Support 'windows','core') - { +if (-not (Get-Command Nuget -ErrorAction SilentlyContinue)) { + if (Test-PlatformSupport -Type 'Nuget' -Support 'windows', 'core') { BootStrap-Nuget -NugetPath $NuGetPath } - if(-not (Get-Command Nuget -ErrorAction SilentlyContinue)) - { + if (-not (Get-Command Nuget -ErrorAction SilentlyContinue)) { Write-Error "Nuget requires Nuget.exe. Ensure this is in your path, or explicitly specified in $ModuleRoot\PSDepend.Config's NugetPath. Skipping [$DependencyName]" return } @@ -123,7 +116,7 @@ if(-not (Get-Command Nuget -ErrorAction SilentlyContinue)) Write-Verbose -Message "Getting dependency [$DependencyName] from Nuget source [$Source]" # This code works for both install and save scenarios. -$PackagePath = Join-Path $Target $DependencyName +$PackagePath = Join-Path $Target $DependencyName $NameIs = if ($PSBoundParameters.ContainsKey('Name')) { $Name @@ -132,10 +125,8 @@ else { $DependencyName } -if(Test-Path $PackagePath) -{ - if($null -eq (Get-ChildItem $PackagePath -Filter "$NameIs*" -Include '*.exe', '*.dll' -Recurse)) - { +if (Test-Path $PackagePath) { + if ($null -eq (Get-ChildItem $PackagePath -Filter "$NameIs*" -Include '*.exe', '*.dll' -Recurse)) { # For now, skip if we don't find a DLL matching the expected name Write-Error "Could not find existing DLL for dependency [$DependencyName] in package path [$PackagePath]" return @@ -149,13 +140,10 @@ if(Test-Path $PackagePath) $GetGalleryVersion = { (Find-NugetPackage -Name $DependencyName -PackageSourceUrl $Source -Credential $Credential -IsLatest).Version } # Version string, and equal to current - if($Version -and $Version -ne 'latest') - { - if(Test-VersionEquality $Version $ExistingVersion) - { + if ($Version -and $Version -ne 'latest') { + if (Test-VersionEquality $Version $ExistingVersion) { Write-Verbose "You have the requested version [$Version] of [$DependencyName]" - if($PSDependAction -contains 'Test') - { + if ($PSDependAction -contains 'Test') { return $True } return $null @@ -163,31 +151,25 @@ if(Test-Path $PackagePath) } # latest, and we have latest - if( $Version -and + if ( $Version -and ($Version -eq 'latest' -or $Version -like '') -and ($GalleryVersion = [System.Version](& $GetGalleryVersion)) -le [System.Version]$ExistingVersion - ) - { + ) { Write-Verbose "You have the latest version of [$DependencyName], with installed version [$ExistingVersion] and Source version [$GalleryVersion]" - if($PSDependAction -contains 'Test') - { + if ($PSDependAction -contains 'Test') { return $True } return $null } Write-Verbose "Removing existing [$PackagePath]`nContinuing to install [$DependencyName]: Requested version [$version], existing version [$ExistingVersion]" - if($PSDependAction -contains 'Install') - { - if($Force) - { + if ($PSDependAction -contains 'Install') { + if ($Force) { Remove-Item $PackagePath -Force -Recurse } - else - { + else { Write-Verbose "Use -Force to remove existing [$PackagePath]`nSkipping install of [$DependencyName]: Requested version [$version], existing version [$ExistingVersion]" - if( $PSDependAction -contains 'Test') - { + if ( $PSDependAction -contains 'Test') { return $false } return $null @@ -196,27 +178,23 @@ if(Test-Path $PackagePath) } #No dependency found, return false if we're testing alone... -if( $PSDependAction -contains 'Test' -and $PSDependAction.count -eq 1) -{ +if ( $PSDependAction -contains 'Test' -and $PSDependAction.count -eq 1) { return $False } -if($PSDependAction -contains 'Install') -{ +if ($PSDependAction -contains 'Install') { $TargetExists = Test-Path $Target -PathType Container Write-Verbose "Saving [$DependencyName] with path [$Target]" $NugetParams = '-Source', $Source, '-ExcludeVersion', '-NonInteractive', '-OutputDirectory', $Target - if(-not $TargetExists) - { + if (-not $TargetExists) { Write-Verbose "Creating directory path to [$Target]" $Null = New-Item -ItemType Directory -Path $Target -Force -ErrorAction SilentlyContinue } - if($Version -and $Version -notlike 'latest') - { + if ($Version -and $Version -notlike 'latest') { $NugetParams += '-version', $Version } $NugetParams = 'install', $DependencyName + $NugetParams - Invoke-ExternalCommand Nuget -Arguments $NugetParams + Invoke-ExternalCommand Nuget -Arguments $NugetParams } diff --git a/PSDepend/PSDependScripts/PSGalleryModule.ps1 b/PSDepend/PSDependScripts/PSGalleryModule.ps1 index cf8e2a7..543165d 100644 --- a/PSDepend/PSDependScripts/PSGalleryModule.ps1 +++ b/PSDepend/PSDependScripts/PSGalleryModule.ps1 @@ -116,27 +116,29 @@ param( # Extract data from Dependency $DependencyName = $Dependency.DependencyName $Name = $Dependency.Name -if(-not $Name) { +if (-not $Name) { $Name = $DependencyName } $Version = $Dependency.Version -if(-not $Version) { +if (-not $Version) { $Version = 'latest' } # We use target as a proxy for Scope -if(-not $Dependency.Target) { +if (-not $Dependency.Target) { $Scope = 'AllUsers' -} else { +} +else { $Scope = $Dependency.Target } $Credential = $Dependency.Credential -if('AllUsers', 'CurrentUser' -notcontains $Scope) { +if ('AllUsers', 'CurrentUser' -notcontains $Scope) { $command = 'save' -} else { +} +else { $command = 'install' } @@ -144,15 +146,15 @@ $nugetProvider = @(Get-PackageProvider -ErrorAction SilentlyContinue) | Where-Object { $_.Name -eq 'NuGet' } | Select-Object -First 1 -if(-not $nugetProvider) { +if (-not $nugetProvider) { Write-Debug 'NuGet provider not found. Attempting to install NuGet provider.' # Bootstrap NuGet provider for Windows PowerShell 5.1 and PowerShell 7+. $installPackageProviderSplat = @{ - Name = 'NuGet' + Name = 'NuGet' ForceBootstrap = $true - Force = $true - Scope = 'CurrentUser' - ErrorAction = 'SilentlyContinue' + Force = $true + Scope = 'CurrentUser' + ErrorAction = 'SilentlyContinue' } $null = Install-PackageProvider @installPackageProviderSplat @@ -162,7 +164,7 @@ Write-Verbose -Message "Getting dependency [$name] from PowerShell repository [$ # Validate that $target has been setup as a valid PowerShell repository, # but allow to rely on all PS repos registered. -if($Repository) { +if ($Repository) { $validRepo = Get-PSRepository -Name $Repository -Verbose:$false -ErrorAction SilentlyContinue if (-not $validRepo) { Write-Error "[$Repository] has not been setup as a valid PowerShell repository." @@ -178,40 +180,41 @@ $params = @{ Force = $True } -if($PSBoundParameters.ContainsKey('AllowPrerelease')) { +if ($PSBoundParameters.ContainsKey('AllowPrerelease')) { $params.Add('AllowPrerelease', $AllowPrerelease) } -if($PSBoundParameters.ContainsKey('AcceptLicense')) { +if ($PSBoundParameters.ContainsKey('AcceptLicense')) { $params.Add('AcceptLicense', $AcceptLicense) } -if($Repository) { - $params.Add('Repository',$Repository) +if ($Repository) { + $params.Add('Repository', $Repository) } -if($Version -and $Version -ne 'latest') { +if ($Version -and $Version -ne 'latest') { $Params.add('RequiredVersion', $Version) } -if($Credential) { +if ($Credential) { $Params.add('Credential', $Credential) } # This code works for both install and save scenarios. -if($command -eq 'Save') { - $ModuleName = Join-Path $Scope $Name +if ($command -eq 'Save') { + $ModuleName = Join-Path $Scope $Name $Params.Remove('AllowClobber') $Params.Remove('SkipPublisherCheck') -} elseif ($Command -eq 'Install') { +} +elseif ($Command -eq 'Install') { $ModuleName = $Name } # Only use "SkipPublisherCheck" (and other) parameter if "Install-Module" supports it $availableParameters = (Get-Command "Install-Module").Parameters $tempParams = $Params.Clone() -foreach($thisParameter in $Params.Keys) { - if(-not ($availableParameters.ContainsKey($thisParameter))) { +foreach ($thisParameter in $Params.Keys) { + if (-not ($availableParameters.ContainsKey($thisParameter))) { Write-Verbose -Message "Removing parameter [$thisParameter] from [Install-Module] as it is not available" $tempParams.Remove($thisParameter) } @@ -223,15 +226,15 @@ Add-ToPsModulePathIfRequired -Dependency $Dependency -Action $PSDependAction $Existing = $null $Existing = Get-Module -ListAvailable -Name $ModuleName -ErrorAction SilentlyContinue -if($Existing) { +if ($Existing) { Write-Verbose "Found existing module [$Name]" - if($Version -and $Version -ne 'latest') { + if ($Version -and $Version -ne 'latest') { $matchedInstall = $Existing | Where-Object { Test-VersionEquality $Version $_.Version.ToString() } | Select-Object -First 1 if ($matchedInstall) { Write-Verbose "You have the requested version [$Version] of [$Name]" Import-PSDependModule -Name $ModuleName -Action $PSDependAction -Version $matchedInstall.Version - if($PSDependAction -contains 'Test') { return $true } + if ($PSDependAction -contains 'Test') { return $true } return $null } } @@ -239,13 +242,13 @@ if($Existing) { # Thanks to Brandon Padgett! $ExistingVersion = $Existing | Measure-Object -Property Version -Maximum | Select-Object -ExpandProperty Maximum $FindModuleParams = @{Name = $Name } - if($Repository) { + if ($Repository) { $FindModuleParams.Add('Repository', $Repository) } - if($Credential) { + if ($Credential) { $FindModuleParams.Add('Credential', $Credential) } - if($AllowPrerelease) { + if ($AllowPrerelease) { $FindModuleParams.Add('AllowPrerelease', $AllowPrerelease) } @@ -259,22 +262,24 @@ if($Existing) { [System.Management.Automation.SemanticVersion]::TryParse([string]$GalleryVersion, [ref]$parsedGallerySemanticVersion) ) { $parsedGallerySemanticVersion -le $parsedExistingSemanticVersion - } elseif ( + } + elseif ( [System.Version]::TryParse([string]$ExistingVersion, [ref]$parsedExistingVersion) -and [System.Version]::TryParse([string]$GalleryVersion, [ref]$parsedGalleryVersion) ) { $parsedGalleryVersion -le $parsedExistingVersion - } else { + } + else { $false } # latest, and we have latest - if( $Version -and ($Version -eq 'latest' -or $Version -eq '') -and $isGalleryVersionLessEquals) { + if ( $Version -and ($Version -eq 'latest' -or $Version -eq '') -and $isGalleryVersionLessEquals) { Write-Verbose "You have the latest version of [$Name], with installed version [$ExistingVersion] and PSGallery version [$GalleryVersion]" # Conditional import Import-PSDependModule -Name $ModuleName -Action $PSDependAction -Version $ExistingVersion - if($PSDependAction -contains 'Test') { + if ($PSDependAction -contains 'Test') { return $True } return $null @@ -283,18 +288,19 @@ if($Existing) { } #No dependency found, return false if we're testing alone... -if( $PSDependAction -contains 'Test' -and $PSDependAction.count -eq 1) { +if ( $PSDependAction -contains 'Test' -and $PSDependAction.count -eq 1) { return $False } -if($PSDependAction -contains 'Install') { - if('AllUsers', 'CurrentUser' -contains $Scope) { +if ($PSDependAction -contains 'Install') { + if ('AllUsers', 'CurrentUser' -contains $Scope) { Write-Verbose "Installing [$Name] with scope [$Scope]" Install-Module @params -Scope $Scope - } else { + } + else { Write-Verbose "Saving [$Name] with path [$Scope]" Write-Verbose "Creating directory path to [$Scope]" - if(-not (Test-Path $Scope -ErrorAction SilentlyContinue)) { + if (-not (Test-Path $Scope -ErrorAction SilentlyContinue)) { $Null = New-Item -ItemType Directory -Path $Scope -Force -ErrorAction SilentlyContinue } Save-Module @params -Path $Scope diff --git a/PSDepend/PSDependScripts/PSGalleryNuget.ps1 b/PSDepend/PSDependScripts/PSGalleryNuget.ps1 index f028cbb..4f1ece7 100644 --- a/PSDepend/PSDependScripts/PSGalleryNuget.ps1 +++ b/PSDepend/PSDependScripts/PSGalleryNuget.ps1 @@ -66,43 +66,36 @@ param( [string[]]$PSDependAction = @('Install') ) # Extract data from Dependency - $DependencyName = $Dependency.DependencyName - $Name = $Dependency.Name - if(-not $Name) - { - $Name = $DependencyName - } +$DependencyName = $Dependency.DependencyName +$Name = $Dependency.Name +if (-not $Name) { + $Name = $DependencyName +} - $Version = $Dependency.Version - if(-not $Version) - { - $Version = 'latest' - } +$Version = $Dependency.Version +if (-not $Version) { + $Version = 'latest' +} - $Source = $Dependency.Source - if(-not $Dependency.Source) - { - $Source = 'https://www.powershellgallery.com/api/v2/' - } +$Source = $Dependency.Source +if (-not $Dependency.Source) { + $Source = 'https://www.powershellgallery.com/api/v2/' +} - # We use target as a proxy for Scope - $Target = $Dependency.Target - if(-not $Dependency.Target) - { - Write-Error "PSGalleryNuget requires a Dependency Target. Skipping [$DependencyName]" - return - } +# We use target as a proxy for Scope +$Target = $Dependency.Target +if (-not $Dependency.Target) { + Write-Error "PSGalleryNuget requires a Dependency Target. Skipping [$DependencyName]" + return +} - $Credential = $Dependency.Credential +$Credential = $Dependency.Credential -if(-not (Get-Command Nuget -ErrorAction SilentlyContinue)) -{ - if(Test-PlatformSupport -Type 'PSGalleryNuget' -Support 'windows','core') - { +if (-not (Get-Command Nuget -ErrorAction SilentlyContinue)) { + if (Test-PlatformSupport -Type 'PSGalleryNuget' -Support 'windows', 'core') { BootStrap-Nuget -NugetPath $NuGetPath } - if(-not (Get-Command Nuget -ErrorAction SilentlyContinue)) - { + if (-not (Get-Command Nuget -ErrorAction SilentlyContinue)) { Write-Error "PSGalleryNuget requires Nuget.exe. Ensure this is in your path, or explicitly specified in $ModuleRoot\PSDepend.Config's NugetPath. Skipping [$DependencyName]" return } @@ -111,15 +104,13 @@ if(-not (Get-Command Nuget -ErrorAction SilentlyContinue)) Write-Verbose -Message "Getting dependency [$name] from Nuget source [$Source]" # This code works for both install and save scenarios. -$ModulePath = Join-Path $Target $Name +$ModulePath = Join-Path $Target $Name Add-ToPsModulePathIfRequired -Dependency $Dependency -Action $PSDependAction -if(Test-Path $ModulePath) -{ +if (Test-Path $ModulePath) { $Manifest = Join-Path $ModulePath "$Name.psd1" - if(-not (Test-Path $Manifest)) - { + if (-not (Test-Path $Manifest)) { # For now, skip if we don't find a psd1 Write-Error "Could not find manifest [$Manifest] for dependency [$Name]" return @@ -133,15 +124,12 @@ if(Test-Path $ModulePath) $GetGalleryVersion = { (Find-NugetPackage -Name $Name -PackageSourceUrl $Source -Credential $Credential -IsLatest).Version } # Version string, and equal to current - if($Version -and $Version -ne 'latest') - { - if(Test-VersionEquality $Version $ExistingVersion) - { + if ($Version -and $Version -ne 'latest') { + if (Test-VersionEquality $Version $ExistingVersion) { Write-Verbose "You have the requested version [$Version] of [$Name]" # Conditional import Import-PSDependModule -Name $ModulePath -Action $PSDependAction -Version $ExistingVersion - if($PSDependAction -contains 'Test') - { + if ($PSDependAction -contains 'Test') { return $True } return $null @@ -149,33 +137,27 @@ if(Test-Path $ModulePath) } # latest, and we have latest - if( $Version -and + if ( $Version -and ($Version -eq 'latest' -or $Version -like '') -and ($GalleryVersion = (& $GetGalleryVersion)) -le $ExistingVersion - ) - { + ) { Write-Verbose "You have the latest version of [$Name], with installed version [$ExistingVersion] and PSGallery version [$GalleryVersion]" # Conditional import Import-PSDependModule -Name $ModulePath -Action $PSDependAction -Version $ExistingVersion - if($PSDependAction -contains 'Test') - { + if ($PSDependAction -contains 'Test') { return $True } return $null } Write-Verbose "Removing existing [$ModulePath]`nContinuing to install [$Name]: Requested version [$version], existing version [$ExistingVersion]" - if($PSDependAction -contains 'Install') - { - if($Force) - { + if ($PSDependAction -contains 'Install') { + if ($Force) { Remove-Item $ModulePath -Force -Recurse } - else - { + else { Write-Verbose "Use -Force to remove existing [$ModulePath]`nSkipping install of [$Name]: Requested version [$version], existing version [$ExistingVersion]" - if( $PSDependAction -contains 'Test') - { + if ( $PSDependAction -contains 'Test') { return $false } return $null @@ -184,29 +166,25 @@ if(Test-Path $ModulePath) } #No dependency found, return false if we're testing alone... -if( $PSDependAction -contains 'Test' -and $PSDependAction.count -eq 1) -{ +if ( $PSDependAction -contains 'Test' -and $PSDependAction.count -eq 1) { return $False } -if($PSDependAction -contains 'Install') -{ +if ($PSDependAction -contains 'Install') { $TargetExists = Test-Path $Target -PathType Container Write-Verbose "Saving [$Name] with path [$Target]" $NugetParams = '-Source', $Source, '-ExcludeVersion', '-NonInteractive', '-OutputDirectory', $Target - if(-not $TargetExists) - { + if (-not $TargetExists) { Write-Verbose "Creating directory path to [$Target]" $Null = New-Item -ItemType Directory -Path $Target -Force -ErrorAction SilentlyContinue } - if($Version -and $Version -notlike 'latest') - { + if ($Version -and $Version -notlike 'latest') { $NugetParams += '-version', $Version } $NugetParams = 'install', $Name + $NugetParams - Invoke-ExternalCommand nuget -Arguments $NugetParams + Invoke-ExternalCommand nuget -Arguments $NugetParams } # Conditional import diff --git a/PSDepend/PSDependScripts/PSResourceGet.ps1 b/PSDepend/PSDependScripts/PSResourceGet.ps1 index 97374bf..0b9f8d6 100644 --- a/PSDepend/PSDependScripts/PSResourceGet.ps1 +++ b/PSDepend/PSDependScripts/PSResourceGet.ps1 @@ -159,7 +159,8 @@ if (-not $Version) { # Target doubles as Scope: AllUsers/CurrentUser = install scope; any other value = filesystem path if (-not $Dependency.Target) { $Scope = 'CurrentUser' -} else { +} +else { $Scope = $Dependency.Target } @@ -167,7 +168,8 @@ $Credential = $Dependency.Credential if ('AllUsers', 'CurrentUser' -notcontains $Scope) { $command = 'save' -} else { +} +else { $command = 'install' } @@ -213,14 +215,16 @@ if ($Credential) { if ($command -eq 'save') { $ModuleName = Join-Path $Scope $Name -} elseif ($command -eq 'install') { +} +elseif ($command -eq 'install') { $ModuleName = $Name } # Filter params to only those accepted by the target command $targetCmd = if ($command -eq 'save') { 'Save-PSResource' -} else { +} +else { 'Install-PSResource' } $availableParameters = (Get-Command $targetCmd).Parameters @@ -279,12 +283,14 @@ if ($Existing) { [System.Management.Automation.SemanticVersion]::TryParse([string]$GalleryVersion, [ref]$parsedTempSemanticVersion) ) { $parsedTempSemanticVersion -le $parsedSemanticVersion - } elseif ( + } + elseif ( [System.Version]::TryParse([string]$ExistingVersion, [ref]$parsedVersion) -and [System.Version]::TryParse([string]$GalleryVersion, [ref]$parsedGalleryVersion) ) { $parsedGalleryVersion -le $parsedVersion - } else { + } + else { $false } @@ -310,7 +316,8 @@ if ($PSDependAction -contains 'Install') { if ('AllUsers', 'CurrentUser' -contains $Scope) { Write-Verbose "Installing [$Name] with scope [$Scope]" Install-PSResource @params -Scope $Scope - } else { + } + else { Write-Verbose "Saving [$Name] to path [$Scope]" Write-Verbose "Creating directory path to [$Scope]" if (-not (Test-Path $Scope -ErrorAction SilentlyContinue)) { diff --git a/PSDepend/PSDependScripts/Package.ps1 b/PSDepend/PSDependScripts/Package.ps1 index 4fd9856..3c52f5a 100644 --- a/PSDepend/PSDependScripts/Package.ps1 +++ b/PSDepend/PSDependScripts/Package.ps1 @@ -62,83 +62,70 @@ param( ) # Extract data from Dependency - $DependencyName = $Dependency.DependencyName - $Source = $Dependency.Source - $Name = $Dependency.Name - if(-not $Name) - { - $Name = $DependencyName - } +$DependencyName = $Dependency.DependencyName +$Source = $Dependency.Source +$Name = $Dependency.Name +if (-not $Name) { + $Name = $DependencyName +} - $Version = $Dependency.Version - if(-not $Version) - { - $Version = 'latest' - } +$Version = $Dependency.Version +if (-not $Version) { + $Version = 'latest' +} $PackageSources = @( Get-PackageSource ) -if($PackageSources.Name -notcontains $Source -and -not $PSBoundParameters.ContainsKey('ProviderName')) -{ +if ($PackageSources.Name -notcontains $Source -and -not $PSBoundParameters.ContainsKey('ProviderName')) { Write-Error "PackageSource [$Source] is not valid. Valid sources:`n$($PackageSources.ProviderName | Out-String)" return } $PackageProviders = @( Get-PackageProvider ) -if($PSBoundParameters.ContainsKey('ProviderName') -and $PackageProviders.Name -notcontains $ProviderName) -{ +if ($PSBoundParameters.ContainsKey('ProviderName') -and $PackageProviders.Name -notcontains $ProviderName) { Write-Error "ProviderName [$ProviderName] is not valid. Valid sources:`n$($PackageProviders.Name | Out-String)" return } Write-Verbose -Message "Getting dependency [$name] from Package source [$Source]" -if($PSBoundParameters.ContainsKey('ProviderName')) -{ +if ($PSBoundParameters.ContainsKey('ProviderName')) { $ThisProvider = $ProviderName } -else # Pick providername from this packagesource -{ - $ThisProvider = $PackageSources | Where-Object {$_.Name -eq $Source} | Select-Object -ExpandProperty ProviderName +else { # Pick providername from this packagesource + $ThisProvider = $PackageSources | Where-Object { $_.Name -eq $Source } | Select-Object -ExpandProperty ProviderName } $GetParam = @{ - Name = $Name + Name = $Name ProviderName = $ThisProvider - ErrorAction = 'SilentlyContinue' + ErrorAction = 'SilentlyContinue' } $InstallParam = @{ - Name = $Name + Name = $Name Source = $Source - Force = $True + Force = $True } -if($Version -notlike 'latest') -{ +if ($Version -notlike 'latest') { $GetParam.add('RequiredVersion', $Version) $InstallParam.add('RequiredVersion', $Version) } # Parse target for PowerShellGet -If($ThisProvider -eq 'PowerShellGet') -{ +If ($ThisProvider -eq 'PowerShellGet') { $ValidScope = 'CurrentUser', 'AllUsers' - if(-not $Dependency.Target) - { + if (-not $Dependency.Target) { $Scope = 'AllUsers' } - else - { + else { $Scope = $Dependency.Target } - if($ValidScope -contains $Scope) - { + if ($ValidScope -contains $Scope) { $InstallParam.Add('Scope', $Scope) } } # Parse target for Nuget -if($ThisProvider -eq 'Nuget') -{ - if(-not $Dependency.Target) - { +if ($ThisProvider -eq 'Nuget') { + if (-not $Dependency.Target) { throw 'Nuget provider requires that you specify a target destination. Use the dependency Target for this.' } $GetParam.Add('Destination', $Dependency.Target) @@ -147,16 +134,12 @@ if($ThisProvider -eq 'Nuget') # Add arbitrary keys to support DynamicOptions... -if($Dependency.Parameters.Keys.Count -gt 0) -{ - foreach($Key in $Dependency.Parameters.Keys) - { - if(-not $InstallParam.ContainsKey($Key)) - { +if ($Dependency.Parameters.Keys.Count -gt 0) { + foreach ($Key in $Dependency.Parameters.Keys) { + if (-not $InstallParam.ContainsKey($Key)) { $InstallParam.add($Key, $Dependency.Parameters.$Key) } - else - { + else { $InstallParam.$Key = $Dependency.Parameters.$Key } } @@ -166,18 +149,14 @@ $Existing = $null Write-Verbose "Running Get-Package with $($GetParam | Out-String)" $Existing = Get-Package @GetParam -if($Existing) -{ +if ($Existing) { Write-Verbose "Found existing package [$Name]" - if($Version -and $Version -ne 'latest') - { + if ($Version -and $Version -ne 'latest') { $matchedInstall = $Existing | Where-Object { Test-VersionEquality $Version $_.Version } | Select-Object -First 1 - if ($matchedInstall) - { + if ($matchedInstall) { Write-Verbose "You have the requested version [$Version] of [$Name]" - if($PSDependAction -contains 'Test') - { + if ($PSDependAction -contains 'Test') { return $True } return $null @@ -198,24 +177,24 @@ if($Existing) [System.Management.Automation.SemanticVersion]::TryParse([string]$SourceVersion, [ref]$parsedSourceSemanticVersion) ) { $parsedSourceSemanticVersion -le $parsedExistingSemanticVersion - } elseif ( + } + elseif ( [System.Version]::TryParse([string]$ExistingVersion, [ref]$parsedExistingVersion) -and [System.Version]::TryParse([string]$SourceVersion, [ref]$parsedSourceVersion) ) { $parsedSourceVersion -le $parsedExistingVersion - } else { + } + else { $false } # latest, and we have latest - if( $Version -and + if ( $Version -and ($Version -eq 'latest' -or $Version -like '') -and $isSourceVersionLessEquals - ) - { + ) { Write-Verbose "You have the latest version of [$Name], with installed version [$ExistingVersion] and package source version [$SourceVersion]" - if($PSDependAction -contains 'Test') - { + if ($PSDependAction -contains 'Test') { return $True } return $null @@ -225,13 +204,11 @@ if($Existing) } #No dependency found, return false if we're testing alone... -if( $PSDependAction -contains 'Test' -and $PSDependAction.count -eq 1) -{ +if ( $PSDependAction -contains 'Test' -and $PSDependAction.count -eq 1) { return $False } -if($PSDependAction -contains 'Install') -{ +if ($PSDependAction -contains 'Install') { Write-Verbose "Installing [$Name] with params $($InstallParam | Out-String)" Install-Package @InstallParam } diff --git a/PSDepend/PSDependScripts/Task.ps1 b/PSDepend/PSDependScripts/Task.ps1 index ea26c9a..2165476 100644 --- a/PSDepend/PSDependScripts/Task.ps1 +++ b/PSDepend/PSDependScripts/Task.ps1 @@ -56,21 +56,16 @@ param ( Write-Verbose "Executing $($Dependency.count) tasks" -foreach($Depend in $Dependency) -{ - foreach($Task in $Depend.Source) - { - if(Test-Path $Task -PathType Leaf) - { +foreach ($Depend in $Dependency) { + foreach ($Task in $Depend.Source) { + if (Test-Path $Task -PathType Leaf) { $params = @{} - if($Depend.Parameters) - { + if ($Depend.Parameters) { $params += $Depend.Parameters } . $Task @params } - else - { + else { Write-Warning "Could not find task file [$Task] from dependency [$($Depend.DependencyName)]" } } diff --git a/PSDepend/Private/Add-ObjectDetail.ps1 b/PSDepend/Private/Add-ObjectDetail.ps1 index 0a929e7..5a8b7c6 100644 --- a/PSDepend/Private/Add-ObjectDetail.ps1 +++ b/PSDepend/Private/Add-ObjectDetail.ps1 @@ -1,5 +1,4 @@ -function Add-ObjectDetail -{ +function Add-ObjectDetail { <# .SYNOPSIS Decorate an object with @@ -101,65 +100,55 @@ #> [CmdletBinding()] param( - [Parameter( Mandatory = $true, - Position=0, - ValueFromPipeline=$true )] - [ValidateNotNullOrEmpty()] - [psobject[]]$InputObject, - - [Parameter( Mandatory = $false, - Position=1)] - [string]$TypeName, - - [Parameter( Mandatory = $false, - Position=2)] - [System.Collections.Hashtable]$PropertyToAdd, - - [Parameter( Mandatory = $false, - Position=3)] - [ValidateNotNullOrEmpty()] - [Alias('dp')] - [System.String[]]$DefaultProperties, - - [boolean]$Passthru = $True + [Parameter( Mandatory = $true, + Position = 0, + ValueFromPipeline = $true )] + [ValidateNotNullOrEmpty()] + [psobject[]]$InputObject, + + [Parameter( Mandatory = $false, + Position = 1)] + [string]$TypeName, + + [Parameter( Mandatory = $false, + Position = 2)] + [System.Collections.Hashtable]$PropertyToAdd, + + [Parameter( Mandatory = $false, + Position = 3)] + [ValidateNotNullOrEmpty()] + [Alias('dp')] + [System.String[]]$DefaultProperties, + + [boolean]$Passthru = $True ) - Begin - { - if($PSBoundParameters.ContainsKey('DefaultProperties')) - { + Begin { + if ($PSBoundParameters.ContainsKey('DefaultProperties')) { # define a subset of properties - $ddps = New-Object System.Management.Automation.PSPropertySet DefaultDisplayPropertySet,$DefaultProperties + $ddps = New-Object System.Management.Automation.PSPropertySet DefaultDisplayPropertySet, $DefaultProperties $PSStandardMembers = [System.Management.Automation.PSMemberInfo[]]$ddps } } - Process - { - foreach($Object in $InputObject) - { - switch ($PSBoundParameters.Keys) - { - 'PropertyToAdd' - { - foreach($Key in $PropertyToAdd.Keys) - { + Process { + foreach ($Object in $InputObject) { + switch ($PSBoundParameters.Keys) { + 'PropertyToAdd' { + foreach ($Key in $PropertyToAdd.Keys) { #Add some noteproperties. Slightly faster than Add-Member. $Object.PSObject.Properties.Add( ( New-Object System.Management.Automation.PSNoteProperty($Key, $PropertyToAdd[$Key]) ) ) } } - 'TypeName' - { + 'TypeName' { #Add specified type - [void]$Object.PSObject.TypeNames.Insert(0,$TypeName) + [void]$Object.PSObject.TypeNames.Insert(0, $TypeName) } - 'DefaultProperties' - { + 'DefaultProperties' { # Attach default display property set Add-Member -InputObject $Object -MemberType MemberSet -Name PSStandardMembers -Value $PSStandardMembers } } - if($Passthru) - { + if ($Passthru) { $Object } } diff --git a/PSDepend/Private/Add-ToItemCollection.ps1 b/PSDepend/Private/Add-ToItemCollection.ps1 index e603e26..01b82ec 100644 --- a/PSDepend/Private/Add-ToItemCollection.ps1 +++ b/PSDepend/Private/Add-ToItemCollection.ps1 @@ -1,4 +1,4 @@ -function Add-ToItemCollection { +function Add-ToItemCollection { param( $Delimiter = [IO.Path]::PathSeparator, $Reference, # e.g. ENV:Path @@ -6,13 +6,11 @@ [switch]$Append ) - $Existing = ( Get-Item -Path $Reference ).Value -split $Delimiter | Where-Object {$_ -ne $Item} - if($Append) - { + $Existing = ( Get-Item -Path $Reference ).Value -split $Delimiter | Where-Object { $_ -ne $Item } + if ($Append) { $ToAdd = ( @($Existing) + $Item | Select-Object -Unique ) -join $Delimiter } - else - { + else { $ToAdd = ( @($Item) + @($Existing) | Select-Object -Unique ) -join $Delimiter } Set-Item -Path $Reference -Value $ToAdd diff --git a/PSDepend/Private/Bootstrap-Nuget.ps1 b/PSDepend/Private/Bootstrap-Nuget.ps1 index 765ccd5..0ac3343 100644 --- a/PSDepend/Private/Bootstrap-Nuget.ps1 +++ b/PSDepend/Private/Bootstrap-Nuget.ps1 @@ -1,32 +1,28 @@ -# Check for nuget exe. If it doesn't exist, create full path to parent, and download it +# Check for nuget exe. If it doesn't exist, create full path to parent, and download it function BootStrap-Nuget { [cmdletbinding()] param( $NugetPath = "$env:APPDATA\nuget.exe" ) - if($c = Get-Command 'nuget.exe' -ErrorAction SilentlyContinue) - { - write-verbose "Found Nuget at [$($c.path)]" + if ($c = Get-Command 'nuget.exe' -ErrorAction SilentlyContinue) { + Write-Verbose "Found Nuget at [$($c.path)]" return } #Don't have it, download it $Parent = Split-Path $NugetPath -Parent - if(-not (Test-Path $NugetPath)) - { - if(-not (Test-Path $Parent)) - { + if (-not (Test-Path $NugetPath)) { + if (-not (Test-Path $Parent)) { Write-Verbose "Creating parent paths to [$NugetPath]'s parent: [$Parent]" $null = New-Item $Parent -ItemType Directory -Force } Write-Verbose "Downloading nuget to [$NugetPath]" - Invoke-WebRequest -uri 'https://dist.nuget.org/win-x86-commandline/latest/nuget.exe' -OutFile $NugetPath + Invoke-WebRequest -Uri 'https://dist.nuget.org/win-x86-commandline/latest/nuget.exe' -OutFile $NugetPath } # Add to path - if( ($ENV:Path -split ';') -notcontains $Parent ) - { + if ( ($ENV:Path -split ';') -notcontains $Parent ) { $ENV:Path = $ENV:Path, $Parent -join ';' } } diff --git a/PSDepend/Private/Find-NugetPackage.ps1 b/PSDepend/Private/Find-NugetPackage.ps1 index 903258e..9737430 100644 --- a/PSDepend/Private/Find-NugetPackage.ps1 +++ b/PSDepend/Private/Find-NugetPackage.ps1 @@ -1,4 +1,4 @@ -# All credit and major props to Joel Bennett for this simplified solution that doesn't depend on PowerShellGet +# All credit and major props to Joel Bennett for this simplified solution that doesn't depend on PowerShellGet # https://gist.github.com/Jaykul/1caf0d6d26380509b04cf4ecef807355 function Find-NugetPackage { [CmdletBinding()] @@ -19,25 +19,21 @@ function Find-NugetPackage { ) #Ugly way to do this. Prefer islatest, otherwise look for version, otherwise grab all matching modules - if($IsLatest) - { + if ($IsLatest) { Write-Verbose "Searching for latest [$name] module" $URI = "${PackageSourceUrl}Packages?`$filter=Id eq '$name' and IsLatestVersion" } - elseif($PSBoundParameters.ContainsKey($Version)) - { + elseif ($PSBoundParameters.ContainsKey('Version')) { Write-Verbose "Searching for version [$version] of [$name]" $URI = "${PackageSourceUrl}Packages?`$filter=Id eq '$name' and Version eq '$Version'" } - else - { + else { Write-Verbose "Searching for all versions of [$name] module" $URI = "${PackageSourceUrl}Packages?`$filter=Id eq '$name'" } $headers = @{} - if ($null -ne $Credential) - { + if ($null -ne $Credential) { $basicAuthToken = [Convert]::ToBase64String(":$($Credential.GetNetworkCredential().Password)") $headers["X-NuGet-ApiKey"] = $Credential.UserName @@ -45,10 +41,10 @@ function Find-NugetPackage { } Invoke-RestMethod $URI -Headers $headers | - Select-Object @{n='Name';ex={$_.title.('#text')}}, - @{n='Author';ex={$_.author.name}}, - @{n='Version';ex={$_.properties.NormalizedVersion}}, - @{n='Uri';ex={$_.Content.src}}, - @{n='Description';ex={$_.properties.Description}}, - @{n='Properties';ex={$_.properties}} + Select-Object @{n = 'Name'; ex = { $_.title.('#text') } }, + @{n = 'Author'; ex = { $_.author.name } }, + @{n = 'Version'; ex = { $_.properties.NormalizedVersion } }, + @{n = 'Uri'; ex = { $_.Content.src } }, + @{n = 'Description'; ex = { $_.properties.Description } }, + @{n = 'Properties'; ex = { $_.properties } } } diff --git a/PSDepend/Private/Get-ClonedObject.ps1 b/PSDepend/Private/Get-ClonedObject.ps1 index 502cd2b..8235a1e 100644 --- a/PSDepend/Private/Get-ClonedObject.ps1 +++ b/PSDepend/Private/Get-ClonedObject.ps1 @@ -31,9 +31,11 @@ function Get-ClonedObject { $val = $DeepCopyObject[$key] if ($val -is [hashtable]) { $clone[$key] = Get-ClonedObject $val - } elseif ($val -is [array]) { + } + elseif ($val -is [array]) { $clone[$key] = $val.Clone() - } else { + } + else { $clone[$key] = $val } } diff --git a/PSDepend/Private/Get-Hash.ps1 b/PSDepend/Private/Get-Hash.ps1 index b50f4a9..f9814fd 100644 --- a/PSDepend/Private/Get-Hash.ps1 +++ b/PSDepend/Private/Get-Hash.ps1 @@ -1,4 +1,4 @@ -function Get-Hash { +function Get-Hash { <# .SYNOPSIS Calculates the hash on a given file based on the seleced hash algorithm. @@ -71,49 +71,46 @@ Uses pipeline input from Get-ChildItem to get MD5 hashes of executables. #> - [CmdletBinding(DefaultParameterSetName='File')] + [CmdletBinding(DefaultParameterSetName = 'File')] Param( - [Parameter( ParameterSetName = 'File', - Position=0, - Mandatory=$true, - ValueFromPipelineByPropertyName=$true, - ValueFromPipeline=$True)] - [Alias("PSPath","FullName")] - [string[]]$Path, - - [Parameter( ParameterSetName = 'String', - Position=0, - Mandatory=$true)] - [string[]]$String, - - [Parameter(Position=1)] - [ValidateSet("MD5","SHA1","SHA256","SHA384","SHA512","RIPEMD160")] - [string[]]$Algorithm = "SHA256" + [Parameter( ParameterSetName = 'File', + Position = 0, + Mandatory = $true, + ValueFromPipelineByPropertyName = $true, + ValueFromPipeline = $True)] + [Alias("PSPath", "FullName")] + [string[]]$Path, + + [Parameter( ParameterSetName = 'String', + Position = 0, + Mandatory = $true)] + [string[]]$String, + + [Parameter(Position = 1)] + [ValidateSet("MD5", "SHA1", "SHA256", "SHA384", "SHA512", "RIPEMD160")] + [string[]]$Algorithm = "SHA256" ) Process { - if($PSCmdlet.ParameterSetName -eq 'File') - { + if ($PSCmdlet.ParameterSetName -eq 'File') { $Items = $Path } - elseif($PSCmdlet.ParameterSetName -eq 'String') - { + elseif ($PSCmdlet.ParameterSetName -eq 'String') { $Items = $String } ForEach ($item in $Items) { - if($PSCmdlet.ParameterSetName -eq 'File') - { + if ($PSCmdlet.ParameterSetName -eq 'File') { $item = (Resolve-Path $item).ProviderPath If (-Not ([uri]$item).IsAbsoluteUri) { - Write-Verbose ("{0} is not a full path, using current directory: {1}" -f $item,$pwd) - $item = (Join-Path $pwd ($item -replace "\.\\","")) + Write-Verbose ("{0} is not a full path, using current directory: {1}" -f $item, $pwd) + $item = (Join-Path $pwd ($item -replace "\.\\", "")) } - If(Test-Path $item -Type Container) { - Write-Warning ("Cannot calculate hash for directory: {0}" -f $item) - Return + If (Test-Path $item -Type Container) { + Write-Warning ("Cannot calculate hash for directory: {0}" -f $item) + Return } $object = New-Object PSObject -Property @{ Path = $item @@ -122,40 +119,38 @@ $stream = ([IO.StreamReader]$item).BaseStream - foreach($Type in $Algorithm) { + foreach ($Type in $Algorithm) { [string]$hash = -join ([Security.Cryptography.HashAlgorithm]::Create( $Type ).ComputeHash( $stream ) | - ForEach-Object { "{0:x2}" -f $_ }) + ForEach-Object { "{0:x2}" -f $_ }) - $null = $stream.Seek(0,0) + $null = $stream.Seek(0, 0) #If multiple algorithms are used, then they will be added to existing object $object = Add-Member -InputObject $Object -MemberType NoteProperty -Name $Type -Value $Hash -PassThru } } - elseif($PSCmdlet.ParameterSetName -eq 'String') - { + elseif ($PSCmdlet.ParameterSetName -eq 'String') { $object = New-Object PSObject -Property @{ String = $item } - foreach($Type in $Algorithm) { + foreach ($Type in $Algorithm) { [string]$hash = -join ([Security.Cryptography.HashAlgorithm]::Create( $Type ).ComputeHash( [System.Text.Encoding]::UTF8.GetBytes($item) ) | - ForEach-Object { "{0:x2}" -f $_ }) + ForEach-Object { "{0:x2}" -f $_ }) #If multiple algorithms are used, then they will be added to existing object $object = Add-Member -InputObject $Object -MemberType NoteProperty -Name $Type -Value $Hash -PassThru } } - $object.pstypenames.insert(0,'System.IO.FileInfo.Hash') + $object.pstypenames.insert(0, 'System.IO.FileInfo.Hash') #Output an object with the hash, algorithm and path Write-Output $object - if($PSCmdlet.ParameterSetName -eq 'File') - { + if ($PSCmdlet.ParameterSetName -eq 'File') { #Close the stream $stream.Close() $stream.Dispose() diff --git a/PSDepend/Private/Get-NodeModule.ps1 b/PSDepend/Private/Get-NodeModule.ps1 index beb3521..4ba5ba0 100644 --- a/PSDepend/Private/Get-NodeModule.ps1 +++ b/PSDepend/Private/Get-NodeModule.ps1 @@ -3,7 +3,8 @@ Function Get-NodeModule { Param([switch]$Global) If ($Global -eq $true) { (npm ls --json --silent --global | ConvertFrom-Json).dependencies - } Else { + } + Else { (npm ls --json --silent | ConvertFrom-Json).dependencies } } \ No newline at end of file diff --git a/PSDepend/Private/Get-Parameter.ps1 b/PSDepend/Private/Get-Parameter.ps1 index 0864d89..3c840e8 100644 --- a/PSDepend/Private/Get-Parameter.ps1 +++ b/PSDepend/Private/Get-Parameter.ps1 @@ -1,224 +1,229 @@ -# Borrowed from http://poshcode.org/5929 with a minor tweak for validateset - thanks all! +# Borrowed from http://poshcode.org/5929 with a minor tweak for validateset - thanks all! Function Get-Parameter { - #.Synopsis - # Enumerates the parameters of one or more commands - #.Description - # Lists all the parameters of a command, by ParameterSet, including their aliases, type, etc. - # - # By default, formats the output to tables grouped by command and parameter set - #.Example - # Get-Command Select-Xml | Get-Parameter - #.Example - # Get-Parameter Select-Xml - [CmdletBinding(DefaultParameterSetName="ParameterName")] - param( - # The name of the command to get parameters for - [Parameter(Position = 1, Mandatory = $true, ValueFromPipelineByPropertyName = $true)] - [Alias("Name")] - [string[]]$CommandName, - - # The parameter name to filter by (allows Wilcards) - [Parameter(Position = 2, ValueFromPipelineByPropertyName=$true, ParameterSetName="FilterNames")] - [string[]]$ParameterName = "*", - - # The ParameterSet name to filter by (allows wildcards) - [Parameter(ValueFromPipelineByPropertyName=$true, ParameterSetName="FilterSets")] - [string[]]$SetName = "*", - - # The name of the module which contains the command (this is for scoping) - [Parameter(ValueFromPipelineByPropertyName = $true)] - $ModuleName, - - # Skip testing for Provider parameters (will be much faster) - [Switch]$SkipProviderParameters, - - # Forces including the CommonParameters in the output - [switch]$Force - ) - - begin { - $PropertySet = @( "Name", - @{n="Position";e={if($_.Position -lt 0){"Named"}else{$_.Position}}}, - "Aliases", - @{n="Short";e={$_.Name}}, - @{n="Type";e={$_.ParameterType.Name}}, - @{n="ParameterSet";e={$paramset}}, - @{n="Command";e={$command}}, - @{n="Mandatory";e={$_.IsMandatory}}, - @{n="Provider";e={$_.DynamicProvider}}, - @{n="ValueFromPipeline";e={$_.ValueFromPipeline}}, - @{n="ValueFromPipelineByPropertyName";e={$_.ValueFromPipelineByPropertyName}}, - "ValidateSetValues" # This is a bit specific and not always applicable, but need it for this project.... - ) - function Join-Object { - Param( - [Parameter(Position=0)] - $First, - - [Parameter(ValueFromPipeline=$true,Position=1)] - $Second - ) - begin { - [string[]] $p1 = $First | Get-Member -MemberType Properties | Select-Object -ExpandProperty Name - } - process { - $Output = $First | Select-Object $p1 - foreach ($p in $Second | Get-Member -MemberType Properties | Where-Object {$p1 -notcontains $_.Name} | Select-Object -ExpandProperty Name) { - Add-Member -InputObject $Output -MemberType NoteProperty -Name $p -Value $Second."$p" - } - $Output - } - } - - function Add-Parameters { - [CmdletBinding()] - param( - [Parameter(Position=0)] - [Hashtable]$Parameters, - - [Parameter(Position=1)] - [System.Management.Automation.ParameterMetadata[]]$MoreParameters - ) - - foreach ($p in $MoreParameters | Where-Object { !$Parameters.ContainsKey($_.Name) } ) { - Write-Debug ("INITIALLY: " + $p.Name) - $Parameters.($p.Name) = $p | Select-Object * - } - - [Array]$Dynamic = $MoreParameters | Where-Object { $_.IsDynamic } - if ($dynamic) { - foreach ($d in $dynamic) { - if (Get-Member -InputObject $Parameters.($d.Name) -Name DynamicProvider) { - Write-Debug ("ADD:" + $d.Name + " " + $provider.Name) - $Parameters.($d.Name).DynamicProvider += $provider.Name - } else { - Write-Debug ("CREATE:" + $d.Name + " " + $provider.Name) - $Parameters.($d.Name) = $Parameters.($d.Name) | Select-Object *, @{ n="DynamicProvider";e={ @($provider.Name) } } - } - } - } - } - } - - process { - foreach ($cmd in $CommandName) { - if ($ModuleName) {$cmd = "$ModuleName\$cmd"} - Write-Verbose "Searching for $cmd" - $commands = @(Get-Command $cmd) - - foreach ($command in $commands) { - Write-Verbose "Searching for $command" - # resolve aliases (an alias can point to another alias) - while ($command.CommandType -eq "Alias") { - $command = @(Get-Command ($command.definition))[0] + #.Synopsis + # Enumerates the parameters of one or more commands + #.Description + # Lists all the parameters of a command, by ParameterSet, including their aliases, type, etc. + # + # By default, formats the output to tables grouped by command and parameter set + #.Example + # Get-Command Select-Xml | Get-Parameter + #.Example + # Get-Parameter Select-Xml + [CmdletBinding(DefaultParameterSetName = "ParameterName")] + param( + # The name of the command to get parameters for + [Parameter(Position = 1, Mandatory = $true, ValueFromPipelineByPropertyName = $true)] + [Alias("Name")] + [string[]]$CommandName, + + # The parameter name to filter by (allows Wilcards) + [Parameter(Position = 2, ValueFromPipelineByPropertyName = $true, ParameterSetName = "FilterNames")] + [string[]]$ParameterName = "*", + + # The ParameterSet name to filter by (allows wildcards) + [Parameter(ValueFromPipelineByPropertyName = $true, ParameterSetName = "FilterSets")] + [string[]]$SetName = "*", + + # The name of the module which contains the command (this is for scoping) + [Parameter(ValueFromPipelineByPropertyName = $true)] + $ModuleName, + + # Skip testing for Provider parameters (will be much faster) + [Switch]$SkipProviderParameters, + + # Forces including the CommonParameters in the output + [switch]$Force + ) + + begin { + $PropertySet = @( "Name", + @{n = "Position"; e = { if ($_.Position -lt 0) { "Named" }else { $_.Position } } }, + "Aliases", + @{n = "Short"; e = { $_.Name } }, + @{n = "Type"; e = { $_.ParameterType.Name } }, + @{n = "ParameterSet"; e = { $paramset } }, + @{n = "Command"; e = { $command } }, + @{n = "Mandatory"; e = { $_.IsMandatory } }, + @{n = "Provider"; e = { $_.DynamicProvider } }, + @{n = "ValueFromPipeline"; e = { $_.ValueFromPipeline } }, + @{n = "ValueFromPipelineByPropertyName"; e = { $_.ValueFromPipelineByPropertyName } }, + "ValidateSetValues" # This is a bit specific and not always applicable, but need it for this project.... + ) + function Join-Object { + Param( + [Parameter(Position = 0)] + $First, + + [Parameter(ValueFromPipeline = $true, Position = 1)] + $Second + ) + begin { + [string[]] $p1 = $First | Get-Member -MemberType Properties | Select-Object -ExpandProperty Name } - if (-not $command) {continue} - - Write-Verbose "Get-Parameters for $($Command.Source)\$($Command.Name)" - - $Parameters = @{} - - ## We need to detect provider parameters ... - $NoProviderParameters = !$SkipProviderParameters - ## Shortcut: assume only the core commands get Provider dynamic parameters - if(!$SkipProviderParameters -and $Command.Source -eq "Microsoft.PowerShell.Management") { - ## The best I can do is to validate that the command has a parameter which could accept a string path - foreach($param in $Command.Parameters.Values) { - if(([String[]],[String] -contains $param.ParameterType) -and ($param.ParameterSets.Values | Where-Object { $_.Position -ge 0 })) { - $NoProviderParameters = $false - break - } - } + process { + $Output = $First | Select-Object $p1 + foreach ($p in $Second | Get-Member -MemberType Properties | Where-Object { $p1 -notcontains $_.Name } | Select-Object -ExpandProperty Name) { + Add-Member -InputObject $Output -MemberType NoteProperty -Name $p -Value $Second."$p" + } + $Output } + } - if($NoProviderParameters) { - if($Command.Parameters) { - Add-Parameters $Parameters $Command.Parameters.Values - } - } else { - foreach ($provider in Get-PSProvider) { - if($provider.Drives.Length -gt 0) { - $drive = Get-Location -PSProvider $Provider.Name - } else { - $drive = "{0}\{1}::\" -f $provider.ModuleName, $provider.Name - } - Write-Verbose ("Get-Command $command -Args $drive | Select -Expand Parameters") - - try { - $MoreParameters = (Get-Command $command -Args $drive).Parameters.Values - } catch {} - - if($MoreParameters.Length -gt 0) { - Add-Parameters $Parameters $MoreParameters - } - } - # If for some reason none of the drive paths worked, just use the default parameters - if($Parameters.Length -eq 0) { - if($Command.Parameters) { - Add-Parameters $Parameters $Command.Parameters.Values - } - } - } + function Add-Parameters { + [CmdletBinding()] + param( + [Parameter(Position = 0)] + [Hashtable]$Parameters, - ## Calculate the shortest distinct parameter name -- do this BEFORE removing the common parameters or else. - $Aliases = $Parameters.Values | Select-Object -ExpandProperty Aliases ## Get defined aliases - $ParameterNames = $Parameters.Keys + $Aliases - foreach ($p in $($Parameters.Keys)) { - $short = "^" - $aliases = @($p) + @($Parameters.$p.Aliases) | Sort-Object { $_.Length } - $shortest = "^" + @($aliases)[0] - - foreach($name in $aliases) { - $short = "^" - foreach ($char in [char[]]$name) { - $short += $char - $mCount = ($ParameterNames -match $short).Count - if ($mCount -eq 1 ) { - if($short.Length -lt $shortest.Length) { - $shortest = $short - } - break - } - } - } - if($shortest.Length -lt @($aliases)[0].Length +1){ - # Overwrite the Aliases with this new value - $Parameters.$p = $Parameters.$p | Add-Member NoteProperty Aliases ($Parameters.$p.Aliases + @("$($shortest.SubString(1))*")) -Force -Passthru - } - - # ValidateSet... - $Parameters.$p = $Parameters.$p | Add-Member NoteProperty ValidateSetValues ($Parameters.$p.Attributes | Where-Object {$_.TypeId.name -like 'ValidateSetAttribute'}).ValidValues -Force -Passthru + [Parameter(Position = 1)] + [System.Management.Automation.ParameterMetadata[]]$MoreParameters + ) + foreach ($p in $MoreParameters | Where-Object { !$Parameters.ContainsKey($_.Name) } ) { + Write-Debug ("INITIALLY: " + $p.Name) + $Parameters.($p.Name) = $p | Select-Object * } - # Write-Verbose "Parameters: $($Parameters.Count)`n $($Parameters | ft | out-string)" - $CommonParameters = [string[]][System.Management.Automation.Cmdlet]::CommonParameters - - foreach ($paramset in @($command.ParameterSets | Select-Object -ExpandProperty "Name")) { - $paramset = $paramset | Add-Member -Name IsDefault -MemberType NoteProperty -Value ($paramset -eq $command.DefaultParameterSet) -PassThru - foreach ($parameter in $Parameters.Keys | Sort-Object) { - # Write-Verbose "Parameter: $Parameter" - if (!$Force -and ($CommonParameters -contains $Parameter)) {continue} - if ($Parameters.$Parameter.ParameterSets.ContainsKey($paramset) -or $Parameters.$Parameter.ParameterSets.ContainsKey("__AllParameterSets")) { - if ($Parameters.$Parameter.ParameterSets.ContainsKey($paramset)) { - $output = Join-Object $Parameters.$Parameter $Parameters.$Parameter.ParameterSets.$paramSet - } else { - $output = Join-Object $Parameters.$Parameter $Parameters.$Parameter.ParameterSets.__AllParameterSets - } - - Write-Output $Output | Select-Object $PropertySet | ForEach-Object { - $null = $_.PSTypeNames.Insert(0,"System.Management.Automation.ParameterMetadata") - $null = $_.PSTypeNames.Insert(0,"System.Management.Automation.ParameterMetadataEx") - # Write-Verbose "$(($_.PSTypeNames.GetEnumerator()) -join ", ")" - $_ - } | - Add-Member ScriptMethod ToString { $this.Name } -Force -Passthru | - Where-Object {$(foreach($pn in $ParameterName) {$_ -like $Pn}) -contains $true} | - Where-Object {$(foreach($sn in $SetName) {$_.ParameterSet -like $sn}) -contains $true} - } - } + [Array]$Dynamic = $MoreParameters | Where-Object { $_.IsDynamic } + if ($dynamic) { + foreach ($d in $dynamic) { + if (Get-Member -InputObject $Parameters.($d.Name) -Name DynamicProvider) { + Write-Debug ("ADD:" + $d.Name + " " + $provider.Name) + $Parameters.($d.Name).DynamicProvider += $provider.Name + } + else { + Write-Debug ("CREATE:" + $d.Name + " " + $provider.Name) + $Parameters.($d.Name) = $Parameters.($d.Name) | Select-Object *, @{ n = "DynamicProvider"; e = { @($provider.Name) } } + } + } + } + } + } + + process { + foreach ($cmd in $CommandName) { + if ($ModuleName) { $cmd = "$ModuleName\$cmd" } + Write-Verbose "Searching for $cmd" + $commands = @(Get-Command $cmd) + + foreach ($command in $commands) { + Write-Verbose "Searching for $command" + # resolve aliases (an alias can point to another alias) + while ($command.CommandType -eq "Alias") { + $command = @(Get-Command ($command.definition))[0] + } + if (-not $command) { continue } + + Write-Verbose "Get-Parameters for $($Command.Source)\$($Command.Name)" + + $Parameters = @{} + + ## We need to detect provider parameters ... + $NoProviderParameters = !$SkipProviderParameters + ## Shortcut: assume only the core commands get Provider dynamic parameters + if (!$SkipProviderParameters -and $Command.Source -eq "Microsoft.PowerShell.Management") { + ## The best I can do is to validate that the command has a parameter which could accept a string path + foreach ($param in $Command.Parameters.Values) { + if (([String[]], [String] -contains $param.ParameterType) -and ($param.ParameterSets.Values | Where-Object { $_.Position -ge 0 })) { + $NoProviderParameters = $false + break + } + } + } + + if ($NoProviderParameters) { + if ($Command.Parameters) { + Add-Parameters $Parameters $Command.Parameters.Values + } + } + else { + foreach ($provider in Get-PSProvider) { + if ($provider.Drives.Length -gt 0) { + $drive = Get-Location -PSProvider $Provider.Name + } + else { + $drive = "{0}\{1}::\" -f $provider.ModuleName, $provider.Name + } + Write-Verbose ("Get-Command $command -Args $drive | Select -Expand Parameters") + + try { + $MoreParameters = (Get-Command $command -Args $drive).Parameters.Values + } + catch {} + + if ($MoreParameters.Length -gt 0) { + Add-Parameters $Parameters $MoreParameters + } + } + # If for some reason none of the drive paths worked, just use the default parameters + if ($Parameters.Length -eq 0) { + if ($Command.Parameters) { + Add-Parameters $Parameters $Command.Parameters.Values + } + } + } + + ## Calculate the shortest distinct parameter name -- do this BEFORE removing the common parameters or else. + $Aliases = $Parameters.Values | Select-Object -ExpandProperty Aliases ## Get defined aliases + $ParameterNames = $Parameters.Keys + $Aliases + foreach ($p in $($Parameters.Keys)) { + $short = "^" + $aliases = @($p) + @($Parameters.$p.Aliases) | Sort-Object { $_.Length } + $shortest = "^" + @($aliases)[0] + + foreach ($name in $aliases) { + $short = "^" + foreach ($char in [char[]]$name) { + $short += $char + $mCount = ($ParameterNames -match $short).Count + if ($mCount -eq 1 ) { + if ($short.Length -lt $shortest.Length) { + $shortest = $short + } + break + } + } + } + if ($shortest.Length -lt @($aliases)[0].Length + 1) { + # Overwrite the Aliases with this new value + $Parameters.$p = $Parameters.$p | Add-Member NoteProperty Aliases ($Parameters.$p.Aliases + @("$($shortest.SubString(1))*")) -Force -PassThru + } + + # ValidateSet... + $Parameters.$p = $Parameters.$p | Add-Member NoteProperty ValidateSetValues ($Parameters.$p.Attributes | Where-Object { $_.TypeId.name -like 'ValidateSetAttribute' }).ValidValues -Force -PassThru + + } + + # Write-Verbose "Parameters: $($Parameters.Count)`n $($Parameters | ft | out-string)" + $CommonParameters = [string[]][System.Management.Automation.Cmdlet]::CommonParameters + + foreach ($paramset in @($command.ParameterSets | Select-Object -ExpandProperty "Name")) { + $paramset = $paramset | Add-Member -Name IsDefault -MemberType NoteProperty -Value ($paramset -eq $command.DefaultParameterSet) -PassThru + foreach ($parameter in $Parameters.Keys | Sort-Object) { + # Write-Verbose "Parameter: $Parameter" + if (!$Force -and ($CommonParameters -contains $Parameter)) { continue } + if ($Parameters.$Parameter.ParameterSets.ContainsKey($paramset) -or $Parameters.$Parameter.ParameterSets.ContainsKey("__AllParameterSets")) { + if ($Parameters.$Parameter.ParameterSets.ContainsKey($paramset)) { + $output = Join-Object $Parameters.$Parameter $Parameters.$Parameter.ParameterSets.$paramSet + } + else { + $output = Join-Object $Parameters.$Parameter $Parameters.$Parameter.ParameterSets.__AllParameterSets + } + + Write-Output $Output | Select-Object $PropertySet | ForEach-Object { + $null = $_.PSTypeNames.Insert(0, "System.Management.Automation.ParameterMetadata") + $null = $_.PSTypeNames.Insert(0, "System.Management.Automation.ParameterMetadataEx") + # Write-Verbose "$(($_.PSTypeNames.GetEnumerator()) -join ", ")" + $_ + } | + Add-Member ScriptMethod ToString { $this.Name } -Force -PassThru | + Where-Object { $(foreach ($pn in $ParameterName) { $_ -like $Pn }) -contains $true } | + Where-Object { $(foreach ($sn in $SetName) { $_.ParameterSet -like $sn }) -contains $true } + } + } + } } - } - } - } + } + } } diff --git a/PSDepend/Private/Get-ParameterName.ps1 b/PSDepend/Private/Get-ParameterName.ps1 index 97a4c15..fe5aa48 100644 --- a/PSDepend/Private/Get-ParameterName.ps1 +++ b/PSDepend/Private/Get-ParameterName.ps1 @@ -1,29 +1,27 @@ Function Get-ParameterName { -#Get parameter names for a specific command + #Get parameter names for a specific command [cmdletbinding()] param( [string]$command, [string]$parameterset = $null, [string[]]$excludeDefault = $( "Verbose", - "Debug", - "ErrorAction", - "WarningAction", - "ErrorVariable", - "WarningVariable", - "OutVariable", - "OutBuffer", - "PipelineVariable", - "Confirm", - "Whatif" ), + "Debug", + "ErrorAction", + "WarningAction", + "ErrorVariable", + "WarningVariable", + "OutVariable", + "OutBuffer", + "PipelineVariable", + "Confirm", + "Whatif" ), [string[]]$exclude = $( "Passthru", "Commit" ) ) - if($parameterset) - { - ((Get-Command -name $command).ParameterSets | Where-Object {$_.name -eq $parameterset} ).Parameters.Name | Where-Object {($exclude + $excludeDefault) -notcontains $_} + if ($parameterset) { + ((Get-Command -Name $command).ParameterSets | Where-Object { $_.name -eq $parameterset } ).Parameters.Name | Where-Object { ($exclude + $excludeDefault) -notcontains $_ } } - else - { - ((Get-Command -name $command).ParameterSets | Where-Object {$_.name -eq "__AllParameterSets"} ).Parameters.Name | Where-Object {($exclude + $excludeDefault) -notcontains $_} + else { + ((Get-Command -Name $command).ParameterSets | Where-Object { $_.name -eq "__AllParameterSets" } ).Parameters.Name | Where-Object { ($exclude + $excludeDefault) -notcontains $_ } } } \ No newline at end of file diff --git a/PSDepend/Private/Get-ProjectDetail.ps1 b/PSDepend/Private/Get-ProjectDetail.ps1 index 2340bbe..390df4b 100644 --- a/PSDepend/Private/Get-ProjectDetail.ps1 +++ b/PSDepend/Private/Get-ProjectDetail.ps1 @@ -1,4 +1,4 @@ -# Borrowed and tweaked from BuildHelpers. TODO: Doc, commit back there +# Borrowed and tweaked from BuildHelpers. TODO: Doc, commit back there function Get-ProjectDetail { <# .SYNOPSIS @@ -56,12 +56,10 @@ function Get-ProjectDetail { $CurrentFolder = Split-Path $Path -Leaf $ExpectedPath = Join-Path -Path $Path -ChildPath $CurrentFolder $ExpectedPsd1 = Join-Path -Path $ExpectedPath -ChildPath "$CurrentFolder.psd1" - if((Test-Path $ExpectedPath) -and (Test-Path $ExpectedPsd1)) - { + if ((Test-Path $ExpectedPath) -and (Test-Path $ExpectedPsd1)) { Resolve-ProjectDetail -Path $Path -RelativePath $CurrentFolder -Name $CurrentFolder } - else - { + else { # Look for properly organized modules $ProjectPaths = Get-ChildItem $Path -Directory | Where-Object { @@ -69,22 +67,18 @@ function Get-ProjectDetail { } | Select-Object -ExpandProperty Fullname - if( @($ProjectPaths).Count -gt 1 ) - { + if ( @($ProjectPaths).Count -gt 1 ) { Write-Warning "Found more than one project path via subfolders with psd1 files: $(Split-Path $ProjectPaths -Leaf | Out-String)" } - elseif( @($ProjectPaths).Count -eq 1 ) - { + elseif ( @($ProjectPaths).Count -eq 1 ) { $Name = Split-Path $ProjectPaths -Leaf Resolve-ProjectDetail -Path $Path -RelativePath $Name -Name $Name } #PSD1 in root of project - ick, but happens. - elseif( Test-Path "$ExpectedPath.psd1" ) - { + elseif ( Test-Path "$ExpectedPath.psd1" ) { Resolve-ProjectDetail -Path $Path -Name $CurrentFolder } - else - { + else { Write-Verbose "Could not find a project from [$Path], using root" Resolve-ProjectDetail -Path $Path -Name $CurrentFolder } diff --git a/PSDepend/Private/Get-PropertyOrder.ps1 b/PSDepend/Private/Get-PropertyOrder.ps1 index 4fdb4ce..6223c44 100644 --- a/PSDepend/Private/Get-PropertyOrder.ps1 +++ b/PSDepend/Private/Get-PropertyOrder.ps1 @@ -1,4 +1,4 @@ -#function to extract properties +#function to extract properties Function Get-PropertyOrder { <# .SYNOPSIS @@ -20,9 +20,9 @@ Function Get-PropertyOrder { PowerShell Language #> [cmdletbinding()] - param( - [Parameter(Mandatory=$true,ValueFromPipeline=$true,ValueFromRemainingArguments=$false)] - [PSObject]$InputObject, + param( + [Parameter(Mandatory = $true, ValueFromPipeline = $true, ValueFromRemainingArguments = $false)] + [PSObject]$InputObject, [validateset("AliasProperty", "CodeProperty", "Property", "NoteProperty", "ScriptProperty", "Properties", "PropertySet", "Method", "CodeMethod", "ScriptMethod", "Methods", @@ -34,21 +34,21 @@ Function Get-PropertyOrder { begin { - if($PSBoundParameters.ContainsKey('inputObject')) { + if ($PSBoundParameters.ContainsKey('inputObject')) { $firstObject = $InputObject[0] } } - process{ + process { #we only care about one object... $firstObject = $InputObject } - end{ + end { #Get properties that meet specified parameters $firstObject.psobject.properties | Where-Object { $memberType -contains $_.memberType } | Select-Object -ExpandProperty Name | - Where-Object{ -not $excludeProperty -or $excludeProperty -notcontains $_ } + Where-Object { -not $excludeProperty -or $excludeProperty -notcontains $_ } } } #Get-PropertyOrder \ No newline at end of file diff --git a/PSDepend/Private/Get-TaggedDependency.ps1 b/PSDepend/Private/Get-TaggedDependency.ps1 index 018c0c0..1571a92 100644 --- a/PSDepend/Private/Get-TaggedDependency.ps1 +++ b/PSDepend/Private/Get-TaggedDependency.ps1 @@ -1,22 +1,18 @@ -Function Get-TaggedDependency { +Function Get-TaggedDependency { param( [object[]]$Dependency, [string[]]$Tags ) # Only return dependency with all specified tags - foreach($Depend in $Dependency) - { + foreach ($Depend in $Dependency) { $Include = $False - foreach($Tag in @($Tags)) - { - if($Depend.Tags -contains $Tag) - { + foreach ($Tag in @($Tags)) { + if ($Depend.Tags -contains $Tag) { $Include = $True } } - If($Include) - { + If ($Include) { $Depend } } diff --git a/PSDepend/Private/Get-TopologicalSort.ps1 b/PSDepend/Private/Get-TopologicalSort.ps1 index c557081..278c40b 100644 --- a/PSDepend/Private/Get-TopologicalSort.ps1 +++ b/PSDepend/Private/Get-TopologicalSort.ps1 @@ -1,73 +1,73 @@ # Thanks to http://stackoverflow.com/questions/8982782/does-anyone-have-a-dependency-graph-and-topological-sorting-code-snippet-for-pow # Input is a hashtable of @{ID = @(Depended,On,IDs);...} function Get-TopologicalSort { - param( - [Parameter(Mandatory = $true, Position = 0)] - [hashtable] $edgeList - ) + param( + [Parameter(Mandatory = $true, Position = 0)] + [hashtable] $edgeList + ) - # Make sure we can use HashSet - Add-Type -AssemblyName System.Core + # Make sure we can use HashSet + Add-Type -AssemblyName System.Core - # Clone it so as to not alter original - $currentEdgeList = [hashtable] (Get-ClonedObject $edgeList) + # Clone it so as to not alter original + $currentEdgeList = [hashtable] (Get-ClonedObject $edgeList) - # algorithm from http://en.wikipedia.org/wiki/Topological_sorting#Algorithms - $topologicallySortedElements = New-Object System.Collections.ArrayList - $setOfAllNodesWithNoIncomingEdges = New-Object System.Collections.Queue + # algorithm from http://en.wikipedia.org/wiki/Topological_sorting#Algorithms + $topologicallySortedElements = New-Object System.Collections.ArrayList + $setOfAllNodesWithNoIncomingEdges = New-Object System.Collections.Queue - $fasterEdgeList = @{} + $fasterEdgeList = @{} - # Keep track of all nodes in case they put it in as an edge destination but not source - $allNodes = New-Object -TypeName System.Collections.Generic.HashSet[object] -ArgumentList (,[object[]] $currentEdgeList.Keys) + # Keep track of all nodes in case they put it in as an edge destination but not source + $allNodes = New-Object -TypeName System.Collections.Generic.HashSet[object] -ArgumentList (, [object[]] $currentEdgeList.Keys) - foreach($currentNode in $currentEdgeList.Keys) { - $currentDestinationNodes = [array] $currentEdgeList[$currentNode] - if($currentDestinationNodes.Length -eq 0) { - $setOfAllNodesWithNoIncomingEdges.Enqueue($currentNode) - } + foreach ($currentNode in $currentEdgeList.Keys) { + $currentDestinationNodes = [array] $currentEdgeList[$currentNode] + if ($currentDestinationNodes.Length -eq 0) { + $setOfAllNodesWithNoIncomingEdges.Enqueue($currentNode) + } - foreach($currentDestinationNode in $currentDestinationNodes) { - if(!$allNodes.Contains($currentDestinationNode)) { - [void] $allNodes.Add($currentDestinationNode) - } - } + foreach ($currentDestinationNode in $currentDestinationNodes) { + if (!$allNodes.Contains($currentDestinationNode)) { + [void] $allNodes.Add($currentDestinationNode) + } + } - # Take this time to convert them to a HashSet for faster operation - $currentDestinationNodes = New-Object -TypeName System.Collections.Generic.HashSet[object] -ArgumentList (,[object[]] $currentDestinationNodes ) - [void] $fasterEdgeList.Add($currentNode, $currentDestinationNodes) - } + # Take this time to convert them to a HashSet for faster operation + $currentDestinationNodes = New-Object -TypeName System.Collections.Generic.HashSet[object] -ArgumentList (, [object[]] $currentDestinationNodes ) + [void] $fasterEdgeList.Add($currentNode, $currentDestinationNodes) + } - # Now let's reconcile by adding empty dependencies for source nodes they didn't tell us about - foreach($currentNode in $allNodes) { - if(!$currentEdgeList.ContainsKey($currentNode)) { - [void] $currentEdgeList.Add($currentNode, (New-Object -TypeName System.Collections.Generic.HashSet[object])) - $setOfAllNodesWithNoIncomingEdges.Enqueue($currentNode) - } - } + # Now let's reconcile by adding empty dependencies for source nodes they didn't tell us about + foreach ($currentNode in $allNodes) { + if (!$currentEdgeList.ContainsKey($currentNode)) { + [void] $currentEdgeList.Add($currentNode, (New-Object -TypeName System.Collections.Generic.HashSet[object])) + $setOfAllNodesWithNoIncomingEdges.Enqueue($currentNode) + } + } - $currentEdgeList = $fasterEdgeList + $currentEdgeList = $fasterEdgeList - while($setOfAllNodesWithNoIncomingEdges.Count -gt 0) { - $currentNode = $setOfAllNodesWithNoIncomingEdges.Dequeue() - [void] $currentEdgeList.Remove($currentNode) - [void] $topologicallySortedElements.Add($currentNode) + while ($setOfAllNodesWithNoIncomingEdges.Count -gt 0) { + $currentNode = $setOfAllNodesWithNoIncomingEdges.Dequeue() + [void] $currentEdgeList.Remove($currentNode) + [void] $topologicallySortedElements.Add($currentNode) - foreach($currentEdgeSourceNode in $currentEdgeList.Keys) { - $currentNodeDestinations = $currentEdgeList[$currentEdgeSourceNode] - if($currentNodeDestinations.Contains($currentNode)) { - [void] $currentNodeDestinations.Remove($currentNode) + foreach ($currentEdgeSourceNode in $currentEdgeList.Keys) { + $currentNodeDestinations = $currentEdgeList[$currentEdgeSourceNode] + if ($currentNodeDestinations.Contains($currentNode)) { + [void] $currentNodeDestinations.Remove($currentNode) - if($currentNodeDestinations.Count -eq 0) { - [void] $setOfAllNodesWithNoIncomingEdges.Enqueue($currentEdgeSourceNode) - } - } - } - } + if ($currentNodeDestinations.Count -eq 0) { + [void] $setOfAllNodesWithNoIncomingEdges.Enqueue($currentEdgeSourceNode) + } + } + } + } - if($currentEdgeList.Count -gt 0) { - throw "Graph has at least one cycle!" - } + if ($currentEdgeList.Count -gt 0) { + throw "Graph has at least one cycle!" + } - return $topologicallySortedElements + return $topologicallySortedElements } \ No newline at end of file diff --git a/PSDepend/Private/Get-WebFile.ps1 b/PSDepend/Private/Get-WebFile.ps1 index ae6333c..2a7dfa6 100644 --- a/PSDepend/Private/Get-WebFile.ps1 +++ b/PSDepend/Private/Get-WebFile.ps1 @@ -1,8 +1,8 @@ -# Wrapped for pester mocking... +# Wrapped for pester mocking... Function Get-WebFile { param($URL, $Path) # We have the info, check for file, download it! - [Net.ServicePointManager]::SecurityProtocol = [Net.ServicePointManager]::SecurityProtocol -bor [Net.SecurityProtocolType]::Tls12 + [Net.ServicePointManager]::SecurityProtocol = [Net.ServicePointManager]::SecurityProtocol -bor [Net.SecurityProtocolType]::Tls12 $webclient = New-Object System.Net.WebClient $webclient.DownloadFile($URL, $Path) $webclient.Dispose() diff --git a/PSDepend/Private/Import-PSDependModule.ps1 b/PSDepend/Private/Import-PSDependModule.ps1 index 386e700..39dffaf 100644 --- a/PSDepend/Private/Import-PSDependModule.ps1 +++ b/PSDepend/Private/Import-PSDependModule.ps1 @@ -1,17 +1,15 @@ -function Import-PSDependModule { +function Import-PSDependModule { [cmdletbinding()] param ( [string[]]$Name = $ModulePath, $Action = $PSDependAction, [string] $Version ) - if($PSDependAction -contains 'Import') - { - foreach($Mod in $Name) - { + if ($PSDependAction -contains 'Import') { + foreach ($Mod in $Name) { Write-Verbose "Importing [$Mod]" $importParams = @{ - Name = $Mod + Name = $Mod Scope = 'Global' Force = $true } @@ -19,7 +17,7 @@ # Sanitize version string. The RequiredVersion parameter is a System.Version and # doesn't know anything about pre-release tags. $BaseVersion = ($Version -split '-')[0] - $importParams.add('RequiredVersion',$BaseVersion) + $importParams.add('RequiredVersion', $BaseVersion) } Import-Module @importParams } diff --git a/PSDepend/Private/Install-Dotnet.ps1 b/PSDepend/Private/Install-Dotnet.ps1 index d826818..d3af33b 100644 --- a/PSDepend/Private/Install-Dotnet.ps1 +++ b/PSDepend/Private/Install-Dotnet.ps1 @@ -4,15 +4,15 @@ function Install-Dotnet { [CmdletBinding()] param( - [Parameter(Mandatory=$true)] + [Parameter(Mandatory = $true)] [string] $Channel, - [Parameter(Mandatory=$true)] + [Parameter(Mandatory = $true)] [string] $Version, - [Parameter(Mandatory=$true)] + [Parameter(Mandatory = $true)] [string] $InstallDir ) @@ -29,7 +29,8 @@ function Install-Dotnet { if ($IsWindowsEnv) { & .\$installScript -Channel $Channel -Version $Version -InstallDir $InstallDir - } else { + } + else { bash ./$installScript -c $Channel -v $Version --install-dir $InstallDir } } diff --git a/PSDepend/Private/Install-NodeModule.ps1 b/PSDepend/Private/Install-NodeModule.ps1 index f4f73dc..217dbf3 100644 --- a/PSDepend/Private/Install-NodeModule.ps1 +++ b/PSDepend/Private/Install-NodeModule.ps1 @@ -5,5 +5,5 @@ Function Install-NodeModule { [switch]$Global, [string]$PackageName ) - npm install --silent $(If($Global -eq $true){'--global'}) $PackageName$(If(![string]::IsNullOrEmpty($Version)){"@$Version"}) + npm install --silent $(If ($Global -eq $true) { '--global' }) $PackageName$(If(![string]::IsNullOrEmpty($Version)){"@$Version"}) } \ No newline at end of file diff --git a/PSDepend/Private/Invoke-ExternalCommand.ps1 b/PSDepend/Private/Invoke-ExternalCommand.ps1 index 3226bd1..1e10b3c 100644 --- a/PSDepend/Private/Invoke-ExternalCommand.ps1 +++ b/PSDepend/Private/Invoke-ExternalCommand.ps1 @@ -1,4 +1,4 @@ -# Pester wasn't mocking git... +# Pester wasn't mocking git... # Borrowed idea from https://github.com/pester/Pester/issues/415 function Invoke-ExternalCommand { [cmdletbinding()] @@ -8,8 +8,7 @@ function Invoke-ExternalCommand { $result = $null $result = & $command @arguments Write-Verbose "$($result | Out-String)" - if($Passthru) - { + if ($Passthru) { $Result } } \ No newline at end of file diff --git a/PSDepend/Private/Resolve-DependScripts.ps1 b/PSDepend/Private/Resolve-DependScripts.ps1 index c657499..5da4198 100644 --- a/PSDepend/Private/Resolve-DependScripts.ps1 +++ b/PSDepend/Private/Resolve-DependScripts.ps1 @@ -1,31 +1,24 @@ -# Borrowed from Pester and stripped down +# Borrowed from Pester and stripped down # This might be overkill -function Resolve-DependScripts -{ +function Resolve-DependScripts { param ([object[]] $Path, [bool]$Recurse = $True) $resolvedScriptInfo = @( - foreach ($object in $Path) - { + foreach ($object in $Path) { $unresolvedPath = [string] $object if ($unresolvedPath -notmatch '[\*\?\[\]]' -and (Test-Path -LiteralPath $unresolvedPath -PathType Leaf) -and - (Get-Item -LiteralPath $unresolvedPath -Force) -is [System.IO.FileInfo]) - { + (Get-Item -LiteralPath $unresolvedPath -Force) -is [System.IO.FileInfo]) { $extension = [System.IO.Path]::GetExtension($unresolvedPath) - if ($extension -ne '.psd1') - { + if ($extension -ne '.psd1') { Write-Error "Script path '$unresolvedPath' is not a psd1 file." } - else - { + else { $ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath($unresolvedPath) } } - else - { - $RecurseParam = @{Recurse = $False} - if($Recurse) - { + else { + $RecurseParam = @{Recurse = $False } + if ($Recurse) { $RecurseParam.Recurse = $True } Resolve-Path -Path $unresolvedPath | diff --git a/PSDepend/Private/Save-NugetPackage.ps1 b/PSDepend/Private/Save-NugetPackage.ps1 index 854624f..0a38e2c 100644 --- a/PSDepend/Private/Save-NugetPackage.ps1 +++ b/PSDepend/Private/Save-NugetPackage.ps1 @@ -1,11 +1,11 @@ -# All credit and major props to Joel Bennett for this simplified solution that doesn't depend on PowerShellGet +# All credit and major props to Joel Bennett for this simplified solution that doesn't depend on PowerShellGet # https://gist.github.com/Jaykul/1caf0d6d26380509b04cf4ecef807355 function Save-NugetPackage { [CmdletBinding()] param( - [Parameter(ValueFromPipelineByPropertyName,Mandatory)]$Name, - [Parameter(ValueFromPipelineByPropertyName,Mandatory)]$Uri, - [Parameter(ValueFromPipelineByPropertyName)]$Version="", + [Parameter(ValueFromPipelineByPropertyName, Mandatory)]$Name, + [Parameter(ValueFromPipelineByPropertyName, Mandatory)]$Uri, + [Parameter(ValueFromPipelineByPropertyName)]$Version = "", [string]$Path = $pwd ) $Path = (Join-Path $Path "$Name.$Version.nupkg") diff --git a/PSDepend/Private/Sort-PSDependency.ps1 b/PSDepend/Private/Sort-PSDependency.ps1 index 1cc2af0..47b77fc 100644 --- a/PSDepend/Private/Sort-PSDependency.ps1 +++ b/PSDepend/Private/Sort-PSDependency.ps1 @@ -5,24 +5,19 @@ function Sort-PSDependency { ) $Order = @{} - Foreach($Dependency in $Dependencies) - { - if($Dependency.DependsOn) - { - if(-not $Order.ContainsKey($Dependency.DependencyName)) - { + Foreach ($Dependency in $Dependencies) { + if ($Dependency.DependsOn) { + if (-not $Order.ContainsKey($Dependency.DependencyName)) { $Order.add($Dependency.DependencyName, $Dependency.DependsOn) } } } - if($Order.Keys.Count -gt 0) - { + if ($Order.Keys.Count -gt 0) { $DependencyOrder = Get-TopologicalSort $Order Sort-ObjectWithCustomList -InputObject $Dependencies -Property DependencyName -CustomList $DependencyOrder } - else - { + else { $Dependencies } } \ No newline at end of file diff --git a/PSDepend/Private/Sort-WithCustomList.ps1 b/PSDepend/Private/Sort-WithCustomList.ps1 index a30cd68..c859c64 100644 --- a/PSDepend/Private/Sort-WithCustomList.ps1 +++ b/PSDepend/Private/Sort-WithCustomList.ps1 @@ -1,11 +1,11 @@ # Thanks to https://gallery.technet.microsoft.com/scriptcenter/Sort-With-Custom-List-07b1d93a Function Sort-ObjectWithCustomList { Param ( - [parameter(ValueFromPipeline=$true)] + [parameter(ValueFromPipeline = $true)] [PSObject] $InputObject, - [parameter(Position=1)] + [parameter(Position = 1)] [String] $Property, @@ -13,8 +13,7 @@ Function Sort-ObjectWithCustomList { [Object[]] $CustomList ) - Begin - { + Begin { # convert customList (array) to hash $hash = @{} $rank = 0 @@ -31,7 +30,8 @@ Function Sort-ObjectWithCustomList { $rank = $hash[$key] if ($rank -ne $null) { $rank - } else { + } + else { [System.Double]::PositiveInfinity } } @@ -40,12 +40,10 @@ Function Sort-ObjectWithCustomList { # (I don't know how to match behavior of Sort's InputObject parameter) $objects = @() } - Process - { + Process { $objects += $InputObject } - End - { + End { $objects | Sort-Object -Property $sortOrder } } \ No newline at end of file diff --git a/PSDepend/Private/Test-Dotnet.ps1 b/PSDepend/Private/Test-Dotnet.ps1 index b21b491..edc2d43 100644 --- a/PSDepend/Private/Test-Dotnet.ps1 +++ b/PSDepend/Private/Test-Dotnet.ps1 @@ -4,7 +4,7 @@ function Test-Dotnet { [CmdletBinding()] param( - [Parameter(Mandatory=$true)] + [Parameter(Mandatory = $true)] [string] $Version, @@ -18,13 +18,15 @@ function Test-Dotnet { if ($InstallDir) { $dotnetExePath = Join-Path -Path $InstallDir -ChildPath $dotnetFile - } else { + } + else { # If dotnet is already in the PATH, check to see if that version of dotnet can find the required SDK. # This is "typically" the globally installed dotnet. $dotnetInPath = Get-Command 'dotnet' -ErrorAction SilentlyContinue if ($dotnetInPath) { $dotnetExePath = $dotnetInPath.Source - } else { + } + else { $LocalDotnetDirPath = if ($IsWindowsEnv) { "$env:LocalAppData\Microsoft\dotnet" } else { "$env:HOME/.dotnet" } $dotnetExePath = Join-Path -Path $LocalDotnetDirPath -ChildPath $dotnetFile } @@ -35,7 +37,8 @@ function Test-Dotnet { if ($Version -eq 'latest') { # TODO: This could query the version if you have the latest return $false - } else { + } + else { # We need to separate the prerelease from the version $installedVer, $installedPre = ($installedVersion -split '-') $ver, $pre = ($Version -split '-') diff --git a/PSDepend/Private/Test-PlatformSupport.ps1 b/PSDepend/Private/Test-PlatformSupport.ps1 index 34eec5e..7b0a727 100644 --- a/PSDepend/Private/Test-PlatformSupport.ps1 +++ b/PSDepend/Private/Test-PlatformSupport.ps1 @@ -1,4 +1,4 @@ -function Test-PlatformSupport { +function Test-PlatformSupport { [CmdletBinding()] param( $Type, @@ -7,37 +7,38 @@ ) # test core/full - if('Core' -eq $PSVersionTable.PSEdition) { + if ('Core' -eq $PSVersionTable.PSEdition) { # On Windows with PS Core, 'windows' in Support is sufficient (backwards compat with types # declared before PS Core on Windows was common) $windowsCoreOk = $IsWindows -and ($Support -contains 'windows') - if(-not $windowsCoreOk -and $Support -notcontains 'core') { + if (-not $windowsCoreOk -and $Support -notcontains 'core') { Write-Verbose "Supported platforms [$Support] for type [$Type] does not contain [core]. Pull requests welcome!" return $false } - } else { + } + else { # full windows powershell - if($Support -notcontains 'windows') { + if ($Support -notcontains 'windows') { Write-Verbose "Supported platforms [$Support] for type [$Type] does not contain [windows]. Pull requests welcome!" return $false } } - if($IsLinux) { - if($Support -notcontains 'linux') { + if ($IsLinux) { + if ($Support -notcontains 'linux') { Write-Verbose "Supported platforms [$Support] for type [$Type] does not contain [linux]. Pull requests welcome!" return $false } } - if($IsMacOS) { - if($Support -notcontains 'macos') { + if ($IsMacOS) { + if ($Support -notcontains 'macos') { Write-Verbose "Supported platforms [$Support] for type [$Type] does not contain [macos]. Pull requests welcome!" return $false } } - if($IsWindows) { + if ($IsWindows) { # covers support for core powershell on windows - if($Support -notcontains 'windows') { + if ($Support -notcontains 'windows') { Write-Verbose "Supported platforms [$Support] for type [$Type] does not contain [windows]. Pull requests welcome!" return $false } diff --git a/PSDepend/Private/Validate-DependencyParameters.ps1 b/PSDepend/Private/Validate-DependencyParameters.ps1 index 5560121..de218e2 100644 --- a/PSDepend/Private/Validate-DependencyParameters.ps1 +++ b/PSDepend/Private/Validate-DependencyParameters.ps1 @@ -1,13 +1,11 @@ -function Validate-DependencyParameters { +function Validate-DependencyParameters { [cmdletbinding()] param( [string[]]$Required, [string[]]$Parameters ) - foreach($RequiredParam in $Required) - { - if($Parameters -notcontains $RequiredParam) - { + foreach ($RequiredParam in $Required) { + if ($Parameters -notcontains $RequiredParam) { return $false } } diff --git a/PSDepend/Public/Get-Dependency.ps1 b/PSDepend/Public/Get-Dependency.ps1 index 7923caa..50f4725 100644 --- a/PSDepend/Public/Get-Dependency.ps1 +++ b/PSDepend/Public/Get-Dependency.ps1 @@ -130,19 +130,19 @@ function Get-Dependency { #> [cmdletbinding(DefaultParameterSetName = 'File')] param( - [parameter(ParameterSetName='File')] + [parameter(ParameterSetName = 'File')] [string[]]$Path = $PWD.Path, [string[]]$Tags, - [parameter(ParameterSetName='File')] + [parameter(ParameterSetName = 'File')] [switch]$Recurse, - [parameter(ParameterSetName='Hashtable')] + [parameter(ParameterSetName = 'Hashtable')] [hashtable[]]$InputObject, - [parameter(ParameterSetName='File')] - [parameter(ParameterSetName='Hashtable')] + [parameter(ParameterSetName = 'File')] + [parameter(ParameterSetName = 'Hashtable')] [hashtable]$Credentials ) @@ -156,18 +156,20 @@ function Get-Dependency { ) # Check for preferred value, otherwise try to get value from key, otherwise use default.... $Output = $Default - if($Prefer) { + if ($Prefer) { $Output = $Prefer - } else { + } + else { try { $Output = $Options[$Name] - } catch { + } + catch { $Output = $Default } } # Inject variables - if( $Name -eq 'Target' -or + if ( $Name -eq 'Target' -or $Name -eq 'Source' -or $Name -eq 'PreScripts' -or $Name -eq 'PostScripts') { @@ -180,7 +182,7 @@ function Get-Dependency { [cmdletbinding()] param( $Value ) $Output = $Value - switch($Value) { + switch ($Value) { { $_ -match '^\.$|^\.\\|^\./' } { $Output = $Output -replace '^\.', $PWD.Path } @@ -219,171 +221,174 @@ function Get-Dependency { # Global settings.... $PSDependOptions = $null - if($Dependencies.Containskey('PSDependOptions')) { + if ($Dependencies.Containskey('PSDependOptions')) { $PSDependOptions = $Dependencies.PSDependOptions $Dependencies.Remove('PSDependOptions') } - foreach($Dependency in $Dependencies.keys) { + foreach ($Dependency in $Dependencies.keys) { $DependencyHash = $Dependencies.$Dependency $DependencyType = Get-GlobalOption -Name DependencyType $CredentialName = Get-GlobalOption -Name Credential # Look simple syntax with helpers in the key first - if( $DependencyHash -is [string] -and + if ( $DependencyHash -is [string] -and $Dependency -match '::' -and ($Dependency -split '::').count -eq 2 ) { [PSCustomObject]@{ - PSTypeName = 'PSDepend.Dependency' - DependencyFile = $DependencyFile - DependencyName = ($Dependency -split '::')[1] - DependencyType = ($Dependency -split '::')[0] - Name = ($Dependency -split '::')[1] - Version = $DependencyHash - Parameters = Get-GlobalOption -Name Parameters - Source = Get-GlobalOption -Name Source - Target = Get-GlobalOption -Name Target - AddToPath = Get-GlobalOption -Name AddToPath - Tags = Get-GlobalOption -Name Tags - DependsOn = Get-GlobalOption -Name DependsOn - PreScripts = Get-GlobalOption -Name PreScripts - PostScripts = Get-GlobalOption -Name PostScripts + PSTypeName = 'PSDepend.Dependency' + DependencyFile = $DependencyFile + DependencyName = ($Dependency -split '::')[1] + DependencyType = ($Dependency -split '::')[0] + Name = ($Dependency -split '::')[1] + Version = $DependencyHash + Parameters = Get-GlobalOption -Name Parameters + Source = Get-GlobalOption -Name Source + Target = Get-GlobalOption -Name Target + AddToPath = Get-GlobalOption -Name AddToPath + Tags = Get-GlobalOption -Name Tags + DependsOn = Get-GlobalOption -Name DependsOn + PreScripts = Get-GlobalOption -Name PreScripts + PostScripts = Get-GlobalOption -Name PostScripts PSDependOptions = $PSDependOptions - Raw = $null + Raw = $null } } #Parse simple key=name, value=version format # It doesn't look like a git repo, and simple syntax: PSGalleryModule - elseif( $DependencyHash -is [string] -and + elseif ( $DependencyHash -is [string] -and $Dependency -notmatch '/' -and (-not $DependencyType -or - $DependencyType -eq 'PSGalleryModule')) { + $DependencyType -eq 'PSGalleryModule')) { [PSCustomObject]@{ - PSTypeName = 'PSDepend.Dependency' - DependencyFile = $DependencyFile - DependencyName = $Dependency - DependencyType = 'PSGalleryModule' - Name = $Dependency - Version = $DependencyHash - Parameters = Get-GlobalOption -Name Parameters - Source = Get-GlobalOption -Name Source - Target = Get-GlobalOption -Name Target - AddToPath = Get-GlobalOption -Name AddToPath - Tags = Get-GlobalOption -Name Tags - DependsOn = Get-GlobalOption -Name DependsOn - PreScripts = Get-GlobalOption -Name PreScripts - PostScripts = Get-GlobalOption -Name PostScripts - Credential = Resolve-Credential -Name $CredentialName + PSTypeName = 'PSDepend.Dependency' + DependencyFile = $DependencyFile + DependencyName = $Dependency + DependencyType = 'PSGalleryModule' + Name = $Dependency + Version = $DependencyHash + Parameters = Get-GlobalOption -Name Parameters + Source = Get-GlobalOption -Name Source + Target = Get-GlobalOption -Name Target + AddToPath = Get-GlobalOption -Name AddToPath + Tags = Get-GlobalOption -Name Tags + DependsOn = Get-GlobalOption -Name DependsOn + PreScripts = Get-GlobalOption -Name PreScripts + PostScripts = Get-GlobalOption -Name PostScripts + Credential = Resolve-Credential -Name $CredentialName PSDependOptions = $PSDependOptions - Raw = $null + Raw = $null } } # It looks like a git repo, simple syntax, and not a full URI - elseif($DependencyHash -is [string] -and + elseif ($DependencyHash -is [string] -and $Dependency -match '/' -and $Dependency.split('/').count -eq 2 -and (-not $DependencyType -or - $DependencyType -eq 'GitHub')) { + $DependencyType -eq 'GitHub')) { [PSCustomObject]@{ - PSTypeName = 'PSDepend.Dependency' - DependencyFile = $DependencyFile - DependencyName = $Dependency - DependencyType = 'GitHub' - Name = $Dependency - Version = $DependencyHash - Parameters = Get-GlobalOption -Name Parameters - Source = Get-GlobalOption -Name Source - Target = Get-GlobalOption -Name Target - AddToPath = Get-GlobalOption -Name AddToPath - Tags = Get-GlobalOption -Name Tags - DependsOn = Get-GlobalOption -Name DependsOn - PreScripts = Get-GlobalOption -Name PreScripts - PostScripts = Get-GlobalOption -Name PostScripts + PSTypeName = 'PSDepend.Dependency' + DependencyFile = $DependencyFile + DependencyName = $Dependency + DependencyType = 'GitHub' + Name = $Dependency + Version = $DependencyHash + Parameters = Get-GlobalOption -Name Parameters + Source = Get-GlobalOption -Name Source + Target = Get-GlobalOption -Name Target + AddToPath = Get-GlobalOption -Name AddToPath + Tags = Get-GlobalOption -Name Tags + DependsOn = Get-GlobalOption -Name DependsOn + PreScripts = Get-GlobalOption -Name PreScripts + PostScripts = Get-GlobalOption -Name PostScripts PSDependOptions = $PSDependOptions - Raw = $null + Raw = $null } } # It looks like a git repo, and simple syntax: Git - elseif($DependencyHash -is [string] -and + elseif ($DependencyHash -is [string] -and $Dependency -match '/' -and (-not $DependencyType -or - $DependencyType -eq 'Git')) { + $DependencyType -eq 'Git')) { [PSCustomObject]@{ - PSTypeName = 'PSDepend.Dependency' - DependencyFile = $DependencyFile - DependencyName = $Dependency - DependencyType = 'Git' - Name = $Dependency - Version = $DependencyHash - Parameters = Get-GlobalOption -Name Parameters - Source = Get-GlobalOption -Name Source - Target = Get-GlobalOption -Name Target - AddToPath = Get-GlobalOption -Name AddToPath - Tags = Get-GlobalOption -Name Tags - DependsOn = Get-GlobalOption -Name DependsOn - PreScripts = Get-GlobalOption -Name PreScripts - PostScripts = Get-GlobalOption -Name PostScripts + PSTypeName = 'PSDepend.Dependency' + DependencyFile = $DependencyFile + DependencyName = $Dependency + DependencyType = 'Git' + Name = $Dependency + Version = $DependencyHash + Parameters = Get-GlobalOption -Name Parameters + Source = Get-GlobalOption -Name Source + Target = Get-GlobalOption -Name Target + AddToPath = Get-GlobalOption -Name AddToPath + Tags = Get-GlobalOption -Name Tags + DependsOn = Get-GlobalOption -Name DependsOn + PreScripts = Get-GlobalOption -Name PreScripts + PostScripts = Get-GlobalOption -Name PostScripts PSDependOptions = $PSDependOptions - Raw = $null + Raw = $null } - } else { + } + else { # Parse dependency hash format # Default type is module, unless it's in a git-style format - if(-not $DependencyHash.DependencyType) { + if (-not $DependencyHash.DependencyType) { # Is it a global option? - if($DependencyType) { + if ($DependencyType) { } # GitHub first - elseif( + elseif ( # Ugly right? Watch out for split called on hashtable... ($Dependency -match '/' -and -not $Dependency.Name -and - ($Dependency -is [string] -and $Dependency.split('/').count -eq 2) + ($Dependency -is [string] -and $Dependency.split('/').count -eq 2) ) -or ($DependencyHash.Name -match '/' -and - ($DependencyHash -is [string] -and $DependencyHash.split('/').count -eq 2) + ($DependencyHash -is [string] -and $DependencyHash.split('/').count -eq 2) ) ) { $DependencyType = 'GitHub' } # Now git... - elseif( + elseif ( ($Dependency -match '/' -and -not $Dependency.Name) -or $DependencyHash.Name -match '/' ) { $DependencyType = 'Git' - } else { + } + else { # finally, psgallerymodule $DependencyType = 'PSGalleryModule' } - } else { + } + else { $DependencyType = $DependencyHash.DependencyType } $CredentialName = Get-GlobalOption -Name Credential -Prefer $DependencyHash.Credential [PSCustomObject]@{ - PSTypeName = 'PSDepend.Dependency' - DependencyFile = $DependencyFile - DependencyName = $Dependency - DependencyType = $DependencyType - Name = $DependencyHash.Name - Version = $DependencyHash.Version - Parameters = Get-GlobalOption -Name Parameters -Prefer $DependencyHash.Parameters - Source = Get-GlobalOption -Name Source -Prefer $DependencyHash.Source - Target = Get-GlobalOption -Name Target -Prefer $DependencyHash.Target - AddToPath = Get-GlobalOption -Name AddToPath -Prefer $DependencyHash.AddToPath - Tags = Get-GlobalOption -Name Tags -Prefer $DependencyHash.Tags - DependsOn = Get-GlobalOption -Name DependsOn -Prefer $DependencyHash.DependsOn - PreScripts = Get-GlobalOption -Name PreScripts -Prefer $DependencyHash.PreScripts - PostScripts = Get-GlobalOption -Name PostScripts -Prefer $DependencyHash.PostScripts - Credential = Resolve-Credential -Name $CredentialName + PSTypeName = 'PSDepend.Dependency' + DependencyFile = $DependencyFile + DependencyName = $Dependency + DependencyType = $DependencyType + Name = $DependencyHash.Name + Version = $DependencyHash.Version + Parameters = Get-GlobalOption -Name Parameters -Prefer $DependencyHash.Parameters + Source = Get-GlobalOption -Name Source -Prefer $DependencyHash.Source + Target = Get-GlobalOption -Name Target -Prefer $DependencyHash.Target + AddToPath = Get-GlobalOption -Name AddToPath -Prefer $DependencyHash.AddToPath + Tags = Get-GlobalOption -Name Tags -Prefer $DependencyHash.Tags + DependsOn = Get-GlobalOption -Name DependsOn -Prefer $DependencyHash.DependsOn + PreScripts = Get-GlobalOption -Name PreScripts -Prefer $DependencyHash.PreScripts + PostScripts = Get-GlobalOption -Name PostScripts -Prefer $DependencyHash.PostScripts + Credential = Resolve-Credential -Name $CredentialName PSDependOptions = $PSDependOptions - Raw = $DependencyHash + Raw = $DependencyHash } } } - } + } # Helper to retrieve the credential for a dependency function Resolve-Credential { @@ -397,7 +402,8 @@ function Get-Dependency { if ($Credentials.ContainsKey($Name)) { $credential = $Credentials[$Name] - } else { + } + else { Write-Warning "No credential found for the specified name $Name. Was the dependency misconfigured?" } } @@ -405,19 +411,20 @@ function Get-Dependency { return $credential } - if($PSCmdlet.ParameterSetName -eq 'File') { - $ParsedDependencies = foreach($DependencyPath in $Path) { + if ($PSCmdlet.ParameterSetName -eq 'File') { + $ParsedDependencies = foreach ($DependencyPath in $Path) { #Resolve relative paths... Thanks Oisin! http://stackoverflow.com/a/3040982/3067642 $DependencyPath = $ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath($DependencyPath) - if(Test-Path $DependencyPath -PathType Container) { + if (Test-Path $DependencyPath -PathType Container) { $DependencyFiles = @( Resolve-DependScripts -Path $DependencyPath -Recurse $Recurse ) - } else { + } + else { $DependencyFiles = @( $DependencyPath ) } $DependencyFiles = $DependencyFiles | Select-Object -Unique - foreach($DependencyFile in $DependencyFiles) { + foreach ($DependencyFile in $DependencyFiles) { # Read the file $Base = Split-Path $DependencyFile -Parent $File = Split-Path $DependencyFile -Leaf @@ -426,18 +433,19 @@ function Get-Dependency { Parse-Dependency -ParamSet $PSCmdlet.ParameterSetName } } - } elseif($PSCmdlet.ParameterSetName -eq 'Hashtable') { + } + elseif ($PSCmdlet.ParameterSetName -eq 'Hashtable') { $DependencyFile = 'Hashtable' - $ParsedDependencies = foreach($InputDependency in $InputObject) { + $ParsedDependencies = foreach ($InputDependency in $InputObject) { $Dependencies = $InputDependency Parse-Dependency -ParamSet $PSCmdlet.ParameterSetName } } - if($PSBoundParameters.ContainsKey('Tags')) { + if ($PSBoundParameters.ContainsKey('Tags')) { $ParsedDependencies = Get-TaggedDependency -Dependency $ParsedDependencies -Tags $Tags - if(-not $ParsedDependencies) { + if (-not $ParsedDependencies) { Write-Warning "No dependencies found with tags '$tags'" return } diff --git a/PSDepend/Public/Get-PSDependScript.ps1 b/PSDepend/Public/Get-PSDependScript.ps1 index d104858..f332410 100644 --- a/PSDepend/Public/Get-PSDependScript.ps1 +++ b/PSDepend/Public/Get-PSDependScript.ps1 @@ -30,7 +30,7 @@ function Get-PSDependScript { #> [cmdletbinding()] param( - [validatescript({ Test-Path $_ -PathType Leaf -ErrorAction Stop })] + [validatescript( { Test-Path $_ -PathType Leaf -ErrorAction Stop })] [string]$Path = $(Join-Path $ModuleRoot PSDependMap.psd1) ) @@ -40,19 +40,21 @@ function Get-PSDependScript { $DependencyDefinitions = Import-LocalizedData -BaseDirectory $Base -FileName $File $DependHash = @{} - foreach($DependencyType in $DependencyDefinitions.Keys) { + foreach ($DependencyType in $DependencyDefinitions.Keys) { #Determine the path to this script - $Script = $DependencyDefinitions.$DependencyType.Script - if(Test-Path $Script -ErrorAction SilentlyContinue) { + $Script = $DependencyDefinitions.$DependencyType.Script + if (Test-Path $Script -ErrorAction SilentlyContinue) { $ScriptPath = $Script - } else { + } + else { # account for missing ps1 $ScriptPath = Join-Path $ModuleRoot "PSDependScripts\$($Script -replace ".ps1$").ps1" } - if(Test-Path $ScriptPath) { + if (Test-Path $ScriptPath) { $DependHash.$DependencyType = $ScriptPath - } else { + } + else { Write-Error "Could not find path '$ScriptPath' for dependency $DependencyType. Origin: $($DependencyDefinitions.$DependencyType.Script)" } } diff --git a/PSDepend/Public/Get-PSDependType.ps1 b/PSDepend/Public/Get-PSDependType.ps1 index 5654ba7..6212e63 100644 --- a/PSDepend/Public/Get-PSDependType.ps1 +++ b/PSDepend/Public/Get-PSDependType.ps1 @@ -48,7 +48,7 @@ Function Get-PSDependType { [cmdletbinding()] param( [string]$DependencyType = '*', - [validatescript({Test-Path $_ -PathType Leaf -ErrorAction Stop})] + [validatescript( { Test-Path $_ -PathType Leaf -ErrorAction Stop })] [string]$Path = $(Join-Path $ModuleRoot PSDependMap.psd1), [switch]$ShowHelp, [switch]$SkipHelp @@ -59,49 +59,41 @@ Function Get-PSDependType { $File = Split-Path $Path -Leaf $DependencyDefinitions = Import-LocalizedData -BaseDirectory $Base -FileName $File $KeysToQuery = $DependencyDefinitions.Keys | - Where-Object {$_ -like $DependencyType} | + Where-Object { $_ -like $DependencyType } | Sort-Object - foreach($Type in $KeysToQuery) - { + foreach ($Type in $KeysToQuery) { #Determine the path to this script. Skip task dependencies... - $Script = $DependencyDefinitions.$Type.Script - if($Script -ne '.') - { - if(Test-Path $Script) - { + $Script = $DependencyDefinitions.$Type.Script + if ($Script -ne '.') { + if (Test-Path $Script) { $ScriptPath = $Script } - else - { + else { # account for missing ps1 $ScriptPath = Join-Path $ModuleRoot "PSDependScripts\$($Script -replace ".ps1$").ps1" } If (-not $SkipHelp) { - Try - { + Try { $ScriptHelp = Get-Help $ScriptPath -Full -ErrorAction Stop } - Catch - { + Catch { $ScriptHelp = "Error retrieving help: $_" } } } - if($ShowHelp) - { + if ($ShowHelp) { $ScriptHelp } - else - { + else { $Support = @($DependencyDefinitions.$Type.Supports) [PSCustomObject]@{ - DependencyType = $Type - Supports = $Support - Supported = Test-PlatformSupport -Type $Type -Support $Support - Description = $DependencyDefinitions.$Type.Description + DependencyType = $Type + Supports = $Support + Supported = Test-PlatformSupport -Type $Type -Support $Support + Description = $DependencyDefinitions.$Type.Description DependencyScript = $ScriptPath - HelpContent = $ScriptHelp + HelpContent = $ScriptHelp } } } diff --git a/PSDepend/Public/Import-Dependency.ps1 b/PSDepend/Public/Import-Dependency.ps1 index 25d9488..8db442f 100644 --- a/PSDepend/Public/Import-Dependency.ps1 +++ b/PSDepend/Public/Import-Dependency.ps1 @@ -35,18 +35,17 @@ Function Import-Dependency { [cmdletbinding()] Param( [parameter( ValueFromPipeline = $True, - ParameterSetName='Map', - Mandatory = $True)] + ParameterSetName = 'Map', + Mandatory = $True)] [PSTypeName('PSDepend.Dependency')] [psobject[]]$Dependency, - [validatescript({Test-Path -Path $_ -PathType Leaf -ErrorAction Stop})] + [validatescript( { Test-Path -Path $_ -PathType Leaf -ErrorAction Stop })] [string]$PSDependTypePath = $(Join-Path $ModuleRoot PSDependMap.psd1), [string[]]$Tags ) - Process - { + Process { Invoke-DependencyScript @PSBoundParameters -PSDependAction Import } } diff --git a/PSDepend/Public/Install-Dependency.ps1 b/PSDepend/Public/Install-Dependency.ps1 index 35fcdb9..7d0ab43 100644 --- a/PSDepend/Public/Install-Dependency.ps1 +++ b/PSDepend/Public/Install-Dependency.ps1 @@ -36,22 +36,21 @@ Function Install-Dependency { https://github.com/PowerShellOrg/PSDepend #> [cmdletbinding( SupportsShouldProcess = $True, - ConfirmImpact='High' )] + ConfirmImpact = 'High' )] Param( [parameter( ValueFromPipeline = $True, - Mandatory = $True)] + Mandatory = $True)] [PSTypeName('PSDepend.Dependency')] [psobject[]]$Dependency, - [validatescript({Test-Path -Path $_ -PathType Leaf -ErrorAction Stop})] + [validatescript( { Test-Path -Path $_ -PathType Leaf -ErrorAction Stop })] [string]$PSDependTypePath = $(Join-Path $ModuleRoot PSDependMap.psd1), [string[]]$Tags, [switch]$Force ) - Process - { + Process { $InvokeParams = @{} + $PSBoundParameters $null = $InvokeParams.Remove('Force') Invoke-DependencyScript @InvokeParams -PSDependAction Install diff --git a/PSDepend/Public/Invoke-DependencyScript.ps1 b/PSDepend/Public/Invoke-DependencyScript.ps1 index 1a52710..8d03067 100644 --- a/PSDepend/Public/Invoke-DependencyScript.ps1 +++ b/PSDepend/Public/Invoke-DependencyScript.ps1 @@ -38,12 +38,12 @@ function Invoke-DependencyScript { [cmdletbinding()] param( [parameter( ValueFromPipeline = $True, - ParameterSetName='Map', + ParameterSetName = 'Map', Mandatory = $True)] [PSTypeName('PSDepend.Dependency')] [psobject]$Dependency, - [validatescript({ Test-Path -Path $_ -PathType Leaf -ErrorAction Stop })] + [validatescript( { Test-Path -Path $_ -PathType Leaf -ErrorAction Stop })] [string]$PSDependTypePath = $(Join-Path $ModuleRoot PSDependMap.psd1), [string[]]$PSDependAction, @@ -65,14 +65,14 @@ function Invoke-DependencyScript { $TheseDependencyTypes = @( $Dependency.DependencyType | Sort-Object -Unique ) #Build up hash, we call each dependencytype script for applicable dependencies - foreach($DependencyType in $TheseDependencyTypes) { + foreach ($DependencyType in $TheseDependencyTypes) { $PSDependType = ($PSDependTypes | Where-Object { $_.DependencyType -eq $DependencyType }) - if(-not $PSDependType.Supported) { + if (-not $PSDependType.Supported) { Write-Warning "Skipping dependency type [$DependencyType]`nThis dependency does not support your platform`nSupported platforms: [$($PSDependType.Supports)]" continue } $DependencyScript = $DependencyDefs.$DependencyType - if(-not $DependencyScript) { + if (-not $DependencyScript) { Write-Error "DependencyType $DependencyType is not defined in PSDependMap.psd1" continue } @@ -84,54 +84,58 @@ function Invoke-DependencyScript { $ValidParamNames = $RawParameters.Name Write-Verbose "Found parameters [$ValidParamNames]" - if($ValidParamNames -notcontains 'PSDependAction') { + if ($ValidParamNames -notcontains 'PSDependAction') { Write-Error "No PSDependAction found on PSDependScript [$DependencyScript]. Skipping [$($Dependency.DependencyName)]" continue } [string[]]$ValidPSDependActions = $RawParameters | Where-Object { $_.Name -like 'PSDependAction' } | Select-Object -ExpandProperty ValidateSetValues -ErrorAction SilentlyContinue - [string[]]$PSDependActions = foreach($Action in $PSDependAction) { - if($ValidPSDependActions -contains $Action) { + [string[]]$PSDependActions = foreach ($Action in $PSDependAction) { + if ($ValidPSDependActions -contains $Action) { $Action - } else { + } + else { Write-Warning "Skipping PSDependAction [$Action] for dependency [$($Dependency.DependencyName)]. Valid actions: [$ValidPSDependActions]" } } - if($PSDependActions.count -like 0) { + if ($PSDependActions.count -like 0) { Write-Verbose "Skipped dependency [$($Dependency.DependencyName)] due to filtered PSDependAction. See Warnings above." continue } - if($PSDependActions -contains 'Test' -and ( $PSDependActions -contains 'Import' -or $PSDependActions -contains 'Install')) { + if ($PSDependActions -contains 'Test' -and ( $PSDependActions -contains 'Import' -or $PSDependActions -contains 'Install')) { Write-Error "Removing [Test] from PSDependActions. The Test action must run on its own." $PSDependActions = $PSDependActions | Where-Object { $_ -ne 'Test' } } - foreach($ThisDependency in $TheseDependencies) { + foreach ($ThisDependency in $TheseDependencies) { #Parameters for dependency types. Only accept valid params... - if($ThisDependency.Parameters.keys.count -gt 0) { + if ($ThisDependency.Parameters.keys.count -gt 0) { $splat = @{} - foreach($key in $ThisDependency.Parameters.keys) { - if($ValidParamNames -contains $key) { + foreach ($key in $ThisDependency.Parameters.keys) { + if ($ValidParamNames -contains $key) { $splat.Add($key, $ThisDependency.Parameters.$key) - } else { + } + else { Write-Warning "Parameter [$Key] with value [$($ThisDependency.Parameters.$Key)] is not a valid parameter for [$DependencyType], ignoring. Valid params:`n[$ValidParamNames]" } } - if($ThisDependency.Parameters.Import -and $PSDependActions -notcontains 'Test') { + if ($ThisDependency.Parameters.Import -and $PSDependActions -notcontains 'Test') { $PSDependActions += 'Import' $PSDependActions = $PSDependActions | Sort-Object -Unique } - if($splat.ContainsKey('PSDependAction')) { + if ($splat.ContainsKey('PSDependAction')) { $Splat['PSDependAction'] = $PSDependActions - } else { + } + else { $Splat.add('PSDependAction', $PSDependActions) } - } else { + } + else { $splat = @{PSDependAction = $PSDependActions } } @@ -139,20 +143,23 @@ function Invoke-DependencyScript { $splat.add('Dependency', $ThisDependency) # PITA, but tasks can run two ways, each different than typical dependency scripts - if($PSDependActions -contains 'Install' -and $DependencyType -eq 'Task') { - foreach($TaskScript in $ThisDependency.Target) { - if( Test-Path $TaskScript -PathType Leaf) { + if ($PSDependActions -contains 'Install' -and $DependencyType -eq 'Task') { + foreach ($TaskScript in $ThisDependency.Target) { + if ( Test-Path $TaskScript -PathType Leaf) { . $TaskScript @splat - } else { + } + else { Write-Error "Could not process task [$TaskScript].`nAre connectivity, privileges, and other needs met to access it?" } } - } else { + } + else { Write-Verbose "Invoking '$DependencyScript' with parameters $($Splat | Out-String)" $Output = . $DependencyScript @splat - if($PSDependActions -contains 'Test' -and -not $Quiet) { + if ($PSDependActions -contains 'Test' -and -not $Quiet) { Add-Member -InputObject $ThisDependency -MemberType NoteProperty -Name DependencyExists -Value $Output -Force -PassThru - } else { + } + else { $Output } } diff --git a/PSDepend/Public/Invoke-PSDepend.ps1 b/PSDepend/Public/Invoke-PSDepend.ps1 index e5095bc..8d9c2b0 100644 --- a/PSDepend/Public/Invoke-PSDepend.ps1 +++ b/PSDepend/Public/Invoke-PSDepend.ps1 @@ -99,31 +99,31 @@ Function Invoke-PSDepend { https://github.com/PowerShellOrg/PSDepend #> [cmdletbinding( DefaultParameterSetName = 'installimport-file', - SupportsShouldProcess = $True, - ConfirmImpact='High' )] + SupportsShouldProcess = $True, + ConfirmImpact = 'High' )] Param( - [validatescript({Test-Path -Path $_ -ErrorAction Stop})] + [validatescript( { Test-Path -Path $_ -ErrorAction Stop })] [parameter( ParameterSetName = 'installimport-file', - Position = 0, - ValueFromPipeline = $True, - ValueFromPipelineByPropertyName = $True)] + Position = 0, + ValueFromPipeline = $True, + ValueFromPipelineByPropertyName = $True)] [parameter( ParameterSetName = 'test-file', - Position = 0, - ValueFromPipeline = $True, - ValueFromPipelineByPropertyName = $True)] + Position = 0, + ValueFromPipeline = $True, + ValueFromPipelineByPropertyName = $True)] [string[]]$Path = '.', [parameter( ParameterSetName = 'installimport-hashtable', - Position = 0, - ValueFromPipeline = $True, - ValueFromPipelineByPropertyName = $True)] + Position = 0, + ValueFromPipeline = $True, + ValueFromPipelineByPropertyName = $True)] [parameter( ParameterSetName = 'test-hashtable', - Position = 0, - ValueFromPipeline = $True, - ValueFromPipelineByPropertyName = $True)] + Position = 0, + ValueFromPipeline = $True, + ValueFromPipelineByPropertyName = $True)] [hashtable[]]$InputObject, - [validatescript({Test-Path -Path $_ -PathType Leaf -ErrorAction Stop})] + [validatescript( { Test-Path -Path $_ -PathType Leaf -ErrorAction Stop })] [string]$PSDependTypePath = $(Join-Path $ModuleRoot PSDependMap.psd1), [string[]]$Tags, @@ -156,21 +156,19 @@ Function Invoke-PSDepend { [parameter(ParameterSetName = 'installimport-hashtable')] [hashtable]$Credentials ) - Begin - { + Begin { # Build parameters $InvokeParams = @{ - PSDependAction = @() + PSDependAction = @() PSDependTypePath = $PSDependTypePath } $DoInstall = $PSCmdlet.ParameterSetName -like 'installimport-*' -and $Install $DoImport = $PSCmdlet.ParameterSetName -like 'installimport-*' -and $Import $DoTest = $PSCmdlet.ParameterSetName -like 'test-*' -and $Test - if($DoInstall){$InvokeParams.PSDependAction += 'Install'} - if($DoImport){$InvokeParams.PSDependAction += 'Import'} - if($DoTest){$InvokeParams.PSDependAction += 'Test'} - if($InvokeParams.PSDependAction.count -like 0) - { + if ($DoInstall) { $InvokeParams.PSDependAction += 'Install' } + if ($DoImport) { $InvokeParams.PSDependAction += 'Import' } + if ($DoTest) { $InvokeParams.PSDependAction += 'Test' } + if ($InvokeParams.PSDependAction.count -like 0) { $InvokeParams.PSDependAction += 'Install' } Write-Verbose "Running Invoke-PSDepend with ParameterSetName '$($PSCmdlet.ParameterSetName)', PSDependAction $($InvokeParams.PSDependAction), and params: $($PSBoundParameters | Out-String)" @@ -178,36 +176,29 @@ Function Invoke-PSDepend { $DependencyFiles = New-Object System.Collections.ArrayList $PSDependTypes = Get-PSDependType -Path $PSDependTypePath -SkipHelp } - Process - { + Process { $GetPSDependParams = @{} - if($PSCmdlet.ParameterSetName -like '*-file') - { - foreach( $PathItem in $Path ) - { + if ($PSCmdlet.ParameterSetName -like '*-file') { + foreach ( $PathItem in $Path ) { # Create a map for dependencies [void]$DependencyFiles.AddRange( @( Resolve-DependScripts -Path $PathItem -Recurse $Recurse ) ) - if ($DependencyFiles.count -gt 0) - { + if ($DependencyFiles.count -gt 0) { Write-Verbose "Working with [$($DependencyFiles.Count)] dependency files from [$PathItem]:`n$($DependencyFiles | Out-String)" } - else - { + else { Write-Warning "No *.depend.psd1 files found under [$PathItem]" } } - $GetPSDependParams.add('Path',$DependencyFiles) + $GetPSDependParams.add('Path', $DependencyFiles) } - elseif($PSCmdlet.ParameterSetName -like '*-hashtable') - { - $GetPSDependParams.add('InputObject',$InputObject) + elseif ($PSCmdlet.ParameterSetName -like '*-hashtable') { + $GetPSDependParams.add('InputObject', $InputObject) } # Parse - if($PSBoundParameters.ContainsKey('Tags')) - { - $GetPSDependParams.Add('Tags',$Tags) + if ($PSBoundParameters.ContainsKey('Tags')) { + $GetPSDependParams.Add('Tags', $Tags) } if ($null -ne $Credentials) { @@ -216,54 +207,43 @@ Function Invoke-PSDepend { # Handle Dependencies $Dependencies = Get-Dependency @GetPSDependParams - $Unsupported = ( $PSDependTypes | Where-Object {-not $_.Supported} ).DependencyType - $Dependencies = foreach($Dependency in $Dependencies) - { - if($Unsupported -contains $Dependency.DependencyType) - { - $Supports = $PSDependTypes | Where-Object {$_.DependencyType -eq $Dependency.DependencyType} | Select -ExpandProperty Supports + $Unsupported = ( $PSDependTypes | Where-Object { -not $_.Supported } ).DependencyType + $Dependencies = foreach ($Dependency in $Dependencies) { + if ($Unsupported -contains $Dependency.DependencyType) { + $Supports = $PSDependTypes | Where-Object { $_.DependencyType -eq $Dependency.DependencyType } | select -ExpandProperty Supports Write-Warning "Skipping unsupported dependency:`n$( $Dependency | Out-String)`nSupported platforms:`n$($Supports | Out-String)" } - else - { + else { $Dependency } } - if($DoTest -and $Quiet) - { + if ($DoTest -and $Quiet) { $TestResult = [System.Collections.ArrayList]@() } #TODO: Add ShouldProcess here if install is specified... - foreach($Dependency in $Dependencies) - { - if($PSBoundParameters.ContainsKey('Target')) - { + foreach ($Dependency in $Dependencies) { + if ($PSBoundParameters.ContainsKey('Target')) { Write-Verbose "Overriding Dependency target [$($Dependency.Target)] with target parameter value [$Target]" $Dependency.Target = $Target } - if( ($Force -and -not $WhatIf) -or + if ( ($Force -and -not $WhatIf) -or ($DoTest) -or $PSCmdlet.ShouldProcess( "Processed the dependency '$($Dependency.DependencyName -join ", ")'", - "Process the dependency '$($Dependency.DependencyName -join ", ")'?", - "Processing dependency" )) - { + "Process the dependency '$($Dependency.DependencyName -join ", ")'?", + "Processing dependency" )) { $PreScriptSuccess = $True #anti pattern! Best I could come up with to handle both prescript fail and dependencies - if($DoInstall -and $Dependency.PreScripts.Count -gt 0) - { + if ($DoInstall -and $Dependency.PreScripts.Count -gt 0) { $ExistingEA = $ErrorActionPreference $ErrorActionPreference = 'Stop' - foreach($script in $Dependency.PreScripts) - { - Try - { + foreach ($script in $Dependency.PreScripts) { + Try { Write-Verbose "Invoking pre script: [$script]" . $script } - Catch - { + Catch { $PreScriptSuccess = $False "Skipping installation due to failed pre script: [$script]" Write-Error $_ @@ -272,36 +252,28 @@ Function Invoke-PSDepend { $ErrorActionPreference = $ExistingEA } - if($PreScriptSuccess) - { - if($DoTest -and $Quiet) - { + if ($PreScriptSuccess) { + if ($DoTest -and $Quiet) { $null = $TestResult.Add( (Invoke-DependencyScript @InvokeParams -Dependency $Dependency -Quiet ) ) } - else - { + else { Invoke-DependencyScript @InvokeParams -Dependency $Dependency } } - if($DoInstall -and $Dependency.PostScripts.Count -gt 0) - { - foreach($script in $Dependency.PostScripts) - { + if ($DoInstall -and $Dependency.PostScripts.Count -gt 0) { + foreach ($script in $Dependency.PostScripts) { Write-Verbose "Invoking post script: $($script)" . $script } } } } - if($DoTest -and $Quiet) - { - if($TestResult -contains $false) - { + if ($DoTest -and $Quiet) { + if ($TestResult -contains $false) { $false } - else - { + else { $true } } diff --git a/PSDepend/Public/Test-Dependency.ps1 b/PSDepend/Public/Test-Dependency.ps1 index fb433d5..73f45b6 100644 --- a/PSDepend/Public/Test-Dependency.ps1 +++ b/PSDepend/Public/Test-Dependency.ps1 @@ -39,12 +39,12 @@ function Test-Dependency { [cmdletbinding()] param( [parameter( ValueFromPipeline = $True, - ParameterSetName='Map', + ParameterSetName = 'Map', Mandatory = $True)] [PSTypeName('PSDepend.Dependency')] [psobject[]]$Dependency, - [validatescript({ Test-Path -Path $_ -PathType Leaf -ErrorAction Stop })] + [validatescript( { Test-Path -Path $_ -PathType Leaf -ErrorAction Stop })] [string]$PSDependTypePath = $(Join-Path $ModuleRoot PSDependMap.psd1), [string[]]$Tags, diff --git a/Tests/DotnetSdk.Type.Tests.ps1 b/Tests/DotnetSdk.Type.Tests.ps1 index 4bbb92b..f48e886 100644 --- a/Tests/DotnetSdk.Type.Tests.ps1 +++ b/Tests/DotnetSdk.Type.Tests.ps1 @@ -22,7 +22,7 @@ Describe 'DotnetSdk script' { BeforeAll { InModuleScope PSDepend { Mock Install-Dotnet { } - Mock Test-Dotnet { $false } + Mock Test-Dotnet { $false } } } diff --git a/Tests/Git.Type.Tests.ps1 b/Tests/Git.Type.Tests.ps1 index 1cbef4b..1b27cd8 100644 --- a/Tests/Git.Type.Tests.ps1 +++ b/Tests/Git.Type.Tests.ps1 @@ -32,7 +32,7 @@ Describe 'Git script' { } } Mock Import-PSDependModule { } - Mock Add-ToItemCollection { } + Mock Add-ToItemCollection { } } } diff --git a/Tests/GitHub.Type.Tests.ps1 b/Tests/GitHub.Type.Tests.ps1 index 280798f..0a29b95 100644 --- a/Tests/GitHub.Type.Tests.ps1 +++ b/Tests/GitHub.Type.Tests.ps1 @@ -16,7 +16,7 @@ Describe 'GitHub script' { BeforeAll { InModuleScope PSDepend { - Mock Get-Module { } -ParameterFilter { $ListAvailable } + Mock Get-Module { } -ParameterFilter { $ListAvailable } Mock Invoke-RestMethod { @() } # No tags returned → treated as branch Mock Import-PSDependModule { } } diff --git a/Tests/Help.tests.ps1 b/Tests/Help.tests.ps1 index d0916a5..7c6f90f 100644 --- a/Tests/Help.tests.ps1 +++ b/Tests/Help.tests.ps1 @@ -22,7 +22,7 @@ BeforeDiscovery { Get-Module $env:BHProjectName | Remove-Module -Force -ErrorAction Ignore Import-Module -Name $outputModVerManifest -Verbose:$false -ErrorAction Stop $params = @{ - Module = (Get-Module $env:BHProjectName) + Module = (Get-Module $env:BHProjectName) CommandType = [System.Management.Automation.CommandTypes[]]'Cmdlet, Function' # Not alias } if ($PSVersionTable.PSVersion.Major -lt 6) { diff --git a/Tests/Npm.Type.Tests.ps1 b/Tests/Npm.Type.Tests.ps1 index 9643a0d..6ab9058 100644 --- a/Tests/Npm.Type.Tests.ps1 +++ b/Tests/Npm.Type.Tests.ps1 @@ -16,7 +16,7 @@ Describe 'Npm script' { BeforeAll { InModuleScope PSDepend { - Mock Get-NodeModule { @{} } + Mock Get-NodeModule { @{} } Mock Install-NodeModule { } } } diff --git a/Tests/PSDepend.Tests.ps1 b/Tests/PSDepend.Tests.ps1 index 076ecb6..a650ee8 100644 --- a/Tests/PSDepend.Tests.ps1 +++ b/Tests/PSDepend.Tests.ps1 @@ -18,15 +18,15 @@ BeforeDiscovery { BeforeAll { $script:TestDepends = Join-Path $ENV:BHProjectPath Tests\DependFiles $script:Verbose = @{} - if($ENV:BHBranchName -notlike "main" -or $env:BHCommitMessage -match "!verbose") { - $script:Verbose.add("Verbose",$True) + if ($ENV:BHBranchName -notlike "main" -or $env:BHCommitMessage -match "!verbose") { + $script:Verbose.add("Verbose", $True) } } Describe "$ENV:BHProjectName PS$PSVersion" -Tag 'Unit' { Context 'Strict mode' { BeforeAll { Set-StrictMode -Version latest } - AfterAll { Set-StrictMode -Off } + AfterAll { Set-StrictMode -Off } It 'Should load' { $Module = Get-Module $ENV:BHProjectName @@ -39,7 +39,7 @@ Describe "$ENV:BHProjectName PS$PSVersion" -Tag 'Unit' { Describe "Get-Dependency PS$PSVersion" -Tag 'Unit' { Context 'Strict mode' { BeforeAll { Set-StrictMode -Version latest } - AfterAll { Set-StrictMode -Off } + AfterAll { Set-StrictMode -Off } It 'Should read ModuleName=Version syntax' { $Dependencies = Get-Dependency -Path $TestDepends\simple.depend.psd1 @@ -106,7 +106,7 @@ Describe "Get-Dependency PS$PSVersion" -Tag 'Unit' { Context 'Error and edge cases' { BeforeAll { Set-StrictMode -Version latest } - AfterAll { Set-StrictMode -Off } + AfterAll { Set-StrictMode -Off } It 'Filters results to matching tags when -Tags is specified' { $Dependencies = Get-Dependency -Path $TestDepends\allprops.depend.psd1 -Tags 'tags' @@ -131,7 +131,7 @@ Describe "Get-Dependency PS$PSVersion" -Tag 'Unit' { Describe "Get-PSDependType PS$PSVersion" -Tag 'Unit' { Context 'Strict mode' { BeforeAll { Set-StrictMode -Version latest } - AfterAll { Set-StrictMode -Off } + AfterAll { Set-StrictMode -Off } It 'Returns objects for all types in the default map' { $Types = Get-PSDependType -SkipHelp @@ -161,7 +161,7 @@ Describe "Get-PSDependType PS$PSVersion" -Tag 'Unit' { Describe "Get-PSDependScript PS$PSVersion" -Tag 'Unit' { Context 'Strict mode' { BeforeAll { Set-StrictMode -Version latest } - AfterAll { Set-StrictMode -Off } + AfterAll { Set-StrictMode -Off } It 'Returns a hashtable keyed by dependency type name' { $Scripts = Get-PSDependScript @@ -203,7 +203,7 @@ Describe "Install-Dependency PS$PSVersion" -Tag 'Unit' { Describe "Invoke-DependencyScript PS$PSVersion" -Tag 'Unit' { Context 'Command type' { BeforeAll { Set-StrictMode -Version latest } - AfterAll { Set-StrictMode -Off } + AfterAll { Set-StrictMode -Off } It 'Returns the script output for a Command dependency' { $Dep = Get-Dependency -Path $TestDepends\command.depend.psd1 | Select-Object -First 1 diff --git a/Tests/PSGalleryModule.Type.Tests.ps1 b/Tests/PSGalleryModule.Type.Tests.ps1 index 0da7cc9..db399e9 100644 --- a/Tests/PSGalleryModule.Type.Tests.ps1 +++ b/Tests/PSGalleryModule.Type.Tests.ps1 @@ -25,12 +25,12 @@ Describe 'PSGalleryModule script' { BeforeAll { InModuleScope PSDepend { Mock Get-PackageProvider { [PSCustomObject]@{ Name = 'NuGet' } } - Mock Get-PSRepository { [PSCustomObject]@{ Name = 'PSGallery' } } - Mock Get-Module { } -ParameterFilter { $ListAvailable } - Mock Find-Module { [PSCustomObject]@{ Name = 'TestModule'; Version = [version]'2.0.0' } } - Mock Install-Module { } - Mock Save-Module { } - Mock Import-PSDependModule { } + Mock Get-PSRepository { [PSCustomObject]@{ Name = 'PSGallery' } } + Mock Get-Module { } -ParameterFilter { $ListAvailable } + Mock Find-Module { [PSCustomObject]@{ Name = 'TestModule'; Version = [version]'2.0.0' } } + Mock Install-Module { } + Mock Save-Module { } + Mock Import-PSDependModule { } Mock Add-ToPsModulePathIfRequired { } } } diff --git a/Tests/PSGalleryNuget.Type.Tests.ps1 b/Tests/PSGalleryNuget.Type.Tests.ps1 index 764cf37..637345c 100644 --- a/Tests/PSGalleryNuget.Type.Tests.ps1 +++ b/Tests/PSGalleryNuget.Type.Tests.ps1 @@ -16,10 +16,10 @@ Describe 'PSGalleryNuget script' { BeforeAll { InModuleScope PSDepend { - Mock Invoke-ExternalCommand { } - Mock Find-NugetPackage { [PSCustomObject]@{ Version = '1.0.0' } } - Mock Add-ToPsModulePathIfRequired { } - Mock Import-PSDependModule { } + Mock Invoke-ExternalCommand { } + Mock Find-NugetPackage { [PSCustomObject]@{ Version = '1.0.0' } } + Mock Add-ToPsModulePathIfRequired { } + Mock Import-PSDependModule { } Mock Get-Command { [PSCustomObject]@{ Name = 'nuget' } } -ParameterFilter { $Name -eq 'Nuget' } } } diff --git a/Tests/PSModuleGallery.Type.Tests.ps1 b/Tests/PSModuleGallery.Type.Tests.ps1 index 76d709d..b5739aa 100644 --- a/Tests/PSModuleGallery.Type.Tests.ps1 +++ b/Tests/PSModuleGallery.Type.Tests.ps1 @@ -11,7 +11,7 @@ BeforeDiscovery { Get-Module $env:BHProjectName | Remove-Module -Force -ErrorAction Ignore Import-Module -Name $outputModVerManifest -Verbose:$false -ErrorAction Stop - if($IsLinux -or $IsMacOS) { + if ($IsLinux -or $IsMacOS) { # Skip tests tagged WindowsOnly on non-Windows platforms $nonWindows = $true } @@ -30,12 +30,12 @@ Describe "PSModuleGallery Type" -Tag 'Integration' { $script:OtherCredential = New-Object System.Management.Automation.PSCredential('otherUser', $script:Password) $script:Credentials = @{ 'imaginaryCreds' = $script:TestCredential - 'otherCreds' = $script:OtherCredential + 'otherCreds' = $script:OtherCredential } $script:Verbose = @{} - if($ENV:BHBranchName -notlike "main" -or $env:BHCommitMessage -match "!verbose") { - $script:Verbose.add("Verbose",$True) + if ($ENV:BHBranchName -notlike "main" -or $env:BHCommitMessage -match "!verbose") { + $script:Verbose.add("Verbose", $True) } } @@ -403,11 +403,11 @@ Describe "PSModuleGallery Type" -Tag 'Integration' { $addToPathTestCases = @( @{ - Version = 'specific version' + Version = 'specific version' DependPsd1File = "psgallerymodule.addtopath.depend.psd1" }, @{ - Version = 'latest version' + Version = 'latest version' DependPsd1File = "psgallerymodule.latestaddtopath.depend.psd1" } ) @@ -792,11 +792,11 @@ Describe "PSModuleGallery Type" -Tag 'Integration' { $addToPathTestCases = @( @{ - Version = 'specific version' + Version = 'specific version' DependPsd1File = "psgallerynuget.addtopath.depend.psd1" }, @{ - Version = 'latest version' + Version = 'latest version' DependPsd1File = "psgallerynuget.latestaddtopath.depend.psd1" } ) @@ -901,9 +901,9 @@ Describe "PSModuleGallery Type" -Tag 'Integration' { # NOTE: 'script:' qualifier is required — without it, the function is created # in a temporary scope that vanishes when the scriptblock returns. & (Get-Module PSDepend) { - function script:Get-Package { [cmdletbinding()]param($ProviderName, $Name, $RequiredVersion) } + function script:Get-Package { [cmdletbinding()]param($ProviderName, $Name, $RequiredVersion) } function script:Install-Package { [cmdletbinding()]param($Source, $Name, $RequiredVersion, $Force) } - function script:Find-Package { [cmdletbinding()]param($Name, $Source) } + function script:Find-Package { [cmdletbinding()]param($Name, $Source) } function script:Get-PackageSource { [cmdletbinding()]param() } } } @@ -916,7 +916,7 @@ Describe "PSModuleGallery Type" -Tag 'Integration' { Context 'Installs Packages' { BeforeAll { - Mock Get-PackageSource { @([PSCustomObject]@{Name = 'chocolatey'; ProviderName = 'chocolatey'}) } -ModuleName PSDepend + Mock Get-PackageSource { @([PSCustomObject]@{Name = 'chocolatey'; ProviderName = 'chocolatey' }) } -ModuleName PSDepend Mock Get-Package -ModuleName PSDepend Mock Install-Package { $True } -ModuleName PSDepend $script:Results = Invoke-PSDepend @Verbose -Path "$TestDepends\package.depend.psd1" -Force @@ -944,7 +944,7 @@ Describe "PSModuleGallery Type" -Tag 'Integration' { Context 'Same package version exists' { BeforeAll { - Mock Get-PackageSource { @([PSCustomObject]@{Name = 'chocolatey'; ProviderName = 'chocolatey'}) } -ModuleName PSDepend + Mock Get-PackageSource { @([PSCustomObject]@{Name = 'chocolatey'; ProviderName = 'chocolatey' }) } -ModuleName PSDepend Mock Install-Package -ModuleName PSDepend Mock Get-Package { [PSCustomObject]@{ @@ -965,7 +965,7 @@ Describe "PSModuleGallery Type" -Tag 'Integration' { Context 'Latest package required, and already installed' { BeforeAll { - Mock Get-PackageSource { @([PSCustomObject]@{Name = 'chocolatey'; ProviderName = 'chocolatey'}) } -ModuleName PSDepend + Mock Get-PackageSource { @([PSCustomObject]@{Name = 'chocolatey'; ProviderName = 'chocolatey' }) } -ModuleName PSDepend Mock Install-Package -ModuleName PSDepend Mock Get-Package { [PSCustomObject]@{ @@ -990,7 +990,7 @@ Describe "PSModuleGallery Type" -Tag 'Integration' { Context 'Test-Dependency' { BeforeEach { - Mock Get-PackageSource { @([PSCustomObject]@{Name = 'chocolatey'; ProviderName = 'chocolatey'}) } -ModuleName PSDepend + Mock Get-PackageSource { @([PSCustomObject]@{Name = 'chocolatey'; ProviderName = 'chocolatey' }) } -ModuleName PSDepend Mock Install-Package {} -ModuleName PSDepend Mock Find-Package {} -ModuleName PSDepend } @@ -1151,12 +1151,14 @@ Describe "PSModuleGallery Type" -Tag 'Integration' { $script:IsWindowsEnv = !$PSVersionTable.Platform -or $PSVersionTable.Platform -eq "Win32NT" $script:GlobalDotnetSdkLocation = if ($script:IsWindowsEnv) { "$env:LocalAppData\Microsoft\dotnet" - } else { + } + else { "$env:HOME/.dotnet" } $script:DotnetFile = if ($script:IsWindowsEnv) { "dotnet.exe" - } else { + } + else { "dotnet" } $script:SavePath = '.dotnet' @@ -1176,7 +1178,7 @@ Describe "PSModuleGallery Type" -Tag 'Integration' { } It 'Installs the .NET Core SDK to the specified directory' { - Mock Test-Dotnet { return $false } -ModuleName PSDepend + Mock Test-Dotnet { return $false } -ModuleName PSDepend Mock Install-Dotnet { } -ModuleName PSDepend Invoke-PSDepend @Verbose -Path "$TestDepends\dotnetsdk.complex.depend.psd1" -Force @@ -1248,7 +1250,7 @@ Describe "PSModuleGallery Type" -Tag 'Integration' { $script:SavePath = (New-Item 'TestDrive:/PSDependPesterTest' -ItemType Directory -Force).FullName # Simulate choco.exe being present so tests don't hit the install-chocolatey branch by default - Mock Get-Command -ParameterFilter { $Name -eq 'choco.exe' } -MockWith { [PSCustomObject]@{Name = 'choco.exe'} } -ModuleName PSDepend + Mock Get-Command -ParameterFilter { $Name -eq 'choco.exe' } -MockWith { [PSCustomObject]@{Name = 'choco.exe' } } -ModuleName PSDepend # Default catch-all for Invoke-ExternalCommand; individual tests register specific ParameterFilter mocks Mock Invoke-ExternalCommand -ModuleName PSDepend } diff --git a/Tests/PSResourceGet.Type.Tests.ps1 b/Tests/PSResourceGet.Type.Tests.ps1 index 6af5ecd..69af71d 100644 --- a/Tests/PSResourceGet.Type.Tests.ps1 +++ b/Tests/PSResourceGet.Type.Tests.ps1 @@ -10,7 +10,7 @@ BeforeAll { Import-Module (Join-Path $PSScriptRoot 'Shared/TestHelpers.psm1') -Force $script:ScriptPath = Join-Path $env:BHProjectPath 'PSDepend/PSDependScripts/PSResourceGet.ps1' - $script:TestCred = New-TestCredential + $script:TestCred = New-TestCredential $script:OrigPSModulePath = $env:PSModulePath } diff --git a/Tests/Package.Type.Tests.ps1 b/Tests/Package.Type.Tests.ps1 index db8c2ef..ecac031 100644 --- a/Tests/Package.Type.Tests.ps1 +++ b/Tests/Package.Type.Tests.ps1 @@ -15,11 +15,11 @@ BeforeAll { # cannot mock directly. Inject simple stub functions into the module's # script scope so Pester can wrap them with Mock. & (Get-Module PSDepend) { - function script:Get-PackageSource { [CmdletBinding()] param() } + function script:Get-PackageSource { [CmdletBinding()] param() } function script:Get-PackageProvider { [CmdletBinding()] param() } - function script:Get-Package { [CmdletBinding()] param([string]$Name, [string]$ProviderName, [string]$RequiredVersion, [string]$Destination, [string]$ErrorAction) } - function script:Find-Package { [CmdletBinding()] param([string]$Name, [string]$Source) } - function script:Install-Package { [CmdletBinding()] param([string]$Name, [string]$Source, [string]$RequiredVersion, [string]$Destination, [string]$Scope, [switch]$Force) } + function script:Get-Package { [CmdletBinding()] param([string]$Name, [string]$ProviderName, [string]$RequiredVersion, [string]$Destination, [string]$ErrorAction) } + function script:Find-Package { [CmdletBinding()] param([string]$Name, [string]$Source) } + function script:Install-Package { [CmdletBinding()] param([string]$Name, [string]$Source, [string]$RequiredVersion, [string]$Destination, [string]$Scope, [switch]$Force) } } } @@ -27,11 +27,11 @@ Describe 'Package script' { BeforeAll { InModuleScope PSDepend { - Mock Get-PackageSource { [PSCustomObject]@{ Name = 'nuget.org'; ProviderName = 'Nuget' } } + Mock Get-PackageSource { [PSCustomObject]@{ Name = 'nuget.org'; ProviderName = 'Nuget' } } Mock Get-PackageProvider { @( [PSCustomObject]@{ Name = 'Nuget' }, [PSCustomObject]@{ Name = 'PowerShellGet' } ) } - Mock Get-Package { } - Mock Find-Package { [PSCustomObject]@{ Name = 'jquery'; Version = '1.0.0' } } - Mock Install-Package { } + Mock Get-Package { } + Mock Find-Package { [PSCustomObject]@{ Name = 'jquery'; Version = '1.0.0' } } + Mock Install-Package { } } } @@ -67,7 +67,7 @@ Describe 'Package script' { It 'Installs when installed version 2.8.0 is behind source version 2.10.0 and latest is requested' { $targetDir = (New-Item 'TestDrive:/pkg3' -ItemType Directory -Force).FullName InModuleScope PSDepend { - Mock Get-Package { [PSCustomObject]@{ Name = 'jquery'; Version = [version]'2.8.0' } } + Mock Get-Package { [PSCustomObject]@{ Name = 'jquery'; Version = [version]'2.8.0' } } Mock Find-Package { [PSCustomObject]@{ Name = 'jquery'; Version = [version]'2.10.0' } } } diff --git a/build.ps1 b/build.ps1 index eb9034e..3ec4120 100644 --- a/build.ps1 +++ b/build.ps1 @@ -27,7 +27,8 @@ param( Get-PSakeScriptTasks -BuildFile './psakeFile.ps1' -ErrorAction 'Stop' | Where-Object { $_.Name -like "$WordToComplete*" } | Select-Object -ExpandProperty 'Name' - } catch { + } + catch { @() } })] @@ -50,14 +51,16 @@ if ($Bootstrap) { } Import-Module -Name PSDepend -Verbose:$false Invoke-PSDepend -Path './requirements.psd1' -Install -Import -Force -WarningAction SilentlyContinue -} else { +} +else { Invoke-PSDepend -Path './requirements.psd1' -Import -Force -WarningAction SilentlyContinue } if ($PSCmdlet.ParameterSetName -eq 'Help') { Get-PSakeScriptTasks -BuildFile $psakeFile | Format-Table -Property Name, Description, Alias, DependsOn -} else { +} +else { Set-BuildEnvironment -Force Invoke-Psake -BuildFile $psakeFile -TaskList $Task -NoLogo exit ([int](-not $psake.build_success)) diff --git a/psakeFile.ps1 b/psakeFile.ps1 index ca84cfa..4880197 100644 --- a/psakeFile.ps1 +++ b/psakeFile.ps1 @@ -11,12 +11,12 @@ Properties { # Test configuration $PSBPreference.Help.DefaultLocale = 'en-US' $PSBPreference.Test.OutputFile = 'out/testResults.xml' - $PSBPreference.Test.OutputFormat = 'JUnitXml' - $PSBPreference.Test.ScriptAnalysis.Enabled = $true + $PSBPreference.Test.OutputFormat = 'JUnitXml' + $PSBPreference.Test.ScriptAnalysis.Enabled = $true $PSBPreference.Test.ScriptAnalysis.FailBuildOnSeverityLevel = 'Error' - $PSBPreference.Test.CodeCoverage.Enabled = $false + $PSBPreference.Test.CodeCoverage.Enabled = $false # Explicit casing required for Linux (case-sensitive filesystem) - $PSBPreference.Test.RootDir = Join-Path $ENV:BHProjectPath 'Tests' + $PSBPreference.Test.RootDir = Join-Path $ENV:BHProjectPath 'Tests' # Exclude Windows-only tests on non-Windows runners if (-not $IsWindows) { @@ -33,15 +33,15 @@ $PSBBuildDependency = @('StageFiles') Task InstallLocal -Depends StageFiles { $label = if ($PreReleaseLabel) { $PreReleaseLabel } else { "pre-$(git rev-parse --short HEAD)" } - $moduleName = $PSBPreference.General.ModuleName - $stagedDir = $PSBPreference.Build.ModuleOutDir + $moduleName = $PSBPreference.General.ModuleName + $stagedDir = $PSBPreference.Build.ModuleOutDir $manifestPath = Join-Path $stagedDir "$moduleName.psd1" - $version = (Import-PowerShellDataFile $manifestPath).ModuleVersion + $version = (Import-PowerShellDataFile $manifestPath).ModuleVersion Update-Metadata -Path $manifestPath -PropertyName Prerelease -Value $label $destRoot = Join-Path ([Environment]::GetFolderPath('MyDocuments')) 'PowerShell\Modules\PSDepend' - $destDir = Join-Path $destRoot "$version-$label" + $destDir = Join-Path $destRoot "$version-$label" if (Test-Path $destDir) { Remove-Item $destDir -Recurse -Force