Skip to content

Commit

Permalink
Merge pull request #2596 from TheCakeIsNaOH/ps-lint
Browse files Browse the repository at this point in the history
(#2556) Expand PowerShell aliases
  • Loading branch information
gep13 authored Jun 24, 2022
2 parents a4dedc1 + 9315a9e commit b2554df
Show file tree
Hide file tree
Showing 13 changed files with 76 additions and 59 deletions.
25 changes: 15 additions & 10 deletions GenerateDocs.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,7 @@ These are the functions from above as one list.
function Get-Aliases($commandName){

$aliasOutput = ''
Get-Alias -Definition $commandName -ErrorAction SilentlyContinue | %{ $aliasOutput += "``$($_.Name)``$lineFeed"}
Get-Alias -Definition $commandName -ErrorAction SilentlyContinue | ForEach-Object { $aliasOutput += "``$($_.Name)``$lineFeed"}

if ($aliasOutput -eq $null -or $aliasOutput -eq '') {
$aliasOutput = 'None'
Expand All @@ -111,7 +111,7 @@ function Convert-Example($objItem) {
~~~powershell
$($objItem.Code.Replace("`n",$lineFeed))
$($objItem.remarks | ? { $_.Text -ne ''} | % { Write-Output $_.Text.Replace("`n", $lineFeed) })
$($objItem.remarks | Where-Object { $_.Text } | ForEach-Object { $_.Text.Replace("`n", $lineFeed) })
~~~
"@
}
Expand Down Expand Up @@ -139,7 +139,7 @@ function Convert-Syntax($objItem, $hasCmdletBinding) {
$cmd = $objItem.Name

if ($objItem.parameter -ne $null) {
$objItem.parameter | % {
$objItem.parameter | ForEach-Object {
$cmd += ' `' + $lineFeed
$cmd += " "
if ($_.required -eq $false) { $cmd += '['}
Expand All @@ -165,7 +165,7 @@ function Convert-Parameter($objItem, $commandName) {
}
$parmText += $lineFeed
if ($objItem.description -ne $null) {
$parmText += (($objItem.description | % { Replace-CommonItems $_.Text }) -join "$lineFeed") + $lineFeed + $lineFeed
$parmText += (($objItem.description | ForEach-Object { Replace-CommonItems $_.Text }) -join "$lineFeed") + $lineFeed + $lineFeed
}
if ($objItem.parameterValueGroup -ne $null) {
$parmText += "$($lineFeed)Valid options: " + ($objItem.parameterValueGroup.parameterValue -join ", ") + $lineFeed + $lineFeed
Expand Down Expand Up @@ -304,7 +304,10 @@ function Generate-TopLevelCommandReference {
$commandOutput += @("$lineFeed~~~$lineFeed")
$commandOutput += @("$lineFeed$lineFeed*NOTE:* This documentation has been automatically generated from ``choco -h``. $lineFeed")

$commandOutput | %{ Convert-CommandText($_) } | %{ Convert-CommandReferenceSpecific($_) } | Out-File $fileName -Encoding UTF8 -Force
$commandOutput |
ForEach-Object { Convert-CommandText($_) } |
ForEach-Object { Convert-CommandReferenceSpecific($_) } |
Out-File $fileName -Encoding UTF8 -Force
}

function Move-GeneratedFiles {
Expand Down Expand Up @@ -373,7 +376,9 @@ function Generate-CommandReference($commandName, $order) {
$commandOutput += $(& $chocoExe $commandName.ToLower() -h -r)
$commandOutput += @("$lineFeed~~~$lineFeed$lineFeed[Command Reference](xref:choco-commands)")
$commandOutput += @("$lineFeed$lineFeed*NOTE:* This documentation has been automatically generated from ``choco $($commandName.ToLower()) -h``. $lineFeed")
$commandOutput | %{ Convert-CommandText $_ $commandName.ToLower() } | Out-File $fileName -Encoding UTF8 -Force
$commandOutput |
ForEach-Object { Convert-CommandText $_ $commandName.ToLower() } |
Out-File $fileName -Encoding UTF8 -Force
}

try
Expand Down Expand Up @@ -428,14 +433,14 @@ RedirectFrom:
$(Replace-CommonItems $_.Synopsis)
## Syntax
$( ($_.syntax.syntaxItem | % { Convert-Syntax $_ $hasCmdletBinding }) -join "$lineFeed$lineFeed")
$( ($_.syntax.syntaxItem | ForEach-Object { Convert-Syntax $_ $hasCmdletBinding }) -join "$lineFeed$lineFeed")
$( if ($_.description -ne $null) { $lineFeed + "## Description" + $lineFeed + $lineFeed + $(Replace-CommonItems $_.description.Text) })
$( if ($_.alertSet -ne $null) { $lineFeed + "## Notes" + $lineFeed + $lineFeed + $(Replace-CommonItems $_.alertSet.alert.Text) })
## Aliases
$(Get-Aliases $_.Name)
$( if ($_.Examples -ne $null) { Write-Output "$lineFeed## Examples$lineFeed$lineFeed"; ($_.Examples.Example | % { Convert-Example $_ }) -join "$lineFeed$lineFeed"; Write-Output "$lineFeed" })
$( if ($_.Examples -ne $null) { Write-Output "$lineFeed## Examples$lineFeed$lineFeed"; ($_.Examples.Example | ForEach-Object { Convert-Example $_ }) -join "$lineFeed$lineFeed"; Write-Output "$lineFeed" })
## Inputs
$( if ($_.InputTypes -ne $null -and $_.InputTypes.Length -gt 0 -and -not $_.InputTypes.Contains('inputType')) { $lineFeed + " * $($_.InputTypes)" + $lineFeed} else { 'None'})
Expand All @@ -445,9 +450,9 @@ $( if ($_.InputTypes -ne $null -and $_.InputTypes.Length -gt 0 -and -not $_.Inpu
$( if ($_.ReturnValues -ne $null -and $_.ReturnValues.Length -gt 0 -and -not $_.ReturnValues.StartsWith('returnValue')) { "$lineFeed * $($_.ReturnValues)$lineFeed"} else { 'None'})
## Parameters
$( if ($_.parameters.parameter.count -gt 0) { $_.parameters.parameter | % { Convert-Parameter $_ $commandName }}) $( if ($hasCmdletBinding) { "$lineFeed### <CommonParameters>$lineFeed$($lineFeed)This cmdlet supports the common parameters: -Verbose, -Debug, -ErrorAction, -ErrorVariable, -OutBuffer, and -OutVariable. For more information, see ``about_CommonParameters`` http://go.microsoft.com/fwlink/p/?LinkID=113216 ." } )
$( if ($_.parameters.parameter.count -gt 0) { $_.parameters.parameter | ForEach-Object { Convert-Parameter $_ $commandName }}) $( if ($hasCmdletBinding) { "$lineFeed### <CommonParameters>$lineFeed$($lineFeed)This cmdlet supports the common parameters: -Verbose, -Debug, -ErrorAction, -ErrorVariable, -OutBuffer, and -OutVariable. For more information, see ``about_CommonParameters`` http://go.microsoft.com/fwlink/p/?LinkID=113216 ." } )
$( if ($_.relatedLinks -ne $null) {Write-Output "$lineFeed## Links$lineFeed$lineFeed"; $_.relatedLinks.navigationLink | ? { $_.linkText -ne $null} | % { Write-Output "* [$($_.LinkText)](xref:$($_.LinkText.ToLower()))$lineFeed" }})
$( if ($_.relatedLinks -ne $null) {Write-Output "$lineFeed## Links$lineFeed$lineFeed"; $_.relatedLinks.navigationLink | Where-Object { $_.linkText -ne $null} | ForEach-Object { Write-Output "* [$($_.LinkText)](xref:$($_.LinkText.ToLower()))$lineFeed" }})
[Function Reference](xref:powershell-reference)
Expand Down
19 changes: 11 additions & 8 deletions nuspec/chocolatey/chocolatey/tools/chocolateysetup.psm1
Original file line number Diff line number Diff line change
Expand Up @@ -291,7 +291,7 @@ param(
$acl = (Get-Item $folder).GetAccessControl('Access,Owner')

Write-Debug "Removing existing permissions."
$acl.Access | % { $acl.RemoveAccessRuleAll($_) }
$acl.Access | ForEach-Object { $acl.RemoveAccessRuleAll($_) }

$inheritanceFlags = ([Security.AccessControl.InheritanceFlags]::ContainerInherit -bor [Security.AccessControl.InheritanceFlags]::ObjectInherit)
$propagationFlags = [Security.AccessControl.PropagationFlags]::None
Expand Down Expand Up @@ -368,7 +368,7 @@ param(

$chocolateyExePathOld = Join-Path $chocolateyPathOld 'bin'
'Machine', 'User' |
% {
ForEach-Object {
$path = Get-EnvironmentVariable -Name 'PATH' -Scope $_
$updatedPath = [System.Text.RegularExpressions.Regex]::Replace($path,[System.Text.RegularExpressions.Regex]::Escape($chocolateyExePathOld) + '(?>;)?', '', [System.Text.RegularExpressions.RegexOptions]::IgnoreCase)
if ($updatedPath -ne $path) {
Expand All @@ -389,7 +389,7 @@ param(
# TODO: This exclusion list needs to be updated once shims are removed
$exclude = @("choco.exe", "chocolatey.exe", "cinst.exe", "clist.exe", "cpush.exe", "cuninst.exe", "cup.exe", "RefreshEnv.cmd")
Get-ChildItem -Path $from -recurse -Exclude $exclude |
% {
ForEach-Object {
Write-Debug "Copying $_ `n to $to"
if ($_.PSIsContainer) {
Copy-Item $_ -Destination (Join-Path $to $_.Parent.FullName.Substring($from.length)) -Force -ErrorAction SilentlyContinue
Expand All @@ -415,7 +415,7 @@ param(
if (Test-Path $chocolateyPathOld) {
Write-ChocolateyWarning "This action will result in Log Errors, you can safely ignore those. `n You may need to finish removing '$chocolateyPathOld' manually."
try {
Get-ChildItem -Path "$chocolateyPathOld" | % {
Get-ChildItem -Path "$chocolateyPathOld" | ForEach-Object {
if (Test-Path $_.FullName) {
Write-Debug "Removing $_ unless matches .log"
Remove-Item $_.FullName -exclude *.log -recurse -force -ErrorAction SilentlyContinue
Expand All @@ -438,11 +438,11 @@ param(
Write-Debug "Install-ChocolateyFiles"

Write-Debug "Removing install files in chocolateyInstall, helpers, redirects, and tools"
"$chocolateyPath\chocolateyInstall", "$chocolateyPath\helpers", "$chocolateyPath\redirects", "$chocolateyPath\tools" | % {
"$chocolateyPath\chocolateyInstall", "$chocolateyPath\helpers", "$chocolateyPath\redirects", "$chocolateyPath\tools" | ForEach-Object {
#Write-Debug "Checking path $_"

if (Test-Path $_) {
Get-ChildItem -Path "$_" | % {
Get-ChildItem -Path "$_" | ForEach-Object {
#Write-Debug "Checking child path $_ ($($_.FullName))"
if (Test-Path $_.FullName) {
Write-Debug "Removing $_ unless matches .log"
Expand Down Expand Up @@ -504,9 +504,12 @@ param(
}

if (!(Test-Path("$chocoPkgDirectory\chocolatey.nupkg"))) {
$chocoPkg = Get-ChildItem "$thisScriptFolder/../../" | ?{$_.name -match "^chocolatey.*nupkg" } | Sort name -Descending | Select -First 1
$chocoPkg = Get-ChildItem "$thisScriptFolder/../../" |
Where-Object {$_.name -match "^chocolatey.*nupkg" } |
Sort-Object name -Descending |
Select-Object -First 1
if ($chocoPkg -ne '') { $chocoPkg = $chocoPkg.FullName }
"$chocoZipFile", "$chocoPkg" | % {
"$chocoZipFile", "$chocoPkg" | ForEach-Object {
if ($_ -ne $null -and $_ -ne '') {
if (Test-Path $_) {
Write-Debug "Copying '$_' to '$chocoPkgDirectory\chocolatey.nupkg'."
Expand Down
2 changes: 1 addition & 1 deletion setup.ps1
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
### install chocolatey ###
if(-not $env:ChocolateyInstall -or -not (Test-Path "$env:ChocolateyInstall")){
iex ((new-object net.webclient).DownloadString("https://community.chocolatey.org/install.ps1"))
Invoke-Expression ((new-object net.webclient).DownloadString("https://community.chocolatey.org/install.ps1"))
}

cinst pester -version 2.0.2
40 changes: 22 additions & 18 deletions src/chocolatey.resources/helpers/ChocolateyTabExpansion.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -29,8 +29,8 @@ function script:chocoCmdOperations($commands, $command, $filter, $currentArgumen
if ($currentArguments -ne $null -and $currentArguments.Trim() -ne '') { $currentOptions = $currentArguments.Trim() -split ' ' }

$commands.$command.Replace(" "," ") -split ' ' |
where { $_ -notmatch "^(?:$($currentOptions -join '|' -replace "=", "\="))(?:\S*)\s?$" } |
where { $_ -like "$filter*" }
Where-Object { $_ -notmatch "^(?:$($currentOptions -join '|' -replace "=", "\="))(?:\S*)\s?$" } |
Where-Object { $_ -like "$filter*" }
}

$script:someCommands = @('-?','search','list','info','install','outdated','upgrade','uninstall','new','download','optimize','pack','push','sync','-h','--help','pin','source','config','feature','apikey','export','help','template','--version')
Expand Down Expand Up @@ -80,31 +80,35 @@ function script:chocoCommands($filter) {
$cmdList += $someCommands -like "$filter*"
} else {
$cmdList += (& $script:choco -h) |
where { $_ -match '^ \S.*' } |
foreach { $_.Split(' ', [StringSplitOptions]::RemoveEmptyEntries) } |
where { $_ -like "$filter*" }
Where-Object { $_ -match '^ \S.*' } |
ForEach-Object { $_.Split(' ', [StringSplitOptions]::RemoveEmptyEntries) } |
Where-Object { $_ -like "$filter*" }
}

$cmdList #| sort
}

function script:chocoLocalPackages($filter) {
if ($filter -ne $null -and $filter.StartsWith(".")) { return; } #file search
@(& $script:choco list $filter -lo -r --id-starts-with) | %{ $_.Split('|')[0] }
@(& $script:choco list $filter -lo -r --id-starts-with) | ForEach-Object { $_.Split('|')[0] }
}

function script:chocoLocalPackagesUpgrade($filter) {
if ($filter -ne $null -and $filter.StartsWith(".")) { return; } #file search
@('all|') + @(& $script:choco list $filter -lo -r --id-starts-with) | where { $_ -like "$filter*" } | %{ $_.Split('|')[0] }
@('all|') + @(& $script:choco list $filter -lo -r --id-starts-with) |
Where-Object { $_ -like "$filter*" } |
ForEach-Object { $_.Split('|')[0] }
}

function script:chocoRemotePackages($filter) {
if ($filter -ne $null -and $filter.StartsWith(".")) { return; } #file search
@('packages.config|') + @(& $script:choco search $filter --page='0' --page-size='30' -r --id-starts-with --order-by-popularity) | where { $_ -like "$filter*" } | %{ $_.Split('|')[0] }
@('packages.config|') + @(& $script:choco search $filter --page='0' --page-size='30' -r --id-starts-with --order-by-popularity) |
Where-Object { $_ -like "$filter*" } |
ForEach-Object { $_.Split('|')[0] }
}

function Get-AliasPattern($exe) {
$aliases = @($exe) + @(Get-Alias | where { $_.Definition -eq $exe } | select -Exp Name)
$aliases = @($exe) + @(Get-Alias | Where-Object { $_.Definition -eq $exe } | Select-Object -Exp Name)

"($($aliases -join '|'))"
}
Expand All @@ -129,46 +133,46 @@ function ChocolateyTabExpansion($lastBlock) {

# Handles list/search first tab
"^(list|search)\s+(?<subcommand>[^-\s]*)$" {
@('<filter>','-?') | where { $_ -like "$($matches['subcommand'])*" }
@('<filter>','-?') | Where-Object { $_ -like "$($matches['subcommand'])*" }
}

# Handles new first tab
"^(new)\s+(?<subcommand>[^-\s]*)$" {
@('<name>','-?') | where { $_ -like "$($matches['subcommand'])*" }
@('<name>','-?') | Where-Object { $_ -like "$($matches['subcommand'])*" }
}

# Handles pack first tab
"^(pack)\s+(?<subcommand>[^-\s]*)$" {
@('<PathtoNuspec>','-?') | where { $_ -like "$($matches['subcommand'])*" }
@('<PathtoNuspec>','-?') | Where-Object { $_ -like "$($matches['subcommand'])*" }
}

# Handles push first tab
"^(push)\s+(?<subcommand>[^-\s]*)$" {
@('<PathtoNupkg>','-?') | where { $_ -like "$($matches['subcommand'])*" }
@('<PathtoNupkg>','-?') | Where-Object { $_ -like "$($matches['subcommand'])*" }
}

# Handles source first tab
"^(source)\s+(?<subcommand>[^-\s]*)$" {
@('list','add','remove','disable','enable','-?') | where { $_ -like "$($matches['subcommand'])*" }
@('list','add','remove','disable','enable','-?') | Where-Object { $_ -like "$($matches['subcommand'])*" }
}

# Handles pin first tab
"^(pin)\s+(?<subcommand>[^-\s]*)$" {
@('list','add','remove','-?') | where { $_ -like "$($matches['subcommand'])*" }
@('list','add','remove','-?') | Where-Object { $_ -like "$($matches['subcommand'])*" }
}

# Handles feature first tab
"^(feature)\s+(?<subcommand>[^-\s]*)$" {
@('list','disable','enable','-?') | where { $_ -like "$($matches['subcommand'])*" }
@('list','disable','enable','-?') | Where-Object { $_ -like "$($matches['subcommand'])*" }
}
# Handles config first tab
"^(config)\s+(?<subcommand>[^-\s]*)$" {
@('list','get','set','unset','-?') | where { $_ -like "$($matches['subcommand'])*" }
@('list','get','set','unset','-?') | Where-Object { $_ -like "$($matches['subcommand'])*" }
}

# Handles template first tab
"^(template)\s+(?<subcommand>[^-\s]*)$" {
@('list', 'info', '-?') | where { $_ -like "$($matches['subcommand'])*" }
@('list', 'info', '-?') | Where-Object { $_ -like "$($matches['subcommand'])*" }
}

# Handles more options after others
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,7 @@ param(

$bitnessMessage = ''
$zipfileFullPath=$fileFullPath
if ((Get-ProcessorBits 32) -or $env:ChocolateyForceX86 -eq 'true') {
if ((Get-OSArchitectureWidth 32) -or $env:ChocolateyForceX86 -eq 'true') {
if (!$fileFullPath) { throw "32-bit archive is not supported for $packageName"; }
if ($fileFullPath64) { $bitnessMessage = '32-bit '; }
} elseif ($fileFullPath64) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -229,7 +229,7 @@ param(
$checksum32 = $checksum
$checksumType32 = $checksumType
$bitWidth = 32
if (Get-ProcessorBits 64) {
if (Get-OSArchitectureWidth 64) {
$bitWidth = 64
}
Write-Debug "CPU is $bitWidth bit"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -150,7 +150,7 @@ param(
foreach ($paramString in $paramStrings) {
if (!$paramString -or $paramString -eq '') { continue }

Select-String '(?:^|\s+)\/(?<ItemKey>[^\:\=\s)]+)(?:(?:\:|=){1}(?:\''|\"){0,1}(?<ItemValue>.*?)(?:\''|\"){0,1}(?:(?=\s+\/)|$))?' -Input $paramString -AllMatches | % { $_.Matches } | % {
Select-String '(?:^|\s+)\/(?<ItemKey>[^\:\=\s)]+)(?:(?:\:|=){1}(?:\''|\"){0,1}(?<ItemValue>.*?)(?:\''|\"){0,1}(?:(?=\s+\/)|$))?' -Input $paramString -AllMatches | ForEach-Object { $_.Matches } | ForEach-Object {
if (!$_) { continue } #Posh v2 issue?
$paramItemName = ($_.Groups["ItemKey"].Value).Trim()
$paramItemValue = ($_.Groups["ItemValue"].Value).Trim()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -134,7 +134,7 @@ param(

$keyPaths = $keys | Select-Object -ExpandProperty PSPath
try {
[array]$foundKey = Get-ItemProperty -LiteralPath $keyPaths -ErrorAction Stop | ? { $_.DisplayName -like $softwareName }
[array]$foundKey = Get-ItemProperty -LiteralPath $keyPaths -ErrorAction Stop | Where-Object { $_.DisplayName -like $softwareName }
$success = $true
} catch {
Write-Debug "Found bad key."
Expand All @@ -146,7 +146,7 @@ param(
}
}
Write-Verbose "Skipping bad key: $badKey"
[array]$keys = $keys | ? { $badKey -NotContains $_.PsPath }
[array]$keys = $keys | Where-Object { $badKey -NotContains $_.PsPath }
}

if ($success) { break; }
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -228,7 +228,7 @@ Start-ChocolateyProcessAsAdmin

$bitnessMessage = ''
$fileFullPath = $file
if ((Get-ProcessorBits 32) -or $env:ChocolateyForceX86 -eq 'true') {
if ((Get-OSArchitectureWidth 32) -or $env:ChocolateyForceX86 -eq 'true') {
if (!$file) { throw "32-bit installation is not supported for $packageName"; }
if ($file64) { $bitnessMessage = '32-bit '; }
}
Expand Down Expand Up @@ -311,14 +311,15 @@ Pro / Business supports a single, ubiquitous install directory option.
try {
# make sure any logging folder exists
$pattern = "(?:['`"])([a-zA-Z]\:\\[^'`"]+)(?:[`"'])|([a-zA-Z]\:\\[\S]+)"
$silentArgs, $additionalInstallArgs | % { Select-String $pattern -input $_ -AllMatches } |
% { $_.Matches } | % {
$argDirectory = $_.Groups[1]
if ($argDirectory -eq $null -or $argDirectory -eq '') { continue }
$argDirectory = [System.IO.Path]::GetFullPath([System.IO.Path]::GetDirectoryName($argDirectory))
Write-Debug "Ensuring '$argDirectory' exists"
if (![System.IO.Directory]::Exists($argDirectory)) { [System.IO.Directory]::CreateDirectory($argDirectory) | Out-Null }
}
$silentArgs, $additionalInstallArgs |
ForEach-Object { Select-String $pattern -input $_ -AllMatches } |
ForEach-Object { $_.Matches } | ForEach-Object {
$argDirectory = $_.Groups[1]
if ($argDirectory -eq $null -or $argDirectory -eq '') { continue }
$argDirectory = [System.IO.Path]::GetFullPath([System.IO.Path]::GetDirectoryName($argDirectory))
Write-Debug "Ensuring '$argDirectory' exists"
if (![System.IO.Directory]::Exists($argDirectory)) { [System.IO.Directory]::CreateDirectory($argDirectory) | Out-Null }
}
}
catch {
Write-Debug "Error ensuring directories exist - $($_.Exception.Message)"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -388,7 +388,7 @@ param(
[string]$filePath = $downloadFilePath
if ($useOriginalLocation) {
$filePath = $url
if (Get-ProcessorBits 64) {
if (Get-OSArchitectureWidth 64) {
$forceX86 = $env:chocolateyForceX86
if ($forceX86) {
Write-Debug "User specified '-x86' so forcing 32-bit"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ param(
$shell=new-object -com "Shell.Application"
$folder=$shell.Namespace($path)
$item = $folder.Parsename((split-path $targetFilePath -leaf))
$itemVerb = $item.Verbs() | ? {$_.Name.Replace("&","") -eq $verb}
$itemVerb = $item.Verbs() | Where-Object {$_.Name.Replace("&","") -eq $verb}
if($itemVerb -eq $null){
Write-Host "TaskBar verb not found for $item. It may have already been pinned"
} else {
Expand Down
Loading

0 comments on commit b2554df

Please sign in to comment.