⬆️ kvm.ps1, kvm.cmd, kvm.sh

Source: aspnet/kvm@27be17b70b
This commit is contained in:
ASP.NET Push Bot 2015-02-03 15:09:44 -08:00 committed by unknown
parent 918cbccd30
commit 0cfbfac556
3 changed files with 440 additions and 473 deletions

View File

@ -2,7 +2,7 @@
PowerShell -NoProfile -NoLogo -ExecutionPolicy unrestricted -Command "[System.Threading.Thread]::CurrentThread.CurrentCulture = ''; [System.Threading.Thread]::CurrentThread.CurrentUICulture = '';& '%~dp0kvm.ps1' %*" PowerShell -NoProfile -NoLogo -ExecutionPolicy unrestricted -Command "[System.Threading.Thread]::CurrentThread.CurrentCulture = ''; [System.Threading.Thread]::CurrentThread.CurrentUICulture = '';& '%~dp0kvm.ps1' %*"
IF EXIST "%USERPROFILE%\.kre\run-once.cmd" ( IF EXIST "%USERPROFILE%\.k\temp-set-envvars.cmd" (
CALL "%USERPROFILE%\.kre\run-once.cmd" CALL "%USERPROFILE%\.k\temp-set-envvars.cmd"
DEL "%USERPROFILE%\.kre\run-once.cmd" DEL "%USERPROFILE%\.k\temp-set-envvars.cmd"
) )

576
kvm.ps1
View File

@ -3,19 +3,14 @@ param(
[string] $Command, [string] $Command,
[string] $Proxy, [string] $Proxy,
[switch] $Verbosity = $false, [switch] $Verbosity = $false,
[alias("g")][switch] $Global = $false,
[alias("p")][switch] $Persistent = $false, [alias("p")][switch] $Persistent = $false,
[alias("f")][switch] $Force = $false, [alias("f")][switch] $Force = $false,
[alias("r")][string] $Runtime, [alias("r")][string] $Runtime,
[alias("arch")][string] $Architecture, [alias("arch")][string] $Architecture,
[switch] $X86 = $false, [switch] $X86 = $false,
[switch] $Amd64 = $false, [alias("amd64")][switch] $X64 = $false,
#deprecated
[switch] $X64 = $false,
#deprecated
[switch] $Svr50 = $false,
#deprecated
[switch] $Svrc50 = $false,
[alias("w")][switch] $Wait = $false, [alias("w")][switch] $Wait = $false,
[alias("a")] [alias("a")]
[string] $Alias = $null, [string] $Alias = $null,
@ -27,21 +22,44 @@ param(
[switch] $AssumeElevated [switch] $AssumeElevated
) )
# Constants
Set-Variable -Option Constant "BuildNumber" "10321"
Set-Variable -Option Constant "RuntimePackageName" "kre"
Set-Variable -Option Constant "RuntimeFriendlyName" "K Runtime"
Set-Variable -Option Constant "RuntimeShortName" "KRE"
Set-Variable -Option Constant "RuntimeFolderName" ".k"
Set-Variable -Option Constant "CommandName" "kvm"
Set-Variable -Option Constant "VersionManagerName" "K Version Manager"
Set-Variable -Option Constant "DefaultFeed" "https://www.myget.org/F/aspnetvnext/api/v2"
Set-Variable -Option Constant "CrossGenCommand" "k-crossgen"
Set-Variable -Option Constant "HomeEnvVar" "KRE_HOME"
Set-Variable -Option Constant "UserHomeEnvVar" "KRE_USER_HOME"
Set-Variable -Option Constant "FeedEnvVar" "KRE_FEED"
$selectedArch=$null; $selectedArch=$null;
$defaultArch="x86" $defaultArch="x86"
$selectedRuntime=$null $selectedRuntime=$null
$defaultRuntime="CLR" $defaultRuntime="clr"
# Get or calculate userKrePath function getenv($name) {
$userKrePath = $env:USER_KRE_PATH if(Test-Path "env:\$name") {
if(!$userKrePath) { $userKrePath = $env:USERPROFILE + "\.kre" } cat "env:\$name"
$userKrePackages = $userKrePath + "\packages" }
}
# Get or calculate globalKrePath # Get or calculate userHome
$globalKrePath = $env:GLOBAL_KRE_PATH $userHome = (getenv $UserHomeEnvVar)
if(!$globalKrePath) { $globalKrePath = $env:ProgramFiles + "\KRE" } if(!$userHome) { $userHome = $env:USERPROFILE + "\$RuntimeFolderName" }
$globalKrePackages = $globalKrePath + "\packages" $userRuntimesPath = $userHome + "\runtimes"
$feed = $env:KRE_FEED
# Get the feed from the environment variable or set it to the default value
$feed = (getenv $FeedEnvVar)
if (!$feed)
{
$feed = $DefaultFeed;
}
$feed = $feed.TrimEnd("/")
# In some environments, like Azure Websites, the Write-* cmdlets don't work # In some environments, like Azure Websites, the Write-* cmdlets don't work
$useHostOutputMethods = $true $useHostOutputMethods = $true
@ -50,122 +68,116 @@ function String-IsEmptyOrWhitespace([string]$str) {
return [string]::IsNullOrEmpty($str) -or $str.Trim().length -eq 0 return [string]::IsNullOrEmpty($str) -or $str.Trim().length -eq 0
} }
if (!$feed)
{
$feed = "https://www.myget.org/F/aspnetvnext/api/v2";
}
$feed = $feed.TrimEnd("/")
$scriptPath = $myInvocation.MyCommand.Definition $scriptPath = $myInvocation.MyCommand.Definition
function Kvm-Help { function _Help {
@" @"
K Runtime Environment Version Manager - Build 10108 $VersionManagerName - Build $BuildNumber
USAGE: kvm <command> [options] USAGE: $CommandName <command> [options]
kvm upgrade [-X86][-Amd64] [-r|-Runtime CLR|CoreCLR] [-g|-Global] [-f|-Force] [-Proxy <ADDRESS>] [-NoNative] $CommandName upgrade [-X86|-X64] [-r|-Runtime CLR|CoreCLR] [-g|-Global] [-f|-Force] [-Proxy <ADDRESS>] [-NoNative]
install latest KRE from feed install latest $RuntimeShortName from feed
set 'default' alias to installed version set 'default' alias to installed version
add KRE bin to user PATH environment variable add $RuntimeShortName bin to user PATH environment variable
-g|-Global install to machine-wide location -g|-Global install to machine-wide location
-f|-Force upgrade even if latest is already installed -f|-Force upgrade even if latest is already installed
-Proxy <ADDRESS> use given address as proxy when accessing remote server (e.g. http://username:password@proxyserver:8080/). Alternatively set proxy using http_proxy environment variable. -Proxy <ADDRESS> use given address as proxy when accessing remote server (e.g. https://username:password@proxyserver:8080/). Alternatively set proxy using http_proxy environment variable.
-NoNative Do not generate native images (Effective only for CoreCLR flavors) -NoNative Do not generate native images (Effective only for CoreCLR flavors)
kvm install <semver>|<alias>|<nupkg>|latest [-X86][-Amd64] [-r|-Runtime CLR|CoreCLR] [-a|-Alias <alias>] [-g|-Global] [-f|-Force] [-Proxy <ADDRESS>] [-NoNative] $CommandName install <semver>|<alias>|<nupkg>|latest [-X86|-X64] [-r|-Runtime CLR|CoreCLR] [-a|-Alias <alias>] [-f|-Force] [-Proxy <ADDRESS>] [-NoNative]
<semver>|<alias> install requested KRE from feed <semver>|<alias> install requested $RuntimeShortName from feed
<nupkg> install requested KRE from package on local filesystem <nupkg> install requested $RuntimeShortName from package on local filesystem
latest install latest KRE from feed latest install latest $RuntimeShortName from feed
add KRE bin to path of current command line add $RuntimeShortName bin to path of current command line
-p|-Persistent add KRE bin to PATH environment variables persistently -p|-Persistent add $RuntimeShortName bin to PATH environment variables persistently
-a|-Alias <alias> set alias <alias> for requested KRE on install -a|-Alias <alias> set alias <alias> for requested $RuntimeShortName on install
-g|-Global install to machine-wide location
-f|-Force install even if specified version is already installed -f|-Force install even if specified version is already installed
-Proxy <ADDRESS> use given address as proxy when accessing remote server (e.g. http://username:password@proxyserver:8080/). Alternatively set proxy using http_proxy environment variable. -Proxy <ADDRESS> use given address as proxy when accessing remote server (e.g. https://username:password@proxyserver:8080/). Alternatively set proxy using http_proxy environment variable.
-NoNative Do not generate native images (Effective only for CoreCLR flavors) -NoNative Do not generate native images (Effective only for CoreCLR flavors)
kvm use <semver>|<alias>|<package>|none [-X86][-Amd64] [-r|-Runtime CLR|CoreCLR] [-p|-Persistent] [-g|-Global] $CommandName use <semver>|<alias>|<package>|none [-X86|-X64] [-r|-Runtime CLR|CoreCLR] [-p|-Persistent]
<semver>|<alias>|<package> add KRE bin to path of current command line <semver>|<alias>|<package> add $RuntimeShortName bin to path of current command line
none remove KRE bin from path of current command line none remove $RuntimeShortName bin from path of current command line
-p|-Persistent add KRE bin to PATH environment variables persistently -p|-Persistent add $RuntimeShortName bin to PATH environment variable across all processes run by the current user
-g|-Global combined with -p to change machine PATH instead of user PATH
kvm list $CommandName list
list KRE versions installed list $RuntimeShortName versions installed
kvm alias $CommandName alias
list KRE aliases which have been defined list $RuntimeShortName aliases which have been defined
kvm alias <alias> $CommandName alias <alias>
display value of the specified alias display value of the specified alias
kvm alias <alias> <semver>|<alias>|<package> [-X86][-Amd64] [-r|-Runtime CLR|CoreCLR] $CommandName alias <alias> <semver>|<alias>|<package> [-X86|-X64] [-r|-Runtime CLR|CoreCLR]
<alias> the name of the alias to set <alias> the name of the alias to set
<semver>|<alias>|<package> the KRE version to set the alias to. Alternatively use the version of the specified alias <semver>|<alias>|<package> the $RuntimeShortName version to set the alias to. Alternatively use the version of the specified alias
kvm unalias <alias> $CommandName unalias <alias>
remove the specified alias remove the specified alias
"@ -replace "`n","`r`n" | Console-Write "@ -replace "`n","`r`n" | Console-Write
} }
function Kvm-Global-Setup { function _Global-Setup {
$kvmBinPath = "$userKrePath\bin" # Sets up the version manager tool and adds the user-local runtime install directory to the home variable
# Note: We no longer do global install via this tool. The MSI handles global install of runtimes AND will set
# the machine level home value.
# In this configuration, the user-level path will OVERRIDE the global path because it is placed first.
$cmdBinPath = "$userHome\bin"
If (Needs-Elevation) If (Needs-Elevation)
{ {
$arguments = "-ExecutionPolicy unrestricted & '$scriptPath' setup -global -wait" $arguments = "-ExecutionPolicy unrestricted & '$scriptPath' setup -wait"
Start-Process "$psHome\powershell.exe" -Verb runAs -ArgumentList $arguments -Wait Start-Process "$psHome\powershell.exe" -Verb runAs -ArgumentList $arguments -Wait
Console-Write "Adding $kvmBinPath to process PATH" Console-Write "Adding $cmdBinPath to process PATH"
Set-Path (Change-Path $env:Path $kvmBinPath ($kvmBinPath)) Set-Path (Change-Path $env:Path $cmdBinPath ($cmdBinPath))
Console-Write "Adding $globalKrePath;%USERPROFILE%\.kre to process KRE_HOME" Console-Write "Adding %USERPROFILE%\$RuntimeFolderName to process $HomeEnvVar"
$envKreHome = $env:KRE_HOME $envRuntimeHome = (getenv $HomeEnvVar)
$envKreHome = Change-Path $envKreHome "%USERPROFILE%\.kre" ("%USERPROFILE%\.kre") $envRuntimeHome = Change-Path $envRuntimeHome "%USERPROFILE%\$RuntimeFolderName" ("%USERPROFILE%\$RuntimeFolderName")
$envKreHome = Change-Path $envKreHome $globalKrePath ($globalKrePath) Set-Content "env:\$HomeEnvVar" $envRuntimeHome
$env:KRE_HOME = $envKreHome
Console-Write "Setup complete" Console-Write "Setup complete"
break break
} }
$scriptFolder = [System.IO.Path]::GetDirectoryName($scriptPath) $scriptFolder = [System.IO.Path]::GetDirectoryName($scriptPath)
Console-Write "Copying file $kvmBinPath\kvm.ps1" Console-Write "Copying file $cmdBinPath\$CommandName.ps1"
md $kvmBinPath -Force | Out-Null md $cmdBinPath -Force | Out-Null
copy "$scriptFolder\kvm.ps1" "$kvmBinPath\kvm.ps1" copy "$scriptFolder\$CommandName.ps1" "$cmdBinPath\$CommandName.ps1"
Console-Write "Copying file $kvmBinPath\kvm.cmd" Console-Write "Copying file $cmdBinPath\$CommandName.cmd"
copy "$scriptFolder\kvm.cmd" "$kvmBinPath\kvm.cmd" copy "$scriptFolder\$CommandName.cmd" "$cmdBinPath\$CommandName.cmd"
Console-Write "Adding $kvmBinPath to process PATH" Console-Write "Adding $cmdBinPath to process PATH"
Set-Path (Change-Path $env:Path $kvmBinPath ($kvmBinPath)) Set-Path (Change-Path $env:Path $cmdBinPath ($cmdBinPath))
Console-Write "Adding $kvmBinPath to user PATH" Console-Write "Adding $cmdBinPath to user PATH"
$userPath = [Environment]::GetEnvironmentVariable("Path", [System.EnvironmentVariableTarget]::User) $userPath = [Environment]::GetEnvironmentVariable("Path", [System.EnvironmentVariableTarget]::User)
$userPath = Change-Path $userPath $kvmBinPath ($kvmBinPath) $userPath = Change-Path $userPath $cmdBinPath ($cmdBinPath)
[Environment]::SetEnvironmentVariable("Path", $userPath, [System.EnvironmentVariableTarget]::User) [Environment]::SetEnvironmentVariable("Path", $userPath, [System.EnvironmentVariableTarget]::User)
Console-Write "Adding $globalKrePath;%USERPROFILE%\.kre to process KRE_HOME" Console-Write "Adding %USERPROFILE%\$RuntimeFolderName to process $HomeEnvVar"
$envKreHome = $env:KRE_HOME $envRuntimeHome = (getenv $HomeEnvVar)
$envKreHome = Change-Path $envKreHome "%USERPROFILE%\.kre" ("%USERPROFILE%\.kre") $envRuntimeHome = Change-Path $envRuntimeHome "%USERPROFILE%\$RuntimeFolderName" ("%USERPROFILE%\$RuntimeFolderName")
$envKreHome = Change-Path $envKreHome $globalKrePath ($globalKrePath) Set-Content "env:\$HomeEnvVar" $envRuntimeHome
$env:KRE_HOME = $envKreHome
Console-Write "Adding $globalKrePath;%USERPROFILE%\.kre to machine KRE_HOME" Console-Write "Adding %USERPROFILE%\$RuntimeFolderName to machine $HomeEnvVar"
$machineKreHome = [Environment]::GetEnvironmentVariable("KRE_HOME", [System.EnvironmentVariableTarget]::Machine) $machineruntimeHome = [Environment]::GetEnvironmentVariable($HomeEnvVar, [System.EnvironmentVariableTarget]::Machine)
$machineKreHome = Change-Path $machineKreHome "%USERPROFILE%\.kre" ("%USERPROFILE%\.kre") $machineruntimeHome = Change-Path $machineruntimeHome "%USERPROFILE%\$RuntimeFolderName" ("%USERPROFILE%\$RuntimeFolderName")
$machineKreHome = Change-Path $machineKreHome $globalKrePath ($globalKrePath) [Environment]::SetEnvironmentVariable($HomeEnvVar, $machineruntimeHome, [System.EnvironmentVariableTarget]::Machine)
[Environment]::SetEnvironmentVariable("KRE_HOME", $machineKreHome, [System.EnvironmentVariableTarget]::Machine)
} }
function Kvm-Upgrade { function _Upgrade {
param( param(
[boolean] $isGlobal [boolean] $isGlobal
) )
$Persistent = $true $Persistent = $true
$Alias="default" $Alias="default"
Kvm-Install "latest" $isGlobal _Install "latest" $isGlobal
} }
function Add-Proxy-If-Specified { function Add-Proxy-If-Specified {
@ -187,213 +199,208 @@ param(
} }
} }
function Kvm-Find-Latest { function _Find-Latest {
param( param(
[string] $platform, [string] $platform,
[string] $architecture [string] $architecture
) )
Console-Write "Determining latest version" Console-Write "Determining latest version"
$url = "$feed/GetUpdates()?packageIds=%27KRE-$platform-$architecture%27&versions=%270.0%27&includePrerelease=true&includeAllVersions=false" $url = "$feed/GetUpdates()?packageIds=%27$RuntimePackageName-$platform-win-$architecture%27&versions=%270.0%27&includePrerelease=true&includeAllVersions=false"
$wc = New-Object System.Net.WebClient $wc = New-Object System.Net.WebClient
Add-Proxy-If-Specified($wc) Add-Proxy-If-Specified($wc)
Write-Verbose "Downloading $url ..."
[xml]$xml = $wc.DownloadString($url) [xml]$xml = $wc.DownloadString($url)
$version = Select-Xml "//d:Version" -Namespace @{d='http://schemas.microsoft.com/ado/2007/08/dataservices'} $xml $version = Select-Xml "//d:Version" -Namespace @{d='http://schemas.microsoft.com/ado/2007/08/dataservices'} $xml
if (String-IsEmptyOrWhitespace($version)) { if (String-IsEmptyOrWhitespace($version)) {
throw "There are no packages for platform '$platform', architecture '$architecture' in the feed '$feed'" throw "There are no runtimes for platform '$platform', architecture '$architecture' in the feed '$feed'"
} }
return $version return $version
} }
function Do-Kvm-Download { function Do-Download {
param( param(
[string] $kreFullName, [string] $runtimeFullName,
[string] $packagesFolder [string] $runtimesFolder
) )
$parts = $kreFullName.Split(".", 2) $parts = $runtimeFullName.Split(".", 2)
$url = "$feed/package/" + $parts[0] + "/" + $parts[1] $url = "$feed/package/" + $parts[0] + "/" + $parts[1]
$kreFolder = Join-Path $packagesFolder $kreFullName $runtimeFolder = Join-Path $runtimesFolder $runtimeFullName
$kreFile = Join-Path $kreFolder "$kreFullName.nupkg" $runtimeFile = Join-Path $runtimeFolder "$runtimeFullName.nupkg"
If (Test-Path $kreFolder) { If (Test-Path $runtimeFolder) {
if($Force) if($Force)
{ {
rm $kreFolder -Recurse -Force rm $runtimeFolder -Recurse -Force
} else { } else {
Console-Write "$kreFullName already installed." Console-Write "$runtimeFullName already installed."
return; return;
} }
} }
Console-Write "Downloading $kreFullName from $feed" Console-Write "Downloading $runtimeFullName from $feed"
#Downloading to temp location #Downloading to temp location
$kreTempDownload = Join-Path $packagesFolder "temp" $runtimeTempDownload = Join-Path $runtimesFolder "temp"
$tempKreFile = Join-Path $kreTempDownload "$kreFullName.nupkg" $tempDownloadFile = Join-Path $runtimeTempDownload "$runtimeFullName.nupkg"
if(Test-Path $kreTempDownload) { if(Test-Path $runtimeTempDownload) {
del "$kreTempDownload\*" -recurse del "$runtimeTempDownload\*" -recurse
} else { } else {
md $kreTempDownload -Force | Out-Null md $runtimeTempDownload -Force | Out-Null
} }
$wc = New-Object System.Net.WebClient $wc = New-Object System.Net.WebClient
Add-Proxy-If-Specified($wc) Add-Proxy-If-Specified($wc)
$wc.DownloadFile($url, $tempKreFile) Write-Verbose "Downloading $url ..."
$wc.DownloadFile($url, $tempDownloadFile)
Do-Kvm-Unpack $tempKreFile $kreTempDownload Do-Unpack $tempDownloadFile $runtimeTempDownload
md $kreFolder -Force | Out-Null md $runtimeFolder -Force | Out-Null
Console-Write "Installing to $kreFolder" Console-Write "Installing to $runtimeFolder"
mv "$kreTempDownload\*" $kreFolder mv "$runtimeTempDownload\*" $runtimeFolder
Remove-Item "$kreTempDownload" -Force | Out-Null Remove-Item "$runtimeTempDownload" -Force | Out-Null
} }
function Do-Kvm-Unpack { function Do-Unpack {
param( param(
[string] $kreFile, [string] $runtimeFile,
[string] $kreFolder [string] $runtimeFolder
) )
Console-Write "Unpacking to $kreFolder" Console-Write "Unpacking to $runtimeFolder"
$compressionLib = [System.Reflection.Assembly]::LoadWithPartialName('System.IO.Compression.FileSystem') $compressionLib = [System.Reflection.Assembly]::LoadWithPartialName('System.IO.Compression.FileSystem')
if($compressionLib -eq $null) { if($compressionLib -eq $null) {
try { try {
# Shell will not recognize nupkg as a zip and throw, so rename it to zip # Shell will not recognize nupkg as a zip and throw, so rename it to zip
$kreZip = [System.IO.Path]::ChangeExtension($kreFile, "zip") $runtimeZip = [System.IO.Path]::ChangeExtension($runtimeFile, "zip")
Rename-Item $kreFile $kreZip Rename-Item $runtimeFile $runtimeZip
# Use the shell to uncompress the nupkg # Use the shell to uncompress the nupkg
$shell_app=new-object -com shell.application $shell_app=new-object -com shell.application
$zip_file = $shell_app.namespace($kreZip) $zip_file = $shell_app.namespace($runtimeZip)
$destination = $shell_app.namespace($kreFolder) $destination = $shell_app.namespace($runtimeFolder)
$destination.Copyhere($zip_file.items(), 0x14) #0x4 = don't show UI, 0x10 = overwrite files $destination.Copyhere($zip_file.items(), 0x14) #0x4 = don't show UI, 0x10 = overwrite files
} }
finally { finally {
# make it a nupkg again # make it a nupkg again
Rename-Item $kreZip $kreFile Rename-Item $runtimeZip $runtimeFile
} }
} else { } else {
[System.IO.Compression.ZipFile]::ExtractToDirectory($kreFile, $kreFolder) [System.IO.Compression.ZipFile]::ExtractToDirectory($runtimeFile, $runtimeFolder)
} }
If (Test-Path ($kreFolder + "\[Content_Types].xml")) { If (Test-Path ($runtimeFolder + "\[Content_Types].xml")) {
Remove-Item ($kreFolder + "\[Content_Types].xml") Remove-Item ($runtimeFolder + "\[Content_Types].xml")
} }
If (Test-Path ($kreFolder + "\_rels\")) { If (Test-Path ($runtimeFolder + "\_rels\")) {
Remove-Item ($kreFolder + "\_rels\") -Force -Recurse Remove-Item ($runtimeFolder + "\_rels\") -Force -Recurse
} }
If (Test-Path ($kreFolder + "\package\")) { If (Test-Path ($runtimeFolder + "\package\")) {
Remove-Item ($kreFolder + "\package\") -Force -Recurse Remove-Item ($runtimeFolder + "\package\") -Force -Recurse
} }
# Clean up the package file itself.
Remove-Item $runtimeFile -Force
} }
function Kvm-Install { function _Install {
param( param(
[string] $versionOrAlias, [string] $versionOrAlias,
[boolean] $isGlobal [boolean] $isGlobal
) )
if ($versionOrAlias -eq "latest") { if ($versionOrAlias -eq "latest") {
$versionOrAlias = Kvm-Find-Latest (Requested-Platform $defaultRuntime) (Requested-Architecture $defaultArch) $versionOrAlias = _Find-Latest (Requested-Platform $defaultRuntime) (Requested-Architecture $defaultArch)
} }
if ($versionOrAlias.EndsWith(".nupkg")) { if ($versionOrAlias.EndsWith(".nupkg")) {
$kreFullName = [System.IO.Path]::GetFileNameWithoutExtension($versionOrAlias) $runtimeFullName = [System.IO.Path]::GetFileNameWithoutExtension($versionOrAlias)
} else { } else {
$kreFullName = Requested-VersionOrAlias $versionOrAlias $runtimeFullName = Requested-VersionOrAlias $versionOrAlias
} }
if ($isGlobal) { $packageFolder = $userRuntimesPath
if (Needs-Elevation) {
$arguments = "-ExecutionPolicy unrestricted & '$scriptPath' install '$versionOrAlias' -global $(Requested-Switches) -wait"
Start-Process "$psHome\powershell.exe" -Verb runAs -ArgumentList $arguments -Wait
Kvm-Use $kreFullName
break
}
$packageFolder = $globalKrePackages
} else {
$packageFolder = $userKrePackages
}
if ($versionOrAlias.EndsWith(".nupkg")) { if ($versionOrAlias.EndsWith(".nupkg")) {
Set-Variable -Name "selectedArch" -Value (Package-Arch $kreFullName) -Scope Script Set-Variable -Name "selectedArch" -Value (Package-Arch $runtimeFullName) -Scope Script
Set-Variable -Name "selectedRuntime" -Value (Package-Platform $kreFullName) -Scope Script Set-Variable -Name "selectedRuntime" -Value (Package-Platform $runtimeFullName) -Scope Script
$kreFolder = "$packageFolder\$kreFullName" $runtimeFolder = "$packageFolder\$runtimeFullName"
$folderExists = Test-Path $kreFolder $folderExists = Test-Path $runtimeFolder
if ($folderExists -and $Force) { if ($folderExists -and $Force) {
del $kreFolder -Recurse -Force del $runtimeFolder -Recurse -Force
$folderExists = $false; $folderExists = $false;
} }
if ($folderExists) { if ($folderExists) {
Console-Write "Target folder '$kreFolder' already exists" Console-Write "Target folder '$runtimeFolder' already exists"
} else { } else {
$tempUnpackFolder = Join-Path $packageFolder "temp" $tempUnpackFolder = Join-Path $packageFolder "temp"
$tempKreFile = Join-Path $tempUnpackFolder "$kreFullName.nupkg" $tempDownloadFile = Join-Path $tempUnpackFolder "$runtimeFullName.nupkg"
if(Test-Path $tempUnpackFolder) { if(Test-Path $tempUnpackFolder) {
del "$tempUnpackFolder\*" -recurse del "$tempUnpackFolder\*" -recurse
} else { } else {
md $tempUnpackFolder -Force | Out-Null md $tempUnpackFolder -Force | Out-Null
} }
copy $versionOrAlias $tempKreFile copy $versionOrAlias $tempDownloadFile
Do-Kvm-Unpack $tempKreFile $tempUnpackFolder Do-Unpack $tempDownloadFile $tempUnpackFolder
md $kreFolder -Force | Out-Null md $runtimeFolder -Force | Out-Null
Console-Write "Installing to $kreFolder" Console-Write "Installing to $runtimeFolder"
mv "$tempUnpackFolder\*" $kreFolder mv "$tempUnpackFolder\*" $runtimeFolder
Remove-Item "$tempUnpackFolder" -Force | Out-Null Remove-Item "$tempUnpackFolder" -Force | Out-Null
} }
$packageVersion = Package-Version $kreFullName $packageVersion = Package-Version $runtimeFullName
Kvm-Use $packageVersion _Use $packageVersion
if (!$(String-IsEmptyOrWhitespace($Alias))) { if (!$(String-IsEmptyOrWhitespace($Alias))) {
Kvm-Alias-Set $Alias $packageVersion _Alias-Set $Alias $packageVersion
} }
} }
else else
{ {
Do-Kvm-Download $kreFullName $packageFolder Do-Download $runtimeFullName $packageFolder
Kvm-Use $versionOrAlias _Use $versionOrAlias
if (!$(String-IsEmptyOrWhitespace($Alias))) { if (!$(String-IsEmptyOrWhitespace($Alias))) {
Kvm-Alias-Set "$Alias" $versionOrAlias _Alias-Set "$Alias" $versionOrAlias
} }
} }
if ($kreFullName.Contains("CoreCLR")) { if ($runtimeFullName.Contains("CoreCLR")) {
if ($NoNative) { if ($NoNative) {
Console-Write "Native image generation is skipped" Console-Write "Native image generation is skipped"
} }
else { else {
Console-Write "Compiling native images for $kreFullName to improve startup performance..." Console-Write "Compiling native images for $runtimeFullName to improve startup performance..."
Start-Process "k-crossgen" -Wait Start-Process $CrossGenCommand -Wait
Console-Write "Finished native image compilation." Console-Write "Finished native image compilation."
} }
} }
} }
function Kvm-List { function _List {
$kreHome = $env:KRE_HOME $runtimeHome = (getenv $HomeEnvVar)
if (!$kreHome) { if (!$runtimeHome) {
$kreHome = "$globalKrePath;$userKrePath" $runtimeHome = "$userHome"
} }
md ($userKrePath + "\alias\") -Force | Out-Null md ($userHome + "\alias\") -Force | Out-Null
$aliases = Get-ChildItem ($userKrePath + "\alias\") | Select @{label='Alias';expression={$_.BaseName}}, @{label='Name';expression={Get-Content $_.FullName }} $aliases = Get-ChildItem ($userHome + "\alias\") | Select @{label='Alias';expression={$_.BaseName}}, @{label='Name';expression={Get-Content $_.FullName }}
$items = @() $items = @()
foreach($portion in $kreHome.Split(';')) { foreach($portion in $runtimeHome.Split(';')) {
$path = [System.Environment]::ExpandEnvironmentVariables($portion) $path = [System.Environment]::ExpandEnvironmentVariables($portion)
if (Test-Path("$path\packages")) { if (Test-Path("$path\runtimes")) {
$items += Get-ChildItem ("$path\packages\KRE-*") | List-Parts $aliases $items += Get-ChildItem ("$path\runtimes\$RuntimePackageName-*") | List-Parts $aliases
} }
} }
@ -428,132 +435,94 @@ filter List-Parts {
} }
$parts1 = $_.Name.Split('.', 2) $parts1 = $_.Name.Split('.', 2)
$parts2 = $parts1[0].Split('-', 3) $parts2 = $parts1[0].Split('-', 4)
return New-Object PSObject -Property @{ return New-Object PSObject -Property @{
Active = if ($active) { "*" } else { "" } Active = if ($active) { "*" } else { "" }
Version = $parts1[1] Version = $parts1[1]
Runtime = $parts2[1] Runtime = $parts2[1]
Architecture = $parts2[2] OperatingSystem = $parts2[2]
Architecture = $parts2[3]
Location = $_.Parent.FullName Location = $_.Parent.FullName
Alias = $fullAlias Alias = $fullAlias
} }
} }
function Kvm-Global-Use { function _Use {
param(
[string] $versionOrAlias
)
Validate-Full-Package-Name-Arguments-Combination $versionOrAlias
If (Needs-Elevation) {
$arguments = "-ExecutionPolicy unrestricted & '$scriptPath' use '$versionOrAlias' -global $(Requested-Switches) -wait"
Start-Process "$psHome\powershell.exe" -Verb runAs -ArgumentList $arguments -Wait
Kvm-Use $versionOrAlias
break
}
Kvm-Use "$versionOrAlias"
if ($versionOrAlias -eq "none") {
if ($Persistent) {
Console-Write "Removing KRE from machine PATH"
$machinePath = [Environment]::GetEnvironmentVariable("Path", [System.EnvironmentVariableTarget]::Machine)
$machinePath = Change-Path $machinePath "" ($globalKrePackages, $userKrePackages)
[Environment]::SetEnvironmentVariable("Path", $machinePath, [System.EnvironmentVariableTarget]::Machine)
}
return;
}
$kreFullName = Requested-VersionOrAlias "$versionOrAlias"
$kreBin = Locate-KreBinFromFullName $kreFullName
if ($kreBin -eq $null) {
throw "Cannot find $kreFullName, do you need to run 'kvm install $versionOrAlias'?"
}
if ($Persistent) {
Console-Write "Adding $kreBin to machine PATH"
$machinePath = [Environment]::GetEnvironmentVariable("Path", [System.EnvironmentVariableTarget]::Machine)
$machinePath = Change-Path $machinePath $kreBin ($globalKrePackages, $userKrePackages)
[Environment]::SetEnvironmentVariable("Path", $machinePath, [System.EnvironmentVariableTarget]::Machine)
}
}
function Kvm-Use {
param( param(
[string] $versionOrAlias [string] $versionOrAlias
) )
Validate-Full-Package-Name-Arguments-Combination $versionOrAlias Validate-Full-Package-Name-Arguments-Combination $versionOrAlias
if ($versionOrAlias -eq "none") { if ($versionOrAlias -eq "none") {
Console-Write "Removing KRE from process PATH" Console-Write "Removing $RuntimeShortName from process PATH"
Set-Path (Change-Path $env:Path "" ($globalKrePackages, $userKrePackages)) Set-Path (Change-Path $env:Path "" ($userRuntimesPath))
if ($Persistent) { if ($Persistent) {
Console-Write "Removing KRE from user PATH" Console-Write "Removing $RuntimeShortName from user PATH"
$userPath = [Environment]::GetEnvironmentVariable("Path", [System.EnvironmentVariableTarget]::User) $userPath = [Environment]::GetEnvironmentVariable("Path", [System.EnvironmentVariableTarget]::User)
$userPath = Change-Path $userPath "" ($globalKrePackages, $userKrePackages) $userPath = Change-Path $userPath "" ($userRuntimesPath)
[Environment]::SetEnvironmentVariable("Path", $userPath, [System.EnvironmentVariableTarget]::User) [Environment]::SetEnvironmentVariable("Path", $userPath, [System.EnvironmentVariableTarget]::User)
} }
return; return;
} }
$kreFullName = Requested-VersionOrAlias $versionOrAlias $runtimeFullName = Requested-VersionOrAlias $versionOrAlias
$kreBin = Locate-KreBinFromFullName $kreFullName $runtimeBin = Locate-RuntimeBinFromFullName $runtimeFullName
if ($kreBin -eq $null) { if ($runtimeBin -eq $null) {
throw "Cannot find $kreFullName, do you need to run 'kvm install $versionOrAlias'?" throw "Cannot find $runtimeFullName, do you need to run '$CommandName install $versionOrAlias'?"
} }
Console-Write "Adding $kreBin to process PATH" Console-Write "Adding $runtimeBin to process PATH"
Set-Path (Change-Path $env:Path $kreBin ($globalKrePackages, $userKrePackages)) Set-Path (Change-Path $env:Path $runtimeBin ($userRuntimesPath))
if ($Persistent) { if ($Persistent) {
Console-Write "Adding $kreBin to user PATH" Console-Write "Adding $runtimeBin to user PATH"
$userPath = [Environment]::GetEnvironmentVariable("Path", [System.EnvironmentVariableTarget]::User) $userPath = [Environment]::GetEnvironmentVariable("Path", [System.EnvironmentVariableTarget]::User)
$userPath = Change-Path $userPath $kreBin ($globalKrePackages, $userKrePackages) $userPath = Change-Path $userPath $runtimeBin ($userRuntimesPath)
[Environment]::SetEnvironmentVariable("Path", $userPath, [System.EnvironmentVariableTarget]::User) [Environment]::SetEnvironmentVariable("Path", $userPath, [System.EnvironmentVariableTarget]::User)
} }
} }
function Kvm-Alias-List { function _Alias-List {
md ($userKrePath + "\alias\") -Force | Out-Null md ($userHome + "\alias\") -Force | Out-Null
Get-ChildItem ($userKrePath + "\alias\") | Select @{label='Alias';expression={$_.BaseName}}, @{label='Name';expression={Get-Content $_.FullName }} | Format-Table -AutoSize Get-ChildItem ($userHome + "\alias\") | Select @{label='Alias';expression={$_.BaseName}}, @{label='Name';expression={Get-Content $_.FullName }} | Format-Table -AutoSize
} }
function Kvm-Alias-Get { function _Alias-Get {
param( param(
[string] $name [string] $name
) )
md ($userKrePath + "\alias\") -Force | Out-Null md ($userHome + "\alias\") -Force | Out-Null
$aliasFilePath=$userKrePath + "\alias\" + $name + ".txt" $aliasFilePath=$userHome + "\alias\" + $name + ".txt"
if (!(Test-Path $aliasFilePath)) { if (!(Test-Path $aliasFilePath)) {
Console-Write "Alias '$name' does not exist" Console-Write "Alias '$name' does not exist"
$script:exitCode = 1 # Return non-zero exit code for scripting $script:exitCode = 1 # Return non-zero exit code for scripting
} else { } else {
$aliasValue = (Get-Content ($userKrePath + "\alias\" + $name + ".txt")) $aliasValue = (Get-Content ($userHome + "\alias\" + $name + ".txt"))
Console-Write "Alias '$name' is set to $aliasValue" Console-Write "Alias '$name' is set to $aliasValue"
} }
} }
function Kvm-Alias-Set { function _Alias-Set {
param( param(
[string] $name, [string] $name,
[string] $value [string] $value
) )
$kreFullName = Requested-VersionOrAlias $value $runtimeFullName = Requested-VersionOrAlias $value
$aliasFilePath = $userKrePath + "\alias\" + $name + ".txt" $aliasFilePath = $userHome + "\alias\" + $name + ".txt"
$action = if (Test-Path $aliasFilePath) { "Updating" } else { "Setting" } $action = if (Test-Path $aliasFilePath) { "Updating" } else { "Setting" }
Console-Write "$action alias '$name' to '$kreFullName'" Console-Write "$action alias '$name' to '$runtimeFullName'"
md ($userKrePath + "\alias\") -Force | Out-Null md ($userHome + "\alias\") -Force | Out-Null
$kreFullName | Out-File ($aliasFilePath) ascii $runtimeFullName | Out-File ($aliasFilePath) ascii
} }
function Kvm-Unalias { function _Unalias {
param( param(
[string] $name [string] $name
) )
$aliasPath=$userKrePath + "\alias\" + $name + ".txt" $aliasPath=$userHome + "\alias\" + $name + ".txt"
if (Test-Path -literalPath "$aliasPath") { if (Test-Path -literalPath "$aliasPath") {
Console-Write "Removing alias $name" Console-Write "Removing alias $name"
Remove-Item -literalPath $aliasPath Remove-Item -literalPath $aliasPath
@ -563,19 +532,19 @@ param(
} }
} }
function Locate-KreBinFromFullName() { function Locate-RuntimeBinFromFullName() {
param( param(
[string] $kreFullName [string] $runtimeFullName
) )
$kreHome = $env:KRE_HOME $runtimeHome = (getenv $HomeEnvVar)
if (!$kreHome) { if (!$runtimeHome) {
$kreHome = "$globalKrePath;$userKrePath" $runtimeHome = $userHome
} }
foreach($portion in $kreHome.Split(';')) { foreach($portion in $runtimeHome.Split(';')) {
$path = [System.Environment]::ExpandEnvironmentVariables($portion) $path = [System.Environment]::ExpandEnvironmentVariables($portion)
$kreBin = "$path\packages\$kreFullName\bin" $runtimeBin = "$path\runtimes\$runtimeFullName\bin"
if (Test-Path "$kreBin") { if (Test-Path "$runtimeBin") {
return $kreBin return $runtimeBin
} }
} }
return $null return $null
@ -583,23 +552,23 @@ param(
function Package-Version() { function Package-Version() {
param( param(
[string] $kreFullName [string] $runtimeFullName
) )
return $kreFullName -replace '[^.]*.(.*)', '$1' return $runtimeFullName -replace '[^.]*.(.*)', '$1'
} }
function Package-Platform() { function Package-Platform() {
param( param(
[string] $kreFullName [string] $runtimeFullName
) )
return $kreFullName -replace 'KRE-([^-]*).*', '$1' return $runtimeFullName -replace "$RuntimePackageName-([^-]*).*", '$1'
} }
function Package-Arch() { function Package-Arch() {
param( param(
[string] $kreFullName [string] $runtimeFullName
) )
return $kreFullName -replace 'KRE-[^-]*-([^.]*).*', '$1' return $runtimeFullName -replace "$RuntimePackageName-[^-]*-[^-]*-([^.]*).*", '$1'
} }
@ -609,26 +578,28 @@ param(
) )
Validate-Full-Package-Name-Arguments-Combination $versionOrAlias Validate-Full-Package-Name-Arguments-Combination $versionOrAlias
$kreBin = Locate-KreBinFromFullName $versionOrAlias $runtimeBin = Locate-RuntimeBinFromFullName $versionOrAlias
# If the name specified is an existing package, just use it as is # If the name specified is an existing package, just use it as is
if ($kreBin -ne $null) { if ($runtimeBin -ne $null) {
return $versionOrAlias return $versionOrAlias
} }
If (Test-Path ($userKrePath + "\alias\" + $versionOrAlias + ".txt")) { If (Test-Path ($userHome + "\alias\" + $versionOrAlias + ".txt")) {
$aliasValue = Get-Content ($userKrePath + "\alias\" + $versionOrAlias + ".txt") $aliasValue = Get-Content ($userHome + "\alias\" + $versionOrAlias + ".txt")
# Split runtime-coreclr-win-x86.1.0.0-beta3-10922 into version and name sections
$parts = $aliasValue.Split('.', 2) $parts = $aliasValue.Split('.', 2)
$pkgVersion = $parts[1] $pkgVersion = $parts[1]
$parts =$parts[0].Split('-', 3) # runtime-coreclr-win-x86
$parts = $parts[0].Split('-', 4)
$pkgPlatform = Requested-Platform $parts[1] $pkgPlatform = Requested-Platform $parts[1]
$pkgArchitecture = Requested-Architecture $parts[2] $pkgArchitecture = Requested-Architecture $parts[3]
} else { } else {
$pkgVersion = $versionOrAlias $pkgVersion = $versionOrAlias
$pkgPlatform = Requested-Platform $defaultRuntime $pkgPlatform = Requested-Platform $defaultRuntime
$pkgArchitecture = Requested-Architecture $defaultArch $pkgArchitecture = Requested-Architecture $defaultArch
} }
return "KRE-" + $pkgPlatform + "-" + $pkgArchitecture + "." + $pkgVersion return $RuntimePackageName + "-" + $pkgPlatform + "-win-" + $pkgArchitecture + "." + $pkgVersion
} }
function Requested-Platform() { function Requested-Platform() {
@ -657,7 +628,7 @@ param(
foreach($portion in $existingPaths.Split(';')) { foreach($portion in $existingPaths.Split(';')) {
$skip = $portion -eq "" $skip = $portion -eq ""
foreach($removePath in $removePaths) { foreach($removePath in $removePaths) {
if ($portion.StartsWith($removePath)) { if ($removePath -and ($portion.StartsWith($removePath))) {
$skip = $true $skip = $true
} }
} }
@ -672,11 +643,11 @@ function Set-Path() {
param( param(
[string] $newPath [string] $newPath
) )
md $userKrePath -Force | Out-Null md $userHome -Force | Out-Null
$env:Path = $newPath $env:Path = $newPath
@" @"
SET "PATH=$newPath" SET "PATH=$newPath"
"@ | Out-File ($userKrePath + "\run-once.cmd") ascii "@ | Out-File ($userHome + "\temp-set-envvars.cmd") ascii
} }
function Needs-Elevation() { function Needs-Elevation() {
@ -692,8 +663,6 @@ function Needs-Elevation() {
function Requested-Switches() { function Requested-Switches() {
$arguments = "" $arguments = ""
if ($X86) {$arguments = "$arguments -x86"} if ($X86) {$arguments = "$arguments -x86"}
if ($Amd64) {$arguments = "$arguments -amd64"}
#deprecated
if ($X64) {$arguments = "$arguments -x64"} if ($X64) {$arguments = "$arguments -x64"}
if ($selectedRuntime) {$arguments = "$arguments -runtime $selectedRuntime"} if ($selectedRuntime) {$arguments = "$arguments -runtime $selectedRuntime"}
if ($Persistent) {$arguments = "$arguments -persistent"} if ($Persistent) {$arguments = "$arguments -persistent"}
@ -704,37 +673,24 @@ function Requested-Switches() {
function Validate-And-Santitize-Switches() function Validate-And-Santitize-Switches()
{ {
if ($Svr50 -and $Runtime) {throw "You cannot select both the -runtime switch and the -svr50 runtimes"}
if ($Svrc50 -and $Runtime) {throw "You cannot select both the -runtime switch and the -svrc50 runtimes"}
if ($X86 -and $Amd64) {throw "You cannot select both x86 and amd64 architectures"}
if ($X86 -and $X64) {throw "You cannot select both x86 and x64 architectures"} if ($X86 -and $X64) {throw "You cannot select both x86 and x64 architectures"}
if ($X64 -and $Amd64) {throw "You cannot select both x64 and amd64 architectures"}
if ($Runtime) { if ($Runtime) {
$validRuntimes = "CoreCLR", "CLR", "svr50", "svrc50" $validRuntimes = "CoreCLR", "CLR"
$match = $validRuntimes | ? { $_ -like $Runtime } | Select -First 1 $match = $validRuntimes | ? { $_ -like $Runtime } | Select -First 1
if (!$match) {throw "'$runtime' is not a valid runtime"} if (!$match) {throw "'$runtime' is not a valid runtime"}
Set-Variable -Name "selectedRuntime" -Value $match -Scope Script Set-Variable -Name "selectedRuntime" -Value $match.ToLowerInvariant() -Scope Script
} elseif ($Svr50) {
Console-Write "Warning: -svr50 is deprecated, use -runtime CLR for new packages."
Set-Variable -Name "selectedRuntime" -Value "svr50" -Scope Script
} elseif ($Svrc50) {
Console-Write "Warning: -svrc50 is deprecated, use -runtime CoreCLR for new packages."
Set-Variable -Name "selectedRuntime" -Value "svrc50" -Scope Script
} }
if($Architecture) { if($Architecture) {
$validArchitectures = "amd64", "x86" $validArchitectures = "x64", "x86"
$match = $validArchitectures | ? { $_ -like $Architecture } | Select -First 1 $match = $validArchitectures | ? { $_ -like $Architecture } | Select -First 1
if(!$match) {throw "'$architecture' is not a valid architecture"} if(!$match) {throw "'$architecture' is not a valid architecture"}
Set-Variable -Name "selectedArch" -Value $match -Scope Script Set-Variable -Name "selectedArch" -Value $match.ToLowerInvariant() -Scope Script
} }
else { else {
if ($X64) { if ($X64) {
Console-Write "Warning: -x64 is deprecated, use -amd64 for new packages."
Set-Variable -Name "selectedArch" -Value "x64" -Scope Script Set-Variable -Name "selectedArch" -Value "x64" -Scope Script
} elseif ($Amd64) {
Set-Variable -Name "selectedArch" -Value "amd64" -Scope Script
} elseif ($X86) { } elseif ($X86) {
Set-Variable -Name "selectedArch" -Value "x86" -Scope Script Set-Variable -Name "selectedArch" -Value "x86" -Scope Script
} }
@ -765,7 +721,7 @@ param(
} }
else { else {
[Console]::WriteLine($message) [Console]::WriteLine($message)
} }
} }
} }
@ -785,50 +741,40 @@ param(
} }
else { else {
[Console]::Error.WriteLine($message) [Console]::Error.WriteLine($message)
} }
} }
function Validate-Full-Package-Name-Arguments-Combination() { function Validate-Full-Package-Name-Arguments-Combination() {
param( param(
[string] $versionOrAlias [string] $versionOrAlias
) )
if ($versionOrAlias -like "KRE-*" -and if ($versionOrAlias -like "$RuntimePackageName-*" -and
($selectedArch -or $selectedRuntime)) { ($selectedArch -or $selectedRuntime)) {
throw "Runtime or architecture cannot be specified when using the full package name." throw "Runtime or architecture cannot be specified when using the full package name."
} }
} }
$script:exitCode = 0 $script:exitCode = 0
try { try {
Validate-And-Santitize-Switches Validate-And-Santitize-Switches
if ($Global) { switch -wildcard ($Command + " " + $Args.Count) {
switch -wildcard ($Command + " " + $Args.Count) { "setup 0" {_Global-Setup}
"setup 0" {Kvm-Global-Setup} "upgrade 0" {_Upgrade $false}
"upgrade 0" {Kvm-Upgrade $true} "install 1" {_Install $Args[0] $false}
"install 1" {Kvm-Install $Args[0] $true} "list 0" {_List}
"use 1" {Kvm-Global-Use $Args[0]} "use 1" {_Use $Args[0]}
default {throw "Unknown command, or global switch not supported"}; "alias 0" {_Alias-List}
} "alias 1" {_Alias-Get $Args[0]}
} else { "alias 2" {_Alias-Set $Args[0] $Args[1]}
switch -wildcard ($Command + " " + $Args.Count) { "unalias 1" {_Unalias $Args[0]}
"setup 0" {Kvm-Global-Setup} "help 0" {_Help}
"upgrade 0" {Kvm-Upgrade $false} " 0" {_Help}
"install 1" {Kvm-Install $Args[0] $false} default {throw "Unknown command"};
"list 0" {Kvm-List}
"use 1" {Kvm-Use $Args[0]}
"alias 0" {Kvm-Alias-List}
"alias 1" {Kvm-Alias-Get $Args[0]}
"alias 2" {Kvm-Alias-Set $Args[0] $Args[1]}
"unalias 1" {Kvm-Unalias $Args[0]}
"help 0" {Kvm-Help}
" 0" {Kvm-Help}
default {throw "Unknown command"};
}
} }
} }
catch { catch {
Console-Write-Error $_ Console-Write-Error $_
Console-Write "Type 'kvm help' for help on how to use kvm." Console-Write "Type '$CommandName help' for help on how to use $CommandName."
$script:exitCode = -1 $script:exitCode = -1
} }
if ($Wait) { if ($Wait) {

331
kvm.sh
View File

@ -1,43 +1,57 @@
# kvm.sh # kvm.sh
# Source this file from your .bash-profile or script to use # Source this file from your .bash-profile or script to use
_kvm_has() {
# "Constants"
_KVM_BUILDNUMBER="10321"
_KVM_RUNTIME_PACKAGE_NAME="kre"
_KVM_RUNTIME_FRIENDLY_NAME="K Runtime"
_KVM_RUNTIME_SHORT_NAME="KRE"
_KVM_RUNTIME_FOLDER_NAME=".k"
_KVM_COMMAND_NAME="kvm"
_KVM_VERSION_MANAGER_NAME="K Version Manager"
_KVM_DEFAULT_FEED="https://www.myget.org/F/aspnetvnext/api/v2"
_KVM_HOME_VAR_NAME="KRE_HOME"
__kvm_has() {
type "$1" > /dev/null 2>&1 type "$1" > /dev/null 2>&1
return $? return $?
} }
if _kvm_has "unsetopt"; then if __kvm_has "unsetopt"; then
unsetopt nomatch 2>/dev/null unsetopt nomatch 2>/dev/null
fi fi
if [ -z "$KRE_USER_HOME" ]; then if [ -z "$KVM_USER_HOME" ]; then
eval KRE_USER_HOME=~/.kre eval KVM_USER_HOME="~/$_KVM_RUNTIME_FOLDER_NAME"
fi fi
KRE_USER_PACKAGES="$KRE_USER_HOME/packages" _KVM_USER_PACKAGES="$KVM_USER_HOME/runtimes"
_KVM_ALIAS_DIR="$KVM_USER_HOME/alias"
if [ -z "$KRE_FEED" ]; then if [ -z "$KRE_FEED" ]; then
KRE_FEED="https://www.myget.org/F/aspnetvnext/api/v2" KRE_FEED="$_KVM_DEFAULT_FEED"
fi fi
_kvm_find_latest() { __kvm_find_latest() {
local platform="Mono" local platform="mono"
if ! _kvm_has "curl"; then if ! __kvm_has "curl"; then
echo 'KVM Needs curl to proceed.' >&2; echo "$_KVM_COMMAND_NAME needs curl to proceed." >&2;
return 1 return 1
fi fi
local url="$KRE_FEED/GetUpdates()?packageIds=%27KRE-$platform%27&versions=%270.0%27&includePrerelease=true&includeAllVersions=false" local url="$KRE_FEED/GetUpdates()?packageIds=%27$_KVM_RUNTIME_PACKAGE_NAME-$platform%27&versions=%270.0%27&includePrerelease=true&includeAllVersions=false"
xml="$(curl $url 2>/dev/null)" xml="$(curl $url 2>/dev/null)"
echo $xml | grep \<[a-zA-Z]:Version\>* >> /dev/null || return 1 echo $xml | grep \<[a-zA-Z]:Version\>* >> /dev/null || return 1
version="$(echo $xml | sed 's/.*<[a-zA-Z]:Version>\([^<]*\).*/\1/')" version="$(echo $xml | sed 's/.*<[a-zA-Z]:Version>\([^<]*\).*/\1/')"
echo $version echo $version
} }
_kvm_strip_path() { __kvm_strip_path() {
echo "$1" | sed -e "s#$KRE_USER_PACKAGES/[^/]*$2[^:]*:##g" -e "s#:$KRE_USER_PACKAGES/[^/]*$2[^:]*##g" -e "s#$KRE_USER_PACKAGES/[^/]*$2[^:]*##g" echo "$1" | sed -e "s#$_KVM_USER_PACKAGES/[^/]*$2[^:]*:##g" -e "s#:$_KVM_USER_PACKAGES/[^/]*$2[^:]*##g" -e "s#$_KVM_USER_PACKAGES/[^/]*$2[^:]*##g"
} }
_kvm_prepend_path() { __kvm_prepend_path() {
if [ -z "$1" ]; then if [ -z "$1" ]; then
echo "$2" echo "$2"
else else
@ -45,169 +59,171 @@ _kvm_prepend_path() {
fi fi
} }
_kvm_package_version() { __kvm_package_version() {
local kreFullName="$1" local runtimeFullName="$1"
echo "$kreFullName" | sed "s/[^.]*.\(.*\)/\1/" echo "$runtimeFullName" | sed "s/[^.]*.\(.*\)/\1/"
} }
_kvm_package_name() { __kvm_package_name() {
local kreFullName="$1" local runtimeFullName="$1"
echo "$kreFullName" | sed "s/\([^.]*\).*/\1/" echo "$runtimeFullName" | sed "s/\([^.]*\).*/\1/"
} }
_kvm_package_runtime() { __kvm_package_runtime() {
local kreFullName="$1" local runtimeFullName="$1"
echo "$kreFullName" | sed "s/KRE-\([^.-]*\).*/\1/" echo "$runtimeFullName" | sed "s/$_KVM_RUNTIME_PACKAGE_NAME-\([^.-]*\).*/\1/"
} }
_kvm_download() { __kvm_download() {
local kreFullName="$1" local runtimeFullName="$1"
local kreFolder="$2" local runtimeFolder="$2"
local pkgName=$(_kvm_package_name "$kreFullName") local pkgName=$(__kvm_package_name "$runtimeFullName")
local pkgVersion=$(_kvm_package_version "$kreFullName") local pkgVersion=$(__kvm_package_version "$runtimeFullName")
local url="$KRE_FEED/package/$pkgName/$pkgVersion" local url="$KRE_FEED/package/$pkgName/$pkgVersion"
local kreFile="$kreFolder/$kreFullName.nupkg" local runtimeFile="$runtimeFolder/$runtimeFullName.nupkg"
if [ -e "$kreFolder" ]; then if [ -e "$runtimeFolder" ]; then
echo "$kreFullName already installed." echo "$runtimeFullName already installed."
return 0 return 0
fi fi
echo "Downloading $kreFullName from $KRE_FEED" echo "Downloading $runtimeFullName from $KRE_FEED"
if ! _kvm_has "curl"; then if ! __kvm_has "curl"; then
echo "KVM Needs curl to proceed." >&2; echo "$_KVM_COMMAND_NAME needs curl to proceed." >&2;
return 1 return 1
fi fi
mkdir -p "$kreFolder" > /dev/null 2>&1 mkdir -p "$runtimeFolder" > /dev/null 2>&1
local httpResult=$(curl -L -D - "$url" -o "$kreFile" 2>/dev/null | grep "^HTTP/1.1" | head -n 1 | sed "s/HTTP.1.1 \([0-9]*\).*/\1/") local httpResult=$(curl -L -D - "$url" -o "$runtimeFile" 2>/dev/null | grep "^HTTP/1.1" | head -n 1 | sed "s/HTTP.1.1 \([0-9]*\).*/\1/")
[[ $httpResult == "404" ]] && echo "$kreFullName was not found in repository $KRE_FEED" && return 1 [[ $httpResult == "404" ]] && echo "$runtimeFullName was not found in repository $KRE_FEED" && return 1
[[ $httpResult != "302" && $httpResult != "200" ]] && echo "HTTP Error $httpResult fetching $kreFullName from $KRE_FEED" && return 1 [[ $httpResult != "302" && $httpResult != "200" ]] && echo "HTTP Error $httpResult fetching $runtimeFullName from $KRE_FEED" && return 1
_kvm_unpack $kreFile $kreFolder __kvm_unpack $runtimeFile $runtimeFolder
return $? return $?
} }
_kvm_unpack() { __kvm_unpack() {
local kreFile="$1" local runtimeFile="$1"
local kreFolder="$2" local runtimeFolder="$2"
echo "Installing to $kreFolder" echo "Installing to $runtimeFolder"
if ! _kvm_has "unzip"; then if ! __kvm_has "unzip"; then
echo "KVM Needs unzip to proceed." >&2; echo "$_KVM_COMMAND_NAME needs unzip to proceed." >&2;
return 1 return 1
fi fi
unzip $kreFile -d $kreFolder > /dev/null 2>&1 unzip $runtimeFile -d $runtimeFolder > /dev/null 2>&1
[ -e "$kreFolder/[Content_Types].xml" ] && rm "$kreFolder/[Content_Types].xml" [ -e "$runtimeFolder/[Content_Types].xml" ] && rm "$runtimeFolder/[Content_Types].xml"
[ -e "$kreFolder/_rels/" ] && rm -rf "$kreFolder/_rels/" [ -e "$runtimeFolder/_rels/" ] && rm -rf "$runtimeFolder/_rels/"
[ -e "$kreFolder/package/" ] && rm -rf "$kreFolder/_package/" [ -e "$runtimeFolder/package/" ] && rm -rf "$runtimeFolder/_package/"
[ -e "$runtimeFile" ] && rm -f "$runtimeFile"
#Set shell commands as executable #Set shell commands as executable
find "$kreFolder/bin/" -type f \ find "$runtimeFolder/bin/" -type f \
-exec sh -c "head -c 11 {} | grep '/bin/bash' > /dev/null" \; -print | xargs chmod 775 -exec sh -c "head -c 11 {} | grep '/bin/bash' > /dev/null" \; -print | xargs chmod 775
} }
_kvm_requested_version_or_alias() { __kvm_requested_version_or_alias() {
local versionOrAlias="$1" local versionOrAlias="$1"
local kreBin=$(_kvm_locate_kre_bin_from_full_name "$versionOrAlias") local runtimeBin=$(__kvm_locate_runtime_bin_from_full_name "$versionOrAlias")
# If the name specified is an existing package, just use it as is # If the name specified is an existing package, just use it as is
if [ -n "$kreBin" ]; then if [ -n "$runtimeBin" ]; then
echo "$versionOrAlias" echo "$versionOrAlias"
else else
if [ -e "$KRE_USER_HOME/alias/$versionOrAlias.alias" ]; then if [ -e "$_KVM_ALIAS_DIR/$versionOrAlias.alias" ]; then
local kreFullName=$(cat "$KRE_USER_HOME/alias/$versionOrAlias.alias") local runtimeFullName=$(cat "$_KVM_ALIAS_DIR/$versionOrAlias.alias")
local pkgName=$(echo $kreFullName | sed "s/\([^.]*\).*/\1/") local pkgName=$(echo $runtimeFullName | sed "s/\([^.]*\).*/\1/")
local pkgVersion=$(echo $kreFullName | sed "s/[^.]*.\(.*\)/\1/") local pkgVersion=$(echo $runtimeFullName | sed "s/[^.]*.\(.*\)/\1/")
local pkgPlatform=$(echo "$pkgName" | sed "s/KRE-\([^.-]*\).*/\1/") local pkgPlatform=$(echo "$pkgName" | sed "s/kre-\([^.-]*\).*/\1/")
else else
local pkgVersion=$versionOrAlias local pkgVersion=$versionOrAlias
local pkgPlatform="Mono" local pkgPlatform="mono"
fi fi
echo "KRE-$pkgPlatform.$pkgVersion" echo "$_KVM_RUNTIME_PACKAGE_NAME-$pkgPlatform.$pkgVersion"
fi fi
} }
# This will be more relevant if we support global installs # This will be more relevant if we support global installs
_kvm_locate_kre_bin_from_full_name() { __kvm_locate_runtime_bin_from_full_name() {
local kreFullName=$1 local runtimeFullName=$1
[ -e "$KRE_USER_PACKAGES/$kreFullName/bin" ] && echo "$KRE_USER_PACKAGES/$kreFullName/bin" && return [ -e "$_KVM_USER_PACKAGES/$runtimeFullName/bin" ] && echo "$_KVM_USER_PACKAGES/$runtimeFullName/bin" && return
} }
kvm() kvm()
{ {
if [ $# -lt 1 ]; then if [ $# -lt 1 ]; then
kvm help $_KVM_COMMAND_NAME help
return return
fi fi
case $1 in case $1 in
"help" ) "help" )
echo "" echo ""
echo "K Runtime Environment Version Manager - Build 10058" echo "$_KVM_VERSION_MANAGER_NAME - Build $_KVM_BUILDNUMBER"
echo "" echo ""
echo "USAGE: kvm <command> [options]" echo "USAGE: $_KVM_COMMAND_NAME <command> [options]"
echo "" echo ""
echo "kvm upgrade" echo "$_KVM_COMMAND_NAME upgrade"
echo "install latest KRE from feed" echo "install latest $_KVM_RUNTIME_SHORT_NAME from feed"
echo "add KRE bin to path of current command line" echo "add $_KVM_RUNTIME_SHORT_NAME bin to path of current command line"
echo "set installed version as default" echo "set installed version as default"
echo "" echo ""
echo "kvm install <semver>|<alias>|<nupkg>|latest [-a|-alias <alias>] [-p -persistent]" echo "$_KVM_COMMAND_NAME install <semver>|<alias>|<nupkg>|latest [-a|-alias <alias>] [-p -persistent]"
echo "<semver>|<alias> install requested KRE from feed" echo "<semver>|<alias> install requested $_KVM_RUNTIME_SHORT_NAME from feed"
echo "<nupkg> install requested KRE from local package on filesystem" echo "<nupkg> install requested $_KVM_RUNTIME_SHORT_NAME from local package on filesystem"
echo "latest install latest version of KRE from feed" echo "latest install latest version of $_KVM_RUNTIME_SHORT_NAME from feed"
echo "-a|-alias <alias> set alias <alias> for requested KRE on install" echo "-a|-alias <alias> set alias <alias> for requested $_KVM_RUNTIME_SHORT_NAME on install"
echo "-p -persistent set installed version as default" echo "-p -persistent set installed version as default"
echo "add KRE bin to path of current command line" echo "add $_KVM_RUNTIME_SHORT_NAME bin to path of current command line"
echo "" echo ""
echo "kvm use <semver>|<alias>|<package>|none [-p -persistent]" echo "$_KVM_COMMAND_NAME use <semver>|<alias>|<package>|none [-p -persistent]"
echo "<semver>|<alias>|<package> add KRE bin to path of current command line " echo "<semver>|<alias>|<package> add $_KVM_RUNTIME_SHORT_NAME bin to path of current command line "
echo "none remove KRE bin from path of current command line" echo "none remove $_KVM_RUNTIME_SHORT_NAME bin from path of current command line"
echo "-p -persistent set selected version as default" echo "-p -persistent set selected version as default"
echo "" echo ""
echo "kvm list" echo "$_KVM_COMMAND_NAME list"
echo "list KRE versions installed " echo "list $_KVM_RUNTIME_SHORT_NAME versions installed "
echo "" echo ""
echo "kvm alias" echo "$_KVM_COMMAND_NAME alias"
echo "list KRE aliases which have been defined" echo "list $_KVM_RUNTIME_SHORT_NAME aliases which have been defined"
echo "" echo ""
echo "kvm alias <alias>" echo "$_KVM_COMMAND_NAME alias <alias>"
echo "display value of the specified alias" echo "display value of the specified alias"
echo "" echo ""
echo "kvm alias <alias> <semver>|<alias>|<package>" echo "$_KVM_COMMAND_NAME alias <alias> <semver>|<alias>|<package>"
echo "<alias> the name of the alias to set" echo "<alias> the name of the alias to set"
echo "<semver>|<alias>|<package> the KRE version to set the alias to. Alternatively use the version of the specified alias" echo "<semver>|<alias>|<package> the $_KVM_RUNTIME_SHORT_NAME version to set the alias to. Alternatively use the version of the specified alias"
echo "" echo ""
echo "kvm unalias <alias>" echo "$_KVM_COMMAND_NAME unalias <alias>"
echo "remove the specified alias" echo "remove the specified alias"
echo "" echo ""
;; ;;
"upgrade" ) "upgrade" )
[ $# -ne 1 ] && kvm help && return [ $# -ne 1 ] && kvm help && return
kvm install latest -p $_KVM_COMMAND_NAME install latest -p
;; ;;
"install" ) "install" )
[ $# -lt 2 ] && kvm help && return [ $# -lt 2 ] && kvm help && return
shift shift
local persistant= local persistent=
local versionOrAlias= local versionOrAlias=
local alias= local alias=
while [ $# -ne 0 ] while [ $# -ne 0 ]
do do
if [[ $1 == "-p" || $1 == "-persistant" ]]; then if [[ $1 == "-p" || $1 == "-persistent" ]]; then
local persistent="-p" local persistent="-p"
elif [[ $1 == "-a" || $1 == "-alias" ]]; then elif [[ $1 == "-a" || $1 == "-alias" ]]; then
local alias=$2 local alias=$2
@ -220,39 +236,39 @@ kvm()
done done
if [[ "$versionOrAlias" == "latest" ]]; then if [[ "$versionOrAlias" == "latest" ]]; then
echo "Determining latest version" echo "Determining latest version"
versionOrAlias=$(_kvm_find_latest) versionOrAlias=$(__kvm_find_latest)
[[ $? == 1 ]] && echo "Error: Could not find latest version from feed $KRE_FEED" && return 1 [[ $? == 1 ]] && echo "Error: Could not find latest version from feed $KRE_FEED" && return 1
echo "Latest version is $versionOrAlias" echo "Latest version is $versionOrAlias"
fi fi
if [[ "$versionOrAlias" == *.nupkg ]]; then if [[ "$versionOrAlias" == *.nupkg ]]; then
local kreFullName=$(basename $versionOrAlias | sed "s/\(.*\)\.nupkg/\1/") local runtimeFullName=$(basename $versionOrAlias | sed "s/\(.*\)\.nupkg/\1/")
local kreVersion=$(_kvm_package_version "$kreFullName") local runtimeVersion=$(__kvm_package_version "$runtimeFullName")
local kreFolder="$KRE_USER_PACKAGES/$kreFullName" local runtimeFolder="$_KVM_USER_PACKAGES/$runtimeFullName"
local kreFile="$kreFolder/$kreFullName.nupkg" local runtimeFile="$runtimeFolder/$runtimeFullName.nupkg"
if [ -e "$kreFolder" ]; then if [ -e "$runtimeFolder" ]; then
echo "$kreFullName already installed" echo "$runtimeFullName already installed"
else else
mkdir "$kreFolder" > /dev/null 2>&1 mkdir "$runtimeFolder" > /dev/null 2>&1
cp -a "$versionOrAlias" "$kreFile" cp -a "$versionOrAlias" "$runtimeFile"
_kvm_unpack "$kreFile" "$kreFolder" __kvm_unpack "$runtimeFile" "$runtimeFolder"
[[ $? == 1 ]] && return 1 [[ $? == 1 ]] && return 1
fi fi
kvm use "$kreVersion" "$persistent" $_KVM_COMMAND_NAME use "$runtimeVersion" "$persistent"
[[ -n $alias ]] && kvm alias "$alias" "$kreVersion" [[ -n $alias ]] && kvm alias "$alias" "$runtimeVersion"
else else
local kreFullName="$(_kvm_requested_version_or_alias $versionOrAlias)" local runtimeFullName="$(__kvm_requested_version_or_alias $versionOrAlias)"
local kreFolder="$KRE_USER_PACKAGES/$kreFullName" local runtimeFolder="$_KVM_USER_PACKAGES/$runtimeFullName"
_kvm_download "$kreFullName" "$kreFolder" __kvm_download "$runtimeFullName" "$runtimeFolder"
[[ $? == 1 ]] && return 1 [[ $? == 1 ]] && return 1
kvm use "$versionOrAlias" "$persistent" $_KVM_COMMAND_NAME use "$versionOrAlias" "$persistent"
[[ -n $alias ]] && kvm alias "$alias" "$versionOrAlias" [[ -n $alias ]] && kvm alias "$alias" "$versionOrAlias"
fi fi
;; ;;
"use" ) "use" )
[ $# -gt 3 ] && kvm help && return [ $# -gt 3 ] && $_KVM_COMMAND_NAME help && return
[ $# -lt 2 ] && kvm help && return [ $# -lt 2 ] && $_KVM_COMMAND_NAME help && return
shift shift
local persistent= local persistent=
@ -267,51 +283,53 @@ kvm()
done done
if [[ $versionOrAlias == "none" ]]; then if [[ $versionOrAlias == "none" ]]; then
echo "Removing KRE from process PATH" echo "Removing $_KVM_RUNTIME_SHORT_NAME from process PATH"
# Strip other version from PATH # Strip other version from PATH
PATH=$(_kvm_strip_path "$PATH" "/bin") PATH=$(__kvm_strip_path "$PATH" "/bin")
if [[ -n $persistent && -e "$KRE_USER_HOME/alias/default.alias" ]]; then if [[ -n $persistent && -e "$_KVM_ALIAS_DIR/default.alias" ]]; then
echo "Setting default KRE to none" echo "Setting default $_KVM_RUNTIME_SHORT_NAME to none"
rm "$KRE_USER_HOME/alias/default.alias" rm "$_KVM_ALIAS_DIR/default.alias"
fi fi
return 0 return 0
fi fi
local kreFullName=$(_kvm_requested_version_or_alias "$versionOrAlias") local runtimeFullName=$(__kvm_requested_version_or_alias "$versionOrAlias")
local kreBin=$(_kvm_locate_kre_bin_from_full_name "$kreFullName") local runtimeBin=$(__kvm_locate_runtime_bin_from_full_name "$runtimeFullName")
if [[ -z $kreBin ]]; then if [[ -z $runtimeBin ]]; then
echo "Cannot find $kreFullName, do you need to run 'kvm install $versionOrAlias'?" echo "Cannot find $runtimeFullName, do you need to run '$_KVM_COMMAND_NAME install $versionOrAlias'?"
return 1 return 1
fi fi
echo "Adding" $kreBin "to process PATH" echo "Adding" $runtimeBin "to process PATH"
PATH=$(_kvm_strip_path "$PATH" "/bin") PATH=$(__kvm_strip_path "$PATH" "/bin")
PATH=$(_kvm_prepend_path "$PATH" "$kreBin") PATH=$(__kvm_prepend_path "$PATH" "$runtimeBin")
if [[ -n $persistent ]]; then if [[ -n $persistent ]]; then
local kreVersion=$(_kvm_package_version "$kreFullName") local runtimeVersion=$(__kvm_package_version "$runtimeFullName")
kvm alias default "$kreVersion" $_KVM_COMMAND_NAME alias default "$runtimeVersion"
fi fi
;; ;;
"alias" ) "alias" )
[[ $# -gt 3 ]] && kvm help && return [[ $# -gt 3 ]] && kvm help && return
[[ ! -e "$KRE_USER_HOME/alias/" ]] && mkdir "$KRE_USER_HOME/alias/" > /dev/null [[ ! -e "$_KVM_ALIAS_DIR/" ]] && mkdir "$_KVM_ALIAS_DIR/" > /dev/null
if [[ $# == 1 ]]; then if [[ $# == 1 ]]; then
echo "" echo ""
local format="%-20s %s\n" local format="%-20s %s\n"
printf "$format" "Alias" "Name" printf "$format" "Alias" "Name"
printf "$format" "-----" "----" printf "$format" "-----" "----"
for _kvm_file in $(find "$KRE_USER_HOME/alias" -name *.alias); do if [ -d "$_KVM_ALIAS_DIR" ]; then
local alias="$(basename $_kvm_file | sed 's/.alias//')" for __kvm_file in $(find "$_KVM_ALIAS_DIR" -name *.alias); do
local name="$(cat $_kvm_file)" local alias="$(basename $__kvm_file | sed 's/\.alias//')"
printf "$format" "$alias" "$name" local name="$(cat $__kvm_file)"
done printf "$format" "$alias" "$name"
done
fi
echo "" echo ""
return return
fi fi
@ -319,27 +337,27 @@ kvm()
local name="$2" local name="$2"
if [[ $# == 2 ]]; then if [[ $# == 2 ]]; then
[[ ! -e "$KRE_USER_HOME/alias/$name.alias" ]] && echo "There is no alias called '$name'" && return [[ ! -e "$_KVM_ALIAS_DIR/$name.alias" ]] && echo "There is no alias called '$name'" && return
cat "$KRE_USER_HOME/alias/$name.alias" cat "$_KVM_ALIAS_DIR/$name.alias"
echo "" echo ""
return return
fi fi
local kreFullName=$(_kvm_requested_version_or_alias "$3") local runtimeFullName=$(__kvm_requested_version_or_alias "$3")
[[ ! -d "$KRE_USER_PACKAGES/$kreFullName" ]] && echo "$kreFullName is not an installed KRE version" && return 1 [[ ! -d "$_KVM_USER_PACKAGES/$runtimeFullName" ]] && echo "$runtimeFullName is not an installed $_KVM_RUNTIME_SHORT_NAME version" && return 1
local action="Setting" local action="Setting"
[[ -e "$KRE_USER_HOME/alias/$name.alias" ]] && action="Updating" [[ -e "$_KVM_ALIAS_DIR/$name.alias" ]] && action="Updating"
echo "$action alias '$name' to '$kreFullName'" echo "$action alias '$name' to '$runtimeFullName'"
echo "$kreFullName" > "$KRE_USER_HOME/alias/$name.alias" echo "$runtimeFullName" > "$_KVM_ALIAS_DIR/$name.alias"
;; ;;
"unalias" ) "unalias" )
[[ $# -ne 2 ]] && kvm help && return [[ $# -ne 2 ]] && kvm help && return
local name=$2 local name=$2
local aliasPath="$KRE_USER_HOME/alias/$name.alias" local aliasPath="$_KVM_ALIAS_DIR/$name.alias"
[[ ! -e "$aliasPath" ]] && echo "Cannot remove alias, '$name' is not a valid alias name" && return 1 [[ ! -e "$aliasPath" ]] && echo "Cannot remove alias, '$name' is not a valid alias name" && return 1
echo "Removing alias $name" echo "Removing alias $name"
rm "$aliasPath" >> /dev/null 2>&1 rm "$aliasPath" >> /dev/null 2>&1
@ -348,12 +366,12 @@ kvm()
"list" ) "list" )
[[ $# -gt 2 ]] && kvm help && return [[ $# -gt 2 ]] && kvm help && return
[[ ! -d $KRE_USER_PACKAGES ]] && echo "KRE is not installed." && return 1 [[ ! -d $_KVM_USER_PACKAGES ]] && echo "$_KVM_RUNTIME_FRIENDLY_NAME is not installed." && return 1
local searchGlob="KRE-*" local searchGlob="$_KVM_RUNTIME_PACKAGE_NAME-*"
if [ $# == 2 ]; then if [ $# == 2 ]; then
local versionOrAlias=$2 local versionOrAlias=$2
local searchGlob=$(_kvm_requested_version_or_alias "$versionOrAlias") local searchGlob=$(__kvm_requested_version_or_alias "$versionOrAlias")
fi fi
echo "" echo ""
@ -365,27 +383,29 @@ kvm()
# Z shell array-index starts at one. # Z shell array-index starts at one.
local i=1 local i=1
local format="%-20s %s\n" local format="%-20s %s\n"
for _kvm_file in $(find "$KRE_USER_HOME/alias" -name *.alias); do if [ -d "$_KVM_ALIAS_DIR" ]; then
arr[$i]="$(basename $_kvm_file | sed 's/.alias//')/$(cat $_kvm_file)" for __kvm_file in $(find "$_KVM_ALIAS_DIR" -name *.alias); do
let i+=1 arr[$i]="$(basename $__kvm_file | sed 's/\.alias//')/$(cat $__kvm_file)"
done let i+=1
done
fi
local formatString="%-6s %-20s %-7s %-20s %s\n" local formatString="%-6s %-20s %-7s %-20s %s\n"
printf "$formatString" "Active" "Version" "Runtime" "Location" "Alias" printf "$formatString" "Active" "Version" "Runtime" "Location" "Alias"
printf "$formatString" "------" "-------" "-------" "--------" "-----" printf "$formatString" "------" "-------" "-------" "--------" "-----"
local formattedHome=`(echo $KRE_USER_PACKAGES | sed s=$HOME=~=g)` local formattedHome=`(echo $_KVM_USER_PACKAGES | sed s=$HOME=~=g)`
for f in $(find $KRE_USER_PACKAGES -name "$searchGlob" \( -type d -or -type l \) -prune -exec basename {} \;); do for f in $(find $_KVM_USER_PACKAGES -name "$searchGlob" \( -type d -or -type l \) -prune -exec basename {} \;); do
local active="" local active=""
[[ $PATH == *"$KRE_USER_PACKAGES/$f/bin"* ]] && local active=" *" [[ $PATH == *"$_KVM_USER_PACKAGES/$f/bin"* ]] && local active=" *"
local pkgName=$(_kvm_package_runtime "$f") local pkgName=$(__kvm_package_runtime "$f")
local pkgVersion=$(_kvm_package_version "$f") local pkgVersion=$(__kvm_package_version "$f")
local alias="" local alias=""
local delim="" local delim=""
for i in "${arr[@]}"; do for i in "${arr[@]}"; do
temp="KRE-$pkgName.$pkgVersion" temp="$_KVM_RUNTIME_PACKAGE_NAME-$pkgName.$pkgVersion"
temp2="KRE-$pkgName-x86.$pkgVersion" temp2="$_KVM_RUNTIME_PACKAGE_NAME-$pkgName-x86.$pkgVersion"
if [[ ${i#*/} == $temp || ${i#*/} == $temp2 ]]; then if [[ ${i#*/} == $temp || ${i#*/} == $temp2 ]]; then
alias+="$delim${i%/*}" alias+="$delim${i%/*}"
delim=", " delim=", "
@ -408,4 +428,5 @@ kvm()
return 0 return 0
} }
kvm list default >/dev/null && kvm use default >/dev/null || true # Generate the command function using the constant defined above.
$_KVM_COMMAND_NAME list default >/dev/null && $_KVM_COMMAND_NAME use default >/dev/null || true