Skip to content

Commit

Permalink
lint(lib): Path-Glueing elimination
Browse files Browse the repository at this point in the history
  • Loading branch information
Ash258 committed Jun 21, 2020
1 parent 55c10b0 commit c961123
Show file tree
Hide file tree
Showing 12 changed files with 202 additions and 217 deletions.
6 changes: 3 additions & 3 deletions lib/Alias.ps1
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
'core', 'commands', 'help', 'install' | ForEach-Object {
. "$PSScriptRoot\$_.ps1"
. (Join-Path $PSScriptRoot "$_.ps1")
}

$ALIAS_CMD_ALIAS = 'alias'
Expand Down Expand Up @@ -38,10 +38,10 @@ function Add-ScoopAlias {

if ($aliases.$Name) { throw "Alias $Name already exists" }

@"
Join-Path $shimDir "$aliasFileName.ps1" | Out-UTF8Content -Content @"
# Summary: $Description
$Command
"@ | Out-UTF8File "$shimDir\$aliasFileName.ps1"
"@

# Add alias to config
$aliases | Add-Member -Name $Name -Value $aliasFileName -MemberType NoteProperty
Expand Down
48 changes: 24 additions & 24 deletions lib/Diagnostic.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,29 @@ Use 'Write-UserMessage -Warning' to highlight the issue, and follow up with the
#>

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

function Test-Drive {
[CmdletBinding()]
[OutputType([bool])]
param()

$result = $true

if ((New-Object System.IO.DriveInfo($SCOOP_GLOBAL_ROOT_DIRECTORY)).DriveFormat -ne 'NTFS') {
Write-UserMessage -Message 'Scoop requires an NTFS volume to work!' -Warning
Write-UserMessage -Message ' Please configure SCOOP_GLOBAL environment variable to NTFS volume'
$result = $false
}

if ((New-Object System.IO.DriveInfo($SCOOP_ROOT_DIRECTORY)).DriveFormat -ne 'NTFS') {
Write-UserMessage -Message 'Scoop requires an NTFS volume to work!' -Warning
Write-UserMessage -Message ' Please install scoop to NTFS volume'
$result = $false
}

return $result
}

function Test-WindowsDefender {
Expand Down Expand Up @@ -166,28 +188,6 @@ function Test-HelpersInstalled {
return $result
}

function Test-Drive {
[CmdletBinding()]
[OutputType([bool])]
param()

$result = $true

if ((New-Object System.IO.DriveInfo($SCOOP_GLOBAL_ROOT_DIRECTORY)).DriveFormat -ne 'NTFS') {
Write-UserMessage -Message 'Scoop requires an NTFS volume to work!' -Warning
Write-UserMessage -Message ' Please configure SCOOP_GLOBAL environment variable to NTFS volume'
$result = $false
}

if ((New-Object System.IO.DriveInfo($SCOOP_ROOT_DIRECTORY)).DriveFormat -ne 'NTFS') {
Write-UserMessage -Message 'Scoop requires an NTFS volume to work!' -Warning
Write-UserMessage -Message ' Please install scoop to NTFS volume'
$result = $false
}

return $result
}

function Test-Config {
[CmdletBinding()]
[OutputType([bool])]
Expand All @@ -198,7 +198,7 @@ function Test-Config {
Write-UserMessage -Message '''lsessmsi'' should be used for extraction of msi installers!' -Warning
Write-UserMessage -Message @(
' Fixable with running following command:'
' scoop config MSIEXTRACT_USE_LESSMSI $true'
' scoop install lessmsi; scoop config MSIEXTRACT_USE_LESSMSI $true'
)
$result = $false
}
Expand Down
2 changes: 1 addition & 1 deletion lib/Git.ps1
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
'core' | ForEach-Object {
. "$PSScriptRoot\$_.ps1"
. (Join-Path $PSScriptRoot "$_.ps1")
}

function Invoke-GitCmd {
Expand Down
15 changes: 7 additions & 8 deletions lib/Update.ps1
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
'core', 'Git', 'buckets', 'install' | ForEach-Object {
. "$PSScriptRoot\$_.ps1"
'core', 'Git', 'Helpers', 'buckets', 'install' | ForEach-Object {
. (Join-Path $PSScriptRoot "$_.ps1")
}

# TODO: Change
Expand Down Expand Up @@ -31,11 +31,10 @@ function Update-ScoopCoreClone {
Write-UserMessage -Message "Cloning scoop installation from $Repo ($Branch)" -Info

$newDir = versiondir 'scoop' 'new'

Invoke-GitCmd -Command 'clone' -Argument '--quiet', '--single-branch', '--branch', """$Branch""", $Repo, """$newDir""" -Proxy

# TODO: Stop-ScoopExecution
# Check if scoop was successful downloaded
# TODO: Stop-ScoopExecution
if (!(Test-Path $newDir -PathType Container)) { abort 'Scoop update failed.' }

# Replace non-git scoop with the git version
Expand Down Expand Up @@ -69,8 +68,8 @@ function Update-ScoopCorePull {
$currentRepo = Invoke-GitCmd @target -Command 'config' -Argument '--get', 'remote.origin.url'
$currentBranch = Invoke-GitCmd @target -Command 'branch' -Argument '--show-current'

$isRepoChanged = !($currentRepo -eq $Repo)
$isBranchChanged = !($currentBranch -eq $Branch)
$isRepoChanged = $currentRepo -ne $Repo
$isBranchChanged = $currentBranch -ne $Branch

# Change remote url if the repo is changed
if ($isRepoChanged) { Invoke-GitCmd @target -Cmd 'config' -Argument 'remote.origin.url', """$Repo""" }
Expand Down Expand Up @@ -171,7 +170,7 @@ function Update-Scoop {
}

ensure_scoop_in_path
shim "$currentDir\bin\scoop.ps1" $false
shim (Join-Path $currentDir 'bin\scoop.ps1') $false

Get-LocalBucket | Update-ScoopLocalBucket

Expand Down Expand Up @@ -298,7 +297,7 @@ function Update-App {
if ($Force -and ($oldVersion -eq $version)) {
$dir = versiondir $App $oldVersion $Global

$old = "$dir/../_$version.old"
$old = Join-Path $dir "..\_$version.old"
if (Test-Path $old -PathType Container) {
$i = 1
while (Test-Path "$old($i)") { ++$i }
Expand Down
17 changes: 9 additions & 8 deletions lib/Versions.ps1
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
'core', 'manifest' | ForEach-Object {
. "$PSScriptRoot\$_.ps1"
'core', 'Helpers', 'manifest' | ForEach-Object {
. (Join-Path $PSScriptRoot "$_.ps1")
}

function Get-LatestVersion {
Expand All @@ -13,8 +13,8 @@ function Get-LatestVersion {
.PARAMETER Uri
Specifies remote app manifest's URI.
#>
[OutputType([String])]
[CmdletBinding()]
[OutputType([String])]
param (
[Parameter(Mandatory, Position = 0, ValueFromPipeline)]
[Alias('App')]
Expand All @@ -40,8 +40,8 @@ function Get-InstalledVersion {
Versions are sorted from oldest to newest, i.e., latest installed version is the last one in the output array.
If no installed version found, empty array will be returned.
#>
[OutputType([Object[]])]
[CmdletBinding()]
[OutputType([Object[]])]
param (
[Parameter(Mandatory = $true, Position = 0, ValueFromPipeline = $true)]
[Alias('App')]
Expand Down Expand Up @@ -74,8 +74,8 @@ function Select-CurrentVersion {
.PARAMETER Global
Specifies globally installed application.
#>
[OutputType([String])]
[CmdletBinding()]
[OutputType([String])]
param (
[Parameter(Mandatory, Position = 0, ValueFromPipeline)]
[Alias('App')]
Expand All @@ -87,10 +87,11 @@ function Select-CurrentVersion {
process {
$appPath = appdir $AppName $Global

if (Test-Path "$appPath\current" -PathType Container) {
$currentPath = Join-Path $appPath 'current'
if (Test-Path $currentPath -PathType Container) {
$currentVersion = (installed_manifest $AppName 'current' $Global).version
# Get version from link target in case of nightly
if ($currentVersion -eq 'nightly') { $currentVersion = ((Get-Item "$appPath\current").Target | Get-Item).BaseName }
if ($currentVersion -eq 'nightly') { $currentVersion = ((Get-Item $currentPath).Target | Get-Item).BaseName }
} else {
$installedVersion = @(Get-InstalledVersion -AppName $AppName -Global:$Global)
$currentVersion = if ($installedVersion) { $installedVersion[-1] } else { $null }
Expand All @@ -116,8 +117,8 @@ function Compare-Version {
'1' if DifferenceVersion is greater then ReferenceVersion,
'-1' if DifferenceVersion is less then ReferenceVersion
#>
[OutputType([Int])]
[CmdletBinding()]
[OutputType([Int])]
param (
[Parameter(Position = 0)]
[Alias('Old')]
Expand Down
60 changes: 34 additions & 26 deletions lib/VirusTotal.ps1
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
'core', 'manifest' | ForEach-Object {
. "$PSScriptRoot\$_.ps1"
'core', 'Helpers', 'manifest' | ForEach-Object {
. (Join-Path $PSScriptRoot "$_.ps1")
}

$VT_ERR = @{
Expand All @@ -16,7 +16,7 @@ function Get-VirusTotalResult {
Specifies the hash of file to search for.
.PARAMETER App
Specifies the name of application.
.OUTPUTs Int
.OUTPUTS Int
Exit code
#>
[CmdletBinding()]
Expand All @@ -31,7 +31,7 @@ function Get-VirusTotalResult {
$Hash = $Hash.ToLower()
$url = "https://www.virustotal.com/ui/files/$hash"
$detectionUrl = $url -replace '/ui/files/', '/#/file/'
$wc = New-Object Net.Webclient
$wc = New-Object System.Net.Webclient
$wc.Headers.Add('User-Agent', (Get-UserAgent))
$result = $wc.DownloadString($url)

Expand All @@ -42,15 +42,16 @@ function Get-VirusTotalResult {
$unsafe = [int]$malicious + [int]$suspicious

switch ($unsafe) {
0 { if ($undetected -eq 0) { $fg = 'Yellow' } else { $fg = 'DarkGreen' } }
0 { $fg = if ($undetected -eq 0) { 'Yellow' } else { 'DarkGreen' } }
1 { $fg = 'DarkYellow' }
2 { $fg = 'Yellow' }
default { $fg = 'Red' }
}
Write-Host "${App}: $unsafe/$undetected, see '$detectionUrl" -ForegroundColor $fg
if ($unsafe -gt 0) { return $VT_ERR.Unsafe }

return 0
Write-UserMessage -Message "${App}: $unsafe/$undetected, see '$detectionUrl" -Color $fg
$ret = if ($unsafe -gt 0) { $VT_ERR.Unsafe } else { 0 }

return $ret
}

function Search-VirusTotal {
Expand All @@ -61,7 +62,7 @@ function Search-VirusTotal {
Specifies the hash of file to search for.
.PARAMETER App
Specifies the name of application.
.OUTPUTs Int
.OUTPUTS Int
Exit code
#>
[CmdletBinding()]
Expand Down Expand Up @@ -98,21 +99,23 @@ function Submit-RedirectedUrl {
#>
[CmdletBinding()]
[OutputType([String])]
param (
[Parameter(Mandatory)]
[String] $URL
)
$request = [System.Net.WebRequest]::Create($url)
$request.AllowAutoRedirect = $false
$response = $request.GetResponse()
if (([int]$response.StatusCode -ge 300) -and ([int]$response.StatusCode -lt 400)) {
$redir = $response.GetResponseHeader('Location')
} else {
$redir = $URL
}
$response.Close()
param ([Parameter(Mandatory, ValueFromPipeline)] [String] $URL)

return $redir
process {
$request = [System.Net.WebRequest]::Create($url)
$request.AllowAutoRedirect = $false
$response = $request.GetResponse()

if (([int]$response.StatusCode -ge 300) -and ([int]$response.StatusCode -lt 400)) {
$redir = $response.GetResponseHeader('Location')
} else {
$redir = $URL
}

$response.Close()

return $redir
}
}

function Submit-ToVirusTotal {
Expand Down Expand Up @@ -142,7 +145,12 @@ function Submit-ToVirusTotal {
$apiKey = get_config 'virustotal_api_key'

if ($DoScan -and !$apiKey) {
Write-UserMessage -Message 'Submitting unknown apps needs a VirusTotal API key. You can configure it with:', "scoop config virustotal_api_key <API key>" -Info
Write-UserMessage -Warning -Message @(
'Submitting unknown apps requires the VirusTotal API key.'
'You can configure it with:'
' scoop config virustotal_api_key <API key>'
)

return
}

Expand All @@ -156,7 +164,7 @@ function Submit-ToVirusTotal {
$newRedir = Submit-RedirectedUrl $origRedir
} while ($origRedir -ne $newRedir)
$requests += 1
$result = Invoke-WebRequest -Uri "https://www.virustotal.com/vtapi/v2/url/scan" -Body @{'apikey' = $apiKey; 'url' = $newRedir } -Method Post -UseBasicParsing
$result = Invoke-WebRequest -Uri 'https://www.virustotal.com/vtapi/v2/url/scan' -Body @{ 'apikey' = $apiKey; 'url' = $newRedir } -Method Post -UseBasicParsing
if ($result.StatusCode -eq 200) {
Write-UserMessage -Message "${app}: not found. Submitted $url" -Warning
return
Expand All @@ -166,8 +174,8 @@ function Submit-ToVirusTotal {
$explained = $false
if (!$Retry) {
if (!$explained) {
$explained = $true
Write-UserMessage -Message 'Sleeping 60+ seconds between requests due to VirusTotal''s 4/min limit'
$explained = $true
}
Start-Sleep -Seconds (60 + $requests)
Submit-ToVirusTotal $newRedir $app -DoScan:$DoScan -Retry
Expand Down
19 changes: 8 additions & 11 deletions lib/getopt.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -9,24 +9,21 @@
# a parameter should end with '='
# returns @(opts hash, remaining_args array, error string)
function getopt($argv, $shortopts, $longopts) {
$opts = @{ }; $rem = @()
$opts = @{ }
$rem = @()

function err($msg) {
$opts, $rem, $msg
}
function err($msg) { return $opts, $rem, $msg }

function regex_escape($str) {
return [regex]::escape($str)
}
function regex_escape($str) { return [System.Text.RegularExpressions.Regex]::Escape($str) }

# ensure these are arrays
# Ensure these are arrays
$argv = @($argv)
$longopts = @($longopts)

for ($i = 0; $i -lt $argv.length; $i++) {
$arg = $argv[$i]
if ($null -eq $arg) { continue }
# don't try to parse array arguments
# Don't try to parse array arguments
if ($arg -is [array]) { $rem += , $arg; continue }
if ($arg -is [int]) { $rem += $arg; continue }
if ($arg -is [decimal]) { $rem += $arg; continue }
Expand All @@ -38,7 +35,7 @@ function getopt($argv, $shortopts, $longopts) {

if ($longopt) {
if ($longopt.endswith('=')) {
# requires arg
# Requires arg
if ($i -eq $argv.length - 1) {
return err "Option --$name requires an argument."
}
Expand Down Expand Up @@ -72,5 +69,5 @@ function getopt($argv, $shortopts, $longopts) {
}
}

$opts, $rem
return $opts, $rem
}
Loading

0 comments on commit c961123

Please sign in to comment.