Skip to content

Commit b9deb57

Browse files
niheavenr15ch13
authored andcommitted
refactor(core): Add more generic 'Invoke-ExternalCommand' instead of 'run' (#3432)
1 parent ad6198e commit b9deb57

File tree

3 files changed

+162
-86
lines changed

3 files changed

+162
-86
lines changed

lib/core.ps1

+84-1
Original file line numberDiff line numberDiff line change
@@ -233,7 +233,7 @@ function Get-AppFilePath {
233233
}
234234

235235
Function Test-CommandAvailable {
236-
Param (
236+
param (
237237
[String]$Name
238238
)
239239
Return [Boolean](Get-Command $Name -ErrorAction Ignore)
@@ -366,6 +366,89 @@ function is_local($path) {
366366
}
367367

368368
# operations
369+
370+
function run($exe, $arg, $msg, $continue_exit_codes) {
371+
Show-DeprecatedWarning $MyInvocation 'Invoke-ExternalCommand'
372+
Invoke-ExternalCommand -FilePath $exe -ArgumentList $arg -Activity $msg -ContinueExitCodes $continue_exit_codes
373+
}
374+
375+
function Invoke-ExternalCommand {
376+
[CmdletBinding()]
377+
[OutputType([Boolean])]
378+
param (
379+
[Parameter(Mandatory = $true,
380+
Position = 0)]
381+
[Alias("Path")]
382+
[ValidateNotNullOrEmpty()]
383+
[String]
384+
$FilePath,
385+
[Parameter(Position = 1)]
386+
[Alias("Args")]
387+
[String[]]
388+
$ArgumentList,
389+
[Switch]
390+
$RunAs,
391+
[Alias("Msg")]
392+
[String]
393+
$Activity,
394+
[Alias("cec")]
395+
[Hashtable]
396+
$ContinueExitCodes,
397+
[Alias("Log")]
398+
[String]
399+
$LogPath
400+
)
401+
if ($Activity) {
402+
Write-Host "$Activity " -NoNewline
403+
}
404+
$Process = New-Object System.Diagnostics.Process
405+
$Process.StartInfo.FileName = $FilePath
406+
$Process.StartInfo.Arguments = ($ArgumentList | Select-Object -Unique) -join ' '
407+
$Process.StartInfo.UseShellExecute = $false
408+
if ($LogPath) {
409+
if ($FilePath -match '(^|\W)msiexec($|\W)') {
410+
$Process.StartInfo.Arguments += " /lwe `"$LogPath`""
411+
} else {
412+
$Process.StartInfo.RedirectStandardOutput = $true
413+
}
414+
}
415+
if ($RunAs) {
416+
$Process.StartInfo.Verb = 'RunAs'
417+
}
418+
try {
419+
$Process.Start() | Out-Null
420+
} catch {
421+
if ($Activity) {
422+
Write-Host "error." -ForegroundColor DarkRed
423+
}
424+
error $_.Exception.Message
425+
return $false
426+
}
427+
if ($LogPath -and ($FilePath -notmatch '(^|\W)msiexec($|\W)')) {
428+
Out-File -FilePath $LogPath -Encoding ASCII -Append -InputObject $Process.StandardOutput.ReadToEnd()
429+
}
430+
$Process.WaitForExit()
431+
if ($Process.ExitCode -ne 0) {
432+
if ($ContinueExitCodes -and ($ContinueExitCodes.ContainsKey($Process.ExitCode))) {
433+
if ($Activity) {
434+
Write-Host "done." -ForegroundColor DarkYellow
435+
}
436+
warn $ContinueExitCodes[$Process.ExitCode]
437+
return $true
438+
} else {
439+
if ($Activity) {
440+
Write-Host "error." -ForegroundColor DarkRed
441+
}
442+
error "Exit code was $($Process.ExitCode)!"
443+
return $false
444+
}
445+
}
446+
if ($Activity) {
447+
Write-Host "done." -ForegroundColor Green
448+
}
449+
return $true
450+
}
451+
369452
function dl($url,$to) {
370453
$wc = New-Object Net.Webclient
371454
$wc.headers.add('Referer', (strip_filename $url))

lib/decompress.ps1

+75-51
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
function Test-7zipRequirement {
22
[CmdletBinding(DefaultParameterSetName = "URL")]
33
[OutputType([Boolean])]
4-
param(
4+
param (
55
[Parameter(Mandatory = $true, ParameterSetName = "URL")]
66
[String[]]
77
$URL,
@@ -23,7 +23,7 @@ function Test-7zipRequirement {
2323
function Test-LessmsiRequirement {
2424
[CmdletBinding()]
2525
[OutputType([Boolean])]
26-
param(
26+
param (
2727
[Parameter(Mandatory = $true)]
2828
[String[]]
2929
$URL
@@ -37,48 +37,53 @@ function Test-LessmsiRequirement {
3737

3838
function Expand-7zipArchive {
3939
[CmdletBinding()]
40-
param(
40+
param (
4141
[Parameter(Mandatory = $true, Position = 0, ValueFromPipeline = $true)]
4242
[String]
4343
$Path,
4444
[Parameter(Position = 1)]
4545
[String]
4646
$DestinationPath = (Split-Path $Path),
47-
[ValidateSet("All", "Skip", "Rename")]
48-
[String]
49-
$Overwrite,
5047
[Parameter(ValueFromRemainingArguments = $true)]
5148
[String]
5249
$Switches,
50+
[ValidateSet("All", "Skip", "Rename")]
51+
[String]
52+
$Overwrite,
5353
[Switch]
5454
$Removal
5555
)
56-
$LogLocation = "$(Split-Path $Path)\7zip.log"
57-
switch ($Overwrite) {
58-
"All" { $Switches += " -aoa" }
59-
"Skip" { $Switches += " -aos" }
60-
"Rename" { $Switches += " -aou" }
61-
}
6256
if ((get_config 7ZIPEXTRACT_USE_EXTERNAL)) {
6357
try {
64-
7z x "$Path" -o"$DestinationPath" (-split $Switches) -y | Out-File $LogLocation
58+
$7zPath = (Get-Command '7z' -CommandType Application | Select-Object -First 1).Source
6559
} catch [System.Management.Automation.CommandNotFoundException] {
6660
abort "Cannot find external 7-Zip (7z.exe) while '7ZIPEXTRACT_USE_EXTERNAL' is 'true'!`nRun 'scoop config 7ZIPEXTRACT_USE_EXTERNAL false' or install 7-Zip manually and try again."
6761
}
6862
} else {
69-
& (Get-HelperPath -Helper 7zip) x "$Path" -o"$DestinationPath" (-split $Switches) -y | Out-File $LogLocation
63+
$7zPath = Get-HelperPath -Helper 7zip
64+
}
65+
$LogPath = "$(Split-Path $Path)\7zip.log"
66+
$ArgList = @('x', "`"$Path`"", "-o`"$DestinationPath`"", '-y')
67+
if ($Switches) {
68+
$ArgList += (-split $Switches)
7069
}
71-
if ($LASTEXITCODE -ne 0) {
72-
abort "Failed to extract files from $Path.`nLog file:`n $(friendly_path $LogLocation)"
70+
switch ($Overwrite) {
71+
"All" { $ArgList += "-aoa" }
72+
"Skip" { $ArgList += "-aos" }
73+
"Rename" { $ArgList += "-aou" }
74+
}
75+
$Status = Invoke-ExternalCommand $7zPath $ArgList -LogPath $LogPath
76+
if (!$Status) {
77+
abort "Failed to extract files from $Path.`nLog file:`n $(friendly_path $LogPath)"
7378
}
74-
if (Test-Path $LogLocation) {
75-
Remove-Item $LogLocation -Force
79+
if (Test-Path $LogPath) {
80+
Remove-Item $LogPath -Force
7681
}
77-
if ((strip_ext $Path) -match '\.tar$' -or $Path -match '\.tgz$') {
82+
if ((strip_ext $Path) -match '\.tar$' -or $Path -match '\.t[abgpx]z2?$') {
7883
# Check for tar
79-
$ArchivedFile = & (Get-HelperPath -Helper 7zip) l "$Path"
80-
if ($LASTEXITCODE -eq 0) {
81-
$TarFile = $ArchivedFile[-3] -replace '.{53}(.*)', '$1' # get inner tar file name
84+
$Status = Invoke-ExternalCommand $7zPath @('l', "`"$Path`"") -LogPath $LogPath
85+
if ($Status) {
86+
$TarFile = (Get-Content -Path $LogPath)[-4] -replace '.{53}(.*)', '$1' # get inner tar file name
8287
Expand-7zipArchive "$DestinationPath\$TarFile" $DestinationPath -Removal
8388
} else {
8489
abort "Failed to list files in $Path.`nNot a 7-Zip supported archive file."
@@ -92,34 +97,42 @@ function Expand-7zipArchive {
9297

9398
function Expand-MsiArchive {
9499
[CmdletBinding()]
95-
param(
100+
param (
96101
[Parameter(Mandatory = $true, Position = 0, ValueFromPipeline = $true)]
97102
[String]
98103
$Path,
99104
[Parameter(Position = 1)]
100105
[String]
101106
$DestinationPath = (Split-Path $Path),
107+
[Parameter(ValueFromRemainingArguments = $true)]
108+
[String]
109+
$Switches,
102110
[Switch]
103111
$Removal
104112
)
105-
$LogLocation = "$(Split-Path $Path)\msi.log"
106113
if ((get_config MSIEXTRACT_USE_LESSMSI)) {
107-
& (Get-HelperPath -Helper Lessmsi) x "$Path" "$DestinationPath\" | Out-File $LogLocation
108-
if ($LASTEXITCODE -ne 0) {
109-
abort "Failed to extract files from $Path.`nLog file:`n $(friendly_path $LogLocation)"
110-
}
111-
if (Test-Path "$DestinationPath\SourceDir") {
112-
movedir "$DestinationPath\SourceDir" "$DestinationPath" | Out-Null
113-
}
114+
$MsiPath = Get-HelperPath -Helper Lessmsi
115+
$ArgList = @('x', "`"$Path`"", "`"$DestinationPath\\`"")
114116
} else {
115-
$ok = run 'msiexec' @('/a', "`"$Path`"", '/qn', "TARGETDIR=`"$DestinationPath`"", "/lwe `"$LogLocation`"")
116-
if (!$ok) {
117-
abort "Failed to extract files from $Path.`nLog file:`n $(friendly_path $LogLocation)"
118-
}
117+
$MsiPath = 'msiexec.exe'
118+
$ArgList = @('/a', "`"$Path`"", '/qn', "TARGETDIR=`"$DestinationPath`"")
119+
}
120+
$LogPath = "$(Split-Path $Path)\msi.log"
121+
if ($Switches) {
122+
$ArgList += (-split $Switches)
123+
}
124+
$Status = Invoke-ExternalCommand $MsiPath $ArgList -LogPath $LogPath
125+
if (!$Status) {
126+
abort "Failed to extract files from $Path.`nLog file:`n $(friendly_path $LogPath)"
127+
}
128+
if (Test-Path "$DestinationPath\SourceDir") {
129+
movedir "$DestinationPath\SourceDir" "$DestinationPath" | Out-Null
130+
}
131+
if (($DestinationPath -ne (Split-Path $Path)) -and (Test-Path "$DestinationPath\$(fname $Path)")) {
119132
Remove-Item "$DestinationPath\$(fname $Path)" -Force
120133
}
121-
if (Test-Path $LogLocation) {
122-
Remove-Item $LogLocation -Force
134+
if (Test-Path $LogPath) {
135+
Remove-Item $LogPath -Force
123136
}
124137
if ($Removal) {
125138
# Remove original archive file
@@ -129,7 +142,7 @@ function Expand-MsiArchive {
129142

130143
function Expand-InnoArchive {
131144
[CmdletBinding()]
132-
param(
145+
param (
133146
[Parameter(Mandatory = $true, Position = 0, ValueFromPipeline = $true)]
134147
[String]
135148
$Path,
@@ -142,13 +155,17 @@ function Expand-InnoArchive {
142155
[Switch]
143156
$Removal
144157
)
145-
$LogLocation = "$(Split-Path $Path)\innounp.log"
146-
& (Get-HelperPath -Helper Innounp) -x -d"$DestinationPath" -c'{app}' "$Path" (-split $Switches) -y | Out-File $LogLocation
147-
if ($LASTEXITCODE -ne 0) {
148-
abort "Failed to extract files from $Path.`nLog file:`n $(friendly_path $LogLocation)"
158+
$LogPath = "$(Split-Path $Path)\innounp.log"
159+
$ArgList = @('-x', "-d`"$DestinationPath`"", "-c`{app`}", "`"$Path`"", '-y')
160+
if ($Switches) {
161+
$ArgList += (-split $Switches)
149162
}
150-
if (Test-Path $LogLocation) {
151-
Remove-Item $LogLocation -Force
163+
$Status = Invoke-ExternalCommand (Get-HelperPath -Helper Innounp) $ArgList -LogPath $LogPath
164+
if (!$Status) {
165+
abort "Failed to extract files from $Path.`nLog file:`n $(friendly_path $LogPath)"
166+
}
167+
if (Test-Path $LogPath) {
168+
Remove-Item $LogPath -Force
152169
}
153170
if ($Removal) {
154171
# Remove original archive file
@@ -158,7 +175,7 @@ function Expand-InnoArchive {
158175

159176
function Expand-ZipArchive {
160177
[CmdletBinding()]
161-
param(
178+
param (
162179
[Parameter(Mandatory = $true, Position = 0, ValueFromPipeline = $true)]
163180
[String]
164181
$Path,
@@ -211,16 +228,23 @@ function Expand-DarkArchive {
211228
[Parameter(Position = 1)]
212229
[String]
213230
$DestinationPath = (Split-Path $Path),
231+
[Parameter(ValueFromRemainingArguments = $true)]
232+
[String]
233+
$Switches,
214234
[Switch]
215235
$Removal
216236
)
217-
$LogLocation = "$(Split-Path $Path)\dark.log"
218-
& (Get-HelperPath -Helper Dark) -nologo -x "$Path" "$DestinationPath" | Out-File $LogLocation
219-
if ($LASTEXITCODE -ne 0) {
220-
abort "Failed to extract files from $Path.`nLog file:`n $(friendly_path $LogLocation)"
237+
$LogPath = "$(Split-Path $Path)\dark.log"
238+
$ArgList = @('-nologo', "-x `"$DestinationPath`"", "`"$Path`"")
239+
if ($Switches) {
240+
$ArgList += (-split $Switches)
241+
}
242+
$Status = Invoke-ExternalCommand (Get-HelperPath -Helper Dark) $ArgList -LogPath $LogPath
243+
if (!$Status) {
244+
abort "Failed to extract files from $Path.`nLog file:`n $(friendly_path $LogPath)"
221245
}
222-
if (Test-Path $LogLocation) {
223-
Remove-Item $LogLocation -Force
246+
if (Test-Path $LogPath) {
247+
Remove-Item $LogPath -Force
224248
}
225249
if ($Removal) {
226250
# Remove original archive file

lib/install.ps1

+3-34
Original file line numberDiff line numberDiff line change
@@ -686,37 +686,6 @@ function args($config, $dir, $global) {
686686
@()
687687
}
688688

689-
function run($exe, $arg, $msg, $continue_exit_codes) {
690-
if($msg) { write-host "$msg " -nonewline }
691-
try {
692-
#Allow null/no arguments to be passed
693-
$parameters = @{ }
694-
if ($arg)
695-
{
696-
$parameters.arg = $arg;
697-
}
698-
699-
# Don't use Start-Process -Wait
700-
# https://github.com/PowerShell/PowerShell/issues/6561
701-
$proc = start-process $exe -ea stop -passthru @parameters
702-
$proc | Wait-Process
703-
704-
705-
if($proc.exitcode -ne 0) {
706-
if($continue_exit_codes -and ($continue_exit_codes.containskey($proc.exitcode))) {
707-
warn $continue_exit_codes[$proc.exitcode]
708-
return $true
709-
}
710-
write-host "Exit code was $($proc.exitcode)."; return $false
711-
}
712-
} catch {
713-
write-host -f darkred $_.exception.tostring()
714-
return $false
715-
}
716-
if($msg) { Write-Host "done." -f Green }
717-
return $true
718-
}
719-
720689
function run_installer($fname, $manifest, $architecture, $dir, $global) {
721690
# MSI or other installer
722691
$msi = msi $manifest $architecture
@@ -753,7 +722,7 @@ function install_msi($fname, $dir, $msi) {
753722

754723
$continue_exit_codes = @{ 3010 = "a restart is required to complete installation" }
755724

756-
$installed = run 'msiexec' $arg "Running installer..." $continue_exit_codes
725+
$installed = Invoke-ExternalCommand 'msiexec' $arg -Activity "Running installer..." -ContinueExitCodes $continue_exit_codes
757726
if(!$installed) {
758727
abort "Installation aborted. You might need to run 'scoop uninstall $app' before trying again."
759728
}
@@ -785,7 +754,7 @@ function install_prog($fname, $dir, $installer, $global) {
785754
if($prog.endswith('.ps1')) {
786755
& $prog @arg
787756
} else {
788-
$installed = run $prog $arg "Running installer..."
757+
$installed = Invoke-ExternalCommand $prog $arg -Activity "Running installer..."
789758
if(!$installed) {
790759
abort "Installation aborted. You might need to run 'scoop uninstall $app' before trying again."
791760
}
@@ -837,7 +806,7 @@ function run_uninstaller($manifest, $architecture, $dir) {
837806
if($exe.endswith('.ps1')) {
838807
& $exe @arg
839808
} else {
840-
$uninstalled = run $exe $arg "Running uninstaller..." $continue_exit_codes
809+
$uninstalled = Invoke-ExternalCommand $exe $arg -Activity "Running uninstaller..." -ContinueExitCodes $continue_exit_codes
841810
if(!$uninstalled) { abort "Uninstallation aborted." }
842811
}
843812
}

0 commit comments

Comments
 (0)