Skip to content

Commit

Permalink
refactor: Remove simple usages of abort function (Wave 1) (#49)
Browse files Browse the repository at this point in the history
  • Loading branch information
Ash258 committed Jul 26, 2020
1 parent 62a6274 commit 64082dc
Show file tree
Hide file tree
Showing 30 changed files with 250 additions and 209 deletions.
2 changes: 1 addition & 1 deletion PSScriptAnalyzerSettings.psd1
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@
Severity = @('Error', 'Warning')

ExcludeRules = @(
# Currently Scoop widely uses Write-Host to output colored text.
'PSUseShouldProcessForStateChangingFunctions',
# Currently Scoop widely uses Write-Host to output colored text.
'PSAvoidUsingWriteHost',
# Temporarily allow uses of Invoke-Expression,
# this command is used by some core functions and hard to be removed.
Expand Down
22 changes: 13 additions & 9 deletions bin/scoop.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -3,32 +3,36 @@ param($cmd)

Set-StrictMode -Off

'core', 'buckets', 'commands', 'Git' | ForEach-Object {
'core', 'buckets', 'Helpers', 'commands', 'Git' | ForEach-Object {
. (Join-Path $PSScriptRoot "..\lib\$_.ps1")
}

reset_aliases
Reset-Alias
$exitCode = 0

if (('--version' -eq $cmd) -or (!$cmd -and ('-v' -in $args))) {
Write-UserMessage -Message 'Current Scoop (soon to be Shovel) version:' -Output
Invoke-GitCmd -Command 'VersionLog' -Repository (versiondir 'scoop' 'current')
Write-UserMessage -Message ''
Write-UserMessage -Message '' -Output

Get-LocalBucket | ForEach-Object {
$b = Find-BucketDirectory $_ -Root

if (Join-Path $b '.git' | Test-Path -PathType Container) {
Write-UserMessage -Message "'$_' bucket:" -Output
Invoke-GitCmd -Command 'VersionLog' -Repository $b
Write-UserMessage -Message ''
Write-UserMessage -Message '' -Output
}
}
} elseif ((@($null, '--help', '/?') -contains $cmd) -or ($args[0] -contains '-h')) {
exec 'help' $args
Invoke-ScoopCommand 'help' $args
$exitCode = $LASTEXITCODE
} elseif ((commands) -contains $cmd) {
exec $cmd $args
Invoke-ScoopCommand $cmd $args
$exitCode = $LASTEXITCODE
} else {
# TODO: Stop-ScoopExecution
Write-UserMessage -Message "scoop: '$cmd' isn't a scoop command. See 'scoop help'."
exit 1
Write-UserMessage -Message "scoop: '$cmd' isn't a scoop command. See 'scoop help'." -Output
$exitCode = 2
}

exit $exitCode
91 changes: 91 additions & 0 deletions lib/Helpers.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,42 @@ function Write-UserMessage {
}
}

function Stop-ScoopExecution {
<#
.SYNOPSIS
Print error message and exit scoop execution with given Exit code.
.DESCRIPTION
This function should be used only as the last thing, where there is not possible to recover from error state or
if you can freely exit entire execution without causing problems to user.
If it is called there is no failsafe / error state handling.
For Example. When there is installation of multiple applications happening, and first fail. This function
is called, and rest of applications are not installed, which is not user friendly.
.PARAMETER Message
Specifies the tessage, which will be printed to user.
.PARAMETER ExitCode
Specifies the exit code.
#>
param(
[Parameter(Position = 0, Mandatory, ValueFromPipeline, ValueFromPipelineByPropertyName)]
[String[]] $Message,
[Parameter(Position = 1, ValueFromPipelineByPropertyName)]
[Int] $ExitCode = 3,
[String[]] $Usage,
[Switch] $SkipSeverity
)

begin { if ($Usage) { $ExitCode = 1 } }

process {
Write-UserMessage -Message $Message -Err:(!$SkipSeverity)
if ($Usage) {
Write-UserMessage -Message $Usage -Output
}
}

end { exit $ExitCode }
}

function Out-UTF8File {
<#
.SYNOPSIS
Expand Down Expand Up @@ -176,3 +212,58 @@ function Get-MagicByte {
return $cont.ToUpper()
}
}

function _resetAlias($name, $value) {
$existing = Get-Alias $name -ErrorAction Ignore

if ($existing -and ($existing | Where-Object -Property Options -Match 'readonly')) {
if ($existing.Definition -ne $value) {
Write-UserMessage "Alias $name is read-only; can't reset it." -Warning
}

# Already set
return
}

if ($value -is [ScriptBlock]) {
if (!(Test-Path "Function:script:$name")) {
New-Item -Path Function: -Name "script:$name" -Value $value | Out-Null
}

return
}

Set-Alias $name $value -Scope Script -Option AllScope
}

function Reset-Alias {
# For aliases where there's a local function, re-alias so the function takes precedence
$aliases = Get-Alias | Where-Object -Property Options -NotMatch 'readonly|allscope' | Select-Object -ExpandProperty Name
Get-ChildItem Function: | ForEach-Object {
$fn = $_.Name
if ($fn -in $aliases) {
Set-Alias $fn Local:$fn -Scope Script
}
}

# User aliases
$defautlAliases = @{
'cp' = 'Copy-Item'
'echo' = 'Write-Output'
'gc' = 'Get-Content'
'gci' = 'Get-ChildItem'
'gcm' = 'Get-Command'
'gm' = 'Get-Member'
'iex' = 'Invoke-Expression'
'ls' = 'Get-ChildItem'
'mkdir' = { New-Item -Type Directory @args }
'mv' = 'Move-Item'
'rm' = 'Remove-Item'
'sc' = 'Set-Content'
'select' = 'Select-Object'
'sls' = 'Select-String'
}

# Set default aliases
$defautlAliases.Keys | ForEach-Object { _resetAlias $_ $defautlAliases[$_] }
}
50 changes: 2 additions & 48 deletions lib/core.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -769,55 +769,9 @@ function pluralize($count, $singular, $plural) {
if ($count -eq 1) { $singular } else { $plural }
}

function reset_alias($name, $value) {
if ($existing = Get-Alias $name -ErrorAction Ignore | Where-Object { $_.Options -match 'readonly' }) {
if ($existing.Definition -ne $value) {
Write-UserMessage "Alias $name is read-only; can't reset it." -Warning
}

return # already set
}
if ($value -is [ScriptBlock]) {
if (!(Test-Path "function:script:$name")) {
New-Item -Path Function: -Name "script:$name" -Value $value | Out-Null
}

return
}

Set-Alias $name $value -Scope Script -Option AllScope
}

function reset_aliases() {
# for aliases where there's a local function, re-alias so the function takes precedence
$aliases = Get-Alias | Where-Object { $_.Options -notmatch 'readonly|allscope' } | ForEach-Object { $_.name }
Get-ChildItem Function: | ForEach-Object {
$fn = $_.Name
if ($aliases -contains $fn) {
Set-Alias $fn Local:$fn -Scope Script
}
}

# for dealing with user aliases
$default_aliases = @{
'cp' = 'copy-item'
'echo' = 'write-output'
'gc' = 'get-content'
'gci' = 'get-childitem'
'gcm' = 'get-command'
'gm' = 'get-member'
'iex' = 'invoke-expression'
'ls' = 'get-childitem'
'mkdir' = { New-Item -Type Directory @args }
'mv' = 'move-item'
'rm' = 'remove-item'
'sc' = 'set-content'
'select' = 'select-object'
'sls' = 'select-string'
}

# set default aliases
$default_aliases.Keys | ForEach-Object { reset_alias $_ $default_aliases[$_] }
Show-DeprecatedWarning $MyInvocation 'Reset-Alias'
Reset-Alias
}

# convert list of apps to list of ($app, $global) tuples
Expand Down
29 changes: 29 additions & 0 deletions lib/help.ps1
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
'commands' | ForEach-Object {
. (Join-Path $PSScriptRoot "$_.ps1")
}

function usage($text) {
$text | Select-String '(?m)^# Usage: ([^\n]*)$' | ForEach-Object { 'Usage: ' + $_.matches[0].Groups[1].Value }
}
Expand All @@ -11,6 +15,31 @@ function scoop_help($text) {
$help_lines -replace '(?ms)^#\s?(Help: )?'
}

function print_help($cmd) {
$file = Get-Content (command_path $cmd) -Raw

$usage = usage $file
$summary = summary $file
$help = scoop_help $file

if ($usage) { Write-UserMessage -Message $usage -Output }
if ($summary) { Write-UserMessage -Message '', $summary -Output }
if ($help) { Write-UserMessage -Message '', $help -Output }
}

function print_summaries {
$commands = @{ }

command_files | ForEach-Object {
$command = command_name $_
$summary = summary (Get-Content (command_path $command) -Raw)
if (!($summary)) { $summary = '' }
$commands.Add("$command ", $summary) # add padding
}

$commands.GetEnumerator() | Sort-Object -Property Name | Format-Table -AutoSize -HideTableHeaders -Wrap
}

function my_usage {
# Gets usage for the calling script
usage (Get-Content $myInvocation.PSCommandPath -Raw)
Expand Down
6 changes: 3 additions & 3 deletions lib/manifest.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -130,9 +130,9 @@ function generate_user_manifest($app, $bucket, $version) {
"Attempting to generate manifest for '$app' ($version)"
)

# TODO: Stop-ScoopExecution
if (!($manifest.autoupdate)) {
abort "'$app' does not have autoupdate capability`r`ncouldn't find manifest for '$app@$version'"
Write-UserMessage -Message "'$app' does not have autoupdate capability`r`ncouldn't find manifest for '$app@$version'" -Warning
return $null
}

$path = usermanifestsdir | ensure
Expand All @@ -141,7 +141,7 @@ function generate_user_manifest($app, $bucket, $version) {

return (usermanifest $app | Resolve-Path).Path
} catch {
Write-UserMessage -Message "Could not install $app@$version" -Color DarkRed
throw "Could not install $app@$version"
}

return $null
Expand Down
2 changes: 1 addition & 1 deletion libexec/scoop-alias.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ switch ($Option) {
}
}
'list' { Get-ScoopAlias -Verbose:$Verbose }
default { my_usage; $exitCode = 1 }
default { Stop-ScoopExecution -Message 'No parameters provided' -Usage (my_usage) }
}

exit $exitCode
2 changes: 1 addition & 1 deletion libexec/scoop-bucket.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ param($Cmd, $Name, $Repo)
. (Join-Path $PSScriptRoot "..\lib\$_.ps1")
}

reset_aliases
Reset-Alias

# TODO: Remove
$usage_add = 'usage: scoop bucket add <name> [<repo>]'
Expand Down
2 changes: 1 addition & 1 deletion libexec/scoop-cache.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ param($cmd, $app)

. (Join-Path $PSScriptRoot "..\lib\help.ps1")

reset_aliases
Reset-Alias

function cacheinfo($file) {
$app, $version, $url = $file.name -split '#'
Expand Down
2 changes: 1 addition & 1 deletion libexec/scoop-cleanup.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
. (Join-Path $PSScriptRoot "..\lib\$_.ps1")
}

reset_aliases
Reset-Alias

$opt, $apps, $err = getopt $args 'gk' 'global', 'cache'
if ($err) { Write-UserMessage -Message "scoop cleanup: $err" -Err; exit 2 }
Expand Down
2 changes: 1 addition & 1 deletion libexec/scoop-config.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,7 @@ param($name, $value)
. (Join-Path $PSScriptRoot "..\lib\$_.ps1")
}

reset_aliases
Reset-Alias

if (!$name) { my_usage; exit 1 }

Expand Down
2 changes: 1 addition & 1 deletion libexec/scoop-depends.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
. (Join-Path $PSScriptRoot "..\lib\$_.ps1")
}

reset_aliases
Reset-Alias

$opt, $apps, $err = getopt $args 'a:' 'arch='
$app = $apps[0]
Expand Down
2 changes: 1 addition & 1 deletion libexec/scoop-download.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
. (Join-Path $PSScriptRoot "..\lib\$_.ps1")
}

reset_aliases
Reset-Alias

#region Parameter validation
$opt, $application, $err = getopt $args 'sba:u:' 'skip', 'all-architectures', 'arch=', 'utility='
Expand Down
2 changes: 1 addition & 1 deletion libexec/scoop-export.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
. (Join-Path $PSScriptRoot "..\lib\$_.ps1")
}

reset_aliases
Reset-Alias
$def_arch = default_architecture

$local = installed_apps $false | ForEach-Object { @{ 'name' = $_; 'global' = $false } }
Expand Down
32 changes: 5 additions & 27 deletions libexec/scoop-help.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -3,43 +3,21 @@

param($cmd)

'core', 'commands', 'help' | ForEach-Object {
'help', 'Helpers' | ForEach-Object {
. (Join-Path $PSScriptRoot "..\lib\$_.ps1")
}

reset_aliases

function print_help($cmd) {
$file = Get-Content (command_path $cmd) -raw

$usage = usage $file
$summary = summary $file
$help = scoop_help $file

if ($usage) { "$usage`n" }
if ($help) { $help }
}

function print_summaries {
$commands = @{ }

command_files | ForEach-Object {
$command = command_name $_
$summary = summary (Get-Content (command_path $command) -raw)
if (!($summary)) { $summary = '' }
$commands.add("$command ", $summary) # add padding
}

$commands.getenumerator() | Sort-Object Name | Format-Table -HideTableHead -AutoSize -Wrap
}
Reset-Alias

$exitCode = 0
$commands = commands

if (!($cmd)) {
Write-UserMessage -Message @(
Write-UserMessage -Output -Message @(
'Usage: scoop <command> [<args>]'
''
'Windows command line installer'
''
'General exit codes'
' 0 - Everything OK'
' 1 - No parameter provided or usage shown'
Expand Down
Loading

0 comments on commit 64082dc

Please sign in to comment.