diff --git a/build-template/build.cmd b/build-template/build.cmd index 86ca5bbbf1..c74ef945ca 100644 --- a/build-template/build.cmd +++ b/build-template/build.cmd @@ -20,9 +20,9 @@ IF EXIST packages\KoreBuild goto run .nuget\NuGet.exe install Sake -version 0.2 -o packages -ExcludeVersion IF "%SKIP_KRE_INSTALL%"=="1" goto run -CALL packages\KoreBuild\build\kvm upgrade -runtime CLR -x86 -CALL packages\KoreBuild\build\kvm install default -runtime CoreCLR -x86 +CALL packages\KoreBuild\build\dnvm upgrade -runtime CLR -x86 +CALL packages\KoreBuild\build\dnvm install default -runtime CoreCLR -x86 :run -CALL packages\KoreBuild\build\kvm use default -runtime CLR -x86 +CALL packages\KoreBuild\build\dnvm use default -runtime CLR -x86 packages\Sake\tools\Sake.exe -I packages\KoreBuild\build -f makefile.shade %* diff --git a/build-template/build.sh b/build-template/build.sh index c7873ef58e..b07295c81b 100644 --- a/build-template/build.sh +++ b/build-template/build.sh @@ -28,11 +28,11 @@ if test ! -d packages/KoreBuild; then fi if ! type k > /dev/null 2>&1; then - source packages/KoreBuild/build/kvm.sh + source packages/KoreBuild/build/dnvm.sh fi if ! type k > /dev/null 2>&1; then - kvm upgrade + dnvm upgrade fi mono packages/Sake/tools/Sake.exe -I packages/KoreBuild/build -f makefile.shade "$@" diff --git a/build.sh b/build.sh index c7873ef58e..b07295c81b 100755 --- a/build.sh +++ b/build.sh @@ -28,11 +28,11 @@ if test ! -d packages/KoreBuild; then fi if ! type k > /dev/null 2>&1; then - source packages/KoreBuild/build/kvm.sh + source packages/KoreBuild/build/dnvm.sh fi if ! type k > /dev/null 2>&1; then - kvm upgrade + dnvm upgrade fi mono packages/Sake/tools/Sake.exe -I packages/KoreBuild/build -f makefile.shade "$@" diff --git a/build/_k-restore.shade b/build/_k-restore.shade index cf25171742..9cf47050de 100644 --- a/build/_k-restore.shade +++ b/build/_k-restore.shade @@ -4,7 +4,7 @@ k-restore Restores nuget packages required for k projects. Downloads and executes k sdk tools. */} -default restore_options='${E("KPM_restore_options")}' +default restore_options='${E("NUGET3_restore_options")}' exec program='cmd' commandline='/C kpm restore${restore_options}' if='!IsMono' exec program='kpm' commandline='restore${restore_options}' if='IsMono' \ No newline at end of file diff --git a/build/_k-standard-goals.shade b/build/_k-standard-goals.shade index aeddc3e909..758544e08d 100644 --- a/build/_k-standard-goals.shade +++ b/build/_k-standard-goals.shade @@ -12,13 +12,13 @@ default TEST_DIR='${Path.Combine(TARGET_DIR, "test")}' default Configuration='${E("Configuration")}' @{ - if (string.IsNullOrEmpty(E("K_BUILD_VERSION"))) + if (string.IsNullOrEmpty(E("DNX_BUILD_VERSION"))) { - E("K_BUILD_VERSION", BuildNumber); + E("DNX_BUILD_VERSION", BuildNumber); } - if (string.IsNullOrEmpty(E("K_AUTHOR"))) + if (string.IsNullOrEmpty(E("DNX_AUTHOR"))) { - E("K_AUTHOR", AUTHORS); + E("DNX_AUTHOR", AUTHORS); } if (string.IsNullOrEmpty(Configuration)) { @@ -126,9 +126,9 @@ default Configuration='${E("Configuration")}' #--quiet @{ - E("KPM_pack_options"," --quiet"); - E("KPM_build_options"," --quiet"); - E("KPM_restore_options"," --quiet"); + E("NUGET3_pack_options"," --quiet"); + E("NUGET3_build_options"," --quiet"); + E("NUGET3_restore_options"," --quiet"); E("bower_install_options","--quiet"); E("npm_install_options","--quiet"); } diff --git a/build/_k-test.shade b/build/_k-test.shade index c297361f0f..c5cfaf5563 100644 --- a/build/_k-test.shade +++ b/build/_k-test.shade @@ -52,5 +52,5 @@ projectFile='' } } -macro name='K' command='string' workingdir='string' kvmUse='string' +macro name='K' command='string' workingdir='string' dnvmUse='string' k diff --git a/build/_k.shade b/build/_k.shade index 2345320c8d..8fd7e10e5b 100644 --- a/build/_k.shade +++ b/build/_k.shade @@ -4,14 +4,14 @@ k Run klr commands in your project. Executes k cmd. command='' -kvmUse='' +dnvmUse='' */} -default kvmUse='' +default dnvmUse='' -var kvmPath='${Directory.GetCurrentDirectory()}\packages\KoreBuild\build\kvm' +var dnvmPath='${Directory.GetCurrentDirectory()}\packages\KoreBuild\build\dnvm' -exec program='cmd' commandline='/C k ${command}' if='!IsMono && string.IsNullOrEmpty(kvmUse)' -exec program='cmd' commandline='/C "${kvmPath}" use ${kvmUse} && k ${command}' if='!IsMono && !string.IsNullOrEmpty(kvmUse)' +exec program='cmd' commandline='/C k ${command}' if='!IsMono && string.IsNullOrEmpty(dnvmUse)' +exec program='cmd' commandline='/C "${dnvmPath}" use ${dnvmUse} && k ${command}' if='!IsMono && !string.IsNullOrEmpty(dnvmUse)' exec program='k' commandline='${command}' if='IsMono' diff --git a/build/_kpm-build.shade b/build/_kpm-build.shade index cf4b9a4886..6d6dfe1518 100644 --- a/build/_kpm-build.shade +++ b/build/_kpm-build.shade @@ -11,7 +11,7 @@ configuration='' */} default configuration = 'Debug' -default build_options='${E("KPM_build_options")}' +default build_options='${E("NUGET3_build_options")}' var projectFolder='${Path.GetDirectoryName(projectFile)}' var projectName='${Path.GetFileName(projectFolder)}' var projectBin='${Path.Combine(projectFolder, "bin", configuration)}' diff --git a/build/_kpm-pack.shade b/build/_kpm-pack.shade index ffb102fc80..04d04ec2db 100644 --- a/build/_kpm-pack.shade +++ b/build/_kpm-pack.shade @@ -11,7 +11,7 @@ configuration='' */} default configuration = 'Debug' -default pack_options='${E("KPM_pack_options")}' +default pack_options='${E("NUGET3_pack_options")}' var projectFolder='${Path.GetDirectoryName(projectFile)}' var projectName='${Path.GetFileName(projectFolder)}' var projectBin='${Path.Combine(projectFolder, "bin", configuration)}' diff --git a/build/dnvm.cmd b/build/dnvm.cmd new file mode 100644 index 0000000000..6e936d7ba8 --- /dev/null +++ b/build/dnvm.cmd @@ -0,0 +1,10 @@ +@Echo off + +set DNVM_CMD_PATH_FILE="%USERPROFILE%\.dnx\temp-set-envvars.cmd" + +PowerShell -NoProfile -NoLogo -ExecutionPolicy unrestricted -Command "[System.Threading.Thread]::CurrentThread.CurrentCulture = ''; [System.Threading.Thread]::CurrentThread.CurrentUICulture = '';$CmdPathFile='%DNVM_CMD_PATH_FILE%';& '%~dp0dnvm.ps1' %*" + +IF EXIST "%DNVM_CMD_PATH_FILE%" ( + CALL "%DNVM_CMD_PATH_FILE%" + DEL "%DNVM_CMD_PATH_FILE%" +) diff --git a/build/dnvm.ps1 b/build/dnvm.ps1 new file mode 100644 index 0000000000..6760f1d56d --- /dev/null +++ b/build/dnvm.ps1 @@ -0,0 +1,1235 @@ +#Requires -Version 3 + +$ScriptPath = $MyInvocation.MyCommand.Definition + +$Script:UseWriteHost = $true +function _WriteDebug($msg) { + if($Script:UseWriteHost) { + try { + Write-Debug $msg + } catch { + $Script:UseWriteHost = $false + _WriteDebug $msg + } + } +} + +function _WriteOut { + param( + [Parameter(Mandatory=$false, Position=0, ValueFromPipeline=$true)][string]$msg, + [Parameter(Mandatory=$false)][ConsoleColor]$ForegroundColor, + [Parameter(Mandatory=$false)][ConsoleColor]$BackgroundColor, + [Parameter(Mandatory=$false)][switch]$NoNewLine) + + if(!$Script:UseWriteHost) { + if(!$msg) { + $msg = "" + } + if($NoNewLine) { + [Console]::Write($msg) + } else { + [Console]::WriteLine($msg) + } + } + else { + try { + if(!$ForegroundColor) { + $ForegroundColor = $host.UI.RawUI.ForegroundColor + } + if(!$BackgroundColor) { + $BackgroundColor = $host.UI.RawUI.BackgroundColor + } + + Write-Host $msg -ForegroundColor:$ForegroundColor -BackgroundColor:$BackgroundColor -NoNewLine:$NoNewLine + } catch { + $Script:UseWriteHost = $false + _WriteOut $msg + } + } + + if($__TeeTo) { + $cur = Get-Variable -Name $__TeeTo -ValueOnly -Scope Global -ErrorAction SilentlyContinue + $val = $cur + "$msg" + if(!$NoNewLine) { + $val += [Environment]::NewLine + } + Set-Variable -Name $__TeeTo -Value $val -Scope Global -Force + } +} + +### Constants +$ProductVersion="1.0.0" +$BuildVersion="beta4-10334" +$Authors="Microsoft Open Technologies, Inc." + +# If the Version hasn't been replaced... +# We can't compare directly with the build version token +# because it'll just get replaced here as well :) +if($BuildVersion.StartsWith("{{")) { + # We're being run from source code rather than the "compiled" artifact + $BuildVersion = "HEAD" +} +$FullVersion="$ProductVersion-$BuildVersion" + +Set-Variable -Option Constant "CommandName" ([IO.Path]::GetFileNameWithoutExtension($ScriptPath)) +Set-Variable -Option Constant "CommandFriendlyName" ".NET Version Manager" +Set-Variable -Option Constant "DefaultUserDirectoryName" ".dnx" +Set-Variable -Option Constant "OldUserDirectoryNames" @(".kre", ".k") +Set-Variable -Option Constant "RuntimePackageName" "dnx" +Set-Variable -Option Constant "DefaultFeed" "https://www.myget.org/F/aspnetvnext/api/v2" +Set-Variable -Option Constant "CrossGenCommand" "k-crossgen" +Set-Variable -Option Constant "CommandPrefix" "dnvm-" +Set-Variable -Option Constant "DefaultArchitecture" "x86" +Set-Variable -Option Constant "DefaultRuntime" "clr" +Set-Variable -Option Constant "AliasExtension" ".txt" + +# These are intentionally using "%" syntax. The environment variables are expanded whenever the value is used. +Set-Variable -Option Constant "OldUserHomes" @("%USERPROFILE%\.kre","%USERPROFILE%\.k") +Set-Variable -Option Constant "DefaultUserHome" "%USERPROFILE%\$DefaultUserDirectoryName" +Set-Variable -Option Constant "HomeEnvVar" "DNX_HOME" + +Set-Variable -Option Constant "AsciiArt" @" + ___ _ ___ ____ ___ + / _ \/ |/ / | / / |/ / + / // / /| |/ / /|_/ / +/____/_/|_/ |___/_/ /_/ +"@ + +$ExitCodes = @{ + "Success" = 0 + "AliasDoesNotExist" = 1001 + "UnknownCommand" = 1002 + "InvalidArguments" = 1003 +} + +$ColorScheme = $DnvmColors +if(!$ColorScheme) { + $ColorScheme = @{ + "Banner"=[ConsoleColor]::Cyan + "RuntimeName"=[ConsoleColor]::Yellow + "Help_Header"=[ConsoleColor]::Yellow + "Help_Switch"=[ConsoleColor]::Green + "Help_Argument"=[ConsoleColor]::Cyan + "Help_Optional"=[ConsoleColor]::Gray + "Help_Command"=[ConsoleColor]::DarkYellow + "Help_Executable"=[ConsoleColor]::DarkYellow + } +} + +Set-Variable -Option Constant "OptionPadding" 20 + +# Test Control Variables +if($__TeeTo) { + _WriteDebug "Saving output to '$__TeeTo' variable" + Set-Variable -Name $__TeeTo -Value "" -Scope Global -Force +} + +# Commands that have been deprecated but do still work. +$DeprecatedCommands = @("unalias") + +# Load Environment variables +$RuntimeHomes = $env:DNX_HOME +$UserHome = $env:DNX_USER_HOME +$ActiveFeed = $env:DNX_FEED + +# Default Exit Code +$Script:ExitCode = $ExitCodes.Success + +############################################################ +### Below this point, the terms "DNVM", "DNX", etc. ### +### should never be used. Instead, use the Constants ### +### defined above ### +############################################################ +# An exception to the above: The commands are defined by functions +# named "dnvm-[command name]" so that extension functions can be added + +$StartPath = $env:PATH + +if($CmdPathFile) { + if(Test-Path $CmdPathFile) { + _WriteDebug "Cleaning old CMD PATH file: $CmdPathFile" + Remove-Item $CmdPathFile -Force + } + _WriteDebug "Using CMD PATH file: $CmdPathFile" +} + +if(!$ActiveFeed) { + $ActiveFeed = $DefaultFeed +} + +# Determine where runtimes can exist (RuntimeHomes) +if(!$RuntimeHomes) { + # Set up a default value for the runtime home + $UnencodedHomes = "%USERPROFILE%\$DefaultUserDirectoryName" +} else { + $UnencodedHomes = $RuntimeHomes +} + +$UnencodedHomes = $UnencodedHomes.Split(";") +$RuntimeHomes = $UnencodedHomes | ForEach-Object { [Environment]::ExpandEnvironmentVariables($_) } +$RuntimeDirs = $RuntimeHomes | ForEach-Object { Join-Path $_ "runtimes" } + +# Determine the default installation directory (UserHome) +if(!$UserHome) { + _WriteDebug "Detecting User Home..." + $pf = $env:ProgramFiles + if(Test-Path "env:\ProgramFiles(x86)") { + $pf32 = cat "env:\ProgramFiles(x86)" + } + + # Canonicalize so we can do StartsWith tests + if(!$pf.EndsWith("\")) { $pf += "\" } + if($pf32 -and !$pf32.EndsWith("\")) { $pf32 += "\" } + + $UserHome = $RuntimeHomes | Where-Object { + # Take the first path that isn't under program files + !($_.StartsWith($pf) -or $_.StartsWith($pf32)) + } | Select-Object -First 1 + + _WriteDebug "Found: $UserHome" + + if(!$UserHome) { + $UserHome = "$env:USERPROFILE\$DefaultUserDirectoryName" + } +} + +_WriteDebug "" +_WriteDebug "=== Running $CommandName ===" +_WriteDebug "Runtime Homes: $RuntimeHomes" +_WriteDebug "User Home: $UserHome" +$AliasesDir = Join-Path $UserHome "alias" +$RuntimesDir = Join-Path $UserHome "runtimes" +$Aliases = $null + +### Helper Functions +function GetArch($Architecture, $FallBackArch = $DefaultArchitecture) { + if(![String]::IsNullOrWhiteSpace($Architecture)) { + $Architecture + } elseif($CompatArch) { + $CompatArch + } else { + $FallBackArch + } +} + +function GetRuntime($Runtime) { + if(![String]::IsNullOrWhiteSpace($Runtime)) { + $Runtime + } else { + $DefaultRuntime + } +} + +function Write-Usage { + _WriteOut -ForegroundColor $ColorScheme.Banner $AsciiArt + _WriteOut "$CommandFriendlyName v$FullVersion" + if(!$Authors.StartsWith("{{")) { + _WriteOut "By $Authors" + } + _WriteOut + _WriteOut -NoNewLine -ForegroundColor $ColorScheme.Help_Header "usage:" + _WriteOut -NoNewLine -ForegroundColor $ColorScheme.Help_Executable " $CommandName" + _WriteOut -NoNewLine -ForegroundColor $ColorScheme.Help_Command " " + _WriteOut -ForegroundColor $ColorScheme.Help_Argument " []" +} + +function Get-RuntimeAlias { + if($Aliases -eq $null) { + _WriteDebug "Scanning for aliases in $AliasesDir" + if(Test-Path $AliasesDir) { + $Aliases = @(Get-ChildItem ($UserHome + "\alias\") | Select-Object @{label='Alias';expression={$_.BaseName}}, @{label='Name';expression={Get-Content $_.FullName }}) + } else { + $Aliases = @() + } + } + $Aliases +} + +function IsOnPath { + param($dir) + + $env:Path.Split(';') -icontains $dir +} + +function Get-RuntimeId( + [Parameter()][string]$Architecture, + [Parameter()][string]$Runtime) { + + $Architecture = GetArch $Architecture + $Runtime = GetRuntime $Runtime + + "$RuntimePackageName-$Runtime-win-$Architecture".ToLowerInvariant() +} + +function Get-RuntimeName( + [Parameter(Mandatory=$true)][string]$Version, + [Parameter()][string]$Architecture, + [Parameter()][string]$Runtime) { + + $aliasPath = Join-Path $AliasesDir "$Version$AliasExtension" + + if(Test-Path $aliasPath) { + $BaseName = Get-Content $aliasPath + + $Architecture = GetArch $Architecture (Get-PackageArch $BaseName) + $Runtime = GetRuntime $Runtime (Get-PackageArch $BaseName) + $Version = Get-PackageVersion $BaseName + } + + "$(Get-RuntimeId $Architecture $Runtime).$Version" +} + +filter List-Parts { + param($aliases) + + $binDir = Join-Path $_.FullName "bin" + if (!(Test-Path $binDir)) { + return + } + $active = IsOnPath $binDir + + $fullAlias="" + $delim="" + + foreach($alias in $aliases) { + if($_.Name.Split('\', 2) -contains $alias.Name) { + $fullAlias += $delim + $alias.Alias + $delim = ", " + } + } + + $parts1 = $_.Name.Split('.', 2) + $parts2 = $parts1[0].Split('-', 4) + return New-Object PSObject -Property @{ + Active = $active + Version = $parts1[1] + Runtime = $parts2[1] + OperatingSystem = $parts2[2] + Architecture = $parts2[3] + Location = $_.Parent.FullName + Alias = $fullAlias + } +} + +function Read-Alias($Name) { + _WriteDebug "Listing aliases matching '$Name'" + + $aliases = Get-RuntimeAlias + + $result = @($aliases | Where-Object { !$Name -or ($_.Alias.Contains($Name)) }) + if($Name -and ($result.Length -eq 1)) { + _WriteOut "Alias '$Name' is set to '$($result[0].Name)'" + } elseif($Name -and ($result.Length -eq 0)) { + _WriteOut "Alias does not exist: '$Name'" + $Script:ExitCode = $ExitCodes.AliasDoesNotExist + } else { + $result + } +} + +function Write-Alias { + param( + [Parameter(Mandatory=$true)][string]$Name, + [Parameter(Mandatory=$true)][string]$Version, + [Parameter(Mandatory=$false)][string]$Architecture, + [Parameter(Mandatory=$false)][string]$Runtime) + + $runtimeFullName = Get-RuntimeName $Version $Architecture $Runtime + $aliasFilePath = Join-Path $AliasesDir "$Name.txt" + $action = if (Test-Path $aliasFilePath) { "Updating" } else { "Setting" } + + if(!(Test-Path $AliasesDir)) { + _WriteDebug "Creating alias directory: $AliasesDir" + New-Item -Type Directory $AliasesDir | Out-Null + } + _WriteOut "$action alias '$Name' to '$runtimeFullName'" + $runtimeFullName | Out-File $aliasFilePath ascii +} + +function Delete-Alias { + param( + [Parameter(Mandatory=$true)][string]$Name) + + $aliasPath = Join-Path $AliasesDir "$Name.txt" + if (Test-Path -literalPath "$aliasPath") { + _WriteOut "Removing alias $Name" + + # Delete with "-Force" because we already confirmed above + Remove-Item -literalPath $aliasPath -Force + } else { + _WriteOut "Cannot remove alias '$Name'. It does not exist." + $Script:ExitCode = $ExitCodes.AliasDoesNotExist # Return non-zero exit code for scripting + } +} + +function Apply-Proxy { +param( + [System.Net.WebClient] $wc, + [string]$Proxy +) + if (!$Proxy) { + $Proxy = $env:http_proxy + } + if ($Proxy) { + $wp = New-Object System.Net.WebProxy($Proxy) + $pb = New-Object UriBuilder($Proxy) + if (!$pb.UserName) { + $wp.Credentials = [System.Net.CredentialCache]::DefaultCredentials + } else { + $wp.Credentials = New-Object System.Net.NetworkCredential($pb.UserName, $pb.Password) + } + $wc.Proxy = $wp + } +} + +function Find-Latest { + param( + [string]$runtime = "", + [string]$architecture = "", + [string]$Feed, + [string]$Proxy + ) + if(!$Feed) { $Feed = $ActiveFeed } + + _WriteOut "Determining latest version" + + $RuntimeId = Get-RuntimeId -Architecture:"$architecture" -Runtime:"$runtime" + $url = "$Feed/GetUpdates()?packageIds=%27$RuntimeId%27&versions=%270.0%27&includePrerelease=true&includeAllVersions=false" + + # NOTE: DO NOT use Invoke-WebRequest. It requires PowerShell 4.0! + + $wc = New-Object System.Net.WebClient + Apply-Proxy $wc -Proxy:$Proxy + _WriteDebug "Downloading $url ..." + [xml]$xml = $wc.DownloadString($url) + + $version = Select-Xml "//d:Version" -Namespace @{d='http://schemas.microsoft.com/ado/2007/08/dataservices'} $xml + + if (![String]::IsNullOrWhiteSpace($version)) { + _WriteDebug "Found latest version: $version" + $version + } +} + +function Get-PackageVersion() { + param( + [string] $runtimeFullName + ) + return $runtimeFullName -replace '[^.]*.(.*)', '$1' +} + +function Get-PackageRuntime() { + param( + [string] $runtimeFullName + ) + return $runtimeFullName -replace "$RuntimePackageName-([^-]*).*", '$1' +} + +function Get-PackageArch() { + param( + [string] $runtimeFullName + ) + return $runtimeFullName -replace "$RuntimePackageName-[^-]*-[^-]*-([^.]*).*", '$1' +} + +function Download-Package( + [string]$Version, + [string]$Architecture, + [string]$Runtime, + [string]$DestinationFile, + [string]$Feed, + [string]$Proxy) { + + if(!$Feed) { $Feed = $ActiveFeed } + + $url = "$Feed/package/" + (Get-RuntimeId $Architecture $Runtime) + "/" + $Version + + _WriteOut "Downloading $runtimeFullName from $feed" + + $wc = New-Object System.Net.WebClient + Apply-Proxy $wc -Proxy:$Proxy + _WriteDebug "Downloading $url ..." + $wc.DownloadFile($url, $DestinationFile) +} + +function Unpack-Package([string]$DownloadFile, [string]$UnpackFolder) { + _WriteDebug "Unpacking $DownloadFile to $UnpackFolder" + + $compressionLib = [System.Reflection.Assembly]::LoadWithPartialName('System.IO.Compression.FileSystem') + + if($compressionLib -eq $null) { + try { + # Shell will not recognize nupkg as a zip and throw, so rename it to zip + $runtimeZip = [System.IO.Path]::ChangeExtension($DownloadFile, "zip") + Rename-Item $runtimeFile $runtimeZip + # Use the shell to uncompress the nupkg + $shell_app=new-object -com shell.application + $zip_file = $shell_app.namespace($runtimeZip) + $destination = $shell_app.namespace($UnpackFolder) + $destination.Copyhere($zip_file.items(), 0x14) #0x4 = don't show UI, 0x10 = overwrite files + } + finally { + # Clean up the package file itself. + Remove-Item $runtimeZip -Force + } + } else { + [System.IO.Compression.ZipFile]::ExtractToDirectory($DownloadFile, $UnpackFolder) + + # Clean up the package file itself. + Remove-Item $DownloadFile -Force + } + + If (Test-Path -LiteralPath ($UnpackFolder + "\[Content_Types].xml")) { + Remove-Item -LiteralPath ($UnpackFolder + "\[Content_Types].xml") + } + If (Test-Path ($UnpackFolder + "\_rels\")) { + Remove-Item -LiteralPath ($UnpackFolder + "\_rels\") -Force -Recurse + } + If (Test-Path ($UnpackFolder + "\package\")) { + Remove-Item -LiteralPath ($UnpackFolder + "\package\") -Force -Recurse + } +} + +function Get-RuntimePath($runtimeFullName) { + _WriteDebug "Resolving $runtimeFullName" + foreach($RuntimeHome in $RuntimeHomes) { + $runtimeBin = "$RuntimeHome\runtimes\$runtimeFullName\bin" + _WriteDebug " Candidate $runtimeBin" + if (Test-Path "$runtimeBin") { + _WriteDebug " Found in $runtimeBin" + return $runtimeBin + } + } + return $null +} + +function Change-Path() { + param( + [string] $existingPaths, + [string] $prependPath, + [string[]] $removePaths + ) + _WriteDebug "Updating value to prepend '$prependPath' and remove '$removePaths'" + + $newPath = $prependPath + foreach($portion in $existingPaths.Split(';')) { + $skip = $portion -eq "" + foreach($removePath in $removePaths) { + $removePrefix = if($removePath.EndsWith("\")) { $removePath } else { "$removePath\" } + + if ($removePath -and (($portion -eq $removePath) -or ($portion.StartsWith($removePrefix)))) { + _WriteDebug " Removing '$portion' because it matches '$removePath'" + $skip = $true + } + } + if (!$skip) { + if(![String]::IsNullOrWhiteSpace($newPath)) { + $newPath += ";" + } + $newPath += $portion + } + } + return $newPath +} + +function Set-Path() { + param( + [string] $newPath + ) + + $env:PATH = $newPath + + if($CmdPathFile) { + $Parent = Split-Path -Parent $CmdPathFile + if(!(Test-Path $Parent)) { + New-Item -Type Directory $Parent -Force | Out-Null + } + _WriteDebug " Writing PATH file for CMD script" + @" +SET "PATH=$newPath" +"@ | Out-File $CmdPathFile ascii + } +} + +function Ngen-Library( + [Parameter(Mandatory=$true)] + [string]$runtimeBin, + + [ValidateSet("x86","x64")] + [Parameter(Mandatory=$true)] + [string]$architecture) { + + if ($architecture -eq 'x64') { + $regView = [Microsoft.Win32.RegistryView]::Registry64 + } + elseif ($architecture -eq 'x86') { + $regView = [Microsoft.Win32.RegistryView]::Registry32 + } + else { + _WriteOut "Installation does not understand architecture $architecture, skipping ngen..." + return + } + + $regHive = [Microsoft.Win32.RegistryHive]::LocalMachine + $regKey = [Microsoft.Win32.RegistryKey]::OpenBaseKey($regHive, $regView) + $frameworkPath = $regKey.OpenSubKey("SOFTWARE\Microsoft\NET Framework Setup\NDP\v4\Full").GetValue("InstallPath") + $ngenExe = Join-Path $frameworkPath 'ngen.exe' + + $ngenCmds = "" + foreach ($bin in Get-ChildItem $runtimeBin -Filter "Microsoft.CodeAnalysis.CSharp.dll") { + $ngenCmds += "$ngenExe install $($bin.FullName);" + } + + $ngenProc = Start-Process "$psHome\powershell.exe" -Verb runAs -ArgumentList "-ExecutionPolicy unrestricted & $ngenCmds" -Wait -PassThru +} + +function Is-Elevated() { + $user = [Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent() + return $user.IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator") +} + +### Commands + +<# +.SYNOPSIS + Displays a list of commands, and help for specific commands +.PARAMETER Command + A specific command to get help for +#> +function dnvm-help { + [CmdletBinding(DefaultParameterSetName="GeneralHelp")] + param( + [Parameter(Mandatory=$true,Position=0,ParameterSetName="SpecificCommand")][string]$Command, + [switch]$PassThru) + + if($Command) { + $cmd = Get-Command "dnvm-$Command" -ErrorAction SilentlyContinue + if(!$cmd) { + _WriteOut "No such command: $Command" + dnvm-help + $Script:ExitCodes = $ExitCodes.UnknownCommand + return + } + $help = Get-Help "dnvm-$Command" + if($PassThru) { + $help + } else { + _WriteOut -ForegroundColor $ColorScheme.Help_Header "$CommandName-$Command" + _WriteOut " $($help.Synopsis.Trim())" + _WriteOut + _WriteOut -ForegroundColor $ColorScheme.Help_Header "usage:" + $help.Syntax.syntaxItem | ForEach-Object { + _WriteOut -NoNewLine -ForegroundColor $ColorScheme.Help_Executable " $CommandName " + _WriteOut -NoNewLine -ForegroundColor $ColorScheme.Help_Command "$Command" + if($_.parameter) { + $_.parameter | ForEach-Object { + $cmdParam = $cmd.Parameters[$_.name] + $name = $_.name + if($cmdParam.Aliases.Length -gt 0) { + $name = $cmdParam.Aliases | Sort-Object | Select-Object -First 1 + } + + _WriteOut -NoNewLine " " + + if($_.required -ne "true") { + _WriteOut -NoNewLine -ForegroundColor $ColorScheme.Help_Optional "[" + } + + if($_.position -eq "Named") { + _WriteOut -NoNewLine -ForegroundColor $ColorScheme.Help_Switch "-$name" + } + if($_.parameterValue) { + if($_.position -eq "Named") { + _WriteOut -NoNewLine " " + } + _WriteOut -NoNewLine -ForegroundColor $ColorScheme.Help_Argument "<$($_.name)>" + } + + if($_.required -ne "true") { + _WriteOut -NoNewLine -ForegroundColor $ColorScheme.Help_Optional "]" + } + } + } + _WriteOut + } + + if($help.parameters -and $help.parameters.parameter) { + _WriteOut + _WriteOut -ForegroundColor $ColorScheme.Help_Header "options:" + $help.parameters.parameter | ForEach-Object { + $cmdParam = $cmd.Parameters[$_.name] + $name = $_.name + if($cmdParam.Aliases.Length -gt 0) { + $name = $cmdParam.Aliases | Sort-Object | Select-Object -First 1 + } + + _WriteOut -NoNewLine " " + + if($_.position -eq "Named") { + _WriteOut -NoNewLine -ForegroundColor $ColorScheme.Help_Switch "-$name".PadRight($OptionPadding) + } else { + _WriteOut -NoNewLine -ForegroundColor $ColorScheme.Help_Argument "<$($_.name)>".PadRight($OptionPadding) + } + _WriteOut " $($_.description.Text)" + } + } + + if($help.description) { + _WriteOut + _WriteOut -ForegroundColor $ColorScheme.Help_Header "remarks:" + $help.description.Text.Split(@("`r","`n"), "RemoveEmptyEntries") | + ForEach-Object { _WriteOut " $_" } + } + + if($DeprecatedCommands -contains $Command) { + _WriteOut "This command has been deprecated and should not longer be used" + } + } + } else { + Write-Usage + _WriteOut + _WriteOut -ForegroundColor $ColorScheme.Help_Header "commands: " + Get-Command "$CommandPrefix*" | + ForEach-Object { + $h = Get-Help $_.Name + $name = $_.Name.Substring($CommandPrefix.Length) + if($DeprecatedCommands -notcontains $name) { + _WriteOut -NoNewLine " " + _WriteOut -NoNewLine -ForegroundColor $ColorScheme.Help_Command $name.PadRight(10) + _WriteOut " $($h.Synopsis.Trim())" + } + } + } +} + +<# +.SYNOPSIS + Lists available runtimes +.PARAMETER PassThru + Set this switch to return unformatted powershell objects for use in scripting +#> +function dnvm-list { + param( + [Parameter(Mandatory=$false)][switch]$PassThru) + $aliases = Get-RuntimeAlias + + $items = @() + $RuntimeHomes | ForEach-Object { + _WriteDebug "Scanning $_ for runtimes..." + if (Test-Path "$_\runtimes") { + $items += Get-ChildItem "$_\runtimes\$RuntimePackageName-*" | List-Parts $aliases + } + } + + if($PassThru) { + $items + } else { + $items | + Sort-Object Version, Runtime, Architecture, Alias | + Format-Table -AutoSize -Property @{name="Active";expression={if($_.Active) { "*" } else { "" }};alignment="center"}, "Version", "Runtime", "Architecture", "Location", "Alias" + } +} + +<# +.SYNOPSIS + Lists and manages aliases +.PARAMETER Name + The name of the alias to read/create/delete +.PARAMETER Version + The version to assign to the new alias +.PARAMETER Architecture + The architecture of the runtime to assign to this alias +.PARAMETER Runtime + The flavor of the runtime to assign to this alias +.PARAMETER Delete + Set this switch to delete the alias with the specified name +.DESCRIPTION + If no arguments are provided, this command lists all aliases. If is provided, + the value of that alias, if present, is displayed. If and are + provided, the alias is set to the runtime defined by , + (defaults to 'x86') and (defaults to 'clr'). + + Finally, if the '-d' switch is provided, the alias is deleted, if it exists. +#> +function dnvm-alias { + param( + [Alias("d")] + [Parameter(ParameterSetName="Delete",Mandatory=$true)] + [switch]$Delete, + + [Parameter(ParameterSetName="Read",Mandatory=$false,Position=0)] + [Parameter(ParameterSetName="Write",Mandatory=$true,Position=0)] + [Parameter(ParameterSetName="Delete",Mandatory=$true,Position=0)] + [string]$Name, + + [Parameter(ParameterSetName="Write",Mandatory=$true,Position=1)] + [string]$Version, + + [Alias("arch")] + [ValidateSet("", "x86","x64")] + [Parameter(ParameterSetName="Write", Mandatory=$false)] + [string]$Architecture = "", + + [Alias("r")] + [ValidateSet("", "clr","coreclr")] + [Parameter(ParameterSetName="Write")] + [string]$Runtime = "") + + switch($PSCmdlet.ParameterSetName) { + "Read" { Read-Alias $Name } + "Write" { Write-Alias $Name $Version -Architecture $Architecture -Runtime $Runtime } + "Delete" { Delete-Alias $Name } + } +} + +<# +.SYNOPSIS + [DEPRECATED] Removes an alias +.PARAMETER Name + The name of the alias to remove +#> +function dnvm-unalias { + param( + [Parameter(Mandatory=$true,Position=0)][string]$Name) + _WriteOut "This command has been deprecated. Use '$CommandName alias -d' instead" + dnvm-alias -Delete -Name $Name +} + +<# +.SYNOPSIS + Installs the latest version of the runtime and reassigns the specified alias to point at it +.PARAMETER Alias + The alias to upgrade (default: 'default') +.PARAMETER Architecture + The processor architecture of the runtime to install (default: x86) +.PARAMETER Runtime + The runtime flavor to install (default: clr) +.PARAMETER Force + Overwrite an existing runtime if it already exists +.PARAMETER Proxy + Use the given address as a proxy when accessing remote server +.PARAMETER NoNative + Skip generation of native images +.PARAMETER Ngen + For CLR flavor only. Generate native images for runtime libraries on Desktop CLR to improve startup time. This option requires elevated privilege and will be automatically turned on if the script is running in administrative mode. To opt-out in administrative mode, use -NoNative switch. +#> +function dnvm-upgrade { + param( + [Alias("a")] + [Parameter(Mandatory=$false, Position=0)] + [string]$Alias = "default", + + [Alias("arch")] + [ValidateSet("", "x86","x64")] + [Parameter(Mandatory=$false)] + [string]$Architecture = "", + + [Alias("r")] + [ValidateSet("", "clr","coreclr")] + [Parameter(Mandatory=$false)] + [string]$Runtime = "", + + [Alias("f")] + [Parameter(Mandatory=$false)] + [switch]$Force, + + [Parameter(Mandatory=$false)] + [string]$Proxy, + + [Parameter(Mandatory=$false)] + [switch]$NoNative, + + [Parameter(Mandatory=$false)] + [switch]$Ngen) + + dnvm-install "latest" -Alias:$Alias -Architecture:$Architecture -Runtime:$Runtime -Force:$Force -Proxy:$Proxy -NoNative:$NoNative -Ngen:$Ngen +} + +<# +.SYNOPSIS + Installs a version of the runtime +.PARAMETER VersionOrNuPkg + The version to install from the current channel, the path to a '.nupkg' file to install, or 'latest' to + install the latest available version from the current channel. +.PARAMETER Architecture + The processor architecture of the runtime to install (default: x86) +.PARAMETER Runtime + The runtime flavor to install (default: clr) +.PARAMETER Alias + Set alias to the installed runtime +.PARAMETER Force + Overwrite an existing runtime if it already exists +.PARAMETER Proxy + Use the given address as a proxy when accessing remote server +.PARAMETER NoNative + Skip generation of native images +.PARAMETER Ngen + For CLR flavor only. Generate native images for runtime libraries on Desktop CLR to improve startup time. This option requires elevated privilege and will be automatically turned on if the script is running in administrative mode. To opt-out in administrative mode, use -NoNative switch. +.DESCRIPTION + A proxy can also be specified by using the 'http_proxy' environment variable + +#> +function dnvm-install { + param( + [Parameter(Mandatory=$false, Position=0)] + [string]$VersionOrNuPkg, + + [Alias("arch")] + [ValidateSet("", "x86","x64")] + [Parameter(Mandatory=$false)] + [string]$Architecture = "", + + [Alias("r")] + [ValidateSet("", "clr","coreclr")] + [Parameter(Mandatory=$false)] + [string]$Runtime = "", + + [Alias("a")] + [Parameter(Mandatory=$false)] + [string]$Alias, + + [Alias("f")] + [Parameter(Mandatory=$false)] + [switch]$Force, + + [Parameter(Mandatory=$false)] + [string]$Proxy, + + [Parameter(Mandatory=$false)] + [switch]$NoNative, + + [Parameter(Mandatory=$false)] + [switch]$Ngen) + + if(!$VersionOrNuPkg) { + _WriteOut "A version, nupkg path, or the string 'latest' must be provided." + dnvm-help install + $Script:ExitCode = $ExitCodes.InvalidArguments + return + } + + if ($VersionOrNuPkg -eq "latest") { + $VersionOrNuPkg = Find-Latest $Runtime $Architecture + } + + $IsNuPkg = $VersionOrNuPkg.EndsWith(".nupkg") + + if ($IsNuPkg) { + if(!(Test-Path $VersionOrNuPkg)) { + throw "Unable to locate package file: '$VersionOrNuPkg'" + } + $runtimeFullName = [System.IO.Path]::GetFileNameWithoutExtension($VersionOrNuPkg) + $Architecture = Get-PackageArch $runtimeFullName + $Runtime = Get-PackageRuntime $runtimeFullName + } else { + $runtimeFullName = Get-RuntimeName $VersionOrNuPkg -Architecture:$Architecture -Runtime:$Runtime + } + + $PackageVersion = Get-PackageVersion $runtimeFullName + + _WriteDebug "Preparing to install runtime '$runtimeFullName'" + _WriteDebug "Architecture: $Architecture" + _WriteDebug "Runtime: $Runtime" + _WriteDebug "Version: $PackageVersion" + + $RuntimeFolder = Join-Path $RuntimesDir $runtimeFullName + _WriteDebug "Destination: $RuntimeFolder" + + if((Test-Path $RuntimeFolder) -and $Force) { + _WriteOut "Cleaning existing installation..." + Remove-Item $RuntimeFolder -Recurse -Force + } + + if(Test-Path $RuntimeFolder) { + _WriteOut "'$runtimeFullName' is already installed." + } + else { + $Architecture = GetArch $Architecture + $Runtime = GetRuntime $Runtime + $UnpackFolder = Join-Path $RuntimesDir "temp" + $DownloadFile = Join-Path $UnpackFolder "$runtimeFullName.nupkg" + + if(Test-Path $UnpackFolder) { + _WriteDebug "Cleaning temporary directory $UnpackFolder" + Remove-Item $UnpackFolder -Recurse -Force + } + New-Item -Type Directory $UnpackFolder | Out-Null + + if($IsNuPkg) { + _WriteDebug "Copying local nupkg $VersionOrNuPkg to $DownloadFile" + Copy-Item $VersionOrNuPkg $DownloadFile + } else { + # Download the package + _WriteDebug "Downloading version $VersionOrNuPkg to $DownloadFile" + Download-Package $VersionOrNuPkg $Architecture $Runtime $DownloadFile -Proxy:$Proxy + } + + Unpack-Package $DownloadFile $UnpackFolder + + New-Item -Type Directory $RuntimeFolder -Force | Out-Null + _WriteOut "Installing to $RuntimeFolder" + _WriteDebug "Moving package contents to $RuntimeFolder" + Move-Item "$UnpackFolder\*" $RuntimeFolder + _WriteDebug "Cleaning temporary directory $UnpackFolder" + Remove-Item $UnpackFolder -Force | Out-Null + + dnvm-use $PackageVersion -Architecture:$Architecture -Runtime:$Runtime + + if ($Runtime -eq "clr") { + if (-not $NoNative) { + if ((Is-Elevated) -or $Ngen) { + $runtimeBin = Get-RuntimePath $runtimeFullName + Ngen-Library $runtimeBin $Architecture + } + else { + _WriteOut "Native image generation (ngen) is skipped. Include -Ngen switch to turn on native image generation to improve application startup time." + } + } + } + elseif ($Runtime -eq "coreclr") { + if ($NoNative) { + _WriteOut "Skipping native image compilation." + } + else { + _WriteOut "Compiling native images for $runtimeFullName to improve startup performance..." + Start-Process $CrossGenCommand -Wait + _WriteOut "Finished native image compilation." + } + } + else { + _WriteOut "Unexpected platform: $Runtime. No optimization would be performed on the package installed." + } + } + + if($Alias) { + _WriteDebug "Aliasing installed runtime to '$Alias'" + dnvm-alias $Alias $PackageVersion -Architecture:$Architecture -Runtime:$Runtime + } +} + + +<# +.SYNOPSIS + Adds a runtime to the PATH environment variable for your current shell +.PARAMETER VersionOrAlias + The version or alias of the runtime to place on the PATH +.PARAMETER Architecture + The processor architecture of the runtime to place on the PATH (default: x86, or whatever the alias specifies in the case of use-ing an alias) +.PARAMETER Runtime + The runtime flavor of the runtime to place on the PATH (default: clr, or whatever the alias specifies in the case of use-ing an alias) +.PARAMETER Persistent + Make the change persistent across all processes run by the current user +#> +function dnvm-use { + param( + [Parameter(Mandatory=$false, Position=0)] + [string]$VersionOrAlias, + + [Alias("arch")] + [ValidateSet("", "x86","x64")] + [Parameter(Mandatory=$false)] + [string]$Architecture = "", + + [Alias("r")] + [ValidateSet("", "clr","coreclr")] + [Parameter(Mandatory=$false)] + [string]$Runtime = "", + + [Alias("p")] + [Parameter(Mandatory=$false)] + [switch]$Persistent) + + if([String]::IsNullOrWhiteSpace($VersionOrAlias)) { + _WriteOut "Missing version or alias to add to path" + dnvm-help use + $Script:ExitCode = $ExitCodes.InvalidArguments + return + } + + if ($versionOrAlias -eq "none") { + _WriteOut "Removing all runtimes from process PATH" + Set-Path (Change-Path $env:Path "" ($RuntimeDirs)) + + if ($Persistent) { + Console-Write "Removing all runtimes from user PATH" + $userPath = [Environment]::GetEnvironmentVariable("Path", [System.EnvironmentVariableTarget]::User) + $userPath = Change-Path $userPath "" ($RuntimeDirs) + [Environment]::SetEnvironmentVariable("Path", $userPath, [System.EnvironmentVariableTarget]::User) + } + return; + } + + $runtimeFullName = Get-RuntimeName $VersionOrAlias $Architecture $Runtime + $runtimeBin = Get-RuntimePath $runtimeFullName + if ($runtimeBin -eq $null) { + throw "Cannot find $runtimeFullName, do you need to run '$CommandName install $versionOrAlias'?" + } + + _WriteOut "Adding $runtimeBin to process PATH" + Set-Path (Change-Path $env:Path $runtimeBin ($RuntimeDirs)) + + if ($Persistent) { + Console-Write "Adding $runtimeBin to user PATH" + $userPath = [Environment]::GetEnvironmentVariable("Path", [System.EnvironmentVariableTarget]::User) + $userPath = Change-Path $userPath $runtimeBin ($RuntimeDirs) + [Environment]::SetEnvironmentVariable("Path", $userPath, [System.EnvironmentVariableTarget]::User) + } +} + +<# +.SYNOPSIS + Gets the full name of a runtime +.PARAMETER VersionOrAlias + The version or alias of the runtime to place on the PATH +.PARAMETER Architecture + The processor architecture of the runtime to place on the PATH (default: x86, or whatever the alias specifies in the case of use-ing an alias) +.PARAMETER Runtime + The runtime flavor of the runtime to place on the PATH (default: clr, or whatever the alias specifies in the case of use-ing an alias) +#> +function dnvm-name { + param( + [Parameter(Mandatory=$false, Position=0)] + [string]$VersionOrAlias, + + [Alias("arch")] + [ValidateSet("x86","x64")] + [Parameter(Mandatory=$false)] + [string]$Architecture = "", + + [Alias("r")] + [ValidateSet("clr","coreclr")] + [Parameter(Mandatory=$false)] + [string]$Runtime = "") + + Get-RuntimeName $VersionOrAlias $Architecture $Runtime +} + +<# +.SYNOPSIS + Installs the version manager into your User profile directory +.PARAMETER SkipUserEnvironmentInstall + Set this switch to skip configuring the user-level DNX_HOME and PATH environment variables +#> +function dnvm-setup { + param( + [switch]$SkipUserEnvironmentInstall) + + $DestinationHome = "$env:USERPROFILE\$DefaultUserDirectoryName" + + # Install scripts + $Destination = "$DestinationHome\bin" + _WriteOut "Installing $CommandFriendlyName to $Destination" + + $ScriptFolder = Split-Path -Parent $ScriptPath + + if(!(Test-Path $Destination)) { + New-Item -Type Directory $Destination | Out-Null + } + + $ps1Command = Join-Path $ScriptFolder "$CommandName.ps1" + if(Test-Path $ps1Command) { + _WriteOut "Installing '$CommandName.ps1' to '$Destination' ..." + Copy-Item $ps1Command $Destination -Force + } else { + _WriteOut "WARNING: Could not find '$CommandName.ps1' in '$ScriptFolder'. Unable to install!" + } + $cmdCommand = Join-Path $ScriptFolder "$CommandName.cmd" + if(Test-Path $cmdCommand) { + _WriteOut "Installing '$CommandName.cmd' to '$Destination' ..." + Copy-Item $cmdCommand $Destination -Force + } else { + _WriteOut "WARNING: Could not find '$CommandName.cmd' in '$ScriptFolder'. Unable to install!" + } + + # Configure Environment Variables + # Also, clean old user home values if present + + # We'll be removing any existing homes, both + $PathsToRemove = @( + "%USERPROFILE%\$DefaultUserDirectoryName", + [Environment]::ExpandEnvironmentVariables($OldUserHome), + $DestinationHome, + $OldUserHome) + + # First: PATH + _WriteOut "Adding $Destination to Process PATH" + Set-Path (Change-Path $env:PATH $Destination $PathsToRemove) + + if(!$SkipUserEnvironmentInstall) { + _WriteOut "Adding $Destination to User PATH" + $userPath = [Environment]::GetEnvironmentVariable("PATH", "User") + $userPath = Change-Path $userPath $Destination $PathsToRemove + [Environment]::SetEnvironmentVariable("PATH", $userPath, "User") + } + + # Now the HomeEnvVar + _WriteOut "Adding $DestinationHome to Process $HomeEnvVar" + $processHome = "" + if(Test-Path "env:\$HomeEnvVar") { + $processHome = cat "env:\$HomeEnvVar" + } + $processHome = Change-Path $processHome "%USERPROFILE%\$DefaultUserDirectoryName" $PathsToRemove + Set-Content "env:\$HomeEnvVar" $processHome + + if(!$SkipUserEnvironmentInstall) { + _WriteOut "Adding $DestinationHome to User $HomeEnvVar" + $userHomeVal = [Environment]::GetEnvironmentVariable($HomeEnvVar, "User") + $userHomeVal = Change-Path $userHomeVal "%USERPROFILE%\$DefaultUserDirectoryName" $PathsToRemove + [Environment]::SetEnvironmentVariable($HomeEnvVar, $userHomeVal, "User") + } +} + +### The main "entry point" + +# Check for old DNX_HOME values +if($UnencodedHomes -contains $OldUserHome) { + _WriteOut -ForegroundColor Yellow "WARNING: Found '$OldUserHome' in your $HomeEnvVar value. This folder has been deprecated." + if($UnencodedHomes -notcontains $DefaultUserHome) { + _WriteOut -ForegroundColor Yellow "WARNING: Didn't find '$DefaultUserHome' in your $HomeEnvVar value. You should run '$CommandName setup' to upgrade." + } +} + +# Read arguments + +$cmd = $args[0] + +if($args.Length -gt 1) { + $cmdargs = @($args[1..($args.Length-1)]) +} else { + $cmdargs = @() +} + +# Can't add this as script-level arguments because they mask '-a' arguments in subcommands! +# So we manually parse them :) +if($cmdargs -icontains "-amd64") { + $CompatArch = "x64" + _WriteOut "The -amd64 switch has been deprecated. Use the '-arch x64' parameter instead" +} elseif($cmdargs -icontains "-x86") { + $CompatArch = "x86" + _WriteOut "The -x86 switch has been deprecated. Use the '-arch x86' parameter instead" +} elseif($cmdargs -icontains "-x64") { + $CompatArch = "x64" + _WriteOut "The -x64 switch has been deprecated. Use the '-arch x64' parameter instead" +} +$cmdargs = @($cmdargs | Where-Object { @("-amd64", "-x86", "-x64") -notcontains $_ }) + +if(!$cmd) { + _WriteOut "You must specify a command!" + $cmd = "help" + $Script:ExitCode = $ExitCodes.InvalidArguments +} + +# Check for the command +if(Get-Command -Name "$CommandPrefix$cmd" -ErrorAction SilentlyContinue) { + _WriteDebug "& dnvm-$cmd $cmdargs" + & "dnvm-$cmd" @cmdargs +} +else { + _WriteOut "Unknown command: '$cmd'" + dnvm-help + $Script:ExitCode = $ExitCodes.UnknownCommand +} + +_WriteDebug "=== End $CommandName (Exit Code $Script:ExitCode) ===" +_WriteDebug "" +exit $Script:ExitCode diff --git a/build/dnvm.sh b/build/dnvm.sh new file mode 100644 index 0000000000..0744a52ae8 --- /dev/null +++ b/build/dnvm.sh @@ -0,0 +1,440 @@ +# dnvm.sh +# Source this file from your .bash-profile or script to use + +# "Constants" +_DNVM_BUILDNUMBER="beta4-10334" +_DNVM_AUTHORS="Microsoft Open Technologies, Inc." +_DNVM_RUNTIME_PACKAGE_NAME="dnx" +_DNVM_RUNTIME_FRIENDLY_NAME=".NET Execution Environment" +_DNVM_RUNTIME_SHORT_NAME="DNX" +_DNVM_RUNTIME_FOLDER_NAME=".dnx" +_DNVM_COMMAND_NAME="dnvm" +_DNVM_VERSION_MANAGER_NAME=".NET Version Manager" +_DNVM_DEFAULT_FEED="https://www.myget.org/F/aspnetvnext/api/v2" +_DNVM_HOME_VAR_NAME="DNX_HOME" + +[ "$_DNVM_BUILDNUMBER" = "{{*" ] && _DNVM_BUILDNUMBER="HEAD" + +__dnvm_has() { + type "$1" > /dev/null 2>&1 + return $? +} + +if __dnvm_has "unsetopt"; then + unsetopt nomatch 2>/dev/null +fi + +if [ -z "$DNX_USER_HOME" ]; then + eval DNX_USER_HOME="~/$_DNVM_RUNTIME_FOLDER_NAME" +fi + +_DNVM_USER_PACKAGES="$DNX_USER_HOME/runtimes" +_DNVM_ALIAS_DIR="$DNX_USER_HOME/alias" + +if [ -z "$DNX_FEED" ]; then + DNX_FEED="$_DNVM_DEFAULT_FEED" +fi + +__dnvm_find_latest() { + local platform="mono" + + if ! __dnvm_has "curl"; then + echo "$_DNVM_COMMAND_NAME needs curl to proceed." >&2; + return 1 + fi + + local url="$DNX_FEED/GetUpdates()?packageIds=%27$_DNVM_RUNTIME_PACKAGE_NAME-$platform%27&versions=%270.0%27&includePrerelease=true&includeAllVersions=false" + xml="$(curl $url 2>/dev/null)" + echo $xml | grep \<[a-zA-Z]:Version\>* >> /dev/null || return 1 + version="$(echo $xml | sed 's/.*<[a-zA-Z]:Version>\([^<]*\).*/\1/')" + echo $version +} + +__dnvm_strip_path() { + echo "$1" | sed -e "s#$_DNVM_USER_PACKAGES/[^/]*$2[^:]*:##g" -e "s#:$_DNVM_USER_PACKAGES/[^/]*$2[^:]*##g" -e "s#$_DNVM_USER_PACKAGES/[^/]*$2[^:]*##g" +} + +__dnvm_prepend_path() { + if [ -z "$1" ]; then + echo "$2" + else + echo "$2:$1" + fi +} + +__dnvm_package_version() { + local runtimeFullName="$1" + echo "$runtimeFullName" | sed "s/[^.]*.\(.*\)/\1/" +} + +__dnvm_package_name() { + local runtimeFullName="$1" + echo "$runtimeFullName" | sed "s/\([^.]*\).*/\1/" +} + +__dnvm_package_runtime() { + local runtimeFullName="$1" + echo "$runtimeFullName" | sed "s/$_DNVM_RUNTIME_PACKAGE_NAME-\([^.-]*\).*/\1/" +} + +__dnvm_download() { + local runtimeFullName="$1" + local runtimeFolder="$2" + + local pkgName=$(__dnvm_package_name "$runtimeFullName") + local pkgVersion=$(__dnvm_package_version "$runtimeFullName") + local url="$DNX_FEED/package/$pkgName/$pkgVersion" + local runtimeFile="$runtimeFolder/$runtimeFullName.nupkg" + + if [ -e "$runtimeFolder" ]; then + echo "$runtimeFullName already installed." + return 0 + fi + + echo "Downloading $runtimeFullName from $DNX_FEED" + + if ! __dnvm_has "curl"; then + echo "$_DNVM_COMMAND_NAME needs curl to proceed." >&2; + return 1 + fi + + mkdir -p "$runtimeFolder" > /dev/null 2>&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 "$runtimeFullName was not found in repository $DNX_FEED" && return 1 + [[ $httpResult != "302" && $httpResult != "200" ]] && echo "HTTP Error $httpResult fetching $runtimeFullName from $DNX_FEED" && return 1 + + __dnvm_unpack $runtimeFile $runtimeFolder + return $? +} + +__dnvm_unpack() { + local runtimeFile="$1" + local runtimeFolder="$2" + + echo "Installing to $runtimeFolder" + + if ! __dnvm_has "unzip"; then + echo "$_DNVM_COMMAND_NAME needs unzip to proceed." >&2; + return 1 + fi + + unzip $runtimeFile -d $runtimeFolder > /dev/null 2>&1 + + [ -e "$runtimeFolder/[Content_Types].xml" ] && rm "$runtimeFolder/[Content_Types].xml" + + [ -e "$runtimeFolder/_rels/" ] && rm -rf "$runtimeFolder/_rels/" + + [ -e "$runtimeFolder/package/" ] && rm -rf "$runtimeFolder/_package/" + + [ -e "$runtimeFile" ] && rm -f "$runtimeFile" + + #Set shell commands as executable + find "$runtimeFolder/bin/" -type f \ + -exec sh -c "head -c 11 {} | grep '/bin/bash' > /dev/null" \; -print | xargs chmod 775 +} + +__dnvm_requested_version_or_alias() { + local versionOrAlias="$1" + local runtimeBin=$(__dnvm_locate_runtime_bin_from_full_name "$versionOrAlias") + + # If the name specified is an existing package, just use it as is + if [ -n "$runtimeBin" ]; then + echo "$versionOrAlias" + else + if [ -e "$_DNVM_ALIAS_DIR/$versionOrAlias.alias" ]; then + local runtimeFullName=$(cat "$_DNVM_ALIAS_DIR/$versionOrAlias.alias") + local pkgName=$(echo $runtimeFullName | sed "s/\([^.]*\).*/\1/") + local pkgVersion=$(echo $runtimeFullName | sed "s/[^.]*.\(.*\)/\1/") + local pkgPlatform=$(echo "$pkgName" | sed "s/$_DNVM_RUNTIME_PACKAGE_NAME-\([^.-]*\).*/\1/") + else + local pkgVersion=$versionOrAlias + local pkgPlatform="mono" + fi + + echo "$_DNVM_RUNTIME_PACKAGE_NAME-$pkgPlatform.$pkgVersion" + fi +} + +# This will be more relevant if we support global installs +__dnvm_locate_runtime_bin_from_full_name() { + local runtimeFullName=$1 + [ -e "$_DNVM_USER_PACKAGES/$runtimeFullName/bin" ] && echo "$_DNVM_USER_PACKAGES/$runtimeFullName/bin" && return +} + +__dnvm_help() { + echo "" + echo "$_DNVM_VERSION_MANAGER_NAME - Version 1.0.0-$_DNVM_BUILDNUMBER" + [ "$_DNVM_AUTHORS" != "{{*" ] && echo "By $_DNVM_AUTHORS" + echo "" + echo "USAGE: $_DNVM_COMMAND_NAME [options]" + echo "" + echo "$_DNVM_COMMAND_NAME upgrade" + echo "install latest $_DNVM_RUNTIME_SHORT_NAME from feed" + echo "add $_DNVM_RUNTIME_SHORT_NAME bin to path of current command line" + echo "set installed version as default" + echo "" + echo "$_DNVM_COMMAND_NAME install |||latest [-a|-alias ] [-p -persistent]" + echo "| install requested $_DNVM_RUNTIME_SHORT_NAME from feed" + echo " install requested $_DNVM_RUNTIME_SHORT_NAME from local package on filesystem" + echo "latest install latest version of $_DNVM_RUNTIME_SHORT_NAME from feed" + echo "-a|-alias set alias for requested $_DNVM_RUNTIME_SHORT_NAME on install" + echo "-p -persistent set installed version as default" + echo "add $_DNVM_RUNTIME_SHORT_NAME bin to path of current command line" + echo "" + echo "$_DNVM_COMMAND_NAME use |||none [-p -persistent]" + echo "|| add $_DNVM_RUNTIME_SHORT_NAME bin to path of current command line " + echo "none remove $_DNVM_RUNTIME_SHORT_NAME bin from path of current command line" + echo "-p -persistent set selected version as default" + echo "" + echo "$_DNVM_COMMAND_NAME list" + echo "list $_DNVM_RUNTIME_SHORT_NAME versions installed " + echo "" + echo "$_DNVM_COMMAND_NAME alias" + echo "list $_DNVM_RUNTIME_SHORT_NAME aliases which have been defined" + echo "" + echo "$_DNVM_COMMAND_NAME alias " + echo "display value of the specified alias" + echo "" + echo "$_DNVM_COMMAND_NAME alias ||" + echo " the name of the alias to set" + echo "|| the $_DNVM_RUNTIME_SHORT_NAME version to set the alias to. Alternatively use the version of the specified alias" + echo "" + echo "$_DNVM_COMMAND_NAME unalias " + echo "remove the specified alias" + echo "" +} + +dnvm() +{ + if [ $# -lt 1 ]; then + __dnvm_help + return + fi + + case $1 in + "help" ) + __dnvm_help + ;; + + "upgrade" ) + [ $# -ne 1 ] && __dnvm_help && return + $_DNVM_COMMAND_NAME install latest -p + ;; + + "install" ) + [ $# -lt 2 ] && __dnvm_help && return + shift + local persistent= + local versionOrAlias= + local alias= + while [ $# -ne 0 ] + do + if [[ $1 == "-p" || $1 == "-persistent" ]]; then + local persistent="-p" + elif [[ $1 == "-a" || $1 == "-alias" ]]; then + local alias=$2 + shift + elif [[ -n $1 ]]; then + [[ -n $versionOrAlias ]] && echo "Invalid option $1" && __dnvm_help && return 1 + local versionOrAlias=$1 + fi + shift + done + if [[ "$versionOrAlias" == "latest" ]]; then + echo "Determining latest version" + versionOrAlias=$(__dnvm_find_latest) + [[ $? == 1 ]] && echo "Error: Could not find latest version from feed $DNX_FEED" && return 1 + echo "Latest version is $versionOrAlias" + fi + if [[ "$versionOrAlias" == *.nupkg ]]; then + local runtimeFullName=$(basename $versionOrAlias | sed "s/\(.*\)\.nupkg/\1/") + local runtimeVersion=$(__dnvm_package_version "$runtimeFullName") + local runtimeFolder="$_DNVM_USER_PACKAGES/$runtimeFullName" + local runtimeFile="$runtimeFolder/$runtimeFullName.nupkg" + + if [ -e "$runtimeFolder" ]; then + echo "$runtimeFullName already installed" + else + mkdir "$runtimeFolder" > /dev/null 2>&1 + cp -a "$versionOrAlias" "$runtimeFile" + __dnvm_unpack "$runtimeFile" "$runtimeFolder" + [[ $? == 1 ]] && return 1 + fi + $_DNVM_COMMAND_NAME use "$runtimeVersion" "$persistent" + [[ -n $alias ]] && $_DNVM_COMMAND_NAME alias "$alias" "$runtimeVersion" + else + local runtimeFullName="$(__dnvm_requested_version_or_alias $versionOrAlias)" + local runtimeFolder="$_DNVM_USER_PACKAGES/$runtimeFullName" + __dnvm_download "$runtimeFullName" "$runtimeFolder" + [[ $? == 1 ]] && return 1 + $_DNVM_COMMAND_NAME use "$versionOrAlias" "$persistent" + [[ -n $alias ]] && $_DNVM_COMMAND_NAME alias "$alias" "$versionOrAlias" + fi + ;; + + "use" ) + [ $# -gt 3 ] && __dnvm_help && return + [ $# -lt 2 ] && __dnvm_help && return + + shift + local persistent= + while [ $# -ne 0 ] + do + if [[ $1 == "-p" || $1 == "-persistent" ]]; then + local persistent="true" + elif [[ -n $1 ]]; then + local versionOrAlias=$1 + fi + shift + done + + if [[ $versionOrAlias == "none" ]]; then + echo "Removing $_DNVM_RUNTIME_SHORT_NAME from process PATH" + # Strip other version from PATH + PATH=$(__dnvm_strip_path "$PATH" "/bin") + + if [[ -n $persistent && -e "$_DNVM_ALIAS_DIR/default.alias" ]]; then + echo "Setting default $_DNVM_RUNTIME_SHORT_NAME to none" + rm "$_DNVM_ALIAS_DIR/default.alias" + fi + return 0 + fi + + local runtimeFullName=$(__dnvm_requested_version_or_alias "$versionOrAlias") + local runtimeBin=$(__dnvm_locate_runtime_bin_from_full_name "$runtimeFullName") + + if [[ -z $runtimeBin ]]; then + echo "Cannot find $runtimeFullName, do you need to run '$_DNVM_COMMAND_NAME install $versionOrAlias'?" + return 1 + fi + + echo "Adding" $runtimeBin "to process PATH" + + PATH=$(__dnvm_strip_path "$PATH" "/bin") + PATH=$(__dnvm_prepend_path "$PATH" "$runtimeBin") + + if [[ -n $persistent ]]; then + local runtimeVersion=$(__dnvm_package_version "$runtimeFullName") + $_DNVM_COMMAND_NAME alias default "$runtimeVersion" + fi + ;; + + "alias" ) + [[ $# -gt 3 ]] && __dnvm_help && return + + [[ ! -e "$_DNVM_ALIAS_DIR/" ]] && mkdir "$_DNVM_ALIAS_DIR/" > /dev/null + + if [[ $# == 1 ]]; then + echo "" + local format="%-20s %s\n" + printf "$format" "Alias" "Name" + printf "$format" "-----" "----" + if [ -d "$_DNVM_ALIAS_DIR" ]; then + for __dnvm_file in $(find "$_DNVM_ALIAS_DIR" -name *.alias); do + local alias="$(basename $__dnvm_file | sed 's/\.alias//')" + local name="$(cat $__dnvm_file)" + printf "$format" "$alias" "$name" + done + fi + echo "" + return + fi + + local name="$2" + + if [[ $# == 2 ]]; then + [[ ! -e "$_DNVM_ALIAS_DIR/$name.alias" ]] && echo "There is no alias called '$name'" && return + cat "$_DNVM_ALIAS_DIR/$name.alias" + echo "" + return + fi + + local runtimeFullName=$(__dnvm_requested_version_or_alias "$3") + + [[ ! -d "$_DNVM_USER_PACKAGES/$runtimeFullName" ]] && echo "$runtimeFullName is not an installed $_DNVM_RUNTIME_SHORT_NAME version" && return 1 + + local action="Setting" + [[ -e "$_DNVM_ALIAS_DIR/$name.alias" ]] && action="Updating" + echo "$action alias '$name' to '$runtimeFullName'" + echo "$runtimeFullName" > "$_DNVM_ALIAS_DIR/$name.alias" + ;; + + "unalias" ) + [[ $# -ne 2 ]] && __dnvm_help && return + + local name=$2 + local aliasPath="$_DNVM_ALIAS_DIR/$name.alias" + [[ ! -e "$aliasPath" ]] && echo "Cannot remove alias, '$name' is not a valid alias name" && return 1 + echo "Removing alias $name" + rm "$aliasPath" >> /dev/null 2>&1 + ;; + + "list" ) + [[ $# -gt 2 ]] && __dnvm_help && return + + [[ ! -d $_DNVM_USER_PACKAGES ]] && echo "$_DNVM_RUNTIME_FRIENDLY_NAME is not installed." && return 1 + + local searchGlob="$_DNVM_RUNTIME_PACKAGE_NAME-*" + if [ $# == 2 ]; then + local versionOrAlias=$2 + local searchGlob=$(__dnvm_requested_version_or_alias "$versionOrAlias") + fi + echo "" + + # Separate empty array declaration from initialization + # to avoid potential ZSH error: local:217: maximum nested function level reached + local arr + arr=() + + # Z shell array-index starts at one. + local i=1 + local format="%-20s %s\n" + if [ -d "$_DNVM_ALIAS_DIR" ]; then + for __dnvm_file in $(find "$_DNVM_ALIAS_DIR" -name *.alias); do + arr[$i]="$(basename $__dnvm_file | sed 's/\.alias//')/$(cat $__dnvm_file)" + let i+=1 + done + fi + + local formatString="%-6s %-20s %-7s %-20s %s\n" + printf "$formatString" "Active" "Version" "Runtime" "Location" "Alias" + printf "$formatString" "------" "-------" "-------" "--------" "-----" + + local formattedHome=`(echo $_DNVM_USER_PACKAGES | sed s=$HOME=~=g)` + for f in $(find $_DNVM_USER_PACKAGES -name "$searchGlob" \( -type d -or -type l \) -prune -exec basename {} \;); do + local active="" + [[ $PATH == *"$_DNVM_USER_PACKAGES/$f/bin"* ]] && local active=" *" + local pkgName=$(__dnvm_package_runtime "$f") + local pkgVersion=$(__dnvm_package_version "$f") + + local alias="" + local delim="" + for i in "${arr[@]}"; do + temp="$_DNVM_RUNTIME_PACKAGE_NAME-$pkgName.$pkgVersion" + temp2="$_DNVM_RUNTIME_PACKAGE_NAME-$pkgName-x86.$pkgVersion" + if [[ ${i#*/} == $temp || ${i#*/} == $temp2 ]]; then + alias+="$delim${i%/*}" + delim=", " + fi + done + + printf "$formatString" "$active" "$pkgVersion" "$pkgName" "$formattedHome" "$alias" + [[ $# == 2 ]] && echo "" && return 0 + done + + echo "" + [[ $# == 2 ]] && echo "$versionOrAlias not found" && return 1 + ;; + + *) + echo "Unknown command $1" + return 1 + esac + + return 0 +} + +# Generate the command function using the constant defined above. +$_DNVM_COMMAND_NAME list default >/dev/null && $_DNVM_COMMAND_NAME use default >/dev/null || true diff --git a/build/kvm.cmd b/build/kvm.cmd deleted file mode 100644 index 6555df1886..0000000000 --- a/build/kvm.cmd +++ /dev/null @@ -1,8 +0,0 @@ -@Echo off - -PowerShell -NoProfile -NoLogo -ExecutionPolicy unrestricted -Command "[System.Threading.Thread]::CurrentThread.CurrentCulture = ''; [System.Threading.Thread]::CurrentThread.CurrentUICulture = '';& '%~dp0kvm.ps1' %*" - -IF EXIST "%USERPROFILE%\.k\temp-set-envvars.cmd" ( - CALL "%USERPROFILE%\.k\temp-set-envvars.cmd" - DEL "%USERPROFILE%\.k\temp-set-envvars.cmd" -) diff --git a/build/kvm.ps1 b/build/kvm.ps1 deleted file mode 100644 index 0ab4ae9634..0000000000 --- a/build/kvm.ps1 +++ /dev/null @@ -1,790 +0,0 @@ -param( - [parameter(Position=0)] - [string] $Command, - [string] $Proxy, - [switch] $Verbosity = $false, - [alias("p")][switch] $Persistent = $false, - [alias("f")][switch] $Force = $false, - [alias("r")][string] $Runtime, - - [alias("arch")][string] $Architecture, - [switch] $X86 = $false, - [alias("amd64")][switch] $X64 = $false, - - [alias("w")][switch] $Wait = $false, - [alias("a")] - [string] $Alias = $null, - [switch] $NoNative = $false, - [parameter(Position=1, ValueFromRemainingArguments=$true)] - [string[]]$Args=@(), - [switch] $Quiet, - [string] $OutputVariable, - [switch] $AssumeElevated -) - -# Constants -Set-Variable -Option Constant "BuildNumber" "10319" -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; -$defaultArch="x86" -$selectedRuntime=$null -$defaultRuntime="clr" - -function getenv($name) { - if(Test-Path "env:\$name") { - cat "env:\$name" - } -} - -# Get or calculate userHome -$userHome = (getenv $UserHomeEnvVar) -if(!$userHome) { $userHome = $env:USERPROFILE + "\$RuntimeFolderName" } -$userRuntimesPath = $userHome + "\runtimes" - -# 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 -$useHostOutputMethods = $true - -function String-IsEmptyOrWhitespace([string]$str) { - return [string]::IsNullOrEmpty($str) -or $str.Trim().length -eq 0 -} - -$scriptPath = $myInvocation.MyCommand.Definition - -function _Help { -@" -$VersionManagerName - Build $BuildNumber - -USAGE: $CommandName [options] - -$CommandName upgrade [-X86|-X64] [-r|-Runtime CLR|CoreCLR] [-g|-Global] [-f|-Force] [-Proxy
] [-NoNative] - install latest $RuntimeShortName from feed - set 'default' alias to installed version - add $RuntimeShortName bin to user PATH environment variable - -g|-Global install to machine-wide location - -f|-Force upgrade even if latest is already installed - -Proxy
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) - -$CommandName install |||latest [-X86|-X64] [-r|-Runtime CLR|CoreCLR] [-a|-Alias ] [-f|-Force] [-Proxy
] [-NoNative] - | install requested $RuntimeShortName from feed - install requested $RuntimeShortName from package on local filesystem - latest install latest $RuntimeShortName from feed - add $RuntimeShortName bin to path of current command line - -p|-Persistent add $RuntimeShortName bin to PATH environment variables persistently - -a|-Alias set alias for requested $RuntimeShortName on install - -f|-Force install even if specified version is already installed - -Proxy
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) - -$CommandName use |||none [-X86|-X64] [-r|-Runtime CLR|CoreCLR] [-p|-Persistent] - || add $RuntimeShortName bin to path of current command line - none remove $RuntimeShortName bin from path of current command line - -p|-Persistent add $RuntimeShortName bin to PATH environment variable across all processes run by the current user - -$CommandName list - list $RuntimeShortName versions installed - -$CommandName alias - list $RuntimeShortName aliases which have been defined - -$CommandName alias - display value of the specified alias - -$CommandName alias || [-X86|-X64] [-r|-Runtime CLR|CoreCLR] - the name of the alias to set - || the $RuntimeShortName version to set the alias to. Alternatively use the version of the specified alias - -$CommandName unalias - remove the specified alias - -"@ -replace "`n","`r`n" | Console-Write -} - -function _Global-Setup { - # 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) - { - $arguments = "-ExecutionPolicy unrestricted & '$scriptPath' setup -wait" - Start-Process "$psHome\powershell.exe" -Verb runAs -ArgumentList $arguments -Wait - Console-Write "Adding $cmdBinPath to process PATH" - Set-Path (Change-Path $env:Path $cmdBinPath ($cmdBinPath)) - Console-Write "Adding %USERPROFILE%\$RuntimeFolderName to process $HomeEnvVar" - $envRuntimeHome = (getenv $HomeEnvVar) - $envRuntimeHome = Change-Path $envRuntimeHome "%USERPROFILE%\$RuntimeFolderName" ("%USERPROFILE%\$RuntimeFolderName") - Set-Content "env:\$HomeEnvVar" $envRuntimeHome - Console-Write "Setup complete" - break - } - - $scriptFolder = [System.IO.Path]::GetDirectoryName($scriptPath) - - Console-Write "Copying file $cmdBinPath\$CommandName.ps1" - md $cmdBinPath -Force | Out-Null - copy "$scriptFolder\$CommandName.ps1" "$cmdBinPath\$CommandName.ps1" - - Console-Write "Copying file $cmdBinPath\$CommandName.cmd" - copy "$scriptFolder\$CommandName.cmd" "$cmdBinPath\$CommandName.cmd" - - Console-Write "Adding $cmdBinPath to process PATH" - Set-Path (Change-Path $env:Path $cmdBinPath ($cmdBinPath)) - - Console-Write "Adding $cmdBinPath to user PATH" - $userPath = [Environment]::GetEnvironmentVariable("Path", [System.EnvironmentVariableTarget]::User) - $userPath = Change-Path $userPath $cmdBinPath ($cmdBinPath) - [Environment]::SetEnvironmentVariable("Path", $userPath, [System.EnvironmentVariableTarget]::User) - - Console-Write "Adding %USERPROFILE%\$RuntimeFolderName to process $HomeEnvVar" - $envRuntimeHome = (getenv $HomeEnvVar) - $envRuntimeHome = Change-Path $envRuntimeHome "%USERPROFILE%\$RuntimeFolderName" ("%USERPROFILE%\$RuntimeFolderName") - Set-Content "env:\$HomeEnvVar" $envRuntimeHome - - Console-Write "Adding %USERPROFILE%\$RuntimeFolderName to machine $HomeEnvVar" - $machineruntimeHome = [Environment]::GetEnvironmentVariable($HomeEnvVar, [System.EnvironmentVariableTarget]::Machine) - $machineruntimeHome = Change-Path $machineruntimeHome "%USERPROFILE%\$RuntimeFolderName" ("%USERPROFILE%\$RuntimeFolderName") - [Environment]::SetEnvironmentVariable($HomeEnvVar, $machineruntimeHome, [System.EnvironmentVariableTarget]::Machine) -} - -function _Upgrade { -param( - [boolean] $isGlobal -) - $Persistent = $true - $Alias="default" - _Install "latest" $isGlobal -} - -function Add-Proxy-If-Specified { -param( - [System.Net.WebClient] $wc -) - if (!$Proxy) { - $Proxy = $env:http_proxy - } - if ($Proxy) { - $wp = New-Object System.Net.WebProxy($Proxy) - $pb = New-Object UriBuilder($Proxy) - if (!$pb.UserName) { - $wp.Credentials = [System.Net.CredentialCache]::DefaultCredentials - } else { - $wp.Credentials = New-Object System.Net.NetworkCredential($pb.UserName, $pb.Password) - } - $wc.Proxy = $wp - } -} - -function _Find-Latest { -param( - [string] $platform, - [string] $architecture -) - Console-Write "Determining latest version" - - $url = "$feed/GetUpdates()?packageIds=%27$RuntimePackageName-$platform-win-$architecture%27&versions=%270.0%27&includePrerelease=true&includeAllVersions=false" - - $wc = New-Object System.Net.WebClient - Add-Proxy-If-Specified($wc) - Write-Verbose "Downloading $url ..." - [xml]$xml = $wc.DownloadString($url) - - $version = Select-Xml "//d:Version" -Namespace @{d='http://schemas.microsoft.com/ado/2007/08/dataservices'} $xml - - if (String-IsEmptyOrWhitespace($version)) { - throw "There are no runtimes for platform '$platform', architecture '$architecture' in the feed '$feed'" - } - - return $version -} - -function Do-Download { -param( - [string] $runtimeFullName, - [string] $runtimesFolder -) - $parts = $runtimeFullName.Split(".", 2) - - $url = "$feed/package/" + $parts[0] + "/" + $parts[1] - $runtimeFolder = Join-Path $runtimesFolder $runtimeFullName - $runtimeFile = Join-Path $runtimeFolder "$runtimeFullName.nupkg" - - If (Test-Path $runtimeFolder) { - if($Force) - { - rm $runtimeFolder -Recurse -Force - } else { - Console-Write "$runtimeFullName already installed." - return; - } - } - - Console-Write "Downloading $runtimeFullName from $feed" - - #Downloading to temp location - $runtimeTempDownload = Join-Path $runtimesFolder "temp" - $tempDownloadFile = Join-Path $runtimeTempDownload "$runtimeFullName.nupkg" - - if(Test-Path $runtimeTempDownload) { - del "$runtimeTempDownload\*" -recurse - } else { - md $runtimeTempDownload -Force | Out-Null - } - - $wc = New-Object System.Net.WebClient - Add-Proxy-If-Specified($wc) - Write-Verbose "Downloading $url ..." - $wc.DownloadFile($url, $tempDownloadFile) - - Do-Unpack $tempDownloadFile $runtimeTempDownload - - md $runtimeFolder -Force | Out-Null - Console-Write "Installing to $runtimeFolder" - mv "$runtimeTempDownload\*" $runtimeFolder - Remove-Item "$runtimeTempDownload" -Force | Out-Null -} - -function Do-Unpack { -param( - [string] $runtimeFile, - [string] $runtimeFolder -) - Console-Write "Unpacking to $runtimeFolder" - - $compressionLib = [System.Reflection.Assembly]::LoadWithPartialName('System.IO.Compression.FileSystem') - - if($compressionLib -eq $null) { - try { - # Shell will not recognize nupkg as a zip and throw, so rename it to zip - $runtimeZip = [System.IO.Path]::ChangeExtension($runtimeFile, "zip") - Rename-Item $runtimeFile $runtimeZip - # Use the shell to uncompress the nupkg - $shell_app=new-object -com shell.application - $zip_file = $shell_app.namespace($runtimeZip) - $destination = $shell_app.namespace($runtimeFolder) - $destination.Copyhere($zip_file.items(), 0x14) #0x4 = don't show UI, 0x10 = overwrite files - } - finally { - # make it a nupkg again - Rename-Item $runtimeZip $runtimeFile - } - } else { - [System.IO.Compression.ZipFile]::ExtractToDirectory($runtimeFile, $runtimeFolder) - } - - If (Test-Path ($runtimeFolder + "\[Content_Types].xml")) { - Remove-Item ($runtimeFolder + "\[Content_Types].xml") - } - If (Test-Path ($runtimeFolder + "\_rels\")) { - Remove-Item ($runtimeFolder + "\_rels\") -Force -Recurse - } - If (Test-Path ($runtimeFolder + "\package\")) { - Remove-Item ($runtimeFolder + "\package\") -Force -Recurse - } - - # Clean up the package file itself. - Remove-Item $runtimeFile -Force -} - -function _Install { -param( - [string] $versionOrAlias, - [boolean] $isGlobal -) - if ($versionOrAlias -eq "latest") { - $versionOrAlias = _Find-Latest (Requested-Platform $defaultRuntime) (Requested-Architecture $defaultArch) - } - - if ($versionOrAlias.EndsWith(".nupkg")) { - $runtimeFullName = [System.IO.Path]::GetFileNameWithoutExtension($versionOrAlias) - } else { - $runtimeFullName = Requested-VersionOrAlias $versionOrAlias - } - - $packageFolder = $userRuntimesPath - - if ($versionOrAlias.EndsWith(".nupkg")) { - Set-Variable -Name "selectedArch" -Value (Package-Arch $runtimeFullName) -Scope Script - Set-Variable -Name "selectedRuntime" -Value (Package-Platform $runtimeFullName) -Scope Script - - $runtimeFolder = "$packageFolder\$runtimeFullName" - $folderExists = Test-Path $runtimeFolder - - if ($folderExists -and $Force) { - del $runtimeFolder -Recurse -Force - $folderExists = $false; - } - - if ($folderExists) { - Console-Write "Target folder '$runtimeFolder' already exists" - } else { - $tempUnpackFolder = Join-Path $packageFolder "temp" - $tempDownloadFile = Join-Path $tempUnpackFolder "$runtimeFullName.nupkg" - - if(Test-Path $tempUnpackFolder) { - del "$tempUnpackFolder\*" -recurse - } else { - md $tempUnpackFolder -Force | Out-Null - } - copy $versionOrAlias $tempDownloadFile - - Do-Unpack $tempDownloadFile $tempUnpackFolder - md $runtimeFolder -Force | Out-Null - Console-Write "Installing to $runtimeFolder" - mv "$tempUnpackFolder\*" $runtimeFolder - Remove-Item "$tempUnpackFolder" -Force | Out-Null - } - - $packageVersion = Package-Version $runtimeFullName - - _Use $packageVersion - if (!$(String-IsEmptyOrWhitespace($Alias))) { - _Alias-Set $Alias $packageVersion - } - } - else - { - Do-Download $runtimeFullName $packageFolder - _Use $versionOrAlias - if (!$(String-IsEmptyOrWhitespace($Alias))) { - _Alias-Set "$Alias" $versionOrAlias - } - } - - if ($runtimeFullName.Contains("CoreCLR")) { - if ($NoNative) { - Console-Write "Native image generation is skipped" - } - else { - Console-Write "Compiling native images for $runtimeFullName to improve startup performance..." - Start-Process $CrossGenCommand -Wait - Console-Write "Finished native image compilation." - } - } -} - -function _List { - $runtimeHome = (getenv $HomeEnvVar) - if (!$runtimeHome) { - $runtimeHome = "$userHome" - } - - md ($userHome + "\alias\") -Force | Out-Null - $aliases = Get-ChildItem ($userHome + "\alias\") | Select @{label='Alias';expression={$_.BaseName}}, @{label='Name';expression={Get-Content $_.FullName }} - - $items = @() - foreach($portion in $runtimeHome.Split(';')) { - $path = [System.Environment]::ExpandEnvironmentVariables($portion) - if (Test-Path("$path\runtimes")) { - $items += Get-ChildItem ("$path\runtimes\$RuntimePackageName-*") | List-Parts $aliases - } - } - - $items | Sort-Object Version, Runtime, Architecture, Alias | Format-Table -AutoSize -Property @{name="Active";expression={$_.Active};alignment="center"}, "Version", "Runtime", "Architecture", "Location", "Alias" -} - -filter List-Parts { - param($aliases) - - $hasBin = Test-Path($_.FullName+"\bin") - if (!$hasBin) { - return - } - $active = $false - foreach($portion in $env:Path.Split(';')) { - # Append \ to the end because otherwise you might see - # multiple active versions if the folders have the same - # name prefix (like 1.0-beta and 1.0) - if ($portion.StartsWith($_.FullName + "\")) { - $active = $true - } - } - - $fullAlias="" - $delim="" - - foreach($alias in $aliases){ - if($_.Name.Split('\', 2) -contains $alias.Name){ - $fullAlias += $delim + $alias.Alias - $delim = ", " - } - } - - $parts1 = $_.Name.Split('.', 2) - $parts2 = $parts1[0].Split('-', 4) - return New-Object PSObject -Property @{ - Active = if ($active) { "*" } else { "" } - Version = $parts1[1] - Runtime = $parts2[1] - OperatingSystem = $parts2[2] - Architecture = $parts2[3] - Location = $_.Parent.FullName - Alias = $fullAlias - } -} - -function _Use { -param( - [string] $versionOrAlias -) - Validate-Full-Package-Name-Arguments-Combination $versionOrAlias - - if ($versionOrAlias -eq "none") { - Console-Write "Removing $RuntimeShortName from process PATH" - Set-Path (Change-Path $env:Path "" ($userRuntimesPath)) - - if ($Persistent) { - Console-Write "Removing $RuntimeShortName from user PATH" - $userPath = [Environment]::GetEnvironmentVariable("Path", [System.EnvironmentVariableTarget]::User) - $userPath = Change-Path $userPath "" ($userRuntimesPath) - [Environment]::SetEnvironmentVariable("Path", $userPath, [System.EnvironmentVariableTarget]::User) - } - return; - } - - $runtimeFullName = Requested-VersionOrAlias $versionOrAlias - - $runtimeBin = Locate-RuntimeBinFromFullName $runtimeFullName - if ($runtimeBin -eq $null) { - throw "Cannot find $runtimeFullName, do you need to run '$CommandName install $versionOrAlias'?" - } - - Console-Write "Adding $runtimeBin to process PATH" - Set-Path (Change-Path $env:Path $runtimeBin ($userRuntimesPath)) - - if ($Persistent) { - Console-Write "Adding $runtimeBin to user PATH" - $userPath = [Environment]::GetEnvironmentVariable("Path", [System.EnvironmentVariableTarget]::User) - $userPath = Change-Path $userPath $runtimeBin ($userRuntimesPath) - [Environment]::SetEnvironmentVariable("Path", $userPath, [System.EnvironmentVariableTarget]::User) - } -} - -function _Alias-List { - md ($userHome + "\alias\") -Force | Out-Null - - Get-ChildItem ($userHome + "\alias\") | Select @{label='Alias';expression={$_.BaseName}}, @{label='Name';expression={Get-Content $_.FullName }} | Format-Table -AutoSize -} - -function _Alias-Get { -param( - [string] $name -) - md ($userHome + "\alias\") -Force | Out-Null - $aliasFilePath=$userHome + "\alias\" + $name + ".txt" - if (!(Test-Path $aliasFilePath)) { - Console-Write "Alias '$name' does not exist" - $script:exitCode = 1 # Return non-zero exit code for scripting - } else { - $aliasValue = (Get-Content ($userHome + "\alias\" + $name + ".txt")) - Console-Write "Alias '$name' is set to $aliasValue" - } -} - -function _Alias-Set { -param( - [string] $name, - [string] $value -) - $runtimeFullName = Requested-VersionOrAlias $value - $aliasFilePath = $userHome + "\alias\" + $name + ".txt" - $action = if (Test-Path $aliasFilePath) { "Updating" } else { "Setting" } - Console-Write "$action alias '$name' to '$runtimeFullName'" - md ($userHome + "\alias\") -Force | Out-Null - $runtimeFullName | Out-File ($aliasFilePath) ascii -} - -function _Unalias { -param( - [string] $name -) - $aliasPath=$userHome + "\alias\" + $name + ".txt" - if (Test-Path -literalPath "$aliasPath") { - Console-Write "Removing alias $name" - Remove-Item -literalPath $aliasPath - } else { - Console-Write "Cannot remove alias, '$name' is not a valid alias name" - $script:exitCode = 1 # Return non-zero exit code for scripting - } -} - -function Locate-RuntimeBinFromFullName() { -param( - [string] $runtimeFullName -) - $runtimeHome = (getenv $HomeEnvVar) - if (!$runtimeHome) { - $runtimeHome = $userHome - } - foreach($portion in $runtimeHome.Split(';')) { - $path = [System.Environment]::ExpandEnvironmentVariables($portion) - $runtimeBin = "$path\runtimes\$runtimeFullName\bin" - if (Test-Path "$runtimeBin") { - return $runtimeBin - } - } - return $null -} - -function Package-Version() { -param( - [string] $runtimeFullName -) - return $runtimeFullName -replace '[^.]*.(.*)', '$1' -} - -function Package-Platform() { -param( - [string] $runtimeFullName -) - return $runtimeFullName -replace "$RuntimePackageName-([^-]*).*", '$1' -} - -function Package-Arch() { -param( - [string] $runtimeFullName -) - return $runtimeFullName -replace "$RuntimePackageName-[^-]*-[^-]*-([^.]*).*", '$1' -} - - -function Requested-VersionOrAlias() { -param( - [string] $versionOrAlias -) - Validate-Full-Package-Name-Arguments-Combination $versionOrAlias - - $runtimeBin = Locate-RuntimeBinFromFullName $versionOrAlias - - # If the name specified is an existing package, just use it as is - if ($runtimeBin -ne $null) { - return $versionOrAlias - } - - If (Test-Path ($userHome + "\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) - $pkgVersion = $parts[1] - # runtime-coreclr-win-x86 - $parts = $parts[0].Split('-', 4) - $pkgPlatform = Requested-Platform $parts[1] - $pkgArchitecture = Requested-Architecture $parts[3] - } else { - $pkgVersion = $versionOrAlias - $pkgPlatform = Requested-Platform $defaultRuntime - $pkgArchitecture = Requested-Architecture $defaultArch - } - return $RuntimePackageName + "-" + $pkgPlatform + "-win-" + $pkgArchitecture + "." + $pkgVersion -} - -function Requested-Platform() { -param( - [string] $default -) - if (!(String-IsEmptyOrWhitespace($selectedRuntime))) {return $selectedRuntime} - return $default -} - -function Requested-Architecture() { -param( - [string] $default -) - if (!(String-IsEmptyOrWhitespace($selectedArch))) {return $selectedArch} - return $default -} - -function Change-Path() { -param( - [string] $existingPaths, - [string] $prependPath, - [string[]] $removePaths -) - $newPath = $prependPath - foreach($portion in $existingPaths.Split(';')) { - $skip = $portion -eq "" - foreach($removePath in $removePaths) { - if ($removePath -and ($portion.StartsWith($removePath))) { - $skip = $true - } - } - if (!$skip) { - $newPath = $newPath + ";" + $portion - } - } - return $newPath -} - -function Set-Path() { -param( - [string] $newPath -) - md $userHome -Force | Out-Null - $env:Path = $newPath -@" -SET "PATH=$newPath" -"@ | Out-File ($userHome + "\temp-set-envvars.cmd") ascii -} - -function Needs-Elevation() { - if($AssumeElevated) { - return $false - } - - $user = [Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent() - $elevated = $user.IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator") - return -NOT $elevated -} - -function Requested-Switches() { - $arguments = "" - if ($X86) {$arguments = "$arguments -x86"} - if ($X64) {$arguments = "$arguments -x64"} - if ($selectedRuntime) {$arguments = "$arguments -runtime $selectedRuntime"} - if ($Persistent) {$arguments = "$arguments -persistent"} - if ($Force) {$arguments = "$arguments -force"} - if (!$(String-IsEmptyOrWhitespace($Alias))) {$arguments = "$arguments -alias '$Alias'"} - return $arguments -} - -function Validate-And-Santitize-Switches() -{ - if ($X86 -and $X64) {throw "You cannot select both x86 and x64 architectures"} - - if ($Runtime) { - $validRuntimes = "CoreCLR", "CLR" - $match = $validRuntimes | ? { $_ -like $Runtime } | Select -First 1 - if (!$match) {throw "'$runtime' is not a valid runtime"} - Set-Variable -Name "selectedRuntime" -Value $match.ToLowerInvariant() -Scope Script - } - - if($Architecture) { - $validArchitectures = "x64", "x86" - $match = $validArchitectures | ? { $_ -like $Architecture } | Select -First 1 - if(!$match) {throw "'$architecture' is not a valid architecture"} - Set-Variable -Name "selectedArch" -Value $match.ToLowerInvariant() -Scope Script - } - else { - if ($X64) { - Set-Variable -Name "selectedArch" -Value "x64" -Scope Script - } elseif ($X86) { - Set-Variable -Name "selectedArch" -Value "x86" -Scope Script - } - } - -} - -$script:capturedOut = @() -function Console-Write() { -param( - [Parameter(ValueFromPipeline=$true)] - [string] $message -) - if($OutputVariable) { - # Update the capture output - $script:capturedOut += @($message) - } - - if(!$Quiet) { - if ($useHostOutputMethods) { - try { - Write-Host $message - } - catch { - $script:useHostOutputMethods = $false - Console-Write $message - } - } - else { - [Console]::WriteLine($message) - } - } -} - -function Console-Write-Error() { -param( - [Parameter(ValueFromPipeline=$true)] - [string] $message -) - if ($useHostOutputMethods) { - try { - Write-Error $message - } - catch { - $script:useHostOutputMethods = $false - Console-Write-Error $message - } - } - else { - [Console]::Error.WriteLine($message) - } -} - -function Validate-Full-Package-Name-Arguments-Combination() { -param( - [string] $versionOrAlias -) - if ($versionOrAlias -like "$RuntimePackageName-*" -and - ($selectedArch -or $selectedRuntime)) { - throw "Runtime or architecture cannot be specified when using the full package name." - } -} - -$script:exitCode = 0 -try { - Validate-And-Santitize-Switches - switch -wildcard ($Command + " " + $Args.Count) { - "setup 0" {_Global-Setup} - "upgrade 0" {_Upgrade $false} - "install 1" {_Install $Args[0] $false} - "list 0" {_List} - "use 1" {_Use $Args[0]} - "alias 0" {_Alias-List} - "alias 1" {_Alias-Get $Args[0]} - "alias 2" {_Alias-Set $Args[0] $Args[1]} - "unalias 1" {_Unalias $Args[0]} - "help 0" {_Help} - " 0" {_Help} - default {throw "Unknown command"}; - } -} -catch { - Console-Write-Error $_ - Console-Write "Type '$CommandName help' for help on how to use $CommandName." - $script:exitCode = -1 -} -if ($Wait) { - Console-Write "Press any key to continue ..." - $x = $host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown,AllowCtrlC") -} - -# If the user specified an output variable, push the value up to the parent scope -if($OutputVariable) { - Set-Variable $OutputVariable $script:capturedOut -Scope 1 -} - -exit $script:exitCode diff --git a/build/kvm.sh b/build/kvm.sh deleted file mode 100644 index bf770d07ca..0000000000 --- a/build/kvm.sh +++ /dev/null @@ -1,432 +0,0 @@ -# kvm.sh -# Source this file from your .bash-profile or script to use - -# "Constants" -_KVM_BUILDNUMBER="10319" -_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/aspnetrelease/api/v2" -_KVM_HOME_VAR_NAME="KRE_HOME" - -__kvm_has() { - type "$1" > /dev/null 2>&1 - return $? -} - -if __kvm_has "unsetopt"; then - unsetopt nomatch 2>/dev/null -fi - -if [ -z "$KVM_USER_HOME" ]; then - eval KVM_USER_HOME="~/$_KVM_RUNTIME_FOLDER_NAME" -fi - -_KVM_USER_PACKAGES="$KVM_USER_HOME/runtimes" -_KVM_ALIAS_DIR="$KVM_USER_HOME/alias" - -if [ -z "$KRE_FEED" ]; then - KRE_FEED="$_KVM_DEFAULT_FEED" -fi - -__kvm_find_latest() { - local platform="mono" - - if ! __kvm_has "curl"; then - echo "$_KVM_COMMAND_NAME needs curl to proceed." >&2; - return 1 - fi - - 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)" - echo $xml | grep \<[a-zA-Z]:Version\>* >> /dev/null || return 1 - version="$(echo $xml | sed 's/.*<[a-zA-Z]:Version>\([^<]*\).*/\1/')" - echo $version -} - -__kvm_strip_path() { - 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() { - if [ -z "$1" ]; then - echo "$2" - else - echo "$2:$1" - fi -} - -__kvm_package_version() { - local runtimeFullName="$1" - echo "$runtimeFullName" | sed "s/[^.]*.\(.*\)/\1/" -} - -__kvm_package_name() { - local runtimeFullName="$1" - echo "$runtimeFullName" | sed "s/\([^.]*\).*/\1/" -} - -__kvm_package_runtime() { - local runtimeFullName="$1" - echo "$runtimeFullName" | sed "s/$_KVM_RUNTIME_PACKAGE_NAME-\([^.-]*\).*/\1/" -} - -__kvm_download() { - local runtimeFullName="$1" - local runtimeFolder="$2" - - local pkgName=$(__kvm_package_name "$runtimeFullName") - local pkgVersion=$(__kvm_package_version "$runtimeFullName") - local url="$KRE_FEED/package/$pkgName/$pkgVersion" - local runtimeFile="$runtimeFolder/$runtimeFullName.nupkg" - - if [ -e "$runtimeFolder" ]; then - echo "$runtimeFullName already installed." - return 0 - fi - - echo "Downloading $runtimeFullName from $KRE_FEED" - - if ! __kvm_has "curl"; then - echo "$_KVM_COMMAND_NAME needs curl to proceed." >&2; - return 1 - fi - - mkdir -p "$runtimeFolder" > /dev/null 2>&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 "$runtimeFullName was not found in repository $KRE_FEED" && return 1 - [[ $httpResult != "302" && $httpResult != "200" ]] && echo "HTTP Error $httpResult fetching $runtimeFullName from $KRE_FEED" && return 1 - - __kvm_unpack $runtimeFile $runtimeFolder - return $? -} - -__kvm_unpack() { - local runtimeFile="$1" - local runtimeFolder="$2" - - echo "Installing to $runtimeFolder" - - if ! __kvm_has "unzip"; then - echo "$_KVM_COMMAND_NAME needs unzip to proceed." >&2; - return 1 - fi - - unzip $runtimeFile -d $runtimeFolder > /dev/null 2>&1 - - [ -e "$runtimeFolder/[Content_Types].xml" ] && rm "$runtimeFolder/[Content_Types].xml" - - [ -e "$runtimeFolder/_rels/" ] && rm -rf "$runtimeFolder/_rels/" - - [ -e "$runtimeFolder/package/" ] && rm -rf "$runtimeFolder/_package/" - - [ -e "$runtimeFile" ] && rm -f "$runtimeFile" - - #Set shell commands as executable - find "$runtimeFolder/bin/" -type f \ - -exec sh -c "head -c 11 {} | grep '/bin/bash' > /dev/null" \; -print | xargs chmod 775 -} - -__kvm_requested_version_or_alias() { - local versionOrAlias="$1" - local runtimeBin=$(__kvm_locate_runtime_bin_from_full_name "$versionOrAlias") - - # If the name specified is an existing package, just use it as is - if [ -n "$runtimeBin" ]; then - echo "$versionOrAlias" - else - if [ -e "$_KVM_ALIAS_DIR/$versionOrAlias.alias" ]; then - local runtimeFullName=$(cat "$_KVM_ALIAS_DIR/$versionOrAlias.alias") - local pkgName=$(echo $runtimeFullName | sed "s/\([^.]*\).*/\1/") - local pkgVersion=$(echo $runtimeFullName | sed "s/[^.]*.\(.*\)/\1/") - local pkgPlatform=$(echo "$pkgName" | sed "s/kre-\([^.-]*\).*/\1/") - else - local pkgVersion=$versionOrAlias - local pkgPlatform="mono" - fi - - echo "$_KVM_RUNTIME_PACKAGE_NAME-$pkgPlatform.$pkgVersion" - fi -} - -# This will be more relevant if we support global installs -__kvm_locate_runtime_bin_from_full_name() { - local runtimeFullName=$1 - [ -e "$_KVM_USER_PACKAGES/$runtimeFullName/bin" ] && echo "$_KVM_USER_PACKAGES/$runtimeFullName/bin" && return -} - -kvm() -{ - if [ $# -lt 1 ]; then - $_KVM_COMMAND_NAME help - return - fi - - case $1 in - "help" ) - echo "" - echo "$_KVM_VERSION_MANAGER_NAME - Build $_KVM_BUILDNUMBER" - echo "" - echo "USAGE: $_KVM_COMMAND_NAME [options]" - echo "" - echo "$_KVM_COMMAND_NAME upgrade" - echo "install latest $_KVM_RUNTIME_SHORT_NAME from feed" - echo "add $_KVM_RUNTIME_SHORT_NAME bin to path of current command line" - echo "set installed version as default" - echo "" - echo "$_KVM_COMMAND_NAME install |||latest [-a|-alias ] [-p -persistent]" - echo "| install requested $_KVM_RUNTIME_SHORT_NAME from feed" - echo " install requested $_KVM_RUNTIME_SHORT_NAME from local package on filesystem" - echo "latest install latest version of $_KVM_RUNTIME_SHORT_NAME from feed" - echo "-a|-alias set alias for requested $_KVM_RUNTIME_SHORT_NAME on install" - echo "-p -persistent set installed version as default" - echo "add $_KVM_RUNTIME_SHORT_NAME bin to path of current command line" - echo "" - echo "$_KVM_COMMAND_NAME use |||none [-p -persistent]" - echo "|| add $_KVM_RUNTIME_SHORT_NAME bin to 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 "" - echo "$_KVM_COMMAND_NAME list" - echo "list $_KVM_RUNTIME_SHORT_NAME versions installed " - echo "" - echo "$_KVM_COMMAND_NAME alias" - echo "list $_KVM_RUNTIME_SHORT_NAME aliases which have been defined" - echo "" - echo "$_KVM_COMMAND_NAME alias " - echo "display value of the specified alias" - echo "" - echo "$_KVM_COMMAND_NAME alias ||" - echo " the name of the alias to set" - echo "|| the $_KVM_RUNTIME_SHORT_NAME version to set the alias to. Alternatively use the version of the specified alias" - echo "" - echo "$_KVM_COMMAND_NAME unalias " - echo "remove the specified alias" - echo "" - ;; - - "upgrade" ) - [ $# -ne 1 ] && kvm help && return - $_KVM_COMMAND_NAME install latest -p - ;; - - "install" ) - [ $# -lt 2 ] && kvm help && return - shift - local persistent= - local versionOrAlias= - local alias= - while [ $# -ne 0 ] - do - if [[ $1 == "-p" || $1 == "-persistent" ]]; then - local persistent="-p" - elif [[ $1 == "-a" || $1 == "-alias" ]]; then - local alias=$2 - shift - elif [[ -n $1 ]]; then - [[ -n $versionOrAlias ]] && echo "Invalid option $1" && kvm help && return 1 - local versionOrAlias=$1 - fi - shift - done - if [[ "$versionOrAlias" == "latest" ]]; then - echo "Determining latest version" - versionOrAlias=$(__kvm_find_latest) - [[ $? == 1 ]] && echo "Error: Could not find latest version from feed $KRE_FEED" && return 1 - echo "Latest version is $versionOrAlias" - fi - if [[ "$versionOrAlias" == *.nupkg ]]; then - local runtimeFullName=$(basename $versionOrAlias | sed "s/\(.*\)\.nupkg/\1/") - local runtimeVersion=$(__kvm_package_version "$runtimeFullName") - local runtimeFolder="$_KVM_USER_PACKAGES/$runtimeFullName" - local runtimeFile="$runtimeFolder/$runtimeFullName.nupkg" - - if [ -e "$runtimeFolder" ]; then - echo "$runtimeFullName already installed" - else - mkdir "$runtimeFolder" > /dev/null 2>&1 - cp -a "$versionOrAlias" "$runtimeFile" - __kvm_unpack "$runtimeFile" "$runtimeFolder" - [[ $? == 1 ]] && return 1 - fi - $_KVM_COMMAND_NAME use "$runtimeVersion" "$persistent" - [[ -n $alias ]] && kvm alias "$alias" "$runtimeVersion" - else - local runtimeFullName="$(__kvm_requested_version_or_alias $versionOrAlias)" - local runtimeFolder="$_KVM_USER_PACKAGES/$runtimeFullName" - __kvm_download "$runtimeFullName" "$runtimeFolder" - [[ $? == 1 ]] && return 1 - $_KVM_COMMAND_NAME use "$versionOrAlias" "$persistent" - [[ -n $alias ]] && kvm alias "$alias" "$versionOrAlias" - fi - ;; - - "use" ) - [ $# -gt 3 ] && $_KVM_COMMAND_NAME help && return - [ $# -lt 2 ] && $_KVM_COMMAND_NAME help && return - - shift - local persistent= - while [ $# -ne 0 ] - do - if [[ $1 == "-p" || $1 == "-persistent" ]]; then - local persistent="true" - elif [[ -n $1 ]]; then - local versionOrAlias=$1 - fi - shift - done - - if [[ $versionOrAlias == "none" ]]; then - echo "Removing $_KVM_RUNTIME_SHORT_NAME from process PATH" - # Strip other version from PATH - PATH=$(__kvm_strip_path "$PATH" "/bin") - - if [[ -n $persistent && -e "$_KVM_ALIAS_DIR/default.alias" ]]; then - echo "Setting default $_KVM_RUNTIME_SHORT_NAME to none" - rm "$_KVM_ALIAS_DIR/default.alias" - fi - return 0 - fi - - local runtimeFullName=$(__kvm_requested_version_or_alias "$versionOrAlias") - local runtimeBin=$(__kvm_locate_runtime_bin_from_full_name "$runtimeFullName") - - if [[ -z $runtimeBin ]]; then - echo "Cannot find $runtimeFullName, do you need to run '$_KVM_COMMAND_NAME install $versionOrAlias'?" - return 1 - fi - - echo "Adding" $runtimeBin "to process PATH" - - PATH=$(__kvm_strip_path "$PATH" "/bin") - PATH=$(__kvm_prepend_path "$PATH" "$runtimeBin") - - if [[ -n $persistent ]]; then - local runtimeVersion=$(__kvm_package_version "$runtimeFullName") - $_KVM_COMMAND_NAME alias default "$runtimeVersion" - fi - ;; - - "alias" ) - [[ $# -gt 3 ]] && kvm help && return - - [[ ! -e "$_KVM_ALIAS_DIR/" ]] && mkdir "$_KVM_ALIAS_DIR/" > /dev/null - - if [[ $# == 1 ]]; then - echo "" - local format="%-20s %s\n" - printf "$format" "Alias" "Name" - printf "$format" "-----" "----" - if [ -d "$_KVM_ALIAS_DIR" ]; then - for __kvm_file in $(find "$_KVM_ALIAS_DIR" -name *.alias); do - local alias="$(basename $__kvm_file | sed 's/\.alias//')" - local name="$(cat $__kvm_file)" - printf "$format" "$alias" "$name" - done - fi - echo "" - return - fi - - local name="$2" - - if [[ $# == 2 ]]; then - [[ ! -e "$_KVM_ALIAS_DIR/$name.alias" ]] && echo "There is no alias called '$name'" && return - cat "$_KVM_ALIAS_DIR/$name.alias" - echo "" - return - fi - - local runtimeFullName=$(__kvm_requested_version_or_alias "$3") - - [[ ! -d "$_KVM_USER_PACKAGES/$runtimeFullName" ]] && echo "$runtimeFullName is not an installed $_KVM_RUNTIME_SHORT_NAME version" && return 1 - - local action="Setting" - [[ -e "$_KVM_ALIAS_DIR/$name.alias" ]] && action="Updating" - echo "$action alias '$name' to '$runtimeFullName'" - echo "$runtimeFullName" > "$_KVM_ALIAS_DIR/$name.alias" - ;; - - "unalias" ) - [[ $# -ne 2 ]] && kvm help && return - - local name=$2 - local aliasPath="$_KVM_ALIAS_DIR/$name.alias" - [[ ! -e "$aliasPath" ]] && echo "Cannot remove alias, '$name' is not a valid alias name" && return 1 - echo "Removing alias $name" - rm "$aliasPath" >> /dev/null 2>&1 - ;; - - "list" ) - [[ $# -gt 2 ]] && kvm help && return - - [[ ! -d $_KVM_USER_PACKAGES ]] && echo "$_KVM_RUNTIME_FRIENDLY_NAME is not installed." && return 1 - - local searchGlob="$_KVM_RUNTIME_PACKAGE_NAME-*" - if [ $# == 2 ]; then - local versionOrAlias=$2 - local searchGlob=$(__kvm_requested_version_or_alias "$versionOrAlias") - fi - echo "" - - # Separate empty array declaration from initialization - # to avoid potential ZSH error: local:217: maximum nested function level reached - local arr - arr=() - - # Z shell array-index starts at one. - local i=1 - local format="%-20s %s\n" - if [ -d "$_KVM_ALIAS_DIR" ]; then - for __kvm_file in $(find "$_KVM_ALIAS_DIR" -name *.alias); do - arr[$i]="$(basename $__kvm_file | sed 's/\.alias//')/$(cat $__kvm_file)" - let i+=1 - done - fi - - local formatString="%-6s %-20s %-7s %-20s %s\n" - printf "$formatString" "Active" "Version" "Runtime" "Location" "Alias" - printf "$formatString" "------" "-------" "-------" "--------" "-----" - - local formattedHome=`(echo $_KVM_USER_PACKAGES | sed s=$HOME=~=g)` - for f in $(find $_KVM_USER_PACKAGES -name "$searchGlob" \( -type d -or -type l \) -prune -exec basename {} \;); do - local active="" - [[ $PATH == *"$_KVM_USER_PACKAGES/$f/bin"* ]] && local active=" *" - local pkgName=$(__kvm_package_runtime "$f") - local pkgVersion=$(__kvm_package_version "$f") - - local alias="" - local delim="" - for i in "${arr[@]}"; do - temp="$_KVM_RUNTIME_PACKAGE_NAME-$pkgName.$pkgVersion" - temp2="$_KVM_RUNTIME_PACKAGE_NAME-$pkgName-x86.$pkgVersion" - if [[ ${i#*/} == $temp || ${i#*/} == $temp2 ]]; then - alias+="$delim${i%/*}" - delim=", " - fi - done - - printf "$formatString" "$active" "$pkgVersion" "$pkgName" "$formattedHome" "$alias" - [[ $# == 2 ]] && echo "" && return 0 - done - - echo "" - [[ $# == 2 ]] && echo "$versionOrAlias not found" && return 1 - ;; - - *) - echo "Unknown command $1" - return 1 - esac - - return 0 -} - -# Generate the command function using the constant defined above. -$_KVM_COMMAND_NAME list default >/dev/null && $_KVM_COMMAND_NAME use default >/dev/null || true diff --git a/makefile.shade b/makefile.shade index 0dd6524cac..e30467cd06 100644 --- a/makefile.shade +++ b/makefile.shade @@ -56,7 +56,7 @@ functions var buildTarget = "compile" @{ - var kBuildVersion = Environment.GetEnvironmentVariable("K_BUILD_VERSION"); + var kBuildVersion = Environment.GetEnvironmentVariable("DNX_BUILD_VERSION"); if (!string.IsNullOrEmpty(kBuildVersion)) { VERSION += "-" + kBuildVersion;