From 768cc595b1a659fd70ac46e352c23553eee48bb2 Mon Sep 17 00:00:00 2001 From: Suhas Joshi Date: Thu, 18 Sep 2014 17:48:50 -0700 Subject: [PATCH 01/27] Updated feed to release --- kvm.ps1 | 2 +- kvminstall.ps1 | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/kvm.ps1 b/kvm.ps1 index 834879a35a67..867737ca39f6 100644 --- a/kvm.ps1 +++ b/kvm.ps1 @@ -24,7 +24,7 @@ $feed = $env:KRE_NUGET_API_URL if (!$feed) { - $feed = "https://www.myget.org/F/aspnetvnext/api/v2"; + $feed = "https://www.myget.org/F/aspnetrelease/api/v2"; } $scriptPath = $myInvocation.MyCommand.Definition diff --git a/kvminstall.ps1 b/kvminstall.ps1 index 22c242262734..1b882f6bbeda 100644 --- a/kvminstall.ps1 +++ b/kvminstall.ps1 @@ -8,8 +8,8 @@ if (!(Test-Path $tempPath)) { md $tempPath | Out-Null } $webClient = New-Object System.Net.WebClient Write-Host "Downloading KVM.ps1 to $kvmPs1Path" -$webClient.DownloadFile('https://raw.githubusercontent.com/aspnet/Home/master/kvm.ps1', $kvmPs1Path) +$webClient.DownloadFile('https://raw.githubusercontent.com/aspnet/Home/release/kvm.ps1', $kvmPs1Path) Write-Host "Downloading KVM.cmd to $kvmCmdPath" -$webClient.DownloadFile('https://raw.githubusercontent.com/aspnet/Home/master/kvm.cmd', $kvmCmdPath) +$webClient.DownloadFile('https://raw.githubusercontent.com/aspnet/Home/release/kvm.cmd', $kvmCmdPath) Write-Host "Installing KVM" & $kvmCmdPath setup \ No newline at end of file From 0ffb0234e413e937dd0e9de2d25706adfb3f5696 Mon Sep 17 00:00:00 2001 From: Ajay Bhargav Baaskaran Date: Thu, 30 Oct 2014 16:59:30 -0700 Subject: [PATCH 02/27] updated project.json and fix error in startup --- NuGet.Config | 2 +- samples/ConsoleApp/project.json | 4 ++-- samples/HelloMvc/Startup.cs | 2 +- samples/HelloMvc/project.json | 4 ++-- samples/HelloWeb/Startup.cs | 2 +- samples/HelloWeb/project.json | 4 ++-- 6 files changed, 9 insertions(+), 9 deletions(-) diff --git a/NuGet.Config b/NuGet.Config index 600a375c7e4a..7d082f77c508 100644 --- a/NuGet.Config +++ b/NuGet.Config @@ -1,7 +1,7 @@  - + \ No newline at end of file diff --git a/samples/ConsoleApp/project.json b/samples/ConsoleApp/project.json index 4545d5367117..bf3278fb6d9e 100644 --- a/samples/ConsoleApp/project.json +++ b/samples/ConsoleApp/project.json @@ -3,7 +3,7 @@ "System.Console": "4.0.0.0" }, "frameworks": { - "net45": {}, - "k10": {} + "aspnet50": {}, + "aspnetcore50": {} } } \ No newline at end of file diff --git a/samples/HelloMvc/Startup.cs b/samples/HelloMvc/Startup.cs index cbe4bc4f59ca..eb17e8a18c8e 100644 --- a/samples/HelloMvc/Startup.cs +++ b/samples/HelloMvc/Startup.cs @@ -6,7 +6,7 @@ namespace HelloMvc { public class Startup { - public void Configure(IBuilder app) + public void Configure(IApplicationBuilder app) { app.UseErrorPage(); diff --git a/samples/HelloMvc/project.json b/samples/HelloMvc/project.json index 2fe4a51df85a..6dee13b65f90 100644 --- a/samples/HelloMvc/project.json +++ b/samples/HelloMvc/project.json @@ -12,7 +12,7 @@ "Kestrel": "Microsoft.AspNet.Hosting --server Kestrel --server.urls http://localhost:5004" }, "frameworks": { - "net45": {}, - "k10": {} + "aspnet50": {}, + "aspnetcore50": {} } } \ No newline at end of file diff --git a/samples/HelloWeb/Startup.cs b/samples/HelloWeb/Startup.cs index 96e399e2efa5..b41f459f03d7 100644 --- a/samples/HelloWeb/Startup.cs +++ b/samples/HelloWeb/Startup.cs @@ -4,7 +4,7 @@ namespace KWebStartup { public class Startup { - public void Configure(IBuilder app) + public void Configure(IApplicationBuilder app) { app.UseStaticFiles(); app.UseWelcomePage(); diff --git a/samples/HelloWeb/project.json b/samples/HelloWeb/project.json index 45c3e666e0e3..69dc29621381 100644 --- a/samples/HelloWeb/project.json +++ b/samples/HelloWeb/project.json @@ -12,7 +12,7 @@ "Kestrel": "Microsoft.AspNet.Hosting --server Kestrel --server.urls http://localhost:5004" }, "frameworks": { - "net45": {}, - "k10": {} + "aspnet50": {}, + "aspnetcore50": {} } } \ No newline at end of file From acb8eddd49df7a31270c0c72cf24166c0c6e0c55 Mon Sep 17 00:00:00 2001 From: Ajay Bhargav Baaskaran Date: Tue, 4 Nov 2014 14:41:27 -0800 Subject: [PATCH 03/27] updated consoleapp project.json --- samples/ConsoleApp/project.json | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/samples/ConsoleApp/project.json b/samples/ConsoleApp/project.json index bf3278fb6d9e..842362bdf571 100644 --- a/samples/ConsoleApp/project.json +++ b/samples/ConsoleApp/project.json @@ -1,9 +1,13 @@ { "dependencies": { - "System.Console": "4.0.0.0" + }, "frameworks": { "aspnet50": {}, - "aspnetcore50": {} + "aspnetcore50": { + "dependencies": { + "System.Console": "4.0.0-*" + } +} } } \ No newline at end of file From 1234f3dc199b56ec84e835347551f894a30368bd Mon Sep 17 00:00:00 2001 From: Ajay Bhargav Baaskaran Date: Tue, 4 Nov 2014 14:44:29 -0800 Subject: [PATCH 04/27] fix for kvm.ps1 --- kvm.ps1 | 1375 ++++++++++++++++++++++++++++++------------------------- 1 file changed, 743 insertions(+), 632 deletions(-) diff --git a/kvm.ps1 b/kvm.ps1 index 867737ca39f6..8983061037a4 100644 --- a/kvm.ps1 +++ b/kvm.ps1 @@ -1,634 +1,745 @@ -param( - [parameter(Position=0)] - [string] $command, - [string] $proxy, - [switch] $verbosity = $false, - [alias("g")][switch] $global = $false, - [alias("p")][switch] $persistent = $false, - [alias("f")][switch] $force = $false, - [switch] $x86 = $false, - [switch] $x64 = $false, - [switch] $svr50 = $false, - [switch] $svrc50 = $false, - [alias("a")] - [string] $alias = $null, - [parameter(Position=1, ValueFromRemainingArguments=$true)] - [string[]]$args=@() -) - -$userKrePath = $env:USERPROFILE + "\.kre" -$userKrePackages = $userKrePath + "\packages" -$globalKrePath = $env:ProgramFiles + "\KRE" -$globalKrePackages = $globalKrePath + "\packages" -$feed = $env:KRE_NUGET_API_URL - -if (!$feed) -{ - $feed = "https://www.myget.org/F/aspnetrelease/api/v2"; -} - -$scriptPath = $myInvocation.MyCommand.Definition - -function Kvm-Help { -@" -K Runtime Environment Version Manager - Build 10002 - -USAGE: kvm [options] - -kvm upgrade [-x86][-x64] [-svr50][-svrc50] [-g|-global] [-proxy
] - install latest KRE from feed - set 'default' alias to installed version - add KRE 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 - -kvm install |||latest [-x86][-x64] [-svr50][-svrc50] [-a|-alias ] [-g|-global] [-f|-force] - | install requested KRE from feed - install requested KRE from package on local filesystem - latest install latest KRE from feed - add KRE bin to path of current command line - -p|-persistent add KRE bin to PATH environment variables persistently - -a|-alias set alias for requested KRE on install - -g|-global install to machine-wide location - -f|-force install even if specified version is already installed - -kvm use ||none [-x86][-x64] [-svr50][-svrc50] [-p|-persistent] [-g|-global] - | add KRE bin to path of current command line - none remove KRE bin from path of current command line - -p|-persistent add KRE bin to PATH environment variables persistently - -g|-global combined with -p to change machine PATH instead of user PATH - -kvm list - list KRE versions installed - -kvm alias - list KRE aliases which have been defined - -kvm alias - display value of named alias - -kvm alias | [-x86][-x64] [-svr50][-svrc50] - The name of the alias to set - | The KRE version to set the alias to. Alternatively use the version of the specified alias - -"@ | Write-Host -} - -function Kvm-Global-Setup { - If (Needs-Elevation) - { - $arguments = "& '$scriptPath' setup $(Requested-Switches) -persistent" - Start-Process "$psHome\powershell.exe" -Verb runAs -ArgumentList $arguments -Wait - Write-Host "Setup complete" - Kvm-Help - break - } - - $scriptFolder = [System.IO.Path]::GetDirectoryName($scriptPath) - - $kvmBinPath = "$userKrePath\bin" - - Write-Host "Copying file $kvmBinPath\kvm.ps1" - md $kvmBinPath -Force | Out-Null - copy "$scriptFolder\kvm.ps1" "$kvmBinPath\kvm.ps1" - - Write-Host "Copying file $kvmBinPath\kvm.cmd" - copy "$scriptFolder\kvm.cmd" "$kvmBinPath\kvm.cmd" - - Write-Host "Adding $kvmBinPath to process PATH" - Set-Path (Change-Path $env:Path $kvmBinPath ($kvmBinPath)) - - Write-Host "Adding $kvmBinPath to user PATH" - $userPath = [Environment]::GetEnvironmentVariable("Path", [System.EnvironmentVariableTarget]::User) - $userPath = Change-Path $userPath $kvmBinPath ($kvmBinPath) - [Environment]::SetEnvironmentVariable("Path", $userPath, [System.EnvironmentVariableTarget]::User) - - Write-Host "Adding $globalKrePath;%USERPROFILE%\.kre to process KRE_HOME" - $envKreHome = $env:KRE_HOME - $envKreHome = Change-Path $envKreHome "%USERPROFILE%\.kre" ("%USERPROFILE%\.kre") - $envKreHome = Change-Path $envKreHome $globalKrePath ($globalKrePath) - $env:KRE_HOME = $envKreHome - - Write-Host "Adding $globalKrePath;%USERPROFILE%\.kre to machine KRE_HOME" - $machineKreHome = [Environment]::GetEnvironmentVariable("KRE_HOME", [System.EnvironmentVariableTarget]::Machine) - $machineKreHome = Change-Path $machineKreHome "%USERPROFILE%\.kre" ("%USERPROFILE%\.kre") - $machineKreHome = Change-Path $machineKreHome $globalKrePath ($globalKrePath) - [Environment]::SetEnvironmentVariable("KRE_HOME", $machineKreHome, [System.EnvironmentVariableTarget]::Machine) - - Write-Host "Press any key to continue ..." - $x = $host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown,AllowCtrlC") -} - -function Kvm-Global-Upgrade { - $persistent = $true - $alias="default" - If (Needs-Elevation) { - $arguments = "& '$scriptPath' upgrade -global $(Requested-Switches)" - Start-Process "$psHome\powershell.exe" -Verb runAs -ArgumentList $arguments -Wait - break - } - Kvm-Global-Install "latest" -} - -function Kvm-Upgrade { - $persistent = $true - $alias="default" - Kvm-Install "latest" -} - -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 Kvm-Find-Latest { -param( - [string] $platform, - [string] $architecture -) - Write-Host "Determining latest version" - - $url = "$feed/GetUpdates()?packageIds=%27KRE-$platform-$architecture%27&versions=%270.0%27&includePrerelease=true&includeAllVersions=false" - - $wc = New-Object System.Net.WebClient - $wc.Credentials = new-object System.Net.NetworkCredential("aspnetreadonly", "4d8a2d9c-7b80-4162-9978-47e918c9658c") - Add-Proxy-If-Specified($wc) - [xml]$xml = $wc.DownloadString($url) - - $version = Select-Xml "//d:Version" -Namespace @{d='http://schemas.microsoft.com/ado/2007/08/dataservices'} $xml - - return $version -} - -function Do-Kvm-Download { -param( - [string] $kreFullName, - [string] $packagesFolder -) - $parts = $kreFullName.Split(".", 2) - - $url = "$feed/package/" + $parts[0] + "/" + $parts[1] - $kreFolder = Join-Path $packagesFolder $kreFullName - $kreFile = Join-Path $kreFolder "$kreFullName.nupkg" - - If (Test-Path $kreFolder) { - if($force) - { - rm $kreFolder -Recurse -Force - } else { - Write-Host "$kreFullName already installed." - return; - } - } - - Write-Host "Downloading" $kreFullName "from $feed" - - #Downloading to temp location - $kreTempDownload = Join-Path $packagesFolder "temp" - $tempKreFile = Join-Path $kreTempDownload "$kreFullName.nupkg" - - if(Test-Path $kreTempDownload) { - del "$kreTempDownload\*" -recurse - } else { - md $kreTempDownload -Force | Out-Null - } - - $wc = New-Object System.Net.WebClient - $wc.Credentials = new-object System.Net.NetworkCredential("aspnetreadonly", "4d8a2d9c-7b80-4162-9978-47e918c9658c") - Add-Proxy-If-Specified($wc) - $wc.DownloadFile($url, $tempKreFile) - - Do-Kvm-Unpack $tempKreFile $kreTempDownload - - md $kreFolder -Force | Out-Null - Write-Host "Installing to $kreFolder" - mv "$kreTempDownload\*" $kreFolder -} - -function Do-Kvm-Unpack { -param( - [string] $kreFile, - [string] $kreFolder -) - Write-Host "Unpacking to" $kreFolder - try { - #Shell will not recognize nupkg as a zip and throw, so rename it to zip - $kreZip = [System.IO.Path]::ChangeExtension($kreFile, "zip") - Rename-Item $kreFile $kreZip - #Use the shell to uncompress the nupkg - $shell_app=new-object -com shell.application - $zip_file = $shell_app.namespace($kreZip) - $destination = $shell_app.namespace($kreFolder) - $destination.Copyhere($zip_file.items(), 0x14) #0x4 = don't show UI, 0x10 = overwrite files - } - finally { - #make it a nupkg again - Rename-Item $kreZip $kreFile - } - - If (Test-Path ($kreFolder + "\[Content_Types].xml")) { - Remove-Item ($kreFolder + "\[Content_Types].xml") - } - If (Test-Path ($kreFolder + "\_rels\")) { - Remove-Item ($kreFolder + "\_rels\") -Force -Recurse - } - If (Test-Path ($kreFolder + "\package\")) { - Remove-Item ($kreFolder + "\package\") -Force -Recurse - } -} - -function Kvm-Global-Install { -param( - [string] $versionOrAlias -) - If (Needs-Elevation) { - $arguments = "& '$scriptPath' install -global $versionOrAlias $(Requested-Switches)" - Start-Process "$psHome\powershell.exe" -Verb runAs -ArgumentList $arguments -Wait - Kvm-Global-Use $versionOrAlias - break - } - - if ($versionOrAlias -eq "latest") { - $versionOrAlias = Kvm-Find-Latest (Requested-Platform "svr50") (Requested-Architecture "x86") - } - - $kreFullName = Requested-VersionOrAlias $versionOrAlias - - Do-Kvm-Download $kreFullName $globalKrePackages - Kvm-Use $versionOrAlias - if (![string]::IsNullOrWhiteSpace($alias)) { - Kvm-Alias-Set $alias $versionOrAlias - } -} - -function Kvm-Install { -param( - [string] $versionOrAlias -) - if ($versionOrAlias.EndsWith(".nupkg")) - { - $kreFullName = [System.IO.Path]::GetFileNameWithoutExtension($versionOrAlias) - $kreFolder = "$userKrePackages\$kreFullName" - $folderExists = Test-Path $kreFolder - - if($folderExists -and $force) { - del $kreFolder -Recurse -Force - $folderExists = $false; - } - - if($folderExists) { - Write-Host "Target folder '$kreFolder' already exists" - } else { - $tempUnpackFolder = Join-Path $userKrePackages "temp" - $tempKreFile = Join-Path $tempUnpackFolder "$kreFullName.nupkg" - - if(Test-Path $tempUnpackFolder) { - del "$tempUnpackFolder\*" -recurse - } else { - md $tempUnpackFolder -Force | Out-Null - } - copy $versionOrAlias $tempKreFile - - Do-Kvm-Unpack $tempKreFile $tempUnpackFolder - md $kreFolder -Force | Out-Null - Write-Host "Installing to $kreFolder" - mv "$tempUnpackFolder\*" $kreFolder - } - - $packageVersion = Package-Version $kreFullName - Kvm-Use $packageVersion - if (![string]::IsNullOrWhiteSpace($alias)) { - Kvm-Alias-Set $alias $packageVersion - } +param( + [parameter(Position=0)] + [string] $command, + [string] $proxy, + [switch] $verbosity = $false, + [alias("g")][switch] $global = $false, + [alias("p")][switch] $persistent = $false, + [alias("f")][switch] $force = $false, + [alias("r")][string] $runtime, + [switch] $x86 = $false, + [switch] $amd64 = $false, + #deprecated + [switch] $x64 = $false, + #deprecated + [switch] $svr50 = $false, + #deprecated + [switch] $svrc50 = $false, + [alias("w")][switch] $wait = $false, + [alias("a")] + [string] $alias = $null, + [parameter(Position=1, ValueFromRemainingArguments=$true)] + [string[]]$args=@() +) + +$selectedArch=$null; +$defaultArch="x86" +$selectedRuntime=$null +$defaultRuntime="CLR" +$userKrePath = $env:USERPROFILE + "\.kre" +$userKrePackages = $userKrePath + "\packages" +$globalKrePath = $env:ProgramFiles + "\KRE" +$globalKrePackages = $globalKrePath + "\packages" +$feed = $env:KRE_NUGET_API_URL + +function String-IsEmptyOrWhitespace([string]$str) { + return [string]::IsNullOrEmpty($str) -or $str.Trim().length -eq 0 +} + +if (!$feed) +{ + $feed = "https://www.myget.org/F/aspnetrelease/api/v2"; +} + +$scriptPath = $myInvocation.MyCommand.Definition + +function Kvm-Help { +@" +K Runtime Environment Version Manager - Build 10017 + +USAGE: kvm [options] + +kvm upgrade [-x86][-amd64] [-r|-runtime CLR|CoreCLR] [-g|-global] [-f|-force] [-proxy
] + install latest KRE from feed + set 'default' alias to installed version + add KRE 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 + +kvm install |||latest [-x86][-amd64] [-r|-runtime CLR|CoreCLR] [-a|-alias ] [-g|-global] [-f|-force] + | install requested KRE from feed + install requested KRE from package on local filesystem + latest install latest KRE from feed + add KRE bin to path of current command line + -p|-persistent add KRE bin to PATH environment variables persistently + -a|-alias set alias for requested KRE on install + -g|-global install to machine-wide location + -f|-force install even if specified version is already installed + +kvm use ||none [-x86][-amd64] [-r|-runtime CLR|CoreCLR] [-p|-persistent] [-g|-global] + | add KRE bin to path of current command line + none remove KRE bin from path of current command line + -p|-persistent add KRE bin to PATH environment variables persistently + -g|-global combined with -p to change machine PATH instead of user PATH + +kvm list + list KRE versions installed + +kvm alias + list KRE aliases which have been defined + +kvm alias + display value of the specified alias + +kvm alias | [-x86][-amd64] [-r|-runtime CLR|CoreCLR] + The name of the alias to set + | The KRE version to set the alias to. Alternatively use the version of the specified alias + +kvm unalias + remove the specified alias + +"@ -replace "`n","`r`n" | Write-Host +} + +function Kvm-Global-Setup { + $kvmBinPath = "$userKrePath\bin" + + If (Needs-Elevation) + { + $arguments = "-ExecutionPolicy unrestricted & '$scriptPath' setup -global -wait" + Start-Process "$psHome\powershell.exe" -Verb runAs -ArgumentList $arguments -Wait + Write-Host "Adding $kvmBinPath to process PATH" + Set-Path (Change-Path $env:Path $kvmBinPath ($kvmBinPath)) + Write-Host "Adding $globalKrePath;%USERPROFILE%\.kre to process KRE_HOME" + $envKreHome = $env:KRE_HOME + $envKreHome = Change-Path $envKreHome "%USERPROFILE%\.kre" ("%USERPROFILE%\.kre") + $envKreHome = Change-Path $envKreHome $globalKrePath ($globalKrePath) + $env:KRE_HOME = $envKreHome + Write-Host "Setup complete" + break + } + + $scriptFolder = [System.IO.Path]::GetDirectoryName($scriptPath) + + Write-Host "Copying file $kvmBinPath\kvm.ps1" + md $kvmBinPath -Force | Out-Null + copy "$scriptFolder\kvm.ps1" "$kvmBinPath\kvm.ps1" + + Write-Host "Copying file $kvmBinPath\kvm.cmd" + copy "$scriptFolder\kvm.cmd" "$kvmBinPath\kvm.cmd" + + Write-Host "Adding $kvmBinPath to process PATH" + Set-Path (Change-Path $env:Path $kvmBinPath ($kvmBinPath)) + + Write-Host "Adding $kvmBinPath to user PATH" + $userPath = [Environment]::GetEnvironmentVariable("Path", [System.EnvironmentVariableTarget]::User) + $userPath = Change-Path $userPath $kvmBinPath ($kvmBinPath) + [Environment]::SetEnvironmentVariable("Path", $userPath, [System.EnvironmentVariableTarget]::User) + + Write-Host "Adding $globalKrePath;%USERPROFILE%\.kre to process KRE_HOME" + $envKreHome = $env:KRE_HOME + $envKreHome = Change-Path $envKreHome "%USERPROFILE%\.kre" ("%USERPROFILE%\.kre") + $envKreHome = Change-Path $envKreHome $globalKrePath ($globalKrePath) + $env:KRE_HOME = $envKreHome + + Write-Host "Adding $globalKrePath;%USERPROFILE%\.kre to machine KRE_HOME" + $machineKreHome = [Environment]::GetEnvironmentVariable("KRE_HOME", [System.EnvironmentVariableTarget]::Machine) + $machineKreHome = Change-Path $machineKreHome "%USERPROFILE%\.kre" ("%USERPROFILE%\.kre") + $machineKreHome = Change-Path $machineKreHome $globalKrePath ($globalKrePath) + [Environment]::SetEnvironmentVariable("KRE_HOME", $machineKreHome, [System.EnvironmentVariableTarget]::Machine) +} + +function Kvm-Global-Upgrade { + $persistent = $true + $alias="default" + $versionOrAlias = Kvm-Find-Latest $selectedRuntime $selectedArch + If (Needs-Elevation) { + $arguments = "-ExecutionPolicy unrestricted & '$scriptPath' install '$versionOrAlias' -global $(Requested-Switches) -wait" + Start-Process "$psHome\powershell.exe" -Verb runAs -ArgumentList $arguments -Wait + Kvm-Set-Global-Process-Path $versionOrAlias + break + } + Kvm-Install $versionOrAlias $true +} + +function Kvm-Upgrade { + $persistent = $true + $alias="default" + Kvm-Install "latest" $false +} + +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) } - else + $wc.Proxy = $wp + } +} + +function Kvm-Find-Latest { +param( + [string] $platform, + [string] $architecture +) + Write-Host "Determining latest version" + + $url = "$feed/GetUpdates()?packageIds=%27KRE-$platform-$architecture%27&versions=%270.0%27&includePrerelease=true&includeAllVersions=false" + + $wc = New-Object System.Net.WebClient + $wc.Credentials = new-object System.Net.NetworkCredential("aspnetreadonly", "4d8a2d9c-7b80-4162-9978-47e918c9658c") + Add-Proxy-If-Specified($wc) + [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 packages for platform '$platform', architecture '$architecture' in the feed '$feed'" + } + + return $version +} + +function Do-Kvm-Download { +param( + [string] $kreFullName, + [string] $packagesFolder +) + $parts = $kreFullName.Split(".", 2) + + $url = "$feed/package/" + $parts[0] + "/" + $parts[1] + $kreFolder = Join-Path $packagesFolder $kreFullName + $kreFile = Join-Path $kreFolder "$kreFullName.nupkg" + + If (Test-Path $kreFolder) { + if($force) { - if ($versionOrAlias -eq "latest") { - $versionOrAlias = Kvm-Find-Latest (Requested-Platform "svr50") (Requested-Architecture "x86") - } - $kreFullName = Requested-VersionOrAlias $versionOrAlias - - Do-Kvm-Download $kreFullName $userKrePackages - Kvm-Use $versionOrAlias - if (![string]::IsNullOrWhiteSpace($alias)) { - Kvm-Alias-Set $alias $versionOrAlias - } - } -} - -function Kvm-List { - $kreHome = $env:KRE_HOME - if (!$kreHome) { - $kreHome = $env:ProgramFiles + "\KRE;%USERPROFILE%\.kre" - } - $items = @() - foreach($portion in $kreHome.Split(';')) { - $path = [System.Environment]::ExpandEnvironmentVariables($portion) - if (Test-Path("$path\packages")) { - $items += Get-ChildItem ("$path\packages\KRE-*") | List-Parts - } - } - $items | Sort-Object Version, Runtime, Architecture | Format-Table -AutoSize -Property @{name="Active";expression={$_.Active};alignment="center"}, "Version", "Runtime", "Architecture", "Location" -} - -filter List-Parts { - $hasBin = Test-Path($_.FullName+"\bin") - if (!$hasBin) { - return - } - $active = $false - foreach($portion in $env:Path.Split(';')) { - if ($portion.StartsWith($_.FullName)) { - $active = $true - } - } - $parts1 = $_.Name.Split('.', 2) - $parts2 = $parts1[0].Split('-', 3) - return New-Object PSObject -Property @{ - Active = if($active){"*"}else{""} - Version = $parts1[1] - Runtime = $parts2[1] - Architecture = $parts2[2] - Location = $_.Parent.FullName - } -} - -function Kvm-Global-Use { -param( - [string] $versionOrAlias -) - If (Needs-Elevation) { - $arguments = "& '$scriptPath' use -global $versionOrAlias $(Requested-Switches)" - if ($persistent) { - $arguments = $arguments + " -persistent" - } - Start-Process "$psHome\powershell.exe" -Verb runAs -ArgumentList $arguments -Wait - break - } - - if ($versionOrAlias -eq "none") { - Write-Host "Removing KRE from process PATH" - Set-Path (Change-Path $env:Path "" ($globalKrePackages, $userKrePackages)) - - if ($persistent) { - Write-Host "Removing KRE from machine PATH" - $machinePath = [Environment]::GetEnvironmentVariable("Path", [System.EnvironmentVariableTarget]::Machine) - $machinePath = Change-Path $machinePath "" ($globalKrePackages, $userKrePackages) - [Environment]::SetEnvironmentVariable("Path", $machinePath, [System.EnvironmentVariableTarget]::Machine) - } - return; - } - - $kreFullName = Requested-VersionOrAlias $versionOrAlias - - $kreBin = Locate-KreBinFromFullName $kreFullName - if ($kreBin -eq $null) { - Write-Host "Cannot find $kreFullName, do you need to run 'kvm install $versionOrAlias'?" - return - } - - Write-Host "Adding" $kreBin "to process PATH" - Set-Path (Change-Path $env:Path $kreBin ($globalKrePackages, $userKrePackages)) - - if ($persistent) { - Write-Host "Adding $kreBin to machine PATH" - $machinePath = [Environment]::GetEnvironmentVariable("Path", [System.EnvironmentVariableTarget]::Machine) - $machinePath = Change-Path $machinePath $kreBin ($globalKrePackages, $userKrePackages) - [Environment]::SetEnvironmentVariable("Path", $machinePath, [System.EnvironmentVariableTarget]::Machine) - } -} - -function Kvm-Use { -param( - [string] $versionOrAlias -) - if ($versionOrAlias -eq "none") { - Write-Host "Removing KRE from process PATH" - Set-Path (Change-Path $env:Path "" ($globalKrePackages, $userKrePackages)) - - if ($persistent) { - Write-Host "Removing KRE from user PATH" - $userPath = [Environment]::GetEnvironmentVariable("Path", [System.EnvironmentVariableTarget]::User) - $userPath = Change-Path $userPath "" ($globalKrePackages, $userKrePackages) - [Environment]::SetEnvironmentVariable("Path", $userPath, [System.EnvironmentVariableTarget]::User) - } - return; - } - - $kreFullName = Requested-VersionOrAlias $versionOrAlias - - $kreBin = Locate-KreBinFromFullName $kreFullName - if ($kreBin -eq $null) { - Write-Host "Cannot find $kreFullName, do you need to run 'kvm install $versionOrAlias'?" - return - } - - Write-Host "Adding" $kreBin "to process PATH" - Set-Path (Change-Path $env:Path $kreBin ($globalKrePackages, $userKrePackages)) - - if ($persistent) { - Write-Host "Adding $kreBin to user PATH" - $userPath = [Environment]::GetEnvironmentVariable("Path", [System.EnvironmentVariableTarget]::User) - $userPath = Change-Path $userPath $kreBin ($globalKrePackages, $userKrePackages) - [Environment]::SetEnvironmentVariable("Path", $userPath, [System.EnvironmentVariableTarget]::User) - } -} - -function Kvm-Alias-List { - md ($userKrePath + "\alias\") -Force | Out-Null - - Get-ChildItem ($userKrePath + "\alias\") | Select @{label='Alias';expression={$_.BaseName}}, @{label='Name';expression={Get-Content $_.FullName }} | Format-Table -AutoSize -} - -function Kvm-Alias-Get { -param( - [string] $name -) - md ($userKrePath + "\alias\") -Force | Out-Null - $aliasFilePath=$userKrePath + "\alias\" + $name + ".txt" - if (!(Test-Path $aliasFilePath)) { - Write-Host "Alias '$name' does not exist" - } else { - Write-Host "Alias '$name' is set to" (Get-Content ($userKrePath + "\alias\" + $name + ".txt")) - } -} - -function Kvm-Alias-Set { -param( - [string] $name, - [string] $value -) - $kreFullName = Requested-VersionOrAlias $value - - Write-Host "Setting alias '$name' to '$kreFullName'" - md ($userKrePath + "\alias\") -Force | Out-Null - $kreFullName | Out-File ($userKrePath + "\alias\" + $name + ".txt") ascii -} - -function Locate-KreBinFromFullName() { -param( - [string] $kreFullName -) - $kreHome = $env:KRE_HOME - if (!$kreHome) { - $kreHome = $env:ProgramFiles + ";%USERPROFILE%\.kre" - } - foreach($portion in $kreHome.Split(';')) { - $path = [System.Environment]::ExpandEnvironmentVariables($portion) - $kreBin = "$path\packages\$kreFullName\bin" - if (Test-Path "$kreBin") { - return $kreBin - } - } - return $null -} - -function Package-Version() { -param( - [string] $kreFullName -) - return $kreFullName -replace '[^.]*.(.*)', '$1' -} - -function Requested-VersionOrAlias() { -param( - [string] $versionOrAlias -) - If (Test-Path ($userKrePath + "\alias\" + $versionOrAlias + ".txt")) { - $aliasValue = Get-Content ($userKrePath + "\alias\" + $versionOrAlias + ".txt") - $parts = $aliasValue.Split('.', 2) - $pkgVersion = $parts[1] - $parts =$parts[0].Split('-', 3) - $pkgPlatform = Requested-Platform $parts[1] - $pkgArchitecture = Requested-Architecture $parts[2] - } else { - $pkgVersion = $versionOrAlias - $pkgPlatform = Requested-Platform "svr50" - $pkgArchitecture = Requested-Architecture "x86" - } - return "KRE-" + $pkgPlatform + "-" + $pkgArchitecture + "." + $pkgVersion -} - -function Requested-Platform() { -param( - [string] $default -) - if ($svr50 -and $svrc50) { - Throw "This command cannot accept both -svr50 and -svrc50" - } - if ($svr50) { - return "svr50" - } - if ($svrc50) { - return "svrc50" - } - return $default -} - -function Requested-Architecture() { -param( - [string] $default -) - if ($x86 -and $x64) { - Throw "This command cannot accept both -x86 and -x64" - } - if ($x86) { - return "x86" - } - if ($x64) { - return "x64" - } - 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 ($portion.StartsWith($removePath)) { - $skip = $true - } - } - if (!$skip) { - $newPath = $newPath + ";" + $portion - } - } - return $newPath -} - -function Set-Path() { -param( - [string] $newPath -) - md $userKrePath -Force | Out-Null - $env:Path = $newPath -@" -SET "PATH=$newPath" -"@ | Out-File ($userKrePath + "\run-once.cmd") ascii -} - -function Needs-Elevation() { - $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 ($svr50) {$arguments = "$arguments -svr50"} - if ($svrc50) {$arguments = "$arguments -svrc50"} - return $arguments -} - - try { - if ($global) { - switch -wildcard ($command + " " + $args.Count) { - "setup 0" {Kvm-Global-Setup} - "upgrade 0" {Kvm-Global-Upgrade} - "install 1" {Kvm-Global-Install $args[0]} -# "list 0" {Kvm-Global-List} - "use 1" {Kvm-Global-Use $args[0]} - default {Write-Host 'Unknown command, or global switch not supported'; Kvm-Help;} - } - } else { - switch -wildcard ($command + " " + $args.Count) { - "setup 0" {Kvm-Global-Setup} - "upgrade 0" {Kvm-Upgrade} - "install 1" {Kvm-Install $args[0]} - "list 0" {Kvm-List} - "use 1" {Kvm-Use $args[0]} - "alias 0" {Kvm-Alias-List} - "alias 1" {Kvm-Alias-Get $args[0]} - "alias 2" {Kvm-Alias-Set $args[0] $args[1]} - "help 0" {Kvm-Help} - " 0" {Kvm-Help} - default {Write-Host 'Unknown command'; Kvm-Help;} - } - } - } - catch { - Write-Host $_ -ForegroundColor Red ; - } + rm $kreFolder -Recurse -Force + } else { + Write-Host "$kreFullName already installed." + return; + } + } + + Write-Host "Downloading" $kreFullName "from $feed" + + #Downloading to temp location + $kreTempDownload = Join-Path $packagesFolder "temp" + $tempKreFile = Join-Path $kreTempDownload "$kreFullName.nupkg" + + if(Test-Path $kreTempDownload) { + del "$kreTempDownload\*" -recurse + } else { + md $kreTempDownload -Force | Out-Null + } + + $wc = New-Object System.Net.WebClient + $wc.Credentials = new-object System.Net.NetworkCredential("aspnetreadonly", "4d8a2d9c-7b80-4162-9978-47e918c9658c") + Add-Proxy-If-Specified($wc) + $wc.DownloadFile($url, $tempKreFile) + + Do-Kvm-Unpack $tempKreFile $kreTempDownload + + md $kreFolder -Force | Out-Null + Write-Host "Installing to $kreFolder" + mv "$kreTempDownload\*" $kreFolder + Remove-Item "$kreTempDownload" -Force | Out-Null +} + +function Do-Kvm-Unpack { +param( + [string] $kreFile, + [string] $kreFolder +) + Write-Host "Unpacking to" $kreFolder + try { + #Shell will not recognize nupkg as a zip and throw, so rename it to zip + $kreZip = [System.IO.Path]::ChangeExtension($kreFile, "zip") + Rename-Item $kreFile $kreZip + #Use the shell to uncompress the nupkg + $shell_app=new-object -com shell.application + $zip_file = $shell_app.namespace($kreZip) + $destination = $shell_app.namespace($kreFolder) + $destination.Copyhere($zip_file.items(), 0x14) #0x4 = don't show UI, 0x10 = overwrite files + } + finally { + #make it a nupkg again + Rename-Item $kreZip $kreFile + } + + If (Test-Path ($kreFolder + "\[Content_Types].xml")) { + Remove-Item ($kreFolder + "\[Content_Types].xml") + } + If (Test-Path ($kreFolder + "\_rels\")) { + Remove-Item ($kreFolder + "\_rels\") -Force -Recurse + } + If (Test-Path ($kreFolder + "\package\")) { + Remove-Item ($kreFolder + "\package\") -Force -Recurse + } +} + +function Kvm-Install { +param( + [string] $versionOrAlias, + [boolean] $isGlobal +) + if ($versionOrAlias -eq "latest") { + $versionOrAlias = Kvm-Find-Latest (Requested-Platform $defaultRuntime) (Requested-Architecture $defaultArch) + } + + if ($versionOrAlias.EndsWith(".nupkg")) { + $kreFullName = [System.IO.Path]::GetFileNameWithoutExtension($versionOrAlias) + } else { + $kreFullName = Requested-VersionOrAlias $versionOrAlias + } + + if ($isGlobal) { + if (Needs-Elevation) { + $arguments = "-ExecutionPolicy unrestricted & '$scriptPath' install '$versionOrAlias' -global $(Requested-Switches) -wait" + Start-Process "$psHome\powershell.exe" -Verb runAs -ArgumentList $arguments -Wait + Kvm-Set-Global-Process-Path $versionOrAlias + break + } + $packageFolder = $globalKrePackages + } else { + $packageFolder = $userKrePackages + } + + if ($versionOrAlias.EndsWith(".nupkg")) { + Set-Variable -Name "selectedArch" -Value (Package-Arch $kreFullName) -Scope Script + Set-Variable -Name "selectedRuntime" -Value (Package-Platform $kreFullName) -Scope Script + + $kreFolder = "$packageFolder\$kreFullName" + $folderExists = Test-Path $kreFolder + + if ($folderExists -and $force) { + del $kreFolder -Recurse -Force + $folderExists = $false; + } + + if ($folderExists) { + Write-Host "Target folder '$kreFolder' already exists" + } else { + $tempUnpackFolder = Join-Path $packageFolder "temp" + $tempKreFile = Join-Path $tempUnpackFolder "$kreFullName.nupkg" + + if(Test-Path $tempUnpackFolder) { + del "$tempUnpackFolder\*" -recurse + } else { + md $tempUnpackFolder -Force | Out-Null + } + copy $versionOrAlias $tempKreFile + + Do-Kvm-Unpack $tempKreFile $tempUnpackFolder + md $kreFolder -Force | Out-Null + Write-Host "Installing to $kreFolder" + mv "$tempUnpackFolder\*" $kreFolder + Remove-Item "$tempUnpackFolder" -Force | Out-Null + } + + $packageVersion = Package-Version $kreFullName + + Kvm-Use $packageVersion + if (!$(String-IsEmptyOrWhitespace($alias))) { + Kvm-Alias-Set $alias $packageVersion + } + } + else + { + Do-Kvm-Download $kreFullName $packageFolder + Kvm-Use $versionOrAlias + if (!$(String-IsEmptyOrWhitespace($alias))) { + Kvm-Alias-Set "$alias" $versionOrAlias + } + } +} + +function Kvm-List { + $kreHome = $env:KRE_HOME + if (!$kreHome) { + $kreHome = "$globalKrePath;$userKrePath" + } + + md ($userKrePath + "\alias\") -Force | Out-Null + $aliases = Get-ChildItem ($userKrePath + "\alias\") | Select @{label='Alias';expression={$_.BaseName}}, @{label='Name';expression={Get-Content $_.FullName }} + + $items = @() + foreach($portion in $kreHome.Split(';')) { + $path = [System.Environment]::ExpandEnvironmentVariables($portion) + if (Test-Path("$path\packages")) { + $items += Get-ChildItem ("$path\packages\KRE-*") | 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(';')) { + 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('-', 3) + return New-Object PSObject -Property @{ + Active = if ($active) { "*" } else { "" } + Version = $parts1[1] + Runtime = $parts2[1] + Architecture = $parts2[2] + Location = $_.Parent.FullName + Alias = $fullAlias + } +} + +function Kvm-Global-Use { +param( + [string] $versionOrAlias +) + If (Needs-Elevation) { + $arguments = "-ExecutionPolicy unrestricted & '$scriptPath' use '$versionOrAlias' -global $(Requested-Switches) -wait" + Start-Process "$psHome\powershell.exe" -Verb runAs -ArgumentList $arguments -Wait + Kvm-Set-Global-Process-Path $versionOrAlias + break + } + + Kvm-Set-Global-Process-Path "$versionOrAlias" + + if ($versionOrAlias -eq "none") { + if ($persistent) { + Write-Host "Removing KRE from machine PATH" + $machinePath = [Environment]::GetEnvironmentVariable("Path", [System.EnvironmentVariableTarget]::Machine) + $machinePath = Change-Path $machinePath "" ($globalKrePackages, $userKrePackages) + [Environment]::SetEnvironmentVariable("Path", $machinePath, [System.EnvironmentVariableTarget]::Machine) + } + return; + } + + $kreFullName = Requested-VersionOrAlias "$versionOrAlias" + $kreBin = Locate-KreBinFromFullName $kreFullName + if ($kreBin -eq $null) { + Write-Host "Cannot find $kreFullName, do you need to run 'kvm install $versionOrAlias'?" + return + } + + if ($persistent) { + Write-Host "Adding $kreBin to machine PATH" + $machinePath = [Environment]::GetEnvironmentVariable("Path", [System.EnvironmentVariableTarget]::Machine) + $machinePath = Change-Path $machinePath $kreBin ($globalKrePackages, $userKrePackages) + [Environment]::SetEnvironmentVariable("Path", $machinePath, [System.EnvironmentVariableTarget]::Machine) + } +} + +function Kvm-Set-Global-Process-Path { +param( + [string] $versionOrAlias +) + if ($versionOrAlias -eq "none") { + Write-Host "Removing KRE from process PATH" + Set-Path (Change-Path $env:Path "" ($globalKrePackages, $userKrePackages)) + return + } + + $kreFullName = Requested-VersionOrAlias $versionOrAlias + $kreBin = Locate-KreBinFromFullName $kreFullName + if ($kreBin -eq $null) { + Write-Host "Cannot find $kreFullName, do you need to run 'kvm install $versionOrAlias'?" + return + } + + Write-Host "Adding" $kreBin "to process PATH" + Set-Path (Change-Path $env:Path $kreBin ($globalKrePackages, $userKrePackages)) +} + +function Kvm-Use { +param( + [string] $versionOrAlias +) + if ($versionOrAlias -eq "none") { + Write-Host "Removing KRE from process PATH" + Set-Path (Change-Path $env:Path "" ($globalKrePackages, $userKrePackages)) + + if ($persistent) { + Write-Host "Removing KRE from user PATH" + $userPath = [Environment]::GetEnvironmentVariable("Path", [System.EnvironmentVariableTarget]::User) + $userPath = Change-Path $userPath "" ($globalKrePackages, $userKrePackages) + [Environment]::SetEnvironmentVariable("Path", $userPath, [System.EnvironmentVariableTarget]::User) + } + return; + } + + $kreFullName = Requested-VersionOrAlias $versionOrAlias + + $kreBin = Locate-KreBinFromFullName $kreFullName + if ($kreBin -eq $null) { + Write-Host "Cannot find $kreFullName, do you need to run 'kvm install $versionOrAlias'?" + return + } + + Write-Host "Adding" $kreBin "to process PATH" + Set-Path (Change-Path $env:Path $kreBin ($globalKrePackages, $userKrePackages)) + + if ($persistent) { + Write-Host "Adding $kreBin to user PATH" + $userPath = [Environment]::GetEnvironmentVariable("Path", [System.EnvironmentVariableTarget]::User) + $userPath = Change-Path $userPath $kreBin ($globalKrePackages, $userKrePackages) + [Environment]::SetEnvironmentVariable("Path", $userPath, [System.EnvironmentVariableTarget]::User) + } +} + +function Kvm-Alias-List { + md ($userKrePath + "\alias\") -Force | Out-Null + + Get-ChildItem ($userKrePath + "\alias\") | Select @{label='Alias';expression={$_.BaseName}}, @{label='Name';expression={Get-Content $_.FullName }} | Format-Table -AutoSize +} + +function Kvm-Alias-Get { +param( + [string] $name +) + md ($userKrePath + "\alias\") -Force | Out-Null + $aliasFilePath=$userKrePath + "\alias\" + $name + ".txt" + if (!(Test-Path $aliasFilePath)) { + Write-Host "Alias '$name' does not exist" + } else { + Write-Host "Alias '$name' is set to" (Get-Content ($userKrePath + "\alias\" + $name + ".txt")) + } +} + +function Kvm-Alias-Set { +param( + [string] $name, + [string] $value +) + $kreFullName = Requested-VersionOrAlias $value + $aliasFilePath = $userKrePath + "\alias\" + $name + ".txt" + $action = if (Test-Path $aliasFilePath) { "Updating" } else { "Setting" } + Write-Host "$action alias '$name' to '$kreFullName'" + md ($userKrePath + "\alias\") -Force | Out-Null + $kreFullName | Out-File ($aliasFilePath) ascii +} + +function Kvm-Unalias { +param( + [string] $name +) + $aliasPath=$userKrePath + "\alias\" + $name + ".txt" + if (Test-Path -literalPath "$aliasPath") { + Write-Host "Removing alias $name" + Remove-Item -literalPath $aliasPath + } else { + Write-Host "Cannot remove alias, '$name' is not a valid alias name" + } +} + +function Locate-KreBinFromFullName() { +param( + [string] $kreFullName +) + $kreHome = $env:KRE_HOME + if (!$kreHome) { + $kreHome = "$globalKrePath;$userKrePath" + } + foreach($portion in $kreHome.Split(';')) { + $path = [System.Environment]::ExpandEnvironmentVariables($portion) + $kreBin = "$path\packages\$kreFullName\bin" + if (Test-Path "$kreBin") { + return $kreBin + } + } + return $null +} + +function Package-Version() { +param( + [string] $kreFullName +) + return $kreFullName -replace '[^.]*.(.*)', '$1' +} + +function Package-Platform() { +param( + [string] $kreFullName +) + return $kreFullName -replace 'KRE-([^-]*).*', '$1' +} + +function Package-Arch() { +param( + [string] $kreFullName +) + return $kreFullName -replace 'KRE-[^-]*-([^.]*).*', '$1' +} + + +function Requested-VersionOrAlias() { +param( + [string] $versionOrAlias +) + If (Test-Path ($userKrePath + "\alias\" + $versionOrAlias + ".txt")) { + $aliasValue = Get-Content ($userKrePath + "\alias\" + $versionOrAlias + ".txt") + $parts = $aliasValue.Split('.', 2) + $pkgVersion = $parts[1] + $parts =$parts[0].Split('-', 3) + $pkgPlatform = Requested-Platform $parts[1] + $pkgArchitecture = Requested-Architecture $parts[2] + } else { + $pkgVersion = $versionOrAlias + $pkgPlatform = Requested-Platform $defaultRuntime + $pkgArchitecture = Requested-Architecture $defaultArch + } + return "KRE-" + $pkgPlatform + "-" + $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 ($portion.StartsWith($removePath)) { + $skip = $true + } + } + if (!$skip) { + $newPath = $newPath + ";" + $portion + } + } + return $newPath +} + +function Set-Path() { +param( + [string] $newPath +) + md $userKrePath -Force | Out-Null + $env:Path = $newPath +@" +SET "PATH=$newPath" +"@ | Out-File ($userKrePath + "\run-once.cmd") ascii +} + +function Needs-Elevation() { + $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 ($amd64) {$arguments = "$arguments -amd64"} + #deprecated + 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-Santitise-Switches() +{ + if ($svr50 -and $runtime) {throw "You cannot select both the -runtime switch and the -svr50 runtimes"} + if ($svrc50 -and $runtime) {throw "You cannot select both the -runtime switch and the -svrc50 runtimes"} + if ($x86 -and $amd64) {throw "You cannot select both x86 and amd64 architectures"} + if ($x86 -and $x64) {throw "You cannot select both x86 and x64 architectures"} + if ($x64 -and $amd64) {throw "You cannot select both x64 and amd64 architectures"} + + if ($runtime) { + $validRuntimes = "CoreCLR", "CLR", "svr50", "svrc50" + $match = $validRuntimes | ? { $_ -like $runtime } | Select -First 1 + if (!$match) {throw "'$runtime' is not a valid runtime"} + Set-Variable -Name "selectedRuntime" -Value $match -Scope Script + } elseif ($svr50) { + Write-Host "Warning: -svr50 is deprecated, use -runtime CLR for new packages." + Set-Variable -Name "selectedRuntime" -Value "svr50" -Scope Script + } elseif ($svrc50) { + Write-Host "Warning: -svrc50 is deprecated, use -runtime CoreCLR for new packages." + Set-Variable -Name "selectedRuntime" -Value "svrc50" -Scope Script + } + + if ($x64) { + Write-Host "Warning: -x64 is deprecated, use -amd64 for new packages." + Set-Variable -Name "selectedArch" -Value "x64" -Scope Script + } elseif ($amd64) { + Set-Variable -Name "selectedArch" -Value "amd64" -Scope Script + } elseif ($x86) { + Set-Variable -Name "selectedArch" -Value "x86" -Scope Script + } +} + +try { + Validate-And-Santitise-Switches + if ($global) { + switch -wildcard ($command + " " + $args.Count) { + "setup 0" {Kvm-Global-Setup} + "upgrade 0" {Kvm-Global-Upgrade} + "install 1" {Kvm-Install $args[0] $true} + "use 1" {Kvm-Global-Use $args[0]} + default {throw "Unknown command, or global switch not supported"}; + } + } else { + switch -wildcard ($command + " " + $args.Count) { + "setup 0" {Kvm-Global-Setup} + "upgrade 0" {Kvm-Upgrade} + "install 1" {Kvm-Install $args[0] $false} + "list 0" {Kvm-List} + "use 1" {Kvm-Use $args[0]} + "alias 0" {Kvm-Alias-List} + "alias 1" {Kvm-Alias-Get $args[0]} + "alias 2" {Kvm-Alias-Set $args[0] $args[1]} + "unalias 1" {Kvm-Unalias $args[0]} + "help 0" {Kvm-Help} + " 0" {Kvm-Help} + default {throw "Unknown command"}; + } + } +} +catch { + Write-Host $_ -ForegroundColor Red ; + Write-Host "Type 'kvm help' for help on how to use kvm." +} +if ($wait) { + Write-Host "Press any key to continue ..." + $x = $host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown,AllowCtrlC") +} From 531cbbb817a45f5e2955ba3aa2b38976d45f934d Mon Sep 17 00:00:00 2001 From: Ajay Bhargav Baaskaran Date: Wed, 5 Nov 2014 13:31:19 -0800 Subject: [PATCH 05/27] updated system.console pkg version --- samples/ConsoleApp/project.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/samples/ConsoleApp/project.json b/samples/ConsoleApp/project.json index 842362bdf571..9c297e5bc9f4 100644 --- a/samples/ConsoleApp/project.json +++ b/samples/ConsoleApp/project.json @@ -6,7 +6,7 @@ "aspnet50": {}, "aspnetcore50": { "dependencies": { - "System.Console": "4.0.0-*" + "System.Console": "4.0.0-beta-*" } } } From b2c0cedeac9241a9d7471c661a5a0e89e5010772 Mon Sep 17 00:00:00 2001 From: Suhas Joshi Date: Tue, 9 Dec 2014 11:44:09 -0800 Subject: [PATCH 06/27] porting master to release and updating changes to beta2 --- CONTRIBUTING.md | 6 +- README.md | 187 +++++++++-------- kvm.ps1 | 367 +++++++++++++++++++++------------- kvm.sh | 139 ++++++++----- samples/HelloMvc/project.json | 2 +- samples/HelloWeb/project.json | 2 +- 6 files changed, 412 insertions(+), 291 deletions(-) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index e23e36ae23ca..9eee938f6c7e 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -17,7 +17,7 @@ Please log a new issue in the appropriate GitHub repo. Here are some of the most * [MVC](https://github.com/aspnet/Mvc) * [SignalR-Server](https://github.com/aspnet/SignalR-Server) -The full repo list is [here](https://github.com/aspnet). +A description of all the repos is [here](https://github.com/aspnet/Home/wiki/Repo-List). ## Other discussions @@ -53,6 +53,10 @@ Before submitting a feature or substantial code contribution please discuss it w Here's a few things you should always do when making changes to the code base: +**Engineering guidelines** + +The coding, style, and general engineering guidelines are published on the [Engineering guidelines](https://github.com/aspnet/Home/wiki/Engineering-guidelines) page. + **Commit/Pull Request Format** ``` diff --git a/README.md b/README.md index 0913e8804e1f..c2e242214f95 100644 --- a/README.md +++ b/README.md @@ -1,144 +1,141 @@ # ASP.NET vNext Home +Latest dev version: [![dev version](http://img.shields.io/myget/aspnetvnext/v/KRE-CLR-x86.svg?style=flat)](https://www.myget.org/gallery/aspnetvnext)
+Latest master version: [![master version](http://img.shields.io/myget/aspnetmaster/v/KRE-CLR-x86.svg?style=flat)](https://www.myget.org/gallery/aspnetmaster) -In the next version of ASP.NET we are working with multiple teams around Microsoft to create a lean, composable .NET stack that provides a familiar and modern framework for web and cloud scenarios. +The Home repository is the starting point for people to learn about ASP.NET vNext. This repo contains samples and [documentation](https://github.com/aspnet/Home/wiki) to help folks get started and learn more about what's coming in ASP.NET vNext. -The Home repository is the starting point for people to learn about ASP.NET vNext, it contains samples and [documentation](https://github.com/aspnet/Home/wiki) to help folks get started and learn more about what we are doing. +ASP.NET vNext is being actively developed by the ASP.NET team assigned to the Microsoft Open Tech Hub and in collaboration with a community of open source developers. Together we are dedicated to creating the best possible platform for web development. -These products are actively developed by the ASP.NET team assigned to the Microsoft Open Tech Hub and in collaboration with a community of open source developers. Together we are dedicated to creating the best possible platform for web development. +The samples provided in this repo are designed to show some of the features of the new framework and to provide a starting point for further exploration. All the component packages are available on NuGet. To try out the latest bits under development switch to the dev branch of the Home repo and use the dev feed in NuGet.config (https://www.myget.org/F/aspnetvnext). -The samples provided are designed to show some of the features of the new framework as well as setting up a sandbox for you to try out some of the new features. The NuGet.config file in the repo points to a MyGet feed (https://www.myget.org/F/aspnetvnext/) that has all the packages being developed. The feed is updated every time a full build succeeds. +## Contents +* [Minimum Requirements](#minimum-requirements) +* [Getting Started](#getting-started) +* [Samples](#samples) +* [Documentation and Further Learning](#documentation-and-further-learning) +* [Repos and Projects](#repos-and-projects) +* [Feedback](#feedback) -# Minimum Requirements +## Minimum Requirements -These are the current minimum requirements, they do not necesarilly represent our RTM minimum. +These are the current minimum requirements for the latest preview release. They do not necessarily represent what the final minimum requirements will be. ### Windows -* Windows 7 or greater, though Core CLR will only work on Windows 8 today. If using Core CLR you will need to be on Windows 8 or above. At RTM the whole stack will support Windows 7+ and Windows Server 2008 R2+. +* Windows 7 or Windows Server 2008 R2. * .NET 4.5.1 for hosting in IIS -### OSX/Linux - * Mono >= 3.4.1 - Currently this means compiling Mono from source from https://github.com/mono/mono (Note: See instructions below to install the Homebrew formula that can install the required mono) - * On Linux, you may need to run `mozroots --import --sync` after installing mono +### OS X/Linux + * Mono 3.4.1 or later (Note: On OS X use the Homebrew formula specified below to install the required version of Mono) * bash or zsh and curl -#Getting Started +## Getting Started -The first thing we need to do is setup the tools required to build and run an application. We will start out by getting the [K Version Manager (KVM)](https://github.com/aspnet/Home/wiki/version-manager) +The easiest way to get started with ASP.NET vNext is to try out the latest preview of Visual Studio 2015 Preview. You can find installation instructions and getting started documentation at http://www.asp.net/vnext. -The easiest way to get the KVM on Windows is to run the following command: -```powershell -@powershell -NoProfile -ExecutionPolicy unrestricted -Command "iex ((new-object net.webclient).DownloadString('https://raw.githubusercontent.com/aspnet/Home/master/kvminstall.ps1'))" -``` -or on OSX: +That said, you can also try out ASP.NET vNext with just a command-prompt and a text editor. The following instructions will walk you through getting your dev environment setup. -Mono and KVM (K Version manager) required to develop & run next generation ASP.NET applications on OSX is available as a Homebrew formula. To install the necessary development tools: +### Install the K Version Manager (KVM) - * Open a terminal on your MAC - * Install [Homebrew](http://brew.sh) by running the following command. If you already have Homebrew installed skip this step. -```ruby -e "$(curl -fsSL https://raw.github.com/Homebrew/homebrew/go/install)"``` - * Run command `brew tap aspnet/k` to tap the aspnet vnext related git repositories. - * Run command `brew install kvm` to install KVM. This also automatically install the latest KRE package from https://www.myget.org/f/aspnetvnext/api/v2 feed. +The first thing we need to do is setup the tools required to build and run an application. We will start out by getting the [K Version Manager (KVM)](https://github.com/aspnet/Home/wiki/version-manager). We use the K Version Manager to install different versions of the ASP.NET vNext runtime and switch between them. -Now you are set for developing next general ASP.NET applications on OSX. A few things to note: - * If you would like to use a different KRE version for your development, you can install the desired version using KVM. See [KVM page](https://github.com/aspnet/Home/wiki/version-manager) for more information. - * Run command `source kvm.sh` on your terminal if your terminal cannot understand kvm. +#### Windows +To install KVM on Windows run the following command, which will download and run a script that installs KVM for the current user (requires admin privileges for Powershell): -or on Linux: ``` -curl https://raw.githubusercontent.com/aspnet/Home/master/kvminstall.sh | sh && source ~/.kre/kvm/kvm.sh +@powershell -NoProfile -ExecutionPolicy unrestricted -Command "iex ((new-object net.webclient).DownloadString('https://raw.githubusercontent.com/aspnet/Home/release/kvminstall.ps1'))" + ``` -This downloads KVM from this repository and puts it on your machine. Alternatively, you you could clone the repo and get it: -* Clone the repository -* On the command line execute - * ```kvm setup``` on Windows or - * ```sh kvminstall.sh && source ~/.kre/kvm/kvm.sh``` on OSX/Linux - -This command will setup your environment, getting it ready to install a version of the runtime. It adds KVM to your path and puts it in your user profile. Once you have KVM then you need to get a version of the runtime: -* Execute ```kvm install 0.1-alpha-build-0446```. This command will download the named version of the KRE and put it on your user profile ready to use. You can get the latest version by running ```kvm upgrade``` but 0446 was the last version explicitly tested. see the [KVM page](https://github.com/aspnet/Home/wiki/version-manager) for more information on KVM. -* Navigate to samples\ConsoleApp -* Run ```kpm restore```. This downloads the System.Console package so the app can do Console.WriteLine -* Run ```k run``` -* You should see a message saying "Hello World" -* Type - * ```SET KRE_TRACE=1``` on Windows or - * ```export KRE_TRACE=1``` on OSX/Linux -* Run ```k run``` -* You should now see compiler output as well as the "Hello World" message +After the script has run open a new command prompt to start using KVM. + +#### OS X: + +To install KVM and the correct version of Mono on OS X using [Homebrew](http://brew.sh) follow the following steps: + + * Install [Homebrew](http://brew.sh) if it is not already installed. + * Run command `brew tap aspnet/k` to tap the ASP.NET vNext related git repositories. If you had already tapped the repo for previous releases, run `brew untap aspnet/k` to delete the old commands and tap again to get the updated brew scripts. + * Run command `brew install kvm` to install KVM. This also automatically install the latest KRE package from https://www.nuget.org/api/v2 feed. + * Run command `source kvm.sh` on your terminal if your terminal cannot understand kvm. + +#### Linux: + +Installing KVM need `curl`. Do verify if that is installed on the machine. Next install KVM on Linux run the following command: ``` -:: getting started -git clone https://github.com/aspnet/Home.git -cd Home -kvm setup -kvm install 0.1-alpha-build-0446 -p - -cd samples\ConsoleApp -kpm restore -k run - -SET KRE_TRACE=1 -k run +curl -sSL https://raw.githubusercontent.com/aspnet/Home/release/kvminstall.sh | sh && source ~/.kre/kvm/kvm.sh ``` -# Samples +Note that on Linux you need to also install [Mono](http://mono-project.com) 3.4.1 or later. + +### Install the K Runtime Environment (KRE) -## Sandbox Samples +Now that you have KVM setup you can install the latest version of the runtime by running the following command: ```kvm upgrade``` + +This command will download the specified version of the K Runtime Environment (KRE), and put it on your user profile ready to use. You are now ready to start using ASP.NET vNext! -These samples, in this repo, are just basic starting points for you to experiment with features. Since there is no File->New Project we thought some simple samples to take the place of scaffolding would be convenient. +## Samples -+ [ConsoleApp](https://github.com/aspnet/Home/tree/master/samples/ConsoleApp). This is just basic console app if you want to use it as a starting point. -+ [HelloWeb](https://github.com/aspnet/Home/tree/master/samples/HelloWeb). This is a minimal startup class that shows welcome page and static file middleware. This is mostly for you to run through the steps in the readme and make sure you have everything setup and working correctly. -+ [HelloMvc](https://github.com/aspnet/Home/tree/master/samples/HelloMvc). This sample is a basic MVC app. It is not designed to show all the functionality of the new web stack, but to give you a starting point to play with features. +The samples in this repo are basic starting points for you to experiment with. -**NOTE: The samples are pinned to a specific version of the packages. If you want to try the latest builds then update the project.json and replace the last part of the version with a '\*', so '0.1-alpha-build-267' becomes '0.1-alpha-\*', and then run ```kpm restore``` to pull down the latest packages** ++ [ConsoleApp](https://github.com/aspnet/Home/tree/release/samples/ConsoleApp). This is just basic console app if you want to use it as a starting point. ++ [HelloWeb](https://github.com/aspnet/Home/tree/release/samples/HelloWeb). This is a minimal startup class that shows welcome page and static file middleware. This is mostly for you to run through the steps in the readme and make sure you have everything setup and working correctly. ++ [HelloMvc](https://github.com/aspnet/Home/tree/release/samples/HelloMvc). This sample is a basic MVC app. It is not designed to show all the functionality of the new web stack, but to give you a starting point to play with features. ++ [MVC Music Store](https://github.com/aspnet/MusicStore) and [BugTracker](https://github.com/aspnet/BugTracker) are application samples that are both being ported to ASP.NET vNext. Each of these samples have their own separate repositories that you can look at. -## Feature Samples -The [Entropy repo](https://github.com/aspnet/Entropy) contains samples of specific features in isolation. Each directory contains just enough code to show an aspect of a feature. +### Running the samples -## Application Samples -[MVC Music Store](https://github.com/aspnet/MusicStore) and [BugTracker](https://github.com/aspnet/BugTracker) application are both being ported. Each of these have their own repository that you can look at. +1. Clone the Home repository +2. Change directory to the folder of the sample you want to run +3. Run ```kpm restore``` to restore the packages required by that sample. +4. You should see a bunch of output as all the dependencies of the app are downloaded from MyGet. +5. Run the sample using the appropriate K command: + - For the console app run ```k run```. + - For the web apps run ```k web``` on Windows or ```k kestrel``` on Mono. +6. You should see the output of the console app or a message that says the site is now started. +7. You can navigate to the web apps in a browser by going to "http://localhost:5001" or "http://localhost:5004" if running on Mono. -# Running the samples +### Switching to Core CLR -## Running HelloWeb +By default when running ASP.NET vNext applications on the Windows platform you are running on the full .NET Framework. You can switch to use the new Cloud Optimized runtime, or Core CLR, using the KVM command. -1. Clone the repository -2. Change directory to Samples\HelloWeb -3. Run ```kpm restore``` -4. You should see a bunch of output as all the dependencies of the app are downloaded from MyGet. The K commands all operate on the app that is in the current directory. -5. Run ```K web``` to run on WebListener. Or run ```K Kestrel``` to run on Mono. -6. You should see build output and a message to show the site is now started -7. Navigate to "http://localhost:5001" or "http://localhost:5004" in case of Mono -8. You should see the welcome page -9. Navigate to "http://localhost:5001/image.jpg" or "http://localhost:5004/image.img" in case of Mono. -10. You should see an image served with the static file middleware +1. Run ```kvm upgrade -runtime CoreCLR``` This command gets the latest Core CLR version of the k runtime and sets it as your default. The `-runtime CoreCLR` switch tells it to use Core CLR. You can use `-r CLR` to target desktop again. +2. Run ```k web``` to run on WebListener. +3. The first line of your output should say "Loaded Module: klr.core45.dll" instead of "Loaded Module: klr.net45.dll" +4. The HelloWeb app should work the same as when running on the full desktop .NET Framework but now as a fully self-contained app with true side-by-side versioning support. -If you can do all of the above then everything should be working. You can try out the WebFx sample now to see some more of the new stack. You should run ```kpm restore``` before using any sample for the first time. +**NOTE: There are many APIs from the .NET Framework that are not yet available when running on Core CLR. This set should get smaller and smaller as time goes on.** -# Switching to Core CLR +**NOTE: There is no Core CLR currently available on OSX/Linux. There is only a single platform (mono45) and a single architecture (x86).** +## Documentation and Further Learning -By default when running the applications you are running against Desktop CLR (4.5), you can change that using the KVM command. +### [Community Standup](http://www.youtube.com/playlist?list=PL0M0zPgJ3HSftTAAHttA3JQU4vOjXFquF) +The community standup is held every week and streamed live to YouTube. You can view past standups in the linked playlist. -1. Run ```kvm install 0.1-alpha-build-0446 -svrc50``` This command gets the latest Core CLR version of the k runtime and sets it as your default. The -svrc50 switch tells it to use Core CLR, you can use -svr50 to target desktop again. -2. Run ```K web``` to run on WebListener. Or run ```K Kestrel``` to run on Mono. -3. The first line of your output should say "Loaded Module: klr.core45.dll" instead of "Loaded Module: klr.net45.dll" -4. The HelloWeb app should work the same as when running on Desktop CLR. +If you have questions you can also jump online during the next standup and have them answered live. + +### [Wiki Documentation] (https://github.com/aspnet/Home/wiki) +We have some useful documentation on the wiki of this Repo. This wiki is a central spot for docs from any part of the stack. -**NOTE: There are going to be parts of the stack that work on Desktop but do not work on Core CLR. This set should get smaller and smaller as time goes on, but it is entirely likely as you use Core CLR you will hit errors that can't be worked around as the Core CLR surface area just does not exist yet.** +If you see errors, or want some extra content, then feel free to create an issue or send a pull request (see feedback section below). -**NOTE: There is no Core CLR currently on OSX/Linux. There is only a single platform (mono45) and a single architecture (x86).** +### [ASP.NET/vNext](http://www.asp.net/vnext) +The vNext page on the ASP.NET site has links to some TechEd videos and articles with some good information about vNext. -#Core CLR Packages +## Repos and Projects -Currently the BCL is split into some fairly fine grained packages, which was one of the goals of this effort. However, the packages that exist today do not necessarily represent the list of packages that we will end up with. We are still experimenting with what makes sense to be a package and what the experience should be. +These are some of the most common repos: -# Known Issues +* [DependencyInjection](https://github.com/aspnet/DependencyInjection) - basic dependency injection infrastructure and default implementation +* [EntityFramework](https://github.com/aspnet/EntityFramework) - data access technology +* [Identity](https://github.com/aspnet/Identity) - users and membership system +* [KRuntime](https://github.com/aspnet/KRuntime) - core runtime, project system, loader +* [MVC](https://github.com/aspnet/Mvc) - MVC framework for web apps and services +* [SignalR-Server](https://github.com/aspnet/SignalR-Server) - real-time -* Core CLR doesn't currently work on Windows OSes earlier than Windows 8 +A description of all the repos is [here](https://github.com/aspnet/Home/wiki/Repo-List). -# Feedback +## Feedback -Check out the [contributing](https://github.com/aspnet/Home/blob/master/CONTRIBUTING.md) page to see the best places to log issues and start discussions. +Check out the [contributing](https://github.com/aspnet/Home/blob/release/CONTRIBUTING.md) page to see the best places to log issues and start discussions. diff --git a/kvm.ps1 b/kvm.ps1 index 8983061037a4..8e108caa3089 100644 --- a/kvm.ps1 +++ b/kvm.ps1 @@ -1,25 +1,26 @@ param( [parameter(Position=0)] - [string] $command, - [string] $proxy, - [switch] $verbosity = $false, - [alias("g")][switch] $global = $false, - [alias("p")][switch] $persistent = $false, - [alias("f")][switch] $force = $false, - [alias("r")][string] $runtime, - [switch] $x86 = $false, - [switch] $amd64 = $false, + [string] $Command, + [string] $Proxy, + [switch] $Verbosity = $false, + [alias("g")][switch] $Global = $false, + [alias("p")][switch] $Persistent = $false, + [alias("f")][switch] $Force = $false, + [alias("r")][string] $Runtime, + [switch] $X86 = $false, + [switch] $Amd64 = $false, #deprecated - [switch] $x64 = $false, + [switch] $X64 = $false, #deprecated - [switch] $svr50 = $false, + [switch] $Svr50 = $false, #deprecated - [switch] $svrc50 = $false, - [alias("w")][switch] $wait = $false, + [switch] $Svrc50 = $false, + [alias("w")][switch] $Wait = $false, [alias("a")] - [string] $alias = $null, + [string] $Alias = $null, + [switch] $NoNative = $false, [parameter(Position=1, ValueFromRemainingArguments=$true)] - [string[]]$args=@() + [string[]]$Args=@() ) $selectedArch=$null; @@ -32,6 +33,9 @@ $globalKrePath = $env:ProgramFiles + "\KRE" $globalKrePackages = $globalKrePath + "\packages" $feed = $env:KRE_NUGET_API_URL +# 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 } @@ -45,33 +49,35 @@ $scriptPath = $myInvocation.MyCommand.Definition function Kvm-Help { @" -K Runtime Environment Version Manager - Build 10017 +K Runtime Environment Version Manager - Build 10031 USAGE: kvm [options] -kvm upgrade [-x86][-amd64] [-r|-runtime CLR|CoreCLR] [-g|-global] [-f|-force] [-proxy
] +kvm upgrade [-X86][-Amd64] [-r|-Runtime CLR|CoreCLR] [-g|-Global] [-f|-Force] [-Proxy
] [-NoNative] install latest KRE from feed set 'default' alias to installed version add KRE 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 + -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 + -NoNative Do not generate native images (Effective only for CoreCLR flavors) -kvm install |||latest [-x86][-amd64] [-r|-runtime CLR|CoreCLR] [-a|-alias ] [-g|-global] [-f|-force] +kvm install |||latest [-X86][-Amd64] [-r|-Runtime CLR|CoreCLR] [-a|-Alias ] [-g|-Global] [-f|-Force] [-NoNative] | install requested KRE from feed install requested KRE from package on local filesystem latest install latest KRE from feed add KRE bin to path of current command line - -p|-persistent add KRE bin to PATH environment variables persistently - -a|-alias set alias for requested KRE on install - -g|-global install to machine-wide location - -f|-force install even if specified version is already installed - -kvm use ||none [-x86][-amd64] [-r|-runtime CLR|CoreCLR] [-p|-persistent] [-g|-global] - | add KRE bin to path of current command line - none remove KRE bin from path of current command line - -p|-persistent add KRE bin to PATH environment variables persistently - -g|-global combined with -p to change machine PATH instead of user PATH + -p|-Persistent add KRE bin to PATH environment variables persistently + -a|-Alias set alias for requested KRE on install + -g|-Global install to machine-wide location + -f|-Force install even if specified version is already installed + -NoNative Do not generate native images (Effective only for CoreCLR flavors) + +kvm use |||none [-X86][-Amd64] [-r|-Runtime CLR|CoreCLR] [-p|-Persistent] [-g|-Global] + || add KRE bin to path of current command line + none remove KRE bin from path of current command line + -p|-Persistent add KRE bin to PATH environment variables persistently + -g|-Global combined with -p to change machine PATH instead of user PATH kvm list list KRE versions installed @@ -82,14 +88,14 @@ kvm alias kvm alias display value of the specified alias -kvm alias | [-x86][-amd64] [-r|-runtime CLR|CoreCLR] - The name of the alias to set - | The KRE version to set the alias to. Alternatively use the version of the specified alias +kvm alias || [-X86][-Amd64] [-r|-Runtime CLR|CoreCLR] + the name of the alias to set + || the KRE version to set the alias to. Alternatively use the version of the specified alias kvm unalias remove the specified alias -"@ -replace "`n","`r`n" | Write-Host +"@ -replace "`n","`r`n" | Console-Write } function Kvm-Global-Setup { @@ -99,41 +105,41 @@ function Kvm-Global-Setup { { $arguments = "-ExecutionPolicy unrestricted & '$scriptPath' setup -global -wait" Start-Process "$psHome\powershell.exe" -Verb runAs -ArgumentList $arguments -Wait - Write-Host "Adding $kvmBinPath to process PATH" + Console-Write "Adding $kvmBinPath to process PATH" Set-Path (Change-Path $env:Path $kvmBinPath ($kvmBinPath)) - Write-Host "Adding $globalKrePath;%USERPROFILE%\.kre to process KRE_HOME" + Console-Write "Adding $globalKrePath;%USERPROFILE%\.kre to process KRE_HOME" $envKreHome = $env:KRE_HOME $envKreHome = Change-Path $envKreHome "%USERPROFILE%\.kre" ("%USERPROFILE%\.kre") $envKreHome = Change-Path $envKreHome $globalKrePath ($globalKrePath) $env:KRE_HOME = $envKreHome - Write-Host "Setup complete" + Console-Write "Setup complete" break } $scriptFolder = [System.IO.Path]::GetDirectoryName($scriptPath) - Write-Host "Copying file $kvmBinPath\kvm.ps1" + Console-Write "Copying file $kvmBinPath\kvm.ps1" md $kvmBinPath -Force | Out-Null copy "$scriptFolder\kvm.ps1" "$kvmBinPath\kvm.ps1" - Write-Host "Copying file $kvmBinPath\kvm.cmd" + Console-Write "Copying file $kvmBinPath\kvm.cmd" copy "$scriptFolder\kvm.cmd" "$kvmBinPath\kvm.cmd" - Write-Host "Adding $kvmBinPath to process PATH" + Console-Write "Adding $kvmBinPath to process PATH" Set-Path (Change-Path $env:Path $kvmBinPath ($kvmBinPath)) - Write-Host "Adding $kvmBinPath to user PATH" + Console-Write "Adding $kvmBinPath to user PATH" $userPath = [Environment]::GetEnvironmentVariable("Path", [System.EnvironmentVariableTarget]::User) $userPath = Change-Path $userPath $kvmBinPath ($kvmBinPath) [Environment]::SetEnvironmentVariable("Path", $userPath, [System.EnvironmentVariableTarget]::User) - Write-Host "Adding $globalKrePath;%USERPROFILE%\.kre to process KRE_HOME" + Console-Write "Adding $globalKrePath;%USERPROFILE%\.kre to process KRE_HOME" $envKreHome = $env:KRE_HOME $envKreHome = Change-Path $envKreHome "%USERPROFILE%\.kre" ("%USERPROFILE%\.kre") $envKreHome = Change-Path $envKreHome $globalKrePath ($globalKrePath) $env:KRE_HOME = $envKreHome - Write-Host "Adding $globalKrePath;%USERPROFILE%\.kre to machine KRE_HOME" + Console-Write "Adding $globalKrePath;%USERPROFILE%\.kre to machine KRE_HOME" $machineKreHome = [Environment]::GetEnvironmentVariable("KRE_HOME", [System.EnvironmentVariableTarget]::Machine) $machineKreHome = Change-Path $machineKreHome "%USERPROFILE%\.kre" ("%USERPROFILE%\.kre") $machineKreHome = Change-Path $machineKreHome $globalKrePath ($globalKrePath) @@ -141,8 +147,8 @@ function Kvm-Global-Setup { } function Kvm-Global-Upgrade { - $persistent = $true - $alias="default" + $Persistent = $true + $Alias="default" $versionOrAlias = Kvm-Find-Latest $selectedRuntime $selectedArch If (Needs-Elevation) { $arguments = "-ExecutionPolicy unrestricted & '$scriptPath' install '$versionOrAlias' -global $(Requested-Switches) -wait" @@ -154,8 +160,8 @@ function Kvm-Global-Upgrade { } function Kvm-Upgrade { - $persistent = $true - $alias="default" + $Persistent = $true + $Alias="default" Kvm-Install "latest" $false } @@ -163,12 +169,12 @@ function Add-Proxy-If-Specified { param( [System.Net.WebClient] $wc ) - if (!$proxy) { - $proxy = $env:http_proxy + if (!$Proxy) { + $Proxy = $env:http_proxy } - if ($proxy) { - $wp = New-Object System.Net.WebProxy($proxy) - $pb = New-Object UriBuilder($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 { @@ -183,7 +189,7 @@ param( [string] $platform, [string] $architecture ) - Write-Host "Determining latest version" + Console-Write "Determining latest version" $url = "$feed/GetUpdates()?packageIds=%27KRE-$platform-$architecture%27&versions=%270.0%27&includePrerelease=true&includeAllVersions=false" @@ -213,16 +219,16 @@ param( $kreFile = Join-Path $kreFolder "$kreFullName.nupkg" If (Test-Path $kreFolder) { - if($force) + if($Force) { rm $kreFolder -Recurse -Force } else { - Write-Host "$kreFullName already installed." + Console-Write "$kreFullName already installed." return; } } - Write-Host "Downloading" $kreFullName "from $feed" + Console-Write "Downloading $kreFullName from $feed" #Downloading to temp location $kreTempDownload = Join-Path $packagesFolder "temp" @@ -242,7 +248,7 @@ param( Do-Kvm-Unpack $tempKreFile $kreTempDownload md $kreFolder -Force | Out-Null - Write-Host "Installing to $kreFolder" + Console-Write "Installing to $kreFolder" mv "$kreTempDownload\*" $kreFolder Remove-Item "$kreTempDownload" -Force | Out-Null } @@ -252,20 +258,27 @@ param( [string] $kreFile, [string] $kreFolder ) - Write-Host "Unpacking to" $kreFolder - try { - #Shell will not recognize nupkg as a zip and throw, so rename it to zip - $kreZip = [System.IO.Path]::ChangeExtension($kreFile, "zip") - Rename-Item $kreFile $kreZip - #Use the shell to uncompress the nupkg - $shell_app=new-object -com shell.application - $zip_file = $shell_app.namespace($kreZip) - $destination = $shell_app.namespace($kreFolder) - $destination.Copyhere($zip_file.items(), 0x14) #0x4 = don't show UI, 0x10 = overwrite files - } - finally { - #make it a nupkg again - Rename-Item $kreZip $kreFile + Console-Write "Unpacking to $kreFolder" + + $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 + $kreZip = [System.IO.Path]::ChangeExtension($kreFile, "zip") + Rename-Item $kreFile $kreZip + # Use the shell to uncompress the nupkg + $shell_app=new-object -com shell.application + $zip_file = $shell_app.namespace($kreZip) + $destination = $shell_app.namespace($kreFolder) + $destination.Copyhere($zip_file.items(), 0x14) #0x4 = don't show UI, 0x10 = overwrite files + } + finally { + # make it a nupkg again + Rename-Item $kreZip $kreFile + } + } else { + [System.IO.Compression.ZipFile]::ExtractToDirectory($kreFile, $kreFolder) } If (Test-Path ($kreFolder + "\[Content_Types].xml")) { @@ -313,13 +326,13 @@ param( $kreFolder = "$packageFolder\$kreFullName" $folderExists = Test-Path $kreFolder - if ($folderExists -and $force) { + if ($folderExists -and $Force) { del $kreFolder -Recurse -Force $folderExists = $false; } if ($folderExists) { - Write-Host "Target folder '$kreFolder' already exists" + Console-Write "Target folder '$kreFolder' already exists" } else { $tempUnpackFolder = Join-Path $packageFolder "temp" $tempKreFile = Join-Path $tempUnpackFolder "$kreFullName.nupkg" @@ -333,7 +346,7 @@ param( Do-Kvm-Unpack $tempKreFile $tempUnpackFolder md $kreFolder -Force | Out-Null - Write-Host "Installing to $kreFolder" + Console-Write "Installing to $kreFolder" mv "$tempUnpackFolder\*" $kreFolder Remove-Item "$tempUnpackFolder" -Force | Out-Null } @@ -341,16 +354,27 @@ param( $packageVersion = Package-Version $kreFullName Kvm-Use $packageVersion - if (!$(String-IsEmptyOrWhitespace($alias))) { - Kvm-Alias-Set $alias $packageVersion + if (!$(String-IsEmptyOrWhitespace($Alias))) { + Kvm-Alias-Set $Alias $packageVersion } } else { Do-Kvm-Download $kreFullName $packageFolder Kvm-Use $versionOrAlias - if (!$(String-IsEmptyOrWhitespace($alias))) { - Kvm-Alias-Set "$alias" $versionOrAlias + if (!$(String-IsEmptyOrWhitespace($Alias))) { + Kvm-Alias-Set "$Alias" $versionOrAlias + } + } + + if ($kreFullName.Contains("CoreCLR")) { + if ($NoNative) { + Console-Write "Native image generation is skipped" + } + else { + Console-Write "Compiling native images for $kreFullName to improve startup performance..." + Start-Process "K" -ArgumentList "crossgen" -Wait + Console-Write "Finished native image compilation." } } } @@ -384,7 +408,10 @@ filter List-Parts { } $active = $false foreach($portion in $env:Path.Split(';')) { - if ($portion.StartsWith($_.FullName)) { + # 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 } } @@ -393,7 +420,7 @@ filter List-Parts { $delim="" foreach($alias in $aliases){ - if($_.Name.Split('\', 2).Contains($alias.Name)){ + if($_.Name.Split('\', 2) -contains $alias.Name){ $fullAlias += $delim + $alias.Alias $delim = ", " } @@ -415,6 +442,8 @@ function Kvm-Global-Use { param( [string] $versionOrAlias ) + Validate-Full-Package-Name-Arguments-Combination $versionOrAlias + If (Needs-Elevation) { $arguments = "-ExecutionPolicy unrestricted & '$scriptPath' use '$versionOrAlias' -global $(Requested-Switches) -wait" Start-Process "$psHome\powershell.exe" -Verb runAs -ArgumentList $arguments -Wait @@ -425,8 +454,8 @@ param( Kvm-Set-Global-Process-Path "$versionOrAlias" if ($versionOrAlias -eq "none") { - if ($persistent) { - Write-Host "Removing KRE from machine PATH" + if ($Persistent) { + Console-Write "Removing KRE from machine PATH" $machinePath = [Environment]::GetEnvironmentVariable("Path", [System.EnvironmentVariableTarget]::Machine) $machinePath = Change-Path $machinePath "" ($globalKrePackages, $userKrePackages) [Environment]::SetEnvironmentVariable("Path", $machinePath, [System.EnvironmentVariableTarget]::Machine) @@ -437,12 +466,11 @@ param( $kreFullName = Requested-VersionOrAlias "$versionOrAlias" $kreBin = Locate-KreBinFromFullName $kreFullName if ($kreBin -eq $null) { - Write-Host "Cannot find $kreFullName, do you need to run 'kvm install $versionOrAlias'?" - return + throw "Cannot find $kreFullName, do you need to run 'kvm install $versionOrAlias'?" } - if ($persistent) { - Write-Host "Adding $kreBin to machine PATH" + if ($Persistent) { + Console-Write "Adding $kreBin to machine PATH" $machinePath = [Environment]::GetEnvironmentVariable("Path", [System.EnvironmentVariableTarget]::Machine) $machinePath = Change-Path $machinePath $kreBin ($globalKrePackages, $userKrePackages) [Environment]::SetEnvironmentVariable("Path", $machinePath, [System.EnvironmentVariableTarget]::Machine) @@ -454,7 +482,7 @@ param( [string] $versionOrAlias ) if ($versionOrAlias -eq "none") { - Write-Host "Removing KRE from process PATH" + Console-Write "Removing KRE from process PATH" Set-Path (Change-Path $env:Path "" ($globalKrePackages, $userKrePackages)) return } @@ -462,11 +490,11 @@ param( $kreFullName = Requested-VersionOrAlias $versionOrAlias $kreBin = Locate-KreBinFromFullName $kreFullName if ($kreBin -eq $null) { - Write-Host "Cannot find $kreFullName, do you need to run 'kvm install $versionOrAlias'?" + Console-Write "Cannot find $kreFullName, do you need to run 'kvm install $versionOrAlias'?" return } - Write-Host "Adding" $kreBin "to process PATH" + Console-Write "Adding $kreBin to process PATH" Set-Path (Change-Path $env:Path $kreBin ($globalKrePackages, $userKrePackages)) } @@ -474,12 +502,14 @@ function Kvm-Use { param( [string] $versionOrAlias ) + Validate-Full-Package-Name-Arguments-Combination $versionOrAlias + if ($versionOrAlias -eq "none") { - Write-Host "Removing KRE from process PATH" + Console-Write "Removing KRE from process PATH" Set-Path (Change-Path $env:Path "" ($globalKrePackages, $userKrePackages)) - if ($persistent) { - Write-Host "Removing KRE from user PATH" + if ($Persistent) { + Console-Write "Removing KRE from user PATH" $userPath = [Environment]::GetEnvironmentVariable("Path", [System.EnvironmentVariableTarget]::User) $userPath = Change-Path $userPath "" ($globalKrePackages, $userKrePackages) [Environment]::SetEnvironmentVariable("Path", $userPath, [System.EnvironmentVariableTarget]::User) @@ -491,15 +521,14 @@ param( $kreBin = Locate-KreBinFromFullName $kreFullName if ($kreBin -eq $null) { - Write-Host "Cannot find $kreFullName, do you need to run 'kvm install $versionOrAlias'?" - return + throw "Cannot find $kreFullName, do you need to run 'kvm install $versionOrAlias'?" } - Write-Host "Adding" $kreBin "to process PATH" + Console-Write "Adding $kreBin to process PATH" Set-Path (Change-Path $env:Path $kreBin ($globalKrePackages, $userKrePackages)) - if ($persistent) { - Write-Host "Adding $kreBin to user PATH" + if ($Persistent) { + Console-Write "Adding $kreBin to user PATH" $userPath = [Environment]::GetEnvironmentVariable("Path", [System.EnvironmentVariableTarget]::User) $userPath = Change-Path $userPath $kreBin ($globalKrePackages, $userKrePackages) [Environment]::SetEnvironmentVariable("Path", $userPath, [System.EnvironmentVariableTarget]::User) @@ -519,9 +548,10 @@ param( md ($userKrePath + "\alias\") -Force | Out-Null $aliasFilePath=$userKrePath + "\alias\" + $name + ".txt" if (!(Test-Path $aliasFilePath)) { - Write-Host "Alias '$name' does not exist" + Console-Write "Alias '$name' does not exist" } else { - Write-Host "Alias '$name' is set to" (Get-Content ($userKrePath + "\alias\" + $name + ".txt")) + $aliasValue = (Get-Content ($userKrePath + "\alias\" + $name + ".txt")) + Console-Write "Alias '$name' is set to $aliasValue" } } @@ -533,7 +563,7 @@ param( $kreFullName = Requested-VersionOrAlias $value $aliasFilePath = $userKrePath + "\alias\" + $name + ".txt" $action = if (Test-Path $aliasFilePath) { "Updating" } else { "Setting" } - Write-Host "$action alias '$name' to '$kreFullName'" + Console-Write "$action alias '$name' to '$kreFullName'" md ($userKrePath + "\alias\") -Force | Out-Null $kreFullName | Out-File ($aliasFilePath) ascii } @@ -544,10 +574,10 @@ param( ) $aliasPath=$userKrePath + "\alias\" + $name + ".txt" if (Test-Path -literalPath "$aliasPath") { - Write-Host "Removing alias $name" + Console-Write "Removing alias $name" Remove-Item -literalPath $aliasPath } else { - Write-Host "Cannot remove alias, '$name' is not a valid alias name" + Console-Write "Cannot remove alias, '$name' is not a valid alias name" } } @@ -595,6 +625,15 @@ function Requested-VersionOrAlias() { param( [string] $versionOrAlias ) + Validate-Full-Package-Name-Arguments-Combination $versionOrAlias + + $kreBin = Locate-KreBinFromFullName $versionOrAlias + + # If the name specified is an existing package, just use it as is + if ($kreBin -ne $null) { + return $versionOrAlias + } + If (Test-Path ($userKrePath + "\alias\" + $versionOrAlias + ".txt")) { $aliasValue = Get-Content ($userKrePath + "\alias\" + $versionOrAlias + ".txt") $parts = $aliasValue.Split('.', 2) @@ -666,69 +705,118 @@ function Needs-Elevation() { function Requested-Switches() { $arguments = "" - if ($x86) {$arguments = "$arguments -x86"} - if ($amd64) {$arguments = "$arguments -amd64"} + if ($X86) {$arguments = "$arguments -x86"} + if ($Amd64) {$arguments = "$arguments -amd64"} #deprecated - if ($x64) {$arguments = "$arguments -x64"} + if ($X64) {$arguments = "$arguments -x64"} if ($selectedRuntime) {$arguments = "$arguments -runtime $selectedRuntime"} - if ($persistent) {$arguments = "$arguments -persistent"} - if ($force) {$arguments = "$arguments -force"} - if (!$(String-IsEmptyOrWhitespace($alias))) {$arguments = "$arguments -alias '$alias'"} + if ($Persistent) {$arguments = "$arguments -persistent"} + if ($Force) {$arguments = "$arguments -force"} + if (!$(String-IsEmptyOrWhitespace($Alias))) {$arguments = "$arguments -alias '$Alias'"} return $arguments } function Validate-And-Santitise-Switches() { - if ($svr50 -and $runtime) {throw "You cannot select both the -runtime switch and the -svr50 runtimes"} - if ($svrc50 -and $runtime) {throw "You cannot select both the -runtime switch and the -svrc50 runtimes"} - if ($x86 -and $amd64) {throw "You cannot select both x86 and amd64 architectures"} - if ($x86 -and $x64) {throw "You cannot select both x86 and x64 architectures"} - if ($x64 -and $amd64) {throw "You cannot select both x64 and amd64 architectures"} + if ($Svr50 -and $Runtime) {throw "You cannot select both the -runtime switch and the -svr50 runtimes"} + if ($Svrc50 -and $Runtime) {throw "You cannot select both the -runtime switch and the -svrc50 runtimes"} + if ($X86 -and $Amd64) {throw "You cannot select both x86 and amd64 architectures"} + if ($X86 -and $X64) {throw "You cannot select both x86 and x64 architectures"} + if ($X64 -and $Amd64) {throw "You cannot select both x64 and amd64 architectures"} - if ($runtime) { + if ($Runtime) { $validRuntimes = "CoreCLR", "CLR", "svr50", "svrc50" - $match = $validRuntimes | ? { $_ -like $runtime } | Select -First 1 + $match = $validRuntimes | ? { $_ -like $Runtime } | Select -First 1 if (!$match) {throw "'$runtime' is not a valid runtime"} Set-Variable -Name "selectedRuntime" -Value $match -Scope Script - } elseif ($svr50) { - Write-Host "Warning: -svr50 is deprecated, use -runtime CLR for new packages." + } elseif ($Svr50) { + Console-Write "Warning: -svr50 is deprecated, use -runtime CLR for new packages." Set-Variable -Name "selectedRuntime" -Value "svr50" -Scope Script - } elseif ($svrc50) { - Write-Host "Warning: -svrc50 is deprecated, use -runtime CoreCLR for new packages." + } elseif ($Svrc50) { + Console-Write "Warning: -svrc50 is deprecated, use -runtime CoreCLR for new packages." Set-Variable -Name "selectedRuntime" -Value "svrc50" -Scope Script } - if ($x64) { - Write-Host "Warning: -x64 is deprecated, use -amd64 for new packages." + if ($X64) { + Console-Write "Warning: -x64 is deprecated, use -amd64 for new packages." Set-Variable -Name "selectedArch" -Value "x64" -Scope Script - } elseif ($amd64) { + } elseif ($Amd64) { Set-Variable -Name "selectedArch" -Value "amd64" -Scope Script - } elseif ($x86) { + } elseif ($X86) { Set-Variable -Name "selectedArch" -Value "x86" -Scope Script } } +function Console-Write() { +param( + [Parameter(ValueFromPipeline=$true)] + [string] $message +) + 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 "KRE-*" -and + ($selectedArch -or $selectedRuntime)) { + throw "Runtime or architecture cannot be specified when using the full package name." + } +} + +$exitCode = 0 try { Validate-And-Santitise-Switches - if ($global) { - switch -wildcard ($command + " " + $args.Count) { + if ($Global) { + switch -wildcard ($Command + " " + $Args.Count) { "setup 0" {Kvm-Global-Setup} "upgrade 0" {Kvm-Global-Upgrade} - "install 1" {Kvm-Install $args[0] $true} - "use 1" {Kvm-Global-Use $args[0]} + "install 1" {Kvm-Install $Args[0] $true} + "use 1" {Kvm-Global-Use $Args[0]} default {throw "Unknown command, or global switch not supported"}; } } else { - switch -wildcard ($command + " " + $args.Count) { + switch -wildcard ($Command + " " + $Args.Count) { "setup 0" {Kvm-Global-Setup} "upgrade 0" {Kvm-Upgrade} - "install 1" {Kvm-Install $args[0] $false} + "install 1" {Kvm-Install $Args[0] $false} "list 0" {Kvm-List} - "use 1" {Kvm-Use $args[0]} + "use 1" {Kvm-Use $Args[0]} "alias 0" {Kvm-Alias-List} - "alias 1" {Kvm-Alias-Get $args[0]} - "alias 2" {Kvm-Alias-Set $args[0] $args[1]} - "unalias 1" {Kvm-Unalias $args[0]} + "alias 1" {Kvm-Alias-Get $Args[0]} + "alias 2" {Kvm-Alias-Set $Args[0] $Args[1]} + "unalias 1" {Kvm-Unalias $Args[0]} "help 0" {Kvm-Help} " 0" {Kvm-Help} default {throw "Unknown command"}; @@ -736,10 +824,13 @@ try { } } catch { - Write-Host $_ -ForegroundColor Red ; - Write-Host "Type 'kvm help' for help on how to use kvm." + Console-Write-Error $_ + Console-Write "Type 'kvm help' for help on how to use kvm." + $exitCode = -1 } -if ($wait) { - Write-Host "Press any key to continue ..." +if ($Wait) { + Console-Write "Press any key to continue ..." $x = $host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown,AllowCtrlC") } + +exit $exitCode diff --git a/kvm.sh b/kvm.sh index c9a91055b539..5fd817084fa6 100644 --- a/kvm.sh +++ b/kvm.sh @@ -14,23 +14,19 @@ if [ -z "$KRE_USER_HOME" ]; then fi KRE_USER_PACKAGES="$KRE_USER_HOME/packages" -KRE_MONO45= -KRE_X86= -KRE_X64= if [ -z "$KRE_FEED" ]; then KRE_FEED="https://www.myget.org/F/aspnetvnext/api/v2" fi _kvm_find_latest() { - local platform="mono45" - local architecture="x86" + local platform="Mono" if ! _kvm_has "curl"; then echo 'KVM Needs curl to proceed.' >&2; return 1 fi - local url="$KRE_FEED/GetUpdates()?packageIds=%27KRE-$platform-$architecture%27&versions=%270.0%27&includePrerelease=true&includeAllVersions=false" + local url="$KRE_FEED/GetUpdates()?packageIds=%27KRE-$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/')" @@ -61,7 +57,7 @@ _kvm_package_name() { _kvm_package_runtime() { local kreFullName="$1" - echo "$kreFullName" | sed "s/KRE-\([^-]*\).*/\1/" + echo "$kreFullName" | sed "s/KRE-\([^.-]*\).*/\1/" } _kvm_download() { @@ -93,6 +89,7 @@ _kvm_download() { [[ $httpResult != "302" && $httpResult != "200" ]] && echo "HTTP Error $httpResult fetching $kreFullName from $KRE_FEED" && return 1 _kvm_unpack $kreFile $kreFolder + return $? } _kvm_unpack() { @@ -119,38 +116,26 @@ _kvm_unpack() { -exec sh -c "head -c 11 {} | grep '/bin/bash' > /dev/null" \; -print | xargs chmod 775 } -# This is not currently required. Placeholder for the case when we have multiple platforms (ie if we bundle mono) -_kvm_requested_platform() { - local default=$1 - [[ -z $KRE_MONO45 ]] && echo "mono45" && return - echo $default -} - -# This is not currently required. Placeholder for the case where we have multiple architectures (ie if we bundle mono) -_kvm_requested_architecture() { - local default=$1 - - [[ -n $KRE_X86 && -n $KRE_X64 ]] && echo "This command cannot accept both -x86 and -x64" && return 1 - [[ -z $KRE_X86 ]] && echo "x86" && return - [[ -z $KRE_X64 ]] && echo "x64" && return - echo $default -} - _kvm_requested_version_or_alias() { local versionOrAlias="$1" - - if [ -e "$KRE_USER_HOME/alias/$versionOrAlias.alias" ]; then - local kreFullName=$(cat "$KRE_USER_HOME/alias/$versionOrAlias.alias") - local pkgName=$(echo $kreFullName | sed "s/\([^.]*\).*/\1/") - local pkgVersion=$(echo $kreFullName | sed "s/[^.]*.\(.*\)/\1/") - local pkgPlatform=$(_kvm_requested_platform $(echo "$pkgName" | sed "s/KRE-\([^-]*\).*/\1/")) - local pkgArchitecture=$(_kvm_requested_architecture $(echo "$pkgName" | sed "s/.*-.*-\([^-]*\).*/\1/")) - else - local pkgVersion=$versionOrAlias - local pkgPlatform=$(_kvm_requested_platform "mono45") - local pkgArchitecture=$(_kvm_requested_architecture "x86") + local kreBin=$(_kvm_locate_kre_bin_from_full_name "$versionOrAlias") + + # If the name specified is an existing package, just use it as is + if [ -n "$kreBin" ]; then + echo "$versionOrAlias" + else + if [ -e "$KRE_USER_HOME/alias/$versionOrAlias.alias" ]; then + local kreFullName=$(cat "$KRE_USER_HOME/alias/$versionOrAlias.alias") + local pkgName=$(echo $kreFullName | sed "s/\([^.]*\).*/\1/") + local pkgVersion=$(echo $kreFullName | sed "s/[^.]*.\(.*\)/\1/") + local pkgPlatform=$(echo "$pkgName" | sed "s/KRE-\([^.-]*\).*/\1/") + else + local pkgVersion=$versionOrAlias + local pkgPlatform="Mono" + fi + + echo "KRE-$pkgPlatform.$pkgVersion" fi - echo "KRE-$pkgPlatform-$pkgArchitecture.$pkgVersion" } # This will be more relevant if we support global installs @@ -169,7 +154,7 @@ kvm() case $1 in "help" ) echo "" - echo "K Runtime Environment Version Manager - Build 10002" + echo "K Runtime Environment Version Manager - Build {{BUILD_NUMBER}}" echo "" echo "USAGE: kvm [options]" echo "" @@ -186,10 +171,10 @@ kvm() echo "-p -persistent set installed version as default" echo "add KRE bin to path of current command line" echo "" - echo "kvm use ||none [-p -persistent]" - echo "| add KRE bin to path of current command line " - echo "none remove KRE bin from path of current command line" - echo "-p -persistent set selected version as default" + echo "kvm use |||none [-p -persistent]" + echo "|| add KRE bin to path of current command line " + echo "none remove KRE bin from path of current command line" + echo "-p -persistent set selected version as default" echo "" echo "kvm list" echo "list KRE versions installed " @@ -198,12 +183,14 @@ kvm() echo "list KRE aliases which have been defined" echo "" echo "kvm alias " - echo "display value of named alias" + echo "display value of the specified alias" echo "" - echo "kvm alias " - echo " The name of the alias to set" - echo "| The KRE version to set the alias to. Alternatively use the version of the specified alias" + echo "kvm alias ||" + echo " the name of the alias to set" + echo "|| the KRE version to set the alias to. Alternatively use the version of the specified alias" echo "" + echo "kvm unalias " + echo "remove the specified alias" echo "" ;; @@ -233,7 +220,7 @@ kvm() done if [[ "$versionOrAlias" == "latest" ]]; then echo "Determining latest version" - versionOrAlias=$(_kvm_find_latest mono45 x86) + versionOrAlias=$(_kvm_find_latest) [[ $? == 1 ]] && echo "Error: Could not find latest version from feed $KRE_FEED" && return 1 echo "Latest version is $versionOrAlias" fi @@ -249,6 +236,7 @@ kvm() mkdir "$kreFolder" > /dev/null 2>&1 cp -a "$versionOrAlias" "$kreFile" _kvm_unpack "$kreFile" "$kreFolder" + [[ $? == 1 ]] && return 1 fi kvm use "$kreVersion" "$persistent" [[ -n $alias ]] && kvm alias "$alias" "$kreVersion" @@ -256,7 +244,7 @@ kvm() local kreFullName="$(_kvm_requested_version_or_alias $versionOrAlias)" local kreFolder="$KRE_USER_PACKAGES/$kreFullName" _kvm_download "$kreFullName" "$kreFolder" - [[ $? == 1 ]] && return + [[ $? == 1 ]] && return 1 kvm use "$versionOrAlias" "$persistent" [[ -n $alias ]] && kvm alias "$alias" "$versionOrAlias" fi @@ -339,13 +327,24 @@ kvm() local kreFullName=$(_kvm_requested_version_or_alias "$3") - [[ ! -d "$KRE_USER_PACKAGES/$kreFullName" ]] && echo "$kreFullName is not an installed KRE version." && return 1 - - echo "Setting alias '$name' to '$kreFullName'" + [[ ! -d "$KRE_USER_PACKAGES/$kreFullName" ]] && echo "$kreFullName is not an installed KRE version" && return 1 + local action="Setting" + [[ -e "$KRE_USER_HOME/alias/$name.alias" ]] && action="Updating" + echo "$action alias '$name' to '$kreFullName'" echo "$kreFullName" > "$KRE_USER_HOME/alias/$name.alias" ;; + "unalias" ) + [[ $# -ne 2 ]] && kvm help && return + + local name=$2 + local aliasPath="$KRE_USER_HOME/alias/$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 @@ -357,15 +356,43 @@ kvm() local searchGlob=$(_kvm_requested_version_or_alias "$versionOrAlias") fi echo "" - local formatString="%-6s %-20s %-7s %-12s %s\n" - printf "$formatString" "Active" "Version" "Runtime" "Architecture" "Location" - printf "$formatString" "------" "-------" "-------" "------------" "--------" - for f in $(find $KRE_USER_PACKAGES/* -name "$searchGlob" -type d -prune -exec basename {} \;); do + + # 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" + for _kvm_file in $(find "$KRE_USER_HOME/alias" -name *.alias); do + arr[$i]="$(basename $_kvm_file | sed 's/.alias//')/$(cat $_kvm_file)" + let i+=1 + done + + local formatString="%-6s %-20s %-7s %-20s %s\n" + printf "$formatString" "Active" "Version" "Runtime" "Location" "Alias" + printf "$formatString" "------" "-------" "-------" "--------" "-----" + + local formattedHome=`(echo $KRE_USER_PACKAGES | sed s=$HOME=~=g)` + for f in $(find $KRE_USER_PACKAGES -name "$searchGlob" \( -type d -or -type l \) -prune -exec basename {} \;); do local active="" [[ $PATH == *"$KRE_USER_PACKAGES/$f/bin"* ]] && local active=" *" local pkgName=$(_kvm_package_runtime "$f") local pkgVersion=$(_kvm_package_version "$f") - printf "$formatString" "$active" "$pkgVersion" "$pkgName" "x86" "$KRE_USER_PACKAGES" + + local alias="" + local delim="" + for i in "${arr[@]}"; do + temp="KRE-$pkgName.$pkgVersion" + temp2="KRE-$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 @@ -377,6 +404,8 @@ kvm() echo "Unknown command $1" return 1 esac + + return 0 } kvm list default >/dev/null && kvm use default >/dev/null || true diff --git a/samples/HelloMvc/project.json b/samples/HelloMvc/project.json index 6dee13b65f90..f22b022725f1 100644 --- a/samples/HelloMvc/project.json +++ b/samples/HelloMvc/project.json @@ -9,7 +9,7 @@ }, "commands": { "web": "Microsoft.AspNet.Hosting --server Microsoft.AspNet.Server.WebListener --server.urls http://localhost:5001", - "Kestrel": "Microsoft.AspNet.Hosting --server Kestrel --server.urls http://localhost:5004" + "kestrel": "Microsoft.AspNet.Hosting --server Kestrel --server.urls http://localhost:5004" }, "frameworks": { "aspnet50": {}, diff --git a/samples/HelloWeb/project.json b/samples/HelloWeb/project.json index 69dc29621381..e14331014886 100644 --- a/samples/HelloWeb/project.json +++ b/samples/HelloWeb/project.json @@ -9,7 +9,7 @@ }, "commands": { "web": "Microsoft.AspNet.Hosting --server Microsoft.AspNet.Server.WebListener --server.urls http://localhost:5001", - "Kestrel": "Microsoft.AspNet.Hosting --server Kestrel --server.urls http://localhost:5004" + "kestrel": "Microsoft.AspNet.Hosting --server Kestrel --server.urls http://localhost:5004" }, "frameworks": { "aspnet50": {}, From d4f4e9cf7f14f6675e79951d91081494639b9de4 Mon Sep 17 00:00:00 2001 From: Praburaj Date: Mon, 5 Jan 2015 18:59:54 -0800 Subject: [PATCH 07/27] Updating kvm scripts in home/release branch. --- kvm.ps1 | 34 +++++++++++----------------------- kvm.sh | 6 +++--- 2 files changed, 14 insertions(+), 26 deletions(-) diff --git a/kvm.ps1 b/kvm.ps1 index 8e108caa3089..1ac4b79d566e 100644 --- a/kvm.ps1 +++ b/kvm.ps1 @@ -31,7 +31,7 @@ $userKrePath = $env:USERPROFILE + "\.kre" $userKrePackages = $userKrePath + "\packages" $globalKrePath = $env:ProgramFiles + "\KRE" $globalKrePackages = $globalKrePath + "\packages" -$feed = $env:KRE_NUGET_API_URL +$feed = $env:KRE_FEED # In some environments, like Azure Websites, the Write-* cmdlets don't work $useHostOutputMethods = $true @@ -49,7 +49,7 @@ $scriptPath = $myInvocation.MyCommand.Definition function Kvm-Help { @" -K Runtime Environment Version Manager - Build 10031 +K Runtime Environment Version Manager - Build 10050 USAGE: kvm [options] @@ -146,23 +146,13 @@ function Kvm-Global-Setup { [Environment]::SetEnvironmentVariable("KRE_HOME", $machineKreHome, [System.EnvironmentVariableTarget]::Machine) } -function Kvm-Global-Upgrade { - $Persistent = $true - $Alias="default" - $versionOrAlias = Kvm-Find-Latest $selectedRuntime $selectedArch - If (Needs-Elevation) { - $arguments = "-ExecutionPolicy unrestricted & '$scriptPath' install '$versionOrAlias' -global $(Requested-Switches) -wait" - Start-Process "$psHome\powershell.exe" -Verb runAs -ArgumentList $arguments -Wait - Kvm-Set-Global-Process-Path $versionOrAlias - break - } - Kvm-Install $versionOrAlias $true -} - function Kvm-Upgrade { +param( + [boolean] $isGlobal +) $Persistent = $true $Alias="default" - Kvm-Install "latest" $false + Kvm-Install "latest" $isGlobal } function Add-Proxy-If-Specified { @@ -194,7 +184,6 @@ param( $url = "$feed/GetUpdates()?packageIds=%27KRE-$platform-$architecture%27&versions=%270.0%27&includePrerelease=true&includeAllVersions=false" $wc = New-Object System.Net.WebClient - $wc.Credentials = new-object System.Net.NetworkCredential("aspnetreadonly", "4d8a2d9c-7b80-4162-9978-47e918c9658c") Add-Proxy-If-Specified($wc) [xml]$xml = $wc.DownloadString($url) @@ -241,7 +230,6 @@ param( } $wc = New-Object System.Net.WebClient - $wc.Credentials = new-object System.Net.NetworkCredential("aspnetreadonly", "4d8a2d9c-7b80-4162-9978-47e918c9658c") Add-Proxy-If-Specified($wc) $wc.DownloadFile($url, $tempKreFile) @@ -373,7 +361,7 @@ param( } else { Console-Write "Compiling native images for $kreFullName to improve startup performance..." - Start-Process "K" -ArgumentList "crossgen" -Wait + Start-Process "k-crossgen" -Wait Console-Write "Finished native image compilation." } } @@ -716,7 +704,7 @@ function Requested-Switches() { return $arguments } -function Validate-And-Santitise-Switches() +function Validate-And-Santitize-Switches() { if ($Svr50 -and $Runtime) {throw "You cannot select both the -runtime switch and the -svr50 runtimes"} if ($Svrc50 -and $Runtime) {throw "You cannot select both the -runtime switch and the -svrc50 runtimes"} @@ -797,11 +785,11 @@ param( $exitCode = 0 try { - Validate-And-Santitise-Switches + Validate-And-Santitize-Switches if ($Global) { switch -wildcard ($Command + " " + $Args.Count) { "setup 0" {Kvm-Global-Setup} - "upgrade 0" {Kvm-Global-Upgrade} + "upgrade 0" {Kvm-Upgrade $true} "install 1" {Kvm-Install $Args[0] $true} "use 1" {Kvm-Global-Use $Args[0]} default {throw "Unknown command, or global switch not supported"}; @@ -809,7 +797,7 @@ try { } else { switch -wildcard ($Command + " " + $Args.Count) { "setup 0" {Kvm-Global-Setup} - "upgrade 0" {Kvm-Upgrade} + "upgrade 0" {Kvm-Upgrade $false} "install 1" {Kvm-Install $Args[0] $false} "list 0" {Kvm-List} "use 1" {Kvm-Use $Args[0]} diff --git a/kvm.sh b/kvm.sh index 5fd817084fa6..62285639cc48 100644 --- a/kvm.sh +++ b/kvm.sh @@ -15,7 +15,7 @@ fi KRE_USER_PACKAGES="$KRE_USER_HOME/packages" if [ -z "$KRE_FEED" ]; then - KRE_FEED="https://www.myget.org/F/aspnetvnext/api/v2" + KRE_FEED="https://www.myget.org/F/aspnetrelease/api/v2" fi _kvm_find_latest() { @@ -83,7 +83,7 @@ _kvm_download() { mkdir -p "$kreFolder" > /dev/null 2>&1 - local httpResult=$(curl -L -D - -u aspnetreadonly:4d8a2d9c-7b80-4162-9978-47e918c9658c "$url" -o "$kreFile" 2>/dev/null | grep "^HTTP/1.1" | head -n 1 | sed "s/HTTP.1.1 \([0-9]*\).*/\1/") + local httpResult=$(curl -L -D - "$url" -o "$kreFile" 2>/dev/null | grep "^HTTP/1.1" | head -n 1 | sed "s/HTTP.1.1 \([0-9]*\).*/\1/") [[ $httpResult == "404" ]] && echo "$kreFullName was not found in repository $KRE_FEED" && return 1 [[ $httpResult != "302" && $httpResult != "200" ]] && echo "HTTP Error $httpResult fetching $kreFullName from $KRE_FEED" && return 1 @@ -154,7 +154,7 @@ kvm() case $1 in "help" ) echo "" - echo "K Runtime Environment Version Manager - Build {{BUILD_NUMBER}}" + echo "K Runtime Environment Version Manager - Build 10050" echo "" echo "USAGE: kvm [options]" echo "" From 162d3c5f306770c717377e16b1cae3830e088bcf Mon Sep 17 00:00:00 2001 From: "ASP.NET Push Bot" Date: Thu, 22 Jan 2015 14:21:44 -0800 Subject: [PATCH 08/27] :arrow_up: dotnetsdk.ps1, dotnetsdk.cmd, dotnetsdk.sh Source: aspnet/kvm@e806a5a31a41ed317c71a6948a1e8ee30cdc1475 --- dotnetsdk.cmd | 8 + dotnetsdk.ps1 | 774 ++++++++++++++++++++++++++++++++++++++++++++++++++ dotnetsdk.sh | 416 +++++++++++++++++++++++++++ 3 files changed, 1198 insertions(+) create mode 100644 dotnetsdk.cmd create mode 100644 dotnetsdk.ps1 create mode 100644 dotnetsdk.sh diff --git a/dotnetsdk.cmd b/dotnetsdk.cmd new file mode 100644 index 000000000000..f920d71aecd6 --- /dev/null +++ b/dotnetsdk.cmd @@ -0,0 +1,8 @@ +@Echo off + +PowerShell -NoProfile -NoLogo -ExecutionPolicy unrestricted -Command "[System.Threading.Thread]::CurrentThread.CurrentCulture = ''; [System.Threading.Thread]::CurrentThread.CurrentUICulture = '';& '%~dp0dotnetsdk.ps1' %*" + +IF EXIST "%USERPROFILE%\.dotnet\temp-set-envvars.cmd" ( + CALL "%USERPROFILE%\.dotnet\temp-set-envvars.cmd" + DEL "%USERPROFILE%\.dotnet\temp-set-envvars.cmd" +) diff --git a/dotnetsdk.ps1 b/dotnetsdk.ps1 new file mode 100644 index 000000000000..d069abc32a77 --- /dev/null +++ b/dotnetsdk.ps1 @@ -0,0 +1,774 @@ +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" (in as much as PowerShell will allow) +$RuntimePackageName = "dotnet" +$RuntimeFriendlyName = ".NET Runtime" +$RuntimeProgramFilesName = "Microsoft .NET Cross-Platform Runtime" +$RuntimeFolderName = ".dotnet" +$DefaultFeed = "https://www.myget.org/F/aspnetvnext/api/v2" +$CrossGenCommand = "k-crossgen" + +$selectedArch=$null; +$defaultArch="x86" +$selectedRuntime=$null +$defaultRuntime="clr" + +# Get or calculate userDotNetPath +$userDotNetPath = $env:DOTNET_USER_PATH +if(!$userDotNetPath) { $userDotNetPath = $env:USERPROFILE + "\$RuntimeFolderName" } +$userDotNetRuntimesPath = $userDotNetPath + "\runtimes" + +# Get the feed from the environment variable or set it to the default value +$feed = $env:DOTNET_FEED +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 DotNetSdk-Help { +@" +.NET SDK Manager - Build 10303 + +USAGE: dotnetsdk [options] + +dotnetsdk upgrade [-X86|-X64] [-r|-Runtime CLR|CoreCLR] [-g|-Global] [-f|-Force] [-Proxy
] [-NoNative] + install latest .NET Runtime from feed + set 'default' alias to installed version + add KRE 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) + +dotnetsdk install |||latest [-X86|-X64] [-r|-Runtime CLR|CoreCLR] [-a|-Alias ] [-f|-Force] [-Proxy
] [-NoNative] + | install requested .NET Runtime from feed + install requested .NET Runtime from package on local filesystem + latest install latest .NET Runtime from feed + add .NET Runtime bin to path of current command line + -p|-Persistent add .NET Runtime bin to PATH environment variables persistently + -a|-Alias set alias for requested .NET Runtime 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) + +dotnetsdk use |||none [-X86|-X64] [-r|-Runtime CLR|CoreCLR] [-p|-Persistent] + || add .NET Runtime bin to path of current command line + none remove .NET Runtime bin from path of current command line + -p|-Persistent add .NET Runtime bin to PATH environment variable across all processes run by the current user + +dotnetsdk list + list .NET Runtime versions installed + +dotnetsdk alias + list .NET Runtime aliases which have been defined + +dotnetsdk alias + display value of the specified alias + +dotnetsdk alias || [-X86|-X64] [-r|-Runtime CLR|CoreCLR] + the name of the alias to set + || the .NET Runtime version to set the alias to. Alternatively use the version of the specified alias + +dotnetsdk unalias + remove the specified alias + +"@ -replace "`n","`r`n" | Console-Write +} + +function DotNetSdk-Global-Setup { + # Sets up the 'dotnetsdk' tool and adds the user-local dotnet install directory to the DOTNET_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 DOTNET_HOME value. + + # In this configuration, the user-level path will OVERRIDE the global path because it is placed first. + + $dotnetsdkBinPath = "$userDotNetPath\bin" + + If (Needs-Elevation) + { + $arguments = "-ExecutionPolicy unrestricted & '$scriptPath' setup -wait" + Start-Process "$psHome\powershell.exe" -Verb runAs -ArgumentList $arguments -Wait + Console-Write "Adding $dotnetsdkBinPath to process PATH" + Set-Path (Change-Path $env:Path $dotnetsdkBinPath ($dotnetsdkBinPath)) + Console-Write "Adding %USERPROFILE%\$RuntimeFolderName to process DOTNET_HOME" + $envDotNetHome = $env:DOTNET_HOME + $envDotNetHome = Change-Path $envDotNetHome "%USERPROFILE%\$RuntimeFolderName" ("%USERPROFILE%\$RuntimeFolderName") + $env:DOTNET_HOME = $envDotNetHome + Console-Write "Setup complete" + break + } + + $scriptFolder = [System.IO.Path]::GetDirectoryName($scriptPath) + + Console-Write "Copying file $dotnetsdkBinPath\dotnetsdk.ps1" + md $dotnetsdkBinPath -Force | Out-Null + copy "$scriptFolder\dotnetsdk.ps1" "$dotnetsdkBinPath\dotnetsdk.ps1" + + Console-Write "Copying file $dotnetsdkBinPath\dotnetsdk.cmd" + copy "$scriptFolder\dotnetsdk.cmd" "$dotnetsdkBinPath\dotnetsdk.cmd" + + Console-Write "Adding $dotnetsdkBinPath to process PATH" + Set-Path (Change-Path $env:Path $dotnetsdkBinPath ($dotnetsdkBinPath)) + + Console-Write "Adding $dotnetsdkBinPath to user PATH" + $userPath = [Environment]::GetEnvironmentVariable("Path", [System.EnvironmentVariableTarget]::User) + $userPath = Change-Path $userPath $dotnetsdkBinPath ($dotnetsdkBinPath) + [Environment]::SetEnvironmentVariable("Path", $userPath, [System.EnvironmentVariableTarget]::User) + + Console-Write "Adding %USERPROFILE%\$RuntimeFolderName to process DOTNET_HOME" + $envDotNetHome = $env:DOTNET_HOME + $envDotNetHome = Change-Path $envDotNetHome "%USERPROFILE%\$RuntimeFolderName" ("%USERPROFILE%\$RuntimeFolderName") + $env:DOTNET_HOME = $envDotNetHome + + Console-Write "Adding %USERPROFILE%\$RuntimeFolderName to machine DOTNET_HOME" + $machineDotNetHome = [Environment]::GetEnvironmentVariable("DOTNET_HOME", [System.EnvironmentVariableTarget]::Machine) + $machineDotNetHome = Change-Path $machineDotNetHome "%USERPROFILE%\$RuntimeFolderName" ("%USERPROFILE%\$RuntimeFolderName") + [Environment]::SetEnvironmentVariable("DOTNET_HOME", $machineDotNetHome, [System.EnvironmentVariableTarget]::Machine) +} + +function DotNetSdk-Upgrade { +param( + [boolean] $isGlobal +) + $Persistent = $true + $Alias="default" + DotNetSdk-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 DotNetSdk-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-DotNetSdk-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-DotNetSdk-Unpack $tempDownloadFile $runtimeTempDownload + + md $runtimeFolder -Force | Out-Null + Console-Write "Installing to $runtimeFolder" + mv "$runtimeTempDownload\*" $runtimeFolder + Remove-Item "$runtimeTempDownload" -Force | Out-Null +} + +function Do-DotNetSdk-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 + } +} + +function DotNetSdk-Install { +param( + [string] $versionOrAlias, + [boolean] $isGlobal +) + if ($versionOrAlias -eq "latest") { + $versionOrAlias = DotNetSdk-Find-Latest (Requested-Platform $defaultRuntime) (Requested-Architecture $defaultArch) + } + + if ($versionOrAlias.EndsWith(".nupkg")) { + $runtimeFullName = [System.IO.Path]::GetFileNameWithoutExtension($versionOrAlias) + } else { + $runtimeFullName = Requested-VersionOrAlias $versionOrAlias + } + + $packageFolder = $userDotNetRuntimesPath + + 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-DotNetSdk-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 + + DotNetSdk-Use $packageVersion + if (!$(String-IsEmptyOrWhitespace($Alias))) { + DotNetSdk-Alias-Set $Alias $packageVersion + } + } + else + { + Do-DotNetSdk-Download $runtimeFullName $packageFolder + DotNetSdk-Use $versionOrAlias + if (!$(String-IsEmptyOrWhitespace($Alias))) { + DotNetSdk-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 DotNetSdk-List { + $dotnetHome = $env:DOTNET_HOME + if (!$dotnetHome) { + $dotnetHome = "$userDotNetPath" + } + + md ($userDotNetPath + "\alias\") -Force | Out-Null + $aliases = Get-ChildItem ($userDotNetPath + "\alias\") | Select @{label='Alias';expression={$_.BaseName}}, @{label='Name';expression={Get-Content $_.FullName }} + + $items = @() + foreach($portion in $dotnetHome.Split(';')) { + $path = [System.Environment]::ExpandEnvironmentVariables($portion) + if (Test-Path("$path\runtimes")) { + $items += Get-ChildItem ("$path\runtimes\dotnet-*") | 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 DotNetSdk-Use { +param( + [string] $versionOrAlias +) + Validate-Full-Package-Name-Arguments-Combination $versionOrAlias + + if ($versionOrAlias -eq "none") { + Console-Write "Removing .NET Runtime from process PATH" + Set-Path (Change-Path $env:Path "" ($userDotNetRuntimesPath)) + + if ($Persistent) { + Console-Write "Removing .NET Runtime from user PATH" + $userPath = [Environment]::GetEnvironmentVariable("Path", [System.EnvironmentVariableTarget]::User) + $userPath = Change-Path $userPath "" ($userDotNetRuntimesPath) + [Environment]::SetEnvironmentVariable("Path", $userPath, [System.EnvironmentVariableTarget]::User) + } + return; + } + + $runtimeFullName = Requested-VersionOrAlias $versionOrAlias + + $runtimeBin = Locate-DotNetBinFromFullName $runtimeFullName + if ($runtimeBin -eq $null) { + throw "Cannot find $runtimeFullName, do you need to run 'dotnetsdk install $versionOrAlias'?" + } + + Console-Write "Adding $runtimeBin to process PATH" + Set-Path (Change-Path $env:Path $runtimeBin ($userDotNetRuntimesPath)) + + if ($Persistent) { + Console-Write "Adding $runtimeBin to user PATH" + $userPath = [Environment]::GetEnvironmentVariable("Path", [System.EnvironmentVariableTarget]::User) + $userPath = Change-Path $userPath $runtimeBin ($userDotNetRuntimesPath) + [Environment]::SetEnvironmentVariable("Path", $userPath, [System.EnvironmentVariableTarget]::User) + } +} + +function DotNetSdk-Alias-List { + md ($userDotNetPath + "\alias\") -Force | Out-Null + + Get-ChildItem ($userDotNetPath + "\alias\") | Select @{label='Alias';expression={$_.BaseName}}, @{label='Name';expression={Get-Content $_.FullName }} | Format-Table -AutoSize +} + +function DotNetSdk-Alias-Get { +param( + [string] $name +) + md ($userDotNetPath + "\alias\") -Force | Out-Null + $aliasFilePath=$userDotNetPath + "\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 ($userDotNetPath + "\alias\" + $name + ".txt")) + Console-Write "Alias '$name' is set to $aliasValue" + } +} + +function DotNetSdk-Alias-Set { +param( + [string] $name, + [string] $value +) + $runtimeFullName = Requested-VersionOrAlias $value + $aliasFilePath = $userDotNetPath + "\alias\" + $name + ".txt" + $action = if (Test-Path $aliasFilePath) { "Updating" } else { "Setting" } + Console-Write "$action alias '$name' to '$runtimeFullName'" + md ($userDotNetPath + "\alias\") -Force | Out-Null + $runtimeFullName | Out-File ($aliasFilePath) ascii +} + +function DotNetSdk-Unalias { +param( + [string] $name +) + $aliasPath=$userDotNetPath + "\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-DotNetBinFromFullName() { +param( + [string] $runtimeFullName +) + $dotnetHome = $env:DOTNET_HOME + if (!$dotnetHome) { + $dotnetHome = "$globalDotNetPath;$userDotNetPath" + } + foreach($portion in $dotnetHome.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 'dotnet-([^-]*).*', '$1' +} + +function Package-Arch() { +param( + [string] $runtimeFullName +) + return $runtimeFullName -replace 'dotnet-[^-]*-[^-]*-([^.]*).*', '$1' +} + + +function Requested-VersionOrAlias() { +param( + [string] $versionOrAlias +) + Validate-Full-Package-Name-Arguments-Combination $versionOrAlias + + $runtimeBin = Locate-DotNetBinFromFullName $versionOrAlias + + # If the name specified is an existing package, just use it as is + if ($runtimeBin -ne $null) { + return $versionOrAlias + } + + If (Test-Path ($userDotNetPath + "\alias\" + $versionOrAlias + ".txt")) { + $aliasValue = Get-Content ($userDotNetPath + "\alias\" + $versionOrAlias + ".txt") + # Split dotnet-coreclr-win-x86.1.0.0-beta3-10922 into version and name sections + $parts = $aliasValue.Split('.', 2) + $pkgVersion = $parts[1] + # dotnet-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 $userDotNetPath -Force | Out-Null + $env:Path = $newPath +@" +SET "PATH=$newPath" +"@ | Out-File ($userDotNetPath + "\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 "dotnet-*" -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" {DotNetSdk-Global-Setup} + "upgrade 0" {DotNetSdk-Upgrade $false} + "install 1" {DotNetSdk-Install $Args[0] $false} + "list 0" {DotNetSdk-List} + "use 1" {DotNetSdk-Use $Args[0]} + "alias 0" {DotNetSdk-Alias-List} + "alias 1" {DotNetSdk-Alias-Get $Args[0]} + "alias 2" {DotNetSdk-Alias-Set $Args[0] $Args[1]} + "unalias 1" {DotNetSdk-Unalias $Args[0]} + "help 0" {DotNetSdk-Help} + " 0" {DotNetSdk-Help} + default {throw "Unknown command"}; + } +} +catch { + Console-Write-Error $_ + Console-Write "Type 'dotnetsdk help' for help on how to use dotnetsdk." + $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/dotnetsdk.sh b/dotnetsdk.sh new file mode 100644 index 000000000000..31a490125c0b --- /dev/null +++ b/dotnetsdk.sh @@ -0,0 +1,416 @@ +# dotnetsdk.sh +# Source this file from your .bash-profile or script to use + +_dotnetsdk_has() { + type "$1" > /dev/null 2>&1 + return $? +} + +if _dotnetsdk_has "unsetopt"; then + unsetopt nomatch 2>/dev/null +fi + +if [ -z "$DOTNET_USER_HOME" ]; then + eval DOTNET_USER_HOME=~/.dotnet +fi + +DOTNET_USER_PACKAGES="$DOTNET_USER_HOME/runtimes" +if [ -z "$DOTNET_FEED" ]; then + DOTNET_FEED="https://www.myget.org/F/aspnetvnext/api/v2" +fi + +_dotnetsdk_find_latest() { + local platform="mono" + + if ! _dotnetsdk_has "curl"; then + echo 'dotnetsdk needs curl to proceed.' >&2; + return 1 + fi + + local url="$DOTNET_FEED/GetUpdates()?packageIds=%27dotnet-$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 +} + +_dotnetsdk_strip_path() { + echo "$1" | sed -e "s#$DOTNET_USER_PACKAGES/[^/]*$2[^:]*:##g" -e "s#:$DOTNET_USER_PACKAGES/[^/]*$2[^:]*##g" -e "s#$DOTNET_USER_PACKAGES/[^/]*$2[^:]*##g" +} + +_dotnetsdk_prepend_path() { + if [ -z "$1" ]; then + echo "$2" + else + echo "$2:$1" + fi +} + +_dotnetsdk_package_version() { + local runtimeFullName="$1" + echo "$runtimeFullName" | sed "s/[^.]*.\(.*\)/\1/" +} + +_dotnetsdk_package_name() { + local runtimeFullName="$1" + echo "$runtimeFullName" | sed "s/\([^.]*\).*/\1/" +} + +_dotnetsdk_package_runtime() { + local runtimeFullName="$1" + echo "$runtimeFullName" | sed "s/KRE-\([^.-]*\).*/\1/" +} + +_dotnetsdk_download() { + local runtimeFullName="$1" + local runtimeFolder="$2" + + local pkgName=$(_dotnetsdk_package_name "$runtimeFullName") + local pkgVersion=$(_dotnetsdk_package_version "$runtimeFullName") + local url="$DOTNET_FEED/package/$pkgName/$pkgVersion" + local runtimeFile="$runtimeFolder/$runtimeFullName.nupkg" + + if [ -e "$runtimeFolder" ]; then + echo "$runtimeFullName already installed." + return 0 + fi + + echo "Downloading $runtimeFullName from $DOTNET_FEED" + + if ! _dotnetsdk_has "curl"; then + echo "dotnetsdk 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 $DOTNET_FEED" && return 1 + [[ $httpResult != "302" && $httpResult != "200" ]] && echo "HTTP Error $httpResult fetching $runtimeFullName from $DOTNET_FEED" && return 1 + + _dotnetsdk_unpack $runtimeFile $runtimeFolder + return $? +} + +_dotnetsdk_unpack() { + local runtimeFile="$1" + local runtimeFolder="$2" + + echo "Installing to $runtimeFolder" + + if ! _dotnetsdk_has "unzip"; then + echo "dotnetsdk 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/" + + #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 +} + +_dotnetsdk_requested_version_or_alias() { + local versionOrAlias="$1" + local runtimeBin=$(_dotnetsdk_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 "$DOTNET_USER_HOME/alias/$versionOrAlias.alias" ]; then + local runtimeFullName=$(cat "$DOTNET_USER_HOME/alias/$versionOrAlias.alias") + local pkgName=$(echo $runtimeFullName | sed "s/\([^.]*\).*/\1/") + local pkgVersion=$(echo $runtimeFullName | sed "s/[^.]*.\(.*\)/\1/") + local pkgPlatform=$(echo "$pkgName" | sed "s/dotnet-\([^.-]*\).*/\1/") + else + local pkgVersion=$versionOrAlias + local pkgPlatform="mono" + fi + + echo "dotnet-$pkgPlatform.$pkgVersion" + fi +} + +# This will be more relevant if we support global installs +_dotnetsdk_locate_runtime_bin_from_full_name() { + local runtimeFullName=$1 + [ -e "$DOTNET_USER_PACKAGES/$runtimeFullName/bin" ] && echo "$DOTNET_USER_PACKAGES/$runtimeFullName/bin" && return +} + +dotnetsdk() +{ + if [ $# -lt 1 ]; then + dotnetsdk help + return + fi + + case $1 in + "help" ) + echo "" + echo ".NET SDK Manager - Build 10303" + echo "" + echo "USAGE: dotnetsdk [options]" + echo "" + echo "dotnetsdk upgrade" + echo "install latest .NET Runtime from feed" + echo "add .NET Runtime bin to path of current command line" + echo "set installed version as default" + echo "" + echo "dotnetsdk install |||latest [-a|-alias ] [-p -persistent]" + echo "| install requested .NET Runtime from feed" + echo " install requested .NET Runtime from local package on filesystem" + echo "latest install latest version of .NET Runtime from feed" + echo "-a|-alias set alias for requested .NET Runtime on install" + echo "-p -persistent set installed version as default" + echo "add .NET Runtime bin to path of current command line" + echo "" + echo "dotnetsdk use |||none [-p -persistent]" + echo "|| add .NET Runtime bin to path of current command line " + echo "none remove .NET Runtime bin from path of current command line" + echo "-p -persistent set selected version as default" + echo "" + echo "dotnetsdk list" + echo "list .NET Runtime versions installed " + echo "" + echo "dotnetsdk alias" + echo "list .NET Runtime aliases which have been defined" + echo "" + echo "dotnetsdk alias " + echo "display value of the specified alias" + echo "" + echo "dotnetsdk alias ||" + echo " the name of the alias to set" + echo "|| the .NET Runtime version to set the alias to. Alternatively use the version of the specified alias" + echo "" + echo "dotnetsdk unalias " + echo "remove the specified alias" + echo "" + ;; + + "upgrade" ) + [ $# -ne 1 ] && dotnetsdk help && return + dotnetsdk install latest -p + ;; + + "install" ) + [ $# -lt 2 ] && dotnetsdk 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" && dotnetsdk help && return 1 + local versionOrAlias=$1 + fi + shift + done + if [[ "$versionOrAlias" == "latest" ]]; then + echo "Determining latest version" + versionOrAlias=$(_dotnetsdk_find_latest) + [[ $? == 1 ]] && echo "Error: Could not find latest version from feed $DOTNET_FEED" && return 1 + echo "Latest version is $versionOrAlias" + fi + if [[ "$versionOrAlias" == *.nupkg ]]; then + local runtimeFullName=$(basename $versionOrAlias | sed "s/\(.*\)\.nupkg/\1/") + local runtimeVersion=$(_dotnetsdk_package_version "$runtimeFullName") + local runtimeFolder="$DOTNET_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" + _dotnetsdk_unpack "$runtimeFile" "$runtimeFolder" + [[ $? == 1 ]] && return 1 + fi + dotnetsdk use "$runtimeVersion" "$persistent" + [[ -n $alias ]] && dotnetsdk alias "$alias" "$runtimeVersion" + else + local runtimeFullName="$(_dotnetsdk_requested_version_or_alias $versionOrAlias)" + local runtimeFolder="$DOTNET_USER_PACKAGES/$runtimeFullName" + _dotnetsdk_download "$runtimeFullName" "$runtimeFolder" + [[ $? == 1 ]] && return 1 + dotnetsdk use "$versionOrAlias" "$persistent" + [[ -n $alias ]] && dotnetsdk alias "$alias" "$versionOrAlias" + fi + ;; + + "use" ) + [ $# -gt 3 ] && dotnetsdk help && return + [ $# -lt 2 ] && dotnetsdk 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 .NET Runtime from process PATH" + # Strip other version from PATH + PATH=$(_dotnetsdk_strip_path "$PATH" "/bin") + + if [[ -n $persistent && -e "$DOTNET_USER_HOME/alias/default.alias" ]]; then + echo "Setting default .NET Runtime to none" + rm "$DOTNET_USER_HOME/alias/default.alias" + fi + return 0 + fi + + local runtimeFullName=$(_dotnetsdk_requested_version_or_alias "$versionOrAlias") + local runtimeBin=$(_dotnetsdk_locate_runtime_bin_from_full_name "$runtimeFullName") + + if [[ -z $runtimeBin ]]; then + echo "Cannot find $runtimeFullName, do you need to run 'dotnetsdk install $versionOrAlias'?" + return 1 + fi + + echo "Adding" $runtimeBin "to process PATH" + + PATH=$(_dotnetsdk_strip_path "$PATH" "/bin") + PATH=$(_dotnetsdk_prepend_path "$PATH" "$runtimeBin") + + if [[ -n $persistent ]]; then + local runtimeVersion=$(_dotnetsdk_package_version "$runtimeFullName") + dotnetsdk alias default "$runtimeVersion" + fi + ;; + + "alias" ) + [[ $# -gt 3 ]] && dotnetsdk help && return + + [[ ! -e "$DOTNET_USER_HOME/alias/" ]] && mkdir "$DOTNET_USER_HOME/alias/" > /dev/null + + if [[ $# == 1 ]]; then + echo "" + local format="%-20s %s\n" + printf "$format" "Alias" "Name" + printf "$format" "-----" "----" + if [ -d "$DOTNET_USER_HOME/alias" ]; then + for _dotnetsdk_file in $(find "$DOTNET_USER_HOME/alias" -name *.alias); do + local alias="$(basename $_dotnetsdk_file | sed 's/\.alias//')" + local name="$(cat $_dotnetsdk_file)" + printf "$format" "$alias" "$name" + done + fi + echo "" + return + fi + + local name="$2" + + if [[ $# == 2 ]]; then + [[ ! -e "$DOTNET_USER_HOME/alias/$name.alias" ]] && echo "There is no alias called '$name'" && return + cat "$DOTNET_USER_HOME/alias/$name.alias" + echo "" + return + fi + + local runtimeFullName=$(_dotnetsdk_requested_version_or_alias "$3") + + [[ ! -d "$DOTNET_USER_PACKAGES/$runtimeFullName" ]] && echo "$runtimeFullName is not an installed .NET Runtime version" && return 1 + + local action="Setting" + [[ -e "$DOTNET_USER_HOME/alias/$name.alias" ]] && action="Updating" + echo "$action alias '$name' to '$runtimeFullName'" + echo "$runtimeFullName" > "$DOTNET_USER_HOME/alias/$name.alias" + ;; + + "unalias" ) + [[ $# -ne 2 ]] && dotnetsdk help && return + + local name=$2 + local aliasPath="$DOTNET_USER_HOME/alias/$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 ]] && dotnetsdk help && return + + [[ ! -d $DOTNET_USER_PACKAGES ]] && echo ".NET Runtime is not installed." && return 1 + + local searchGlob="dotnet-*" + if [ $# == 2 ]; then + local versionOrAlias=$2 + local searchGlob=$(_dotnetsdk_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 "$DOTNET_USER_HOME/alias" ]; then + for _dotnetsdk_file in $(find "$DOTNET_USER_HOME/alias" -name *.alias); do + arr[$i]="$(basename $_dotnetsdk_file | sed 's/\.alias//')/$(cat $_dotnetsdk_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 $DOTNET_USER_PACKAGES | sed s=$HOME=~=g)` + for f in $(find $DOTNET_USER_PACKAGES -name "$searchGlob" \( -type d -or -type l \) -prune -exec basename {} \;); do + local active="" + [[ $PATH == *"$DOTNET_USER_PACKAGES/$f/bin"* ]] && local active=" *" + local pkgName=$(_dotnetsdk_package_runtime "$f") + local pkgVersion=$(_dotnetsdk_package_version "$f") + + local alias="" + local delim="" + for i in "${arr[@]}"; do + temp="dotnet-$pkgName.$pkgVersion" + temp2="dotnet-$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 +} + +dotnetsdk list default >/dev/null && dotnetsdk use default >/dev/null || true From 9f0fd62342afb5311f6f97ca52bbe89fa16d941f Mon Sep 17 00:00:00 2001 From: "ASP.NET Push Bot" Date: Fri, 30 Jan 2015 13:38:31 -0800 Subject: [PATCH 09/27] :arrow_up: kvm.ps1, kvm.cmd, kvm.sh Source: aspnet/kvm@51671bb431bf9d97f26fc470d5eeda9865972a2d --- kvm.cmd | 6 +- kvm.ps1 | 652 +++++++++++++++++++++++++++----------------------------- kvm.sh | 331 ++++++++++++++-------------- 3 files changed, 488 insertions(+), 501 deletions(-) diff --git a/kvm.cmd b/kvm.cmd index 79909f761909..259e1fe6a1a1 100644 --- a/kvm.cmd +++ b/kvm.cmd @@ -2,7 +2,7 @@ PowerShell -NoProfile -NoLogo -ExecutionPolicy unrestricted -Command "[System.Threading.Thread]::CurrentThread.CurrentCulture = ''; [System.Threading.Thread]::CurrentThread.CurrentUICulture = '';& '%~dp0kvm.ps1' %*" -IF EXIST "%USERPROFILE%\.kre\run-once.cmd" ( - CALL "%USERPROFILE%\.kre\run-once.cmd" - DEL "%USERPROFILE%\.kre\run-once.cmd" +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/kvm.ps1 b/kvm.ps1 index 1ac4b79d566e..944ffbe4106e 100644 --- a/kvm.ps1 +++ b/kvm.ps1 @@ -3,35 +3,63 @@ param( [string] $Command, [string] $Proxy, [switch] $Verbosity = $false, - [alias("g")][switch] $Global = $false, [alias("p")][switch] $Persistent = $false, [alias("f")][switch] $Force = $false, [alias("r")][string] $Runtime, + + [alias("arch")][string] $Architecture, [switch] $X86 = $false, - [switch] $Amd64 = $false, - #deprecated - [switch] $X64 = $false, - #deprecated - [switch] $Svr50 = $false, - #deprecated - [switch] $Svrc50 = $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=@() + [string[]]$Args=@(), + [switch] $Quiet, + [string] $OutputVariable, + [switch] $AssumeElevated ) +# Constants +Set-Variable -Option Constant "BuildNumber" "10318" +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" -$userKrePath = $env:USERPROFILE + "\.kre" -$userKrePackages = $userKrePath + "\packages" -$globalKrePath = $env:ProgramFiles + "\KRE" -$globalKrePackages = $globalKrePath + "\packages" -$feed = $env:KRE_FEED +$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 @@ -40,119 +68,116 @@ function String-IsEmptyOrWhitespace([string]$str) { return [string]::IsNullOrEmpty($str) -or $str.Trim().length -eq 0 } -if (!$feed) -{ - $feed = "https://www.myget.org/F/aspnetrelease/api/v2"; -} - $scriptPath = $myInvocation.MyCommand.Definition -function Kvm-Help { +function _Help { @" -K Runtime Environment Version Manager - Build 10050 +$VersionManagerName - Build $BuildNumber -USAGE: kvm [options] +USAGE: $CommandName [options] -kvm upgrade [-X86][-Amd64] [-r|-Runtime CLR|CoreCLR] [-g|-Global] [-f|-Force] [-Proxy
] [-NoNative] - install latest KRE from feed +$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 KRE bin to user PATH environment variable + 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 + -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) -kvm install |||latest [-X86][-Amd64] [-r|-Runtime CLR|CoreCLR] [-a|-Alias ] [-g|-Global] [-f|-Force] [-NoNative] - | install requested KRE from feed - install requested KRE from package on local filesystem - latest install latest KRE from feed - add KRE bin to path of current command line - -p|-Persistent add KRE bin to PATH environment variables persistently - -a|-Alias set alias for requested KRE on install - -g|-Global install to machine-wide location +$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) -kvm use |||none [-X86][-Amd64] [-r|-Runtime CLR|CoreCLR] [-p|-Persistent] [-g|-Global] - || add KRE bin to path of current command line - none remove KRE bin from path of current command line - -p|-Persistent add KRE bin to PATH environment variables persistently - -g|-Global combined with -p to change machine PATH instead of user PATH +$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 -kvm list - list KRE versions installed +$CommandName list + list $RuntimeShortName versions installed -kvm alias - list KRE aliases which have been defined +$CommandName alias + list $RuntimeShortName aliases which have been defined -kvm alias +$CommandName alias display value of the specified alias -kvm alias || [-X86][-Amd64] [-r|-Runtime CLR|CoreCLR] +$CommandName alias || [-X86|-X64] [-r|-Runtime CLR|CoreCLR] the name of the alias to set - || the KRE version to set the alias to. Alternatively use the version of the specified alias + || the $RuntimeShortName version to set the alias to. Alternatively use the version of the specified alias -kvm unalias +$CommandName unalias remove the specified alias "@ -replace "`n","`r`n" | Console-Write } -function Kvm-Global-Setup { - $kvmBinPath = "$userKrePath\bin" +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 -global -wait" + $arguments = "-ExecutionPolicy unrestricted & '$scriptPath' setup -wait" Start-Process "$psHome\powershell.exe" -Verb runAs -ArgumentList $arguments -Wait - Console-Write "Adding $kvmBinPath to process PATH" - Set-Path (Change-Path $env:Path $kvmBinPath ($kvmBinPath)) - Console-Write "Adding $globalKrePath;%USERPROFILE%\.kre to process KRE_HOME" - $envKreHome = $env:KRE_HOME - $envKreHome = Change-Path $envKreHome "%USERPROFILE%\.kre" ("%USERPROFILE%\.kre") - $envKreHome = Change-Path $envKreHome $globalKrePath ($globalKrePath) - $env:KRE_HOME = $envKreHome + 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 $kvmBinPath\kvm.ps1" - md $kvmBinPath -Force | Out-Null - copy "$scriptFolder\kvm.ps1" "$kvmBinPath\kvm.ps1" + Console-Write "Copying file $cmdBinPath\$CommandName.ps1" + md $cmdBinPath -Force | Out-Null + copy "$scriptFolder\$CommandName.ps1" "$cmdBinPath\$CommandName.ps1" - Console-Write "Copying file $kvmBinPath\kvm.cmd" - copy "$scriptFolder\kvm.cmd" "$kvmBinPath\kvm.cmd" + Console-Write "Copying file $cmdBinPath\$CommandName.cmd" + copy "$scriptFolder\$CommandName.cmd" "$cmdBinPath\$CommandName.cmd" - Console-Write "Adding $kvmBinPath to process PATH" - Set-Path (Change-Path $env:Path $kvmBinPath ($kvmBinPath)) + Console-Write "Adding $cmdBinPath to process PATH" + Set-Path (Change-Path $env:Path $cmdBinPath ($cmdBinPath)) - Console-Write "Adding $kvmBinPath to user PATH" + Console-Write "Adding $cmdBinPath to user PATH" $userPath = [Environment]::GetEnvironmentVariable("Path", [System.EnvironmentVariableTarget]::User) - $userPath = Change-Path $userPath $kvmBinPath ($kvmBinPath) + $userPath = Change-Path $userPath $cmdBinPath ($cmdBinPath) [Environment]::SetEnvironmentVariable("Path", $userPath, [System.EnvironmentVariableTarget]::User) - Console-Write "Adding $globalKrePath;%USERPROFILE%\.kre to process KRE_HOME" - $envKreHome = $env:KRE_HOME - $envKreHome = Change-Path $envKreHome "%USERPROFILE%\.kre" ("%USERPROFILE%\.kre") - $envKreHome = Change-Path $envKreHome $globalKrePath ($globalKrePath) - $env:KRE_HOME = $envKreHome + 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 $globalKrePath;%USERPROFILE%\.kre to machine KRE_HOME" - $machineKreHome = [Environment]::GetEnvironmentVariable("KRE_HOME", [System.EnvironmentVariableTarget]::Machine) - $machineKreHome = Change-Path $machineKreHome "%USERPROFILE%\.kre" ("%USERPROFILE%\.kre") - $machineKreHome = Change-Path $machineKreHome $globalKrePath ($globalKrePath) - [Environment]::SetEnvironmentVariable("KRE_HOME", $machineKreHome, [System.EnvironmentVariableTarget]::Machine) + 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 Kvm-Upgrade { +function _Upgrade { param( [boolean] $isGlobal ) $Persistent = $true $Alias="default" - Kvm-Install "latest" $isGlobal + _Install "latest" $isGlobal } function Add-Proxy-If-Specified { @@ -174,213 +199,208 @@ param( } } -function Kvm-Find-Latest { +function _Find-Latest { param( [string] $platform, [string] $architecture ) Console-Write "Determining latest version" - $url = "$feed/GetUpdates()?packageIds=%27KRE-$platform-$architecture%27&versions=%270.0%27&includePrerelease=true&includeAllVersions=false" + $url = "$feed/GetUpdates()?packageIds=%27$RuntimePackageName-$platform-win-$architecture%27&versions=%270.0%27&includePrerelease=true&includeAllVersions=false" $wc = New-Object System.Net.WebClient 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 packages for platform '$platform', architecture '$architecture' in the feed '$feed'" + throw "There are no runtimes for platform '$platform', architecture '$architecture' in the feed '$feed'" } return $version } -function Do-Kvm-Download { +function Do-Download { param( - [string] $kreFullName, - [string] $packagesFolder + [string] $runtimeFullName, + [string] $runtimesFolder ) - $parts = $kreFullName.Split(".", 2) + $parts = $runtimeFullName.Split(".", 2) $url = "$feed/package/" + $parts[0] + "/" + $parts[1] - $kreFolder = Join-Path $packagesFolder $kreFullName - $kreFile = Join-Path $kreFolder "$kreFullName.nupkg" + $runtimeFolder = Join-Path $runtimesFolder $runtimeFullName + $runtimeFile = Join-Path $runtimeFolder "$runtimeFullName.nupkg" - If (Test-Path $kreFolder) { + If (Test-Path $runtimeFolder) { if($Force) { - rm $kreFolder -Recurse -Force + rm $runtimeFolder -Recurse -Force } else { - Console-Write "$kreFullName already installed." + Console-Write "$runtimeFullName already installed." return; } } - Console-Write "Downloading $kreFullName from $feed" + Console-Write "Downloading $runtimeFullName from $feed" #Downloading to temp location - $kreTempDownload = Join-Path $packagesFolder "temp" - $tempKreFile = Join-Path $kreTempDownload "$kreFullName.nupkg" + $runtimeTempDownload = Join-Path $runtimesFolder "temp" + $tempDownloadFile = Join-Path $runtimeTempDownload "$runtimeFullName.nupkg" - if(Test-Path $kreTempDownload) { - del "$kreTempDownload\*" -recurse + if(Test-Path $runtimeTempDownload) { + del "$runtimeTempDownload\*" -recurse } else { - md $kreTempDownload -Force | Out-Null + md $runtimeTempDownload -Force | Out-Null } $wc = New-Object System.Net.WebClient Add-Proxy-If-Specified($wc) - $wc.DownloadFile($url, $tempKreFile) + Write-Verbose "Downloading $url ..." + $wc.DownloadFile($url, $tempDownloadFile) - Do-Kvm-Unpack $tempKreFile $kreTempDownload + Do-Unpack $tempDownloadFile $runtimeTempDownload - md $kreFolder -Force | Out-Null - Console-Write "Installing to $kreFolder" - mv "$kreTempDownload\*" $kreFolder - Remove-Item "$kreTempDownload" -Force | Out-Null + md $runtimeFolder -Force | Out-Null + Console-Write "Installing to $runtimeFolder" + mv "$runtimeTempDownload\*" $runtimeFolder + Remove-Item "$runtimeTempDownload" -Force | Out-Null } -function Do-Kvm-Unpack { +function Do-Unpack { param( - [string] $kreFile, - [string] $kreFolder + [string] $runtimeFile, + [string] $runtimeFolder ) - Console-Write "Unpacking to $kreFolder" + 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 - $kreZip = [System.IO.Path]::ChangeExtension($kreFile, "zip") - Rename-Item $kreFile $kreZip + $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($kreZip) - $destination = $shell_app.namespace($kreFolder) + $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 $kreZip $kreFile + Rename-Item $runtimeZip $runtimeFile } } else { - [System.IO.Compression.ZipFile]::ExtractToDirectory($kreFile, $kreFolder) + [System.IO.Compression.ZipFile]::ExtractToDirectory($runtimeFile, $runtimeFolder) } - If (Test-Path ($kreFolder + "\[Content_Types].xml")) { - Remove-Item ($kreFolder + "\[Content_Types].xml") + If (Test-Path ($runtimeFolder + "\[Content_Types].xml")) { + Remove-Item ($runtimeFolder + "\[Content_Types].xml") } - If (Test-Path ($kreFolder + "\_rels\")) { - Remove-Item ($kreFolder + "\_rels\") -Force -Recurse + If (Test-Path ($runtimeFolder + "\_rels\")) { + Remove-Item ($runtimeFolder + "\_rels\") -Force -Recurse } - If (Test-Path ($kreFolder + "\package\")) { - Remove-Item ($kreFolder + "\package\") -Force -Recurse + If (Test-Path ($runtimeFolder + "\package\")) { + Remove-Item ($runtimeFolder + "\package\") -Force -Recurse } + + # Clean up the package file itself. + Remove-Item $runtimeFile -Force } -function Kvm-Install { +function _Install { param( [string] $versionOrAlias, [boolean] $isGlobal ) if ($versionOrAlias -eq "latest") { - $versionOrAlias = Kvm-Find-Latest (Requested-Platform $defaultRuntime) (Requested-Architecture $defaultArch) + $versionOrAlias = _Find-Latest (Requested-Platform $defaultRuntime) (Requested-Architecture $defaultArch) } if ($versionOrAlias.EndsWith(".nupkg")) { - $kreFullName = [System.IO.Path]::GetFileNameWithoutExtension($versionOrAlias) + $runtimeFullName = [System.IO.Path]::GetFileNameWithoutExtension($versionOrAlias) } else { - $kreFullName = Requested-VersionOrAlias $versionOrAlias + $runtimeFullName = Requested-VersionOrAlias $versionOrAlias } - if ($isGlobal) { - if (Needs-Elevation) { - $arguments = "-ExecutionPolicy unrestricted & '$scriptPath' install '$versionOrAlias' -global $(Requested-Switches) -wait" - Start-Process "$psHome\powershell.exe" -Verb runAs -ArgumentList $arguments -Wait - Kvm-Set-Global-Process-Path $versionOrAlias - break - } - $packageFolder = $globalKrePackages - } else { - $packageFolder = $userKrePackages - } + $packageFolder = $userRuntimesPath if ($versionOrAlias.EndsWith(".nupkg")) { - Set-Variable -Name "selectedArch" -Value (Package-Arch $kreFullName) -Scope Script - Set-Variable -Name "selectedRuntime" -Value (Package-Platform $kreFullName) -Scope Script + Set-Variable -Name "selectedArch" -Value (Package-Arch $runtimeFullName) -Scope Script + Set-Variable -Name "selectedRuntime" -Value (Package-Platform $runtimeFullName) -Scope Script - $kreFolder = "$packageFolder\$kreFullName" - $folderExists = Test-Path $kreFolder + $runtimeFolder = "$packageFolder\$runtimeFullName" + $folderExists = Test-Path $runtimeFolder if ($folderExists -and $Force) { - del $kreFolder -Recurse -Force + del $runtimeFolder -Recurse -Force $folderExists = $false; } if ($folderExists) { - Console-Write "Target folder '$kreFolder' already exists" + Console-Write "Target folder '$runtimeFolder' already exists" } else { $tempUnpackFolder = Join-Path $packageFolder "temp" - $tempKreFile = Join-Path $tempUnpackFolder "$kreFullName.nupkg" + $tempDownloadFile = Join-Path $tempUnpackFolder "$runtimeFullName.nupkg" if(Test-Path $tempUnpackFolder) { del "$tempUnpackFolder\*" -recurse } else { md $tempUnpackFolder -Force | Out-Null } - copy $versionOrAlias $tempKreFile + copy $versionOrAlias $tempDownloadFile - Do-Kvm-Unpack $tempKreFile $tempUnpackFolder - md $kreFolder -Force | Out-Null - Console-Write "Installing to $kreFolder" - mv "$tempUnpackFolder\*" $kreFolder + 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 $kreFullName + $packageVersion = Package-Version $runtimeFullName - Kvm-Use $packageVersion + _Use $packageVersion if (!$(String-IsEmptyOrWhitespace($Alias))) { - Kvm-Alias-Set $Alias $packageVersion + _Alias-Set $Alias $packageVersion } } else { - Do-Kvm-Download $kreFullName $packageFolder - Kvm-Use $versionOrAlias + Do-Download $runtimeFullName $packageFolder + _Use $versionOrAlias if (!$(String-IsEmptyOrWhitespace($Alias))) { - Kvm-Alias-Set "$Alias" $versionOrAlias + _Alias-Set "$Alias" $versionOrAlias } } - if ($kreFullName.Contains("CoreCLR")) { + if ($runtimeFullName.Contains("CoreCLR")) { if ($NoNative) { Console-Write "Native image generation is skipped" } else { - Console-Write "Compiling native images for $kreFullName to improve startup performance..." - Start-Process "k-crossgen" -Wait + Console-Write "Compiling native images for $runtimeFullName to improve startup performance..." + Start-Process $CrossGenCommand -Wait Console-Write "Finished native image compilation." } } } -function Kvm-List { - $kreHome = $env:KRE_HOME - if (!$kreHome) { - $kreHome = "$globalKrePath;$userKrePath" +function _List { + $runtimeHome = (getenv $HomeEnvVar) + if (!$runtimeHome) { + $runtimeHome = "$userHome" } - md ($userKrePath + "\alias\") -Force | Out-Null - $aliases = Get-ChildItem ($userKrePath + "\alias\") | Select @{label='Alias';expression={$_.BaseName}}, @{label='Name';expression={Get-Content $_.FullName }} + 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 $kreHome.Split(';')) { + foreach($portion in $runtimeHome.Split(';')) { $path = [System.Environment]::ExpandEnvironmentVariables($portion) - if (Test-Path("$path\packages")) { - $items += Get-ChildItem ("$path\packages\KRE-*") | List-Parts $aliases + if (Test-Path("$path\runtimes")) { + $items += Get-ChildItem ("$path\runtimes\$RuntimePackageName-*") | List-Parts $aliases } } @@ -415,173 +435,116 @@ filter List-Parts { } $parts1 = $_.Name.Split('.', 2) - $parts2 = $parts1[0].Split('-', 3) + $parts2 = $parts1[0].Split('-', 4) return New-Object PSObject -Property @{ Active = if ($active) { "*" } else { "" } Version = $parts1[1] Runtime = $parts2[1] - Architecture = $parts2[2] + OperatingSystem = $parts2[2] + Architecture = $parts2[3] Location = $_.Parent.FullName Alias = $fullAlias } } -function Kvm-Global-Use { -param( - [string] $versionOrAlias -) - Validate-Full-Package-Name-Arguments-Combination $versionOrAlias - - If (Needs-Elevation) { - $arguments = "-ExecutionPolicy unrestricted & '$scriptPath' use '$versionOrAlias' -global $(Requested-Switches) -wait" - Start-Process "$psHome\powershell.exe" -Verb runAs -ArgumentList $arguments -Wait - Kvm-Set-Global-Process-Path $versionOrAlias - break - } - - Kvm-Set-Global-Process-Path "$versionOrAlias" - - if ($versionOrAlias -eq "none") { - if ($Persistent) { - Console-Write "Removing KRE from machine PATH" - $machinePath = [Environment]::GetEnvironmentVariable("Path", [System.EnvironmentVariableTarget]::Machine) - $machinePath = Change-Path $machinePath "" ($globalKrePackages, $userKrePackages) - [Environment]::SetEnvironmentVariable("Path", $machinePath, [System.EnvironmentVariableTarget]::Machine) - } - return; - } - - $kreFullName = Requested-VersionOrAlias "$versionOrAlias" - $kreBin = Locate-KreBinFromFullName $kreFullName - if ($kreBin -eq $null) { - throw "Cannot find $kreFullName, do you need to run 'kvm install $versionOrAlias'?" - } - - if ($Persistent) { - Console-Write "Adding $kreBin to machine PATH" - $machinePath = [Environment]::GetEnvironmentVariable("Path", [System.EnvironmentVariableTarget]::Machine) - $machinePath = Change-Path $machinePath $kreBin ($globalKrePackages, $userKrePackages) - [Environment]::SetEnvironmentVariable("Path", $machinePath, [System.EnvironmentVariableTarget]::Machine) - } -} - -function Kvm-Set-Global-Process-Path { -param( - [string] $versionOrAlias -) - if ($versionOrAlias -eq "none") { - Console-Write "Removing KRE from process PATH" - Set-Path (Change-Path $env:Path "" ($globalKrePackages, $userKrePackages)) - return - } - - $kreFullName = Requested-VersionOrAlias $versionOrAlias - $kreBin = Locate-KreBinFromFullName $kreFullName - if ($kreBin -eq $null) { - Console-Write "Cannot find $kreFullName, do you need to run 'kvm install $versionOrAlias'?" - return - } - - Console-Write "Adding $kreBin to process PATH" - Set-Path (Change-Path $env:Path $kreBin ($globalKrePackages, $userKrePackages)) -} - -function Kvm-Use { +function _Use { param( [string] $versionOrAlias ) Validate-Full-Package-Name-Arguments-Combination $versionOrAlias if ($versionOrAlias -eq "none") { - Console-Write "Removing KRE from process PATH" - Set-Path (Change-Path $env:Path "" ($globalKrePackages, $userKrePackages)) + Console-Write "Removing $RuntimeShortName from process PATH" + Set-Path (Change-Path $env:Path "" ($userRuntimesPath)) if ($Persistent) { - Console-Write "Removing KRE from user PATH" + Console-Write "Removing $RuntimeShortName from user PATH" $userPath = [Environment]::GetEnvironmentVariable("Path", [System.EnvironmentVariableTarget]::User) - $userPath = Change-Path $userPath "" ($globalKrePackages, $userKrePackages) + $userPath = Change-Path $userPath "" ($userRuntimesPath) [Environment]::SetEnvironmentVariable("Path", $userPath, [System.EnvironmentVariableTarget]::User) } return; } - $kreFullName = Requested-VersionOrAlias $versionOrAlias + $runtimeFullName = Requested-VersionOrAlias $versionOrAlias - $kreBin = Locate-KreBinFromFullName $kreFullName - if ($kreBin -eq $null) { - throw "Cannot find $kreFullName, do you need to run 'kvm install $versionOrAlias'?" + $runtimeBin = Locate-RuntimeBinFromFullName $runtimeFullName + if ($runtimeBin -eq $null) { + throw "Cannot find $runtimeFullName, do you need to run '$CommandName install $versionOrAlias'?" } - Console-Write "Adding $kreBin to process PATH" - Set-Path (Change-Path $env:Path $kreBin ($globalKrePackages, $userKrePackages)) + Console-Write "Adding $runtimeBin to process PATH" + Set-Path (Change-Path $env:Path $runtimeBin ($userRuntimesPath)) if ($Persistent) { - Console-Write "Adding $kreBin to user PATH" + Console-Write "Adding $runtimeBin to user PATH" $userPath = [Environment]::GetEnvironmentVariable("Path", [System.EnvironmentVariableTarget]::User) - $userPath = Change-Path $userPath $kreBin ($globalKrePackages, $userKrePackages) + $userPath = Change-Path $userPath $runtimeBin ($userRuntimesPath) [Environment]::SetEnvironmentVariable("Path", $userPath, [System.EnvironmentVariableTarget]::User) } } -function Kvm-Alias-List { - md ($userKrePath + "\alias\") -Force | Out-Null +function _Alias-List { + md ($userHome + "\alias\") -Force | Out-Null - Get-ChildItem ($userKrePath + "\alias\") | Select @{label='Alias';expression={$_.BaseName}}, @{label='Name';expression={Get-Content $_.FullName }} | Format-Table -AutoSize + Get-ChildItem ($userHome + "\alias\") | Select @{label='Alias';expression={$_.BaseName}}, @{label='Name';expression={Get-Content $_.FullName }} | Format-Table -AutoSize } -function Kvm-Alias-Get { +function _Alias-Get { param( [string] $name ) - md ($userKrePath + "\alias\") -Force | Out-Null - $aliasFilePath=$userKrePath + "\alias\" + $name + ".txt" + 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 ($userKrePath + "\alias\" + $name + ".txt")) - Console-Write "Alias '$name' is set to $aliasValue" + $aliasValue = (Get-Content ($userHome + "\alias\" + $name + ".txt")) + Console-Write "Alias '$name' is set to $aliasValue" } } -function Kvm-Alias-Set { +function _Alias-Set { param( [string] $name, [string] $value ) - $kreFullName = Requested-VersionOrAlias $value - $aliasFilePath = $userKrePath + "\alias\" + $name + ".txt" + $runtimeFullName = Requested-VersionOrAlias $value + $aliasFilePath = $userHome + "\alias\" + $name + ".txt" $action = if (Test-Path $aliasFilePath) { "Updating" } else { "Setting" } - Console-Write "$action alias '$name' to '$kreFullName'" - md ($userKrePath + "\alias\") -Force | Out-Null - $kreFullName | Out-File ($aliasFilePath) ascii + Console-Write "$action alias '$name' to '$runtimeFullName'" + md ($userHome + "\alias\") -Force | Out-Null + $runtimeFullName | Out-File ($aliasFilePath) ascii } -function Kvm-Unalias { +function _Unalias { param( [string] $name ) - $aliasPath=$userKrePath + "\alias\" + $name + ".txt" + $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-KreBinFromFullName() { +function Locate-RuntimeBinFromFullName() { param( - [string] $kreFullName + [string] $runtimeFullName ) - $kreHome = $env:KRE_HOME - if (!$kreHome) { - $kreHome = "$globalKrePath;$userKrePath" + $runtimeHome = (getenv $HomeEnvVar) + if (!$runtimeHome) { + $runtimeHome = $userHome } - foreach($portion in $kreHome.Split(';')) { + foreach($portion in $runtimeHome.Split(';')) { $path = [System.Environment]::ExpandEnvironmentVariables($portion) - $kreBin = "$path\packages\$kreFullName\bin" - if (Test-Path "$kreBin") { - return $kreBin + $runtimeBin = "$path\runtimes\$runtimeFullName\bin" + if (Test-Path "$runtimeBin") { + return $runtimeBin } } return $null @@ -589,23 +552,23 @@ param( function Package-Version() { param( - [string] $kreFullName + [string] $runtimeFullName ) - return $kreFullName -replace '[^.]*.(.*)', '$1' + return $runtimeFullName -replace '[^.]*.(.*)', '$1' } function Package-Platform() { param( - [string] $kreFullName + [string] $runtimeFullName ) - return $kreFullName -replace 'KRE-([^-]*).*', '$1' + return $runtimeFullName -replace "$RuntimePackageName-([^-]*).*", '$1' } function Package-Arch() { param( - [string] $kreFullName + [string] $runtimeFullName ) - return $kreFullName -replace 'KRE-[^-]*-([^.]*).*', '$1' + return $runtimeFullName -replace "$RuntimePackageName-[^-]*-[^-]*-([^.]*).*", '$1' } @@ -615,26 +578,28 @@ param( ) Validate-Full-Package-Name-Arguments-Combination $versionOrAlias - $kreBin = Locate-KreBinFromFullName $versionOrAlias + $runtimeBin = Locate-RuntimeBinFromFullName $versionOrAlias # If the name specified is an existing package, just use it as is - if ($kreBin -ne $null) { + if ($runtimeBin -ne $null) { return $versionOrAlias } - If (Test-Path ($userKrePath + "\alias\" + $versionOrAlias + ".txt")) { - $aliasValue = Get-Content ($userKrePath + "\alias\" + $versionOrAlias + ".txt") + 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] - $parts =$parts[0].Split('-', 3) + # runtime-coreclr-win-x86 + $parts = $parts[0].Split('-', 4) $pkgPlatform = Requested-Platform $parts[1] - $pkgArchitecture = Requested-Architecture $parts[2] + $pkgArchitecture = Requested-Architecture $parts[3] } else { $pkgVersion = $versionOrAlias $pkgPlatform = Requested-Platform $defaultRuntime $pkgArchitecture = Requested-Architecture $defaultArch } - return "KRE-" + $pkgPlatform + "-" + $pkgArchitecture + "." + $pkgVersion + return $RuntimePackageName + "-" + $pkgPlatform + "-win-" + $pkgArchitecture + "." + $pkgVersion } function Requested-Platform() { @@ -663,7 +628,7 @@ param( foreach($portion in $existingPaths.Split(';')) { $skip = $portion -eq "" foreach($removePath in $removePaths) { - if ($portion.StartsWith($removePath)) { + if ($removePath -and ($portion.StartsWith($removePath))) { $skip = $true } } @@ -678,14 +643,18 @@ function Set-Path() { param( [string] $newPath ) - md $userKrePath -Force | Out-Null + md $userHome -Force | Out-Null $env:Path = $newPath @" SET "PATH=$newPath" -"@ | Out-File ($userKrePath + "\run-once.cmd") ascii +"@ | 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 @@ -694,8 +663,6 @@ function Needs-Elevation() { function Requested-Switches() { $arguments = "" if ($X86) {$arguments = "$arguments -x86"} - if ($Amd64) {$arguments = "$arguments -amd64"} - #deprecated if ($X64) {$arguments = "$arguments -x64"} if ($selectedRuntime) {$arguments = "$arguments -runtime $selectedRuntime"} if ($Persistent) {$arguments = "$arguments -persistent"} @@ -706,52 +673,56 @@ function Requested-Switches() { function Validate-And-Santitize-Switches() { - if ($Svr50 -and $Runtime) {throw "You cannot select both the -runtime switch and the -svr50 runtimes"} - if ($Svrc50 -and $Runtime) {throw "You cannot select both the -runtime switch and the -svrc50 runtimes"} - if ($X86 -and $Amd64) {throw "You cannot select both x86 and amd64 architectures"} if ($X86 -and $X64) {throw "You cannot select both x86 and x64 architectures"} - if ($X64 -and $Amd64) {throw "You cannot select both x64 and amd64 architectures"} if ($Runtime) { - $validRuntimes = "CoreCLR", "CLR", "svr50", "svrc50" + $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 -Scope Script - } elseif ($Svr50) { - Console-Write "Warning: -svr50 is deprecated, use -runtime CLR for new packages." - Set-Variable -Name "selectedRuntime" -Value "svr50" -Scope Script - } elseif ($Svrc50) { - Console-Write "Warning: -svrc50 is deprecated, use -runtime CoreCLR for new packages." - Set-Variable -Name "selectedRuntime" -Value "svrc50" -Scope Script + Set-Variable -Name "selectedRuntime" -Value $match.ToLowerInvariant() -Scope Script } - if ($X64) { - Console-Write "Warning: -x64 is deprecated, use -amd64 for new packages." - Set-Variable -Name "selectedArch" -Value "x64" -Scope Script - } elseif ($Amd64) { - Set-Variable -Name "selectedArch" -Value "amd64" -Scope Script - } elseif ($X86) { - Set-Variable -Name "selectedArch" -Value "x86" -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 ($useHostOutputMethods) { - try { - Write-Host $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 + } } - catch { - $script:useHostOutputMethods = $false - Console-Write $message + else { + [Console]::WriteLine($message) } } - else { - [Console]::WriteLine($message) - } } function Console-Write-Error() { @@ -770,55 +741,50 @@ param( } else { [Console]::Error.WriteLine($message) - } + } } function Validate-Full-Package-Name-Arguments-Combination() { param( - [string] $versionOrAlias + [string] $versionOrAlias ) - if ($versionOrAlias -like "KRE-*" -and - ($selectedArch -or $selectedRuntime)) { - throw "Runtime or architecture cannot be specified when using the full package name." + if ($versionOrAlias -like "$RuntimePackageName-*" -and + ($selectedArch -or $selectedRuntime)) { + throw "Runtime or architecture cannot be specified when using the full package name." } } -$exitCode = 0 +$script:exitCode = 0 try { Validate-And-Santitize-Switches - if ($Global) { - switch -wildcard ($Command + " " + $Args.Count) { - "setup 0" {Kvm-Global-Setup} - "upgrade 0" {Kvm-Upgrade $true} - "install 1" {Kvm-Install $Args[0] $true} - "use 1" {Kvm-Global-Use $Args[0]} - default {throw "Unknown command, or global switch not supported"}; - } - } else { - switch -wildcard ($Command + " " + $Args.Count) { - "setup 0" {Kvm-Global-Setup} - "upgrade 0" {Kvm-Upgrade $false} - "install 1" {Kvm-Install $Args[0] $false} - "list 0" {Kvm-List} - "use 1" {Kvm-Use $Args[0]} - "alias 0" {Kvm-Alias-List} - "alias 1" {Kvm-Alias-Get $Args[0]} - "alias 2" {Kvm-Alias-Set $Args[0] $Args[1]} - "unalias 1" {Kvm-Unalias $Args[0]} - "help 0" {Kvm-Help} - " 0" {Kvm-Help} - default {throw "Unknown command"}; - } + 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 'kvm help' for help on how to use kvm." - $exitCode = -1 + 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") } -exit $exitCode +# 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/kvm.sh b/kvm.sh index 62285639cc48..a746e147e364 100644 --- a/kvm.sh +++ b/kvm.sh @@ -1,43 +1,57 @@ # kvm.sh # Source this file from your .bash-profile or script to use -_kvm_has() { + +# "Constants" +_KVM_BUILDNUMBER="10318" +_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 +if __kvm_has "unsetopt"; then unsetopt nomatch 2>/dev/null fi -if [ -z "$KRE_USER_HOME" ]; then - eval KRE_USER_HOME=~/.kre +if [ -z "$KVM_USER_HOME" ]; then + eval KVM_USER_HOME="~/$_KVM_RUNTIME_FOLDER_NAME" fi -KRE_USER_PACKAGES="$KRE_USER_HOME/packages" +_KVM_USER_PACKAGES="$KVM_USER_HOME/runtimes" +_KVM_ALIAS_DIR="$KVM_USER_HOME/alias" + if [ -z "$KRE_FEED" ]; then - KRE_FEED="https://www.myget.org/F/aspnetrelease/api/v2" + KRE_FEED="$_KVM_DEFAULT_FEED" fi -_kvm_find_latest() { - local platform="Mono" +__kvm_find_latest() { + local platform="mono" - if ! _kvm_has "curl"; then - echo 'KVM Needs curl to proceed.' >&2; + if ! __kvm_has "curl"; then + echo "$_KVM_COMMAND_NAME needs curl to proceed." >&2; return 1 fi - local url="$KRE_FEED/GetUpdates()?packageIds=%27KRE-$platform%27&versions=%270.0%27&includePrerelease=true&includeAllVersions=false" + local url="$KRE_FEED/GetUpdates()?packageIds=%27$_KVM_RUNTIME_PACKAGE_NAME-$platform%27&versions=%270.0%27&includePrerelease=true&includeAllVersions=false" xml="$(curl $url 2>/dev/null)" 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#$KRE_USER_PACKAGES/[^/]*$2[^:]*:##g" -e "s#:$KRE_USER_PACKAGES/[^/]*$2[^:]*##g" -e "s#$KRE_USER_PACKAGES/[^/]*$2[^:]*##g" +__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() { +__kvm_prepend_path() { if [ -z "$1" ]; then echo "$2" else @@ -45,169 +59,171 @@ _kvm_prepend_path() { fi } -_kvm_package_version() { - local kreFullName="$1" - echo "$kreFullName" | sed "s/[^.]*.\(.*\)/\1/" +__kvm_package_version() { + local runtimeFullName="$1" + echo "$runtimeFullName" | sed "s/[^.]*.\(.*\)/\1/" } -_kvm_package_name() { - local kreFullName="$1" - echo "$kreFullName" | sed "s/\([^.]*\).*/\1/" +__kvm_package_name() { + local runtimeFullName="$1" + echo "$runtimeFullName" | sed "s/\([^.]*\).*/\1/" } -_kvm_package_runtime() { - local kreFullName="$1" - echo "$kreFullName" | sed "s/KRE-\([^.-]*\).*/\1/" +__kvm_package_runtime() { + local runtimeFullName="$1" + echo "$runtimeFullName" | sed "s/$_KVM_RUNTIME_PACKAGE_NAME-\([^.-]*\).*/\1/" } -_kvm_download() { - local kreFullName="$1" - local kreFolder="$2" +__kvm_download() { + local runtimeFullName="$1" + local runtimeFolder="$2" - local pkgName=$(_kvm_package_name "$kreFullName") - local pkgVersion=$(_kvm_package_version "$kreFullName") + local pkgName=$(__kvm_package_name "$runtimeFullName") + local pkgVersion=$(__kvm_package_version "$runtimeFullName") local url="$KRE_FEED/package/$pkgName/$pkgVersion" - local kreFile="$kreFolder/$kreFullName.nupkg" + local runtimeFile="$runtimeFolder/$runtimeFullName.nupkg" - if [ -e "$kreFolder" ]; then - echo "$kreFullName already installed." + if [ -e "$runtimeFolder" ]; then + echo "$runtimeFullName already installed." return 0 fi - echo "Downloading $kreFullName from $KRE_FEED" + echo "Downloading $runtimeFullName from $KRE_FEED" - if ! _kvm_has "curl"; then - echo "KVM Needs curl to proceed." >&2; + if ! __kvm_has "curl"; then + echo "$_KVM_COMMAND_NAME needs curl to proceed." >&2; return 1 fi - mkdir -p "$kreFolder" > /dev/null 2>&1 + mkdir -p "$runtimeFolder" > /dev/null 2>&1 - local httpResult=$(curl -L -D - "$url" -o "$kreFile" 2>/dev/null | grep "^HTTP/1.1" | head -n 1 | sed "s/HTTP.1.1 \([0-9]*\).*/\1/") + local httpResult=$(curl -L -D - "$url" -o "$runtimeFile" 2>/dev/null | grep "^HTTP/1.1" | head -n 1 | sed "s/HTTP.1.1 \([0-9]*\).*/\1/") - [[ $httpResult == "404" ]] && echo "$kreFullName was not found in repository $KRE_FEED" && return 1 - [[ $httpResult != "302" && $httpResult != "200" ]] && echo "HTTP Error $httpResult fetching $kreFullName from $KRE_FEED" && return 1 + [[ $httpResult == "404" ]] && echo "$runtimeFullName was not found in repository $KRE_FEED" && return 1 + [[ $httpResult != "302" && $httpResult != "200" ]] && echo "HTTP Error $httpResult fetching $runtimeFullName from $KRE_FEED" && return 1 - _kvm_unpack $kreFile $kreFolder - return $? + __kvm_unpack $runtimeFile $runtimeFolder + return $? } -_kvm_unpack() { - local kreFile="$1" - local kreFolder="$2" +__kvm_unpack() { + local runtimeFile="$1" + local runtimeFolder="$2" - echo "Installing to $kreFolder" + echo "Installing to $runtimeFolder" - if ! _kvm_has "unzip"; then - echo "KVM Needs unzip to proceed." >&2; + if ! __kvm_has "unzip"; then + echo "$_KVM_COMMAND_NAME needs unzip to proceed." >&2; return 1 fi - unzip $kreFile -d $kreFolder > /dev/null 2>&1 + unzip $runtimeFile -d $runtimeFolder > /dev/null 2>&1 + + [ -e "$runtimeFolder/[Content_Types].xml" ] && rm "$runtimeFolder/[Content_Types].xml" - [ -e "$kreFolder/[Content_Types].xml" ] && rm "$kreFolder/[Content_Types].xml" + [ -e "$runtimeFolder/_rels/" ] && rm -rf "$runtimeFolder/_rels/" - [ -e "$kreFolder/_rels/" ] && rm -rf "$kreFolder/_rels/" + [ -e "$runtimeFolder/package/" ] && rm -rf "$runtimeFolder/_package/" - [ -e "$kreFolder/package/" ] && rm -rf "$kreFolder/_package/" + [ -e "$runtimeFile" ] && rm -f "$runtimeFile" #Set shell commands as executable - find "$kreFolder/bin/" -type f \ + find "$runtimeFolder/bin/" -type f \ -exec sh -c "head -c 11 {} | grep '/bin/bash' > /dev/null" \; -print | xargs chmod 775 } -_kvm_requested_version_or_alias() { +__kvm_requested_version_or_alias() { local versionOrAlias="$1" - local kreBin=$(_kvm_locate_kre_bin_from_full_name "$versionOrAlias") - - # If the name specified is an existing package, just use it as is - if [ -n "$kreBin" ]; then - echo "$versionOrAlias" - else - if [ -e "$KRE_USER_HOME/alias/$versionOrAlias.alias" ]; then - local kreFullName=$(cat "$KRE_USER_HOME/alias/$versionOrAlias.alias") - local pkgName=$(echo $kreFullName | sed "s/\([^.]*\).*/\1/") - local pkgVersion=$(echo $kreFullName | sed "s/[^.]*.\(.*\)/\1/") - local pkgPlatform=$(echo "$pkgName" | sed "s/KRE-\([^.-]*\).*/\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" + local pkgPlatform="mono" fi - echo "KRE-$pkgPlatform.$pkgVersion" + echo "$_KVM_RUNTIME_PACKAGE_NAME-$pkgPlatform.$pkgVersion" fi } # This will be more relevant if we support global installs -_kvm_locate_kre_bin_from_full_name() { - local kreFullName=$1 - [ -e "$KRE_USER_PACKAGES/$kreFullName/bin" ] && echo "$KRE_USER_PACKAGES/$kreFullName/bin" && return +__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 help + $_KVM_COMMAND_NAME help return fi case $1 in "help" ) echo "" - echo "K Runtime Environment Version Manager - Build 10050" + echo "$_KVM_VERSION_MANAGER_NAME - Build $_KVM_BUILDNUMBER" echo "" - echo "USAGE: kvm [options]" + echo "USAGE: $_KVM_COMMAND_NAME [options]" echo "" - echo "kvm upgrade" - echo "install latest KRE from feed" - echo "add KRE bin to path of current command line" + 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 install |||latest [-a|-alias ] [-p -persistent]" - echo "| install requested KRE from feed" - echo " install requested KRE from local package on filesystem" - echo "latest install latest version of KRE from feed" - echo "-a|-alias set alias for requested KRE on install" + 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 KRE bin to path of current command line" + echo "add $_KVM_RUNTIME_SHORT_NAME bin to path of current command line" echo "" - echo "kvm use |||none [-p -persistent]" - echo "|| add KRE bin to path of current command line " - echo "none remove KRE bin from path of current command line" + 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 list" - echo "list KRE versions installed " + echo "$_KVM_COMMAND_NAME list" + echo "list $_KVM_RUNTIME_SHORT_NAME versions installed " echo "" - echo "kvm alias" - echo "list KRE aliases which have been defined" + echo "$_KVM_COMMAND_NAME alias" + echo "list $_KVM_RUNTIME_SHORT_NAME aliases which have been defined" echo "" - echo "kvm alias " + echo "$_KVM_COMMAND_NAME alias " echo "display value of the specified alias" echo "" - echo "kvm alias ||" + echo "$_KVM_COMMAND_NAME alias ||" echo " the name of the alias to set" - echo "|| the KRE version to set the alias to. Alternatively use the version of the specified alias" + echo "|| the $_KVM_RUNTIME_SHORT_NAME version to set the alias to. Alternatively use the version of the specified alias" echo "" - echo "kvm unalias " + echo "$_KVM_COMMAND_NAME unalias " echo "remove the specified alias" echo "" ;; "upgrade" ) [ $# -ne 1 ] && kvm help && return - kvm install latest -p + $_KVM_COMMAND_NAME install latest -p ;; "install" ) [ $# -lt 2 ] && kvm help && return shift - local persistant= + local persistent= local versionOrAlias= local alias= while [ $# -ne 0 ] do - if [[ $1 == "-p" || $1 == "-persistant" ]]; then + if [[ $1 == "-p" || $1 == "-persistent" ]]; then local persistent="-p" elif [[ $1 == "-a" || $1 == "-alias" ]]; then local alias=$2 @@ -220,39 +236,39 @@ kvm() done if [[ "$versionOrAlias" == "latest" ]]; then echo "Determining latest version" - versionOrAlias=$(_kvm_find_latest) + versionOrAlias=$(__kvm_find_latest) [[ $? == 1 ]] && echo "Error: Could not find latest version from feed $KRE_FEED" && return 1 echo "Latest version is $versionOrAlias" fi if [[ "$versionOrAlias" == *.nupkg ]]; then - local kreFullName=$(basename $versionOrAlias | sed "s/\(.*\)\.nupkg/\1/") - local kreVersion=$(_kvm_package_version "$kreFullName") - local kreFolder="$KRE_USER_PACKAGES/$kreFullName" - local kreFile="$kreFolder/$kreFullName.nupkg" + 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 "$kreFolder" ]; then - echo "$kreFullName already installed" + if [ -e "$runtimeFolder" ]; then + echo "$runtimeFullName already installed" else - mkdir "$kreFolder" > /dev/null 2>&1 - cp -a "$versionOrAlias" "$kreFile" - _kvm_unpack "$kreFile" "$kreFolder" + mkdir "$runtimeFolder" > /dev/null 2>&1 + cp -a "$versionOrAlias" "$runtimeFile" + __kvm_unpack "$runtimeFile" "$runtimeFolder" [[ $? == 1 ]] && return 1 fi - kvm use "$kreVersion" "$persistent" - [[ -n $alias ]] && kvm alias "$alias" "$kreVersion" + $_KVM_COMMAND_NAME use "$runtimeVersion" "$persistent" + [[ -n $alias ]] && kvm alias "$alias" "$runtimeVersion" else - local kreFullName="$(_kvm_requested_version_or_alias $versionOrAlias)" - local kreFolder="$KRE_USER_PACKAGES/$kreFullName" - _kvm_download "$kreFullName" "$kreFolder" + local runtimeFullName="$(__kvm_requested_version_or_alias $versionOrAlias)" + local runtimeFolder="$_KVM_USER_PACKAGES/$runtimeFullName" + __kvm_download "$runtimeFullName" "$runtimeFolder" [[ $? == 1 ]] && return 1 - kvm use "$versionOrAlias" "$persistent" + $_KVM_COMMAND_NAME use "$versionOrAlias" "$persistent" [[ -n $alias ]] && kvm alias "$alias" "$versionOrAlias" fi ;; "use" ) - [ $# -gt 3 ] && kvm help && return - [ $# -lt 2 ] && kvm help && return + [ $# -gt 3 ] && $_KVM_COMMAND_NAME help && return + [ $# -lt 2 ] && $_KVM_COMMAND_NAME help && return shift local persistent= @@ -267,51 +283,53 @@ kvm() done if [[ $versionOrAlias == "none" ]]; then - echo "Removing KRE from process PATH" + echo "Removing $_KVM_RUNTIME_SHORT_NAME from process PATH" # Strip other version from PATH - PATH=$(_kvm_strip_path "$PATH" "/bin") + PATH=$(__kvm_strip_path "$PATH" "/bin") - if [[ -n $persistent && -e "$KRE_USER_HOME/alias/default.alias" ]]; then - echo "Setting default KRE to none" - rm "$KRE_USER_HOME/alias/default.alias" + 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 kreFullName=$(_kvm_requested_version_or_alias "$versionOrAlias") - local kreBin=$(_kvm_locate_kre_bin_from_full_name "$kreFullName") + local runtimeFullName=$(__kvm_requested_version_or_alias "$versionOrAlias") + local runtimeBin=$(__kvm_locate_runtime_bin_from_full_name "$runtimeFullName") - if [[ -z $kreBin ]]; then - echo "Cannot find $kreFullName, do you need to run 'kvm install $versionOrAlias'?" + if [[ -z $runtimeBin ]]; then + echo "Cannot find $runtimeFullName, do you need to run '$_KVM_COMMAND_NAME install $versionOrAlias'?" return 1 fi - echo "Adding" $kreBin "to process PATH" + echo "Adding" $runtimeBin "to process PATH" - PATH=$(_kvm_strip_path "$PATH" "/bin") - PATH=$(_kvm_prepend_path "$PATH" "$kreBin") + PATH=$(__kvm_strip_path "$PATH" "/bin") + PATH=$(__kvm_prepend_path "$PATH" "$runtimeBin") if [[ -n $persistent ]]; then - local kreVersion=$(_kvm_package_version "$kreFullName") - kvm alias default "$kreVersion" + local runtimeVersion=$(__kvm_package_version "$runtimeFullName") + $_KVM_COMMAND_NAME alias default "$runtimeVersion" fi ;; "alias" ) [[ $# -gt 3 ]] && kvm help && return - [[ ! -e "$KRE_USER_HOME/alias/" ]] && mkdir "$KRE_USER_HOME/alias/" > /dev/null + [[ ! -e "$_KVM_ALIAS_DIR/" ]] && mkdir "$_KVM_ALIAS_DIR/" > /dev/null if [[ $# == 1 ]]; then echo "" local format="%-20s %s\n" printf "$format" "Alias" "Name" printf "$format" "-----" "----" - for _kvm_file in $(find "$KRE_USER_HOME/alias" -name *.alias); do - local alias="$(basename $_kvm_file | sed 's/.alias//')" - local name="$(cat $_kvm_file)" - printf "$format" "$alias" "$name" - done + 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 @@ -319,27 +337,27 @@ kvm() local name="$2" if [[ $# == 2 ]]; then - [[ ! -e "$KRE_USER_HOME/alias/$name.alias" ]] && echo "There is no alias called '$name'" && return - cat "$KRE_USER_HOME/alias/$name.alias" + [[ ! -e "$_KVM_ALIAS_DIR/$name.alias" ]] && echo "There is no alias called '$name'" && return + cat "$_KVM_ALIAS_DIR/$name.alias" echo "" return fi - local kreFullName=$(_kvm_requested_version_or_alias "$3") + local runtimeFullName=$(__kvm_requested_version_or_alias "$3") - [[ ! -d "$KRE_USER_PACKAGES/$kreFullName" ]] && echo "$kreFullName is not an installed KRE version" && return 1 + [[ ! -d "$_KVM_USER_PACKAGES/$runtimeFullName" ]] && echo "$runtimeFullName is not an installed $_KVM_RUNTIME_SHORT_NAME version" && return 1 local action="Setting" - [[ -e "$KRE_USER_HOME/alias/$name.alias" ]] && action="Updating" - echo "$action alias '$name' to '$kreFullName'" - echo "$kreFullName" > "$KRE_USER_HOME/alias/$name.alias" + [[ -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="$KRE_USER_HOME/alias/$name.alias" + local aliasPath="$_KVM_ALIAS_DIR/$name.alias" [[ ! -e "$aliasPath" ]] && echo "Cannot remove alias, '$name' is not a valid alias name" && return 1 echo "Removing alias $name" rm "$aliasPath" >> /dev/null 2>&1 @@ -348,12 +366,12 @@ kvm() "list" ) [[ $# -gt 2 ]] && kvm help && return - [[ ! -d $KRE_USER_PACKAGES ]] && echo "KRE is not installed." && return 1 + [[ ! -d $_KVM_USER_PACKAGES ]] && echo "$_KVM_RUNTIME_FRIENDLY_NAME is not installed." && return 1 - local searchGlob="KRE-*" + local searchGlob="$_KVM_RUNTIME_PACKAGE_NAME-*" if [ $# == 2 ]; then local versionOrAlias=$2 - local searchGlob=$(_kvm_requested_version_or_alias "$versionOrAlias") + local searchGlob=$(__kvm_requested_version_or_alias "$versionOrAlias") fi echo "" @@ -365,27 +383,29 @@ kvm() # Z shell array-index starts at one. local i=1 local format="%-20s %s\n" - for _kvm_file in $(find "$KRE_USER_HOME/alias" -name *.alias); do - arr[$i]="$(basename $_kvm_file | sed 's/.alias//')/$(cat $_kvm_file)" - let i+=1 - done + 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 $KRE_USER_PACKAGES | sed s=$HOME=~=g)` - for f in $(find $KRE_USER_PACKAGES -name "$searchGlob" \( -type d -or -type l \) -prune -exec basename {} \;); do + 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 == *"$KRE_USER_PACKAGES/$f/bin"* ]] && local active=" *" - local pkgName=$(_kvm_package_runtime "$f") - local pkgVersion=$(_kvm_package_version "$f") + [[ $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="KRE-$pkgName.$pkgVersion" - temp2="KRE-$pkgName-x86.$pkgVersion" + 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=", " @@ -408,4 +428,5 @@ kvm() return 0 } -kvm list default >/dev/null && kvm use default >/dev/null || true +# Generate the command function using the constant defined above. +$_KVM_COMMAND_NAME list default >/dev/null && $_KVM_COMMAND_NAME use default >/dev/null || true From 0bc5685e8d31db33e8ea96d5c5a4715d5282fe29 Mon Sep 17 00:00:00 2001 From: "ASP.NET Push Bot" Date: Fri, 30 Jan 2015 14:34:38 -0800 Subject: [PATCH 10/27] :arrow_up: kvm.ps1, kvm.cmd, kvm.sh Source: aspnet/kvm@6bd60a2f3cc9dc62fd7e302d7f0f2d99bbaccc4d --- kvm.ps1 | 4 ++-- kvm.sh | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/kvm.ps1 b/kvm.ps1 index 944ffbe4106e..d90f4e145ea4 100644 --- a/kvm.ps1 +++ b/kvm.ps1 @@ -23,14 +23,14 @@ param( ) # Constants -Set-Variable -Option Constant "BuildNumber" "10318" +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 "DefaultFeed" "https://www.myget.org/F/aspnetrelease/api/v2" Set-Variable -Option Constant "CrossGenCommand" "k-crossgen" Set-Variable -Option Constant "HomeEnvVar" "KRE_HOME" Set-Variable -Option Constant "UserHomeEnvVar" "KRE_USER_HOME" diff --git a/kvm.sh b/kvm.sh index a746e147e364..bf770d07ca53 100644 --- a/kvm.sh +++ b/kvm.sh @@ -2,7 +2,7 @@ # Source this file from your .bash-profile or script to use # "Constants" -_KVM_BUILDNUMBER="10318" +_KVM_BUILDNUMBER="10319" _KVM_RUNTIME_PACKAGE_NAME="kre" _KVM_RUNTIME_FRIENDLY_NAME="K Runtime" _KVM_RUNTIME_SHORT_NAME="KRE" From 065c6ee0cfd782e70227874473216fedfc2e7d64 Mon Sep 17 00:00:00 2001 From: anurse Date: Mon, 2 Feb 2015 14:15:10 -0800 Subject: [PATCH 11/27] :lipstick: clean up README and add support for using other branches of kvm --- README.md | 20 +- dotnetsdk.cmd | 8 - dotnetsdk.ps1 | 774 ------------------------------------------------- dotnetsdk.sh | 416 -------------------------- kvminstall.ps1 | 8 +- kvminstall.sh | 5 +- 6 files changed, 26 insertions(+), 1205 deletions(-) delete mode 100644 dotnetsdk.cmd delete mode 100644 dotnetsdk.ps1 delete mode 100644 dotnetsdk.sh diff --git a/README.md b/README.md index c2e242214f95..c442742d3a91 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # ASP.NET vNext Home -Latest dev version: [![dev version](http://img.shields.io/myget/aspnetvnext/v/KRE-CLR-x86.svg?style=flat)](https://www.myget.org/gallery/aspnetvnext)
-Latest master version: [![master version](http://img.shields.io/myget/aspnetmaster/v/KRE-CLR-x86.svg?style=flat)](https://www.myget.org/gallery/aspnetmaster) +Latest dev version: [![dev version](http://img.shields.io/myget/aspnetvnext/v/kre-clr-win-x86.svg?style=flat)](https://www.myget.org/gallery/aspnetvnext)
+Latest master version: [![master version](http://img.shields.io/myget/aspnetmaster/v/kre-clr-win-x86.svg?style=flat)](https://www.myget.org/gallery/aspnetmaster) The Home repository is the starting point for people to learn about ASP.NET vNext. This repo contains samples and [documentation](https://github.com/aspnet/Home/wiki) to help folks get started and learn more about what's coming in ASP.NET vNext. @@ -40,13 +40,19 @@ That said, you can also try out ASP.NET vNext with just a command-prompt and a t The first thing we need to do is setup the tools required to build and run an application. We will start out by getting the [K Version Manager (KVM)](https://github.com/aspnet/Home/wiki/version-manager). We use the K Version Manager to install different versions of the ASP.NET vNext runtime and switch between them. #### Windows -To install KVM on Windows run the following command, which will download and run a script that installs KVM for the current user (requires admin privileges for Powershell): +To install KVM on Windows run the following command, which will download and run a script that installs KVM for the current user (requires admin privileges for Powershell). This will use the currently released version of `kvm` (from the `release` branch of this repo). ``` @powershell -NoProfile -ExecutionPolicy unrestricted -Command "iex ((new-object net.webclient).DownloadString('https://raw.githubusercontent.com/aspnet/Home/release/kvminstall.ps1'))" ``` +If you want to run on the bleeding edge and install the latest development version of KVM, download the `kvminstall.ps1` file locally and invoke it in powershell with the following arguments: + +```powershell +& C:\Path\To\kvminstall.ps1 dev +``` + After the script has run open a new command prompt to start using KVM. #### OS X: @@ -66,6 +72,12 @@ Installing KVM need `curl`. Do verify if that is installed on the machine. Next curl -sSL https://raw.githubusercontent.com/aspnet/Home/release/kvminstall.sh | sh && source ~/.kre/kvm/kvm.sh ``` +If you want to run on the bleeding edge and install the latest development version of KVM, use this command: + +``` +curl -sSL https://raw.githubusercontent.com/aspnet/Home/release/kvminstall.sh | KVM_BRANCH=dev sh && source ~/.kre/kvm/kvm.sh +``` + Note that on Linux you need to also install [Mono](http://mono-project.com) 3.4.1 or later. ### Install the K Runtime Environment (KRE) @@ -115,7 +127,7 @@ The community standup is held every week and streamed live to YouTube. You can v If you have questions you can also jump online during the next standup and have them answered live. -### [Wiki Documentation] (https://github.com/aspnet/Home/wiki) +### [Wiki Documentation](https://github.com/aspnet/Home/wiki) We have some useful documentation on the wiki of this Repo. This wiki is a central spot for docs from any part of the stack. If you see errors, or want some extra content, then feel free to create an issue or send a pull request (see feedback section below). diff --git a/dotnetsdk.cmd b/dotnetsdk.cmd deleted file mode 100644 index f920d71aecd6..000000000000 --- a/dotnetsdk.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 = '';& '%~dp0dotnetsdk.ps1' %*" - -IF EXIST "%USERPROFILE%\.dotnet\temp-set-envvars.cmd" ( - CALL "%USERPROFILE%\.dotnet\temp-set-envvars.cmd" - DEL "%USERPROFILE%\.dotnet\temp-set-envvars.cmd" -) diff --git a/dotnetsdk.ps1 b/dotnetsdk.ps1 deleted file mode 100644 index d069abc32a77..000000000000 --- a/dotnetsdk.ps1 +++ /dev/null @@ -1,774 +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" (in as much as PowerShell will allow) -$RuntimePackageName = "dotnet" -$RuntimeFriendlyName = ".NET Runtime" -$RuntimeProgramFilesName = "Microsoft .NET Cross-Platform Runtime" -$RuntimeFolderName = ".dotnet" -$DefaultFeed = "https://www.myget.org/F/aspnetvnext/api/v2" -$CrossGenCommand = "k-crossgen" - -$selectedArch=$null; -$defaultArch="x86" -$selectedRuntime=$null -$defaultRuntime="clr" - -# Get or calculate userDotNetPath -$userDotNetPath = $env:DOTNET_USER_PATH -if(!$userDotNetPath) { $userDotNetPath = $env:USERPROFILE + "\$RuntimeFolderName" } -$userDotNetRuntimesPath = $userDotNetPath + "\runtimes" - -# Get the feed from the environment variable or set it to the default value -$feed = $env:DOTNET_FEED -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 DotNetSdk-Help { -@" -.NET SDK Manager - Build 10303 - -USAGE: dotnetsdk [options] - -dotnetsdk upgrade [-X86|-X64] [-r|-Runtime CLR|CoreCLR] [-g|-Global] [-f|-Force] [-Proxy
] [-NoNative] - install latest .NET Runtime from feed - set 'default' alias to installed version - add KRE 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) - -dotnetsdk install |||latest [-X86|-X64] [-r|-Runtime CLR|CoreCLR] [-a|-Alias ] [-f|-Force] [-Proxy
] [-NoNative] - | install requested .NET Runtime from feed - install requested .NET Runtime from package on local filesystem - latest install latest .NET Runtime from feed - add .NET Runtime bin to path of current command line - -p|-Persistent add .NET Runtime bin to PATH environment variables persistently - -a|-Alias set alias for requested .NET Runtime 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) - -dotnetsdk use |||none [-X86|-X64] [-r|-Runtime CLR|CoreCLR] [-p|-Persistent] - || add .NET Runtime bin to path of current command line - none remove .NET Runtime bin from path of current command line - -p|-Persistent add .NET Runtime bin to PATH environment variable across all processes run by the current user - -dotnetsdk list - list .NET Runtime versions installed - -dotnetsdk alias - list .NET Runtime aliases which have been defined - -dotnetsdk alias - display value of the specified alias - -dotnetsdk alias || [-X86|-X64] [-r|-Runtime CLR|CoreCLR] - the name of the alias to set - || the .NET Runtime version to set the alias to. Alternatively use the version of the specified alias - -dotnetsdk unalias - remove the specified alias - -"@ -replace "`n","`r`n" | Console-Write -} - -function DotNetSdk-Global-Setup { - # Sets up the 'dotnetsdk' tool and adds the user-local dotnet install directory to the DOTNET_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 DOTNET_HOME value. - - # In this configuration, the user-level path will OVERRIDE the global path because it is placed first. - - $dotnetsdkBinPath = "$userDotNetPath\bin" - - If (Needs-Elevation) - { - $arguments = "-ExecutionPolicy unrestricted & '$scriptPath' setup -wait" - Start-Process "$psHome\powershell.exe" -Verb runAs -ArgumentList $arguments -Wait - Console-Write "Adding $dotnetsdkBinPath to process PATH" - Set-Path (Change-Path $env:Path $dotnetsdkBinPath ($dotnetsdkBinPath)) - Console-Write "Adding %USERPROFILE%\$RuntimeFolderName to process DOTNET_HOME" - $envDotNetHome = $env:DOTNET_HOME - $envDotNetHome = Change-Path $envDotNetHome "%USERPROFILE%\$RuntimeFolderName" ("%USERPROFILE%\$RuntimeFolderName") - $env:DOTNET_HOME = $envDotNetHome - Console-Write "Setup complete" - break - } - - $scriptFolder = [System.IO.Path]::GetDirectoryName($scriptPath) - - Console-Write "Copying file $dotnetsdkBinPath\dotnetsdk.ps1" - md $dotnetsdkBinPath -Force | Out-Null - copy "$scriptFolder\dotnetsdk.ps1" "$dotnetsdkBinPath\dotnetsdk.ps1" - - Console-Write "Copying file $dotnetsdkBinPath\dotnetsdk.cmd" - copy "$scriptFolder\dotnetsdk.cmd" "$dotnetsdkBinPath\dotnetsdk.cmd" - - Console-Write "Adding $dotnetsdkBinPath to process PATH" - Set-Path (Change-Path $env:Path $dotnetsdkBinPath ($dotnetsdkBinPath)) - - Console-Write "Adding $dotnetsdkBinPath to user PATH" - $userPath = [Environment]::GetEnvironmentVariable("Path", [System.EnvironmentVariableTarget]::User) - $userPath = Change-Path $userPath $dotnetsdkBinPath ($dotnetsdkBinPath) - [Environment]::SetEnvironmentVariable("Path", $userPath, [System.EnvironmentVariableTarget]::User) - - Console-Write "Adding %USERPROFILE%\$RuntimeFolderName to process DOTNET_HOME" - $envDotNetHome = $env:DOTNET_HOME - $envDotNetHome = Change-Path $envDotNetHome "%USERPROFILE%\$RuntimeFolderName" ("%USERPROFILE%\$RuntimeFolderName") - $env:DOTNET_HOME = $envDotNetHome - - Console-Write "Adding %USERPROFILE%\$RuntimeFolderName to machine DOTNET_HOME" - $machineDotNetHome = [Environment]::GetEnvironmentVariable("DOTNET_HOME", [System.EnvironmentVariableTarget]::Machine) - $machineDotNetHome = Change-Path $machineDotNetHome "%USERPROFILE%\$RuntimeFolderName" ("%USERPROFILE%\$RuntimeFolderName") - [Environment]::SetEnvironmentVariable("DOTNET_HOME", $machineDotNetHome, [System.EnvironmentVariableTarget]::Machine) -} - -function DotNetSdk-Upgrade { -param( - [boolean] $isGlobal -) - $Persistent = $true - $Alias="default" - DotNetSdk-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 DotNetSdk-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-DotNetSdk-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-DotNetSdk-Unpack $tempDownloadFile $runtimeTempDownload - - md $runtimeFolder -Force | Out-Null - Console-Write "Installing to $runtimeFolder" - mv "$runtimeTempDownload\*" $runtimeFolder - Remove-Item "$runtimeTempDownload" -Force | Out-Null -} - -function Do-DotNetSdk-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 - } -} - -function DotNetSdk-Install { -param( - [string] $versionOrAlias, - [boolean] $isGlobal -) - if ($versionOrAlias -eq "latest") { - $versionOrAlias = DotNetSdk-Find-Latest (Requested-Platform $defaultRuntime) (Requested-Architecture $defaultArch) - } - - if ($versionOrAlias.EndsWith(".nupkg")) { - $runtimeFullName = [System.IO.Path]::GetFileNameWithoutExtension($versionOrAlias) - } else { - $runtimeFullName = Requested-VersionOrAlias $versionOrAlias - } - - $packageFolder = $userDotNetRuntimesPath - - 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-DotNetSdk-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 - - DotNetSdk-Use $packageVersion - if (!$(String-IsEmptyOrWhitespace($Alias))) { - DotNetSdk-Alias-Set $Alias $packageVersion - } - } - else - { - Do-DotNetSdk-Download $runtimeFullName $packageFolder - DotNetSdk-Use $versionOrAlias - if (!$(String-IsEmptyOrWhitespace($Alias))) { - DotNetSdk-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 DotNetSdk-List { - $dotnetHome = $env:DOTNET_HOME - if (!$dotnetHome) { - $dotnetHome = "$userDotNetPath" - } - - md ($userDotNetPath + "\alias\") -Force | Out-Null - $aliases = Get-ChildItem ($userDotNetPath + "\alias\") | Select @{label='Alias';expression={$_.BaseName}}, @{label='Name';expression={Get-Content $_.FullName }} - - $items = @() - foreach($portion in $dotnetHome.Split(';')) { - $path = [System.Environment]::ExpandEnvironmentVariables($portion) - if (Test-Path("$path\runtimes")) { - $items += Get-ChildItem ("$path\runtimes\dotnet-*") | 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 DotNetSdk-Use { -param( - [string] $versionOrAlias -) - Validate-Full-Package-Name-Arguments-Combination $versionOrAlias - - if ($versionOrAlias -eq "none") { - Console-Write "Removing .NET Runtime from process PATH" - Set-Path (Change-Path $env:Path "" ($userDotNetRuntimesPath)) - - if ($Persistent) { - Console-Write "Removing .NET Runtime from user PATH" - $userPath = [Environment]::GetEnvironmentVariable("Path", [System.EnvironmentVariableTarget]::User) - $userPath = Change-Path $userPath "" ($userDotNetRuntimesPath) - [Environment]::SetEnvironmentVariable("Path", $userPath, [System.EnvironmentVariableTarget]::User) - } - return; - } - - $runtimeFullName = Requested-VersionOrAlias $versionOrAlias - - $runtimeBin = Locate-DotNetBinFromFullName $runtimeFullName - if ($runtimeBin -eq $null) { - throw "Cannot find $runtimeFullName, do you need to run 'dotnetsdk install $versionOrAlias'?" - } - - Console-Write "Adding $runtimeBin to process PATH" - Set-Path (Change-Path $env:Path $runtimeBin ($userDotNetRuntimesPath)) - - if ($Persistent) { - Console-Write "Adding $runtimeBin to user PATH" - $userPath = [Environment]::GetEnvironmentVariable("Path", [System.EnvironmentVariableTarget]::User) - $userPath = Change-Path $userPath $runtimeBin ($userDotNetRuntimesPath) - [Environment]::SetEnvironmentVariable("Path", $userPath, [System.EnvironmentVariableTarget]::User) - } -} - -function DotNetSdk-Alias-List { - md ($userDotNetPath + "\alias\") -Force | Out-Null - - Get-ChildItem ($userDotNetPath + "\alias\") | Select @{label='Alias';expression={$_.BaseName}}, @{label='Name';expression={Get-Content $_.FullName }} | Format-Table -AutoSize -} - -function DotNetSdk-Alias-Get { -param( - [string] $name -) - md ($userDotNetPath + "\alias\") -Force | Out-Null - $aliasFilePath=$userDotNetPath + "\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 ($userDotNetPath + "\alias\" + $name + ".txt")) - Console-Write "Alias '$name' is set to $aliasValue" - } -} - -function DotNetSdk-Alias-Set { -param( - [string] $name, - [string] $value -) - $runtimeFullName = Requested-VersionOrAlias $value - $aliasFilePath = $userDotNetPath + "\alias\" + $name + ".txt" - $action = if (Test-Path $aliasFilePath) { "Updating" } else { "Setting" } - Console-Write "$action alias '$name' to '$runtimeFullName'" - md ($userDotNetPath + "\alias\") -Force | Out-Null - $runtimeFullName | Out-File ($aliasFilePath) ascii -} - -function DotNetSdk-Unalias { -param( - [string] $name -) - $aliasPath=$userDotNetPath + "\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-DotNetBinFromFullName() { -param( - [string] $runtimeFullName -) - $dotnetHome = $env:DOTNET_HOME - if (!$dotnetHome) { - $dotnetHome = "$globalDotNetPath;$userDotNetPath" - } - foreach($portion in $dotnetHome.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 'dotnet-([^-]*).*', '$1' -} - -function Package-Arch() { -param( - [string] $runtimeFullName -) - return $runtimeFullName -replace 'dotnet-[^-]*-[^-]*-([^.]*).*', '$1' -} - - -function Requested-VersionOrAlias() { -param( - [string] $versionOrAlias -) - Validate-Full-Package-Name-Arguments-Combination $versionOrAlias - - $runtimeBin = Locate-DotNetBinFromFullName $versionOrAlias - - # If the name specified is an existing package, just use it as is - if ($runtimeBin -ne $null) { - return $versionOrAlias - } - - If (Test-Path ($userDotNetPath + "\alias\" + $versionOrAlias + ".txt")) { - $aliasValue = Get-Content ($userDotNetPath + "\alias\" + $versionOrAlias + ".txt") - # Split dotnet-coreclr-win-x86.1.0.0-beta3-10922 into version and name sections - $parts = $aliasValue.Split('.', 2) - $pkgVersion = $parts[1] - # dotnet-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 $userDotNetPath -Force | Out-Null - $env:Path = $newPath -@" -SET "PATH=$newPath" -"@ | Out-File ($userDotNetPath + "\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 "dotnet-*" -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" {DotNetSdk-Global-Setup} - "upgrade 0" {DotNetSdk-Upgrade $false} - "install 1" {DotNetSdk-Install $Args[0] $false} - "list 0" {DotNetSdk-List} - "use 1" {DotNetSdk-Use $Args[0]} - "alias 0" {DotNetSdk-Alias-List} - "alias 1" {DotNetSdk-Alias-Get $Args[0]} - "alias 2" {DotNetSdk-Alias-Set $Args[0] $Args[1]} - "unalias 1" {DotNetSdk-Unalias $Args[0]} - "help 0" {DotNetSdk-Help} - " 0" {DotNetSdk-Help} - default {throw "Unknown command"}; - } -} -catch { - Console-Write-Error $_ - Console-Write "Type 'dotnetsdk help' for help on how to use dotnetsdk." - $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/dotnetsdk.sh b/dotnetsdk.sh deleted file mode 100644 index 31a490125c0b..000000000000 --- a/dotnetsdk.sh +++ /dev/null @@ -1,416 +0,0 @@ -# dotnetsdk.sh -# Source this file from your .bash-profile or script to use - -_dotnetsdk_has() { - type "$1" > /dev/null 2>&1 - return $? -} - -if _dotnetsdk_has "unsetopt"; then - unsetopt nomatch 2>/dev/null -fi - -if [ -z "$DOTNET_USER_HOME" ]; then - eval DOTNET_USER_HOME=~/.dotnet -fi - -DOTNET_USER_PACKAGES="$DOTNET_USER_HOME/runtimes" -if [ -z "$DOTNET_FEED" ]; then - DOTNET_FEED="https://www.myget.org/F/aspnetvnext/api/v2" -fi - -_dotnetsdk_find_latest() { - local platform="mono" - - if ! _dotnetsdk_has "curl"; then - echo 'dotnetsdk needs curl to proceed.' >&2; - return 1 - fi - - local url="$DOTNET_FEED/GetUpdates()?packageIds=%27dotnet-$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 -} - -_dotnetsdk_strip_path() { - echo "$1" | sed -e "s#$DOTNET_USER_PACKAGES/[^/]*$2[^:]*:##g" -e "s#:$DOTNET_USER_PACKAGES/[^/]*$2[^:]*##g" -e "s#$DOTNET_USER_PACKAGES/[^/]*$2[^:]*##g" -} - -_dotnetsdk_prepend_path() { - if [ -z "$1" ]; then - echo "$2" - else - echo "$2:$1" - fi -} - -_dotnetsdk_package_version() { - local runtimeFullName="$1" - echo "$runtimeFullName" | sed "s/[^.]*.\(.*\)/\1/" -} - -_dotnetsdk_package_name() { - local runtimeFullName="$1" - echo "$runtimeFullName" | sed "s/\([^.]*\).*/\1/" -} - -_dotnetsdk_package_runtime() { - local runtimeFullName="$1" - echo "$runtimeFullName" | sed "s/KRE-\([^.-]*\).*/\1/" -} - -_dotnetsdk_download() { - local runtimeFullName="$1" - local runtimeFolder="$2" - - local pkgName=$(_dotnetsdk_package_name "$runtimeFullName") - local pkgVersion=$(_dotnetsdk_package_version "$runtimeFullName") - local url="$DOTNET_FEED/package/$pkgName/$pkgVersion" - local runtimeFile="$runtimeFolder/$runtimeFullName.nupkg" - - if [ -e "$runtimeFolder" ]; then - echo "$runtimeFullName already installed." - return 0 - fi - - echo "Downloading $runtimeFullName from $DOTNET_FEED" - - if ! _dotnetsdk_has "curl"; then - echo "dotnetsdk 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 $DOTNET_FEED" && return 1 - [[ $httpResult != "302" && $httpResult != "200" ]] && echo "HTTP Error $httpResult fetching $runtimeFullName from $DOTNET_FEED" && return 1 - - _dotnetsdk_unpack $runtimeFile $runtimeFolder - return $? -} - -_dotnetsdk_unpack() { - local runtimeFile="$1" - local runtimeFolder="$2" - - echo "Installing to $runtimeFolder" - - if ! _dotnetsdk_has "unzip"; then - echo "dotnetsdk 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/" - - #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 -} - -_dotnetsdk_requested_version_or_alias() { - local versionOrAlias="$1" - local runtimeBin=$(_dotnetsdk_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 "$DOTNET_USER_HOME/alias/$versionOrAlias.alias" ]; then - local runtimeFullName=$(cat "$DOTNET_USER_HOME/alias/$versionOrAlias.alias") - local pkgName=$(echo $runtimeFullName | sed "s/\([^.]*\).*/\1/") - local pkgVersion=$(echo $runtimeFullName | sed "s/[^.]*.\(.*\)/\1/") - local pkgPlatform=$(echo "$pkgName" | sed "s/dotnet-\([^.-]*\).*/\1/") - else - local pkgVersion=$versionOrAlias - local pkgPlatform="mono" - fi - - echo "dotnet-$pkgPlatform.$pkgVersion" - fi -} - -# This will be more relevant if we support global installs -_dotnetsdk_locate_runtime_bin_from_full_name() { - local runtimeFullName=$1 - [ -e "$DOTNET_USER_PACKAGES/$runtimeFullName/bin" ] && echo "$DOTNET_USER_PACKAGES/$runtimeFullName/bin" && return -} - -dotnetsdk() -{ - if [ $# -lt 1 ]; then - dotnetsdk help - return - fi - - case $1 in - "help" ) - echo "" - echo ".NET SDK Manager - Build 10303" - echo "" - echo "USAGE: dotnetsdk [options]" - echo "" - echo "dotnetsdk upgrade" - echo "install latest .NET Runtime from feed" - echo "add .NET Runtime bin to path of current command line" - echo "set installed version as default" - echo "" - echo "dotnetsdk install |||latest [-a|-alias ] [-p -persistent]" - echo "| install requested .NET Runtime from feed" - echo " install requested .NET Runtime from local package on filesystem" - echo "latest install latest version of .NET Runtime from feed" - echo "-a|-alias set alias for requested .NET Runtime on install" - echo "-p -persistent set installed version as default" - echo "add .NET Runtime bin to path of current command line" - echo "" - echo "dotnetsdk use |||none [-p -persistent]" - echo "|| add .NET Runtime bin to path of current command line " - echo "none remove .NET Runtime bin from path of current command line" - echo "-p -persistent set selected version as default" - echo "" - echo "dotnetsdk list" - echo "list .NET Runtime versions installed " - echo "" - echo "dotnetsdk alias" - echo "list .NET Runtime aliases which have been defined" - echo "" - echo "dotnetsdk alias " - echo "display value of the specified alias" - echo "" - echo "dotnetsdk alias ||" - echo " the name of the alias to set" - echo "|| the .NET Runtime version to set the alias to. Alternatively use the version of the specified alias" - echo "" - echo "dotnetsdk unalias " - echo "remove the specified alias" - echo "" - ;; - - "upgrade" ) - [ $# -ne 1 ] && dotnetsdk help && return - dotnetsdk install latest -p - ;; - - "install" ) - [ $# -lt 2 ] && dotnetsdk 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" && dotnetsdk help && return 1 - local versionOrAlias=$1 - fi - shift - done - if [[ "$versionOrAlias" == "latest" ]]; then - echo "Determining latest version" - versionOrAlias=$(_dotnetsdk_find_latest) - [[ $? == 1 ]] && echo "Error: Could not find latest version from feed $DOTNET_FEED" && return 1 - echo "Latest version is $versionOrAlias" - fi - if [[ "$versionOrAlias" == *.nupkg ]]; then - local runtimeFullName=$(basename $versionOrAlias | sed "s/\(.*\)\.nupkg/\1/") - local runtimeVersion=$(_dotnetsdk_package_version "$runtimeFullName") - local runtimeFolder="$DOTNET_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" - _dotnetsdk_unpack "$runtimeFile" "$runtimeFolder" - [[ $? == 1 ]] && return 1 - fi - dotnetsdk use "$runtimeVersion" "$persistent" - [[ -n $alias ]] && dotnetsdk alias "$alias" "$runtimeVersion" - else - local runtimeFullName="$(_dotnetsdk_requested_version_or_alias $versionOrAlias)" - local runtimeFolder="$DOTNET_USER_PACKAGES/$runtimeFullName" - _dotnetsdk_download "$runtimeFullName" "$runtimeFolder" - [[ $? == 1 ]] && return 1 - dotnetsdk use "$versionOrAlias" "$persistent" - [[ -n $alias ]] && dotnetsdk alias "$alias" "$versionOrAlias" - fi - ;; - - "use" ) - [ $# -gt 3 ] && dotnetsdk help && return - [ $# -lt 2 ] && dotnetsdk 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 .NET Runtime from process PATH" - # Strip other version from PATH - PATH=$(_dotnetsdk_strip_path "$PATH" "/bin") - - if [[ -n $persistent && -e "$DOTNET_USER_HOME/alias/default.alias" ]]; then - echo "Setting default .NET Runtime to none" - rm "$DOTNET_USER_HOME/alias/default.alias" - fi - return 0 - fi - - local runtimeFullName=$(_dotnetsdk_requested_version_or_alias "$versionOrAlias") - local runtimeBin=$(_dotnetsdk_locate_runtime_bin_from_full_name "$runtimeFullName") - - if [[ -z $runtimeBin ]]; then - echo "Cannot find $runtimeFullName, do you need to run 'dotnetsdk install $versionOrAlias'?" - return 1 - fi - - echo "Adding" $runtimeBin "to process PATH" - - PATH=$(_dotnetsdk_strip_path "$PATH" "/bin") - PATH=$(_dotnetsdk_prepend_path "$PATH" "$runtimeBin") - - if [[ -n $persistent ]]; then - local runtimeVersion=$(_dotnetsdk_package_version "$runtimeFullName") - dotnetsdk alias default "$runtimeVersion" - fi - ;; - - "alias" ) - [[ $# -gt 3 ]] && dotnetsdk help && return - - [[ ! -e "$DOTNET_USER_HOME/alias/" ]] && mkdir "$DOTNET_USER_HOME/alias/" > /dev/null - - if [[ $# == 1 ]]; then - echo "" - local format="%-20s %s\n" - printf "$format" "Alias" "Name" - printf "$format" "-----" "----" - if [ -d "$DOTNET_USER_HOME/alias" ]; then - for _dotnetsdk_file in $(find "$DOTNET_USER_HOME/alias" -name *.alias); do - local alias="$(basename $_dotnetsdk_file | sed 's/\.alias//')" - local name="$(cat $_dotnetsdk_file)" - printf "$format" "$alias" "$name" - done - fi - echo "" - return - fi - - local name="$2" - - if [[ $# == 2 ]]; then - [[ ! -e "$DOTNET_USER_HOME/alias/$name.alias" ]] && echo "There is no alias called '$name'" && return - cat "$DOTNET_USER_HOME/alias/$name.alias" - echo "" - return - fi - - local runtimeFullName=$(_dotnetsdk_requested_version_or_alias "$3") - - [[ ! -d "$DOTNET_USER_PACKAGES/$runtimeFullName" ]] && echo "$runtimeFullName is not an installed .NET Runtime version" && return 1 - - local action="Setting" - [[ -e "$DOTNET_USER_HOME/alias/$name.alias" ]] && action="Updating" - echo "$action alias '$name' to '$runtimeFullName'" - echo "$runtimeFullName" > "$DOTNET_USER_HOME/alias/$name.alias" - ;; - - "unalias" ) - [[ $# -ne 2 ]] && dotnetsdk help && return - - local name=$2 - local aliasPath="$DOTNET_USER_HOME/alias/$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 ]] && dotnetsdk help && return - - [[ ! -d $DOTNET_USER_PACKAGES ]] && echo ".NET Runtime is not installed." && return 1 - - local searchGlob="dotnet-*" - if [ $# == 2 ]; then - local versionOrAlias=$2 - local searchGlob=$(_dotnetsdk_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 "$DOTNET_USER_HOME/alias" ]; then - for _dotnetsdk_file in $(find "$DOTNET_USER_HOME/alias" -name *.alias); do - arr[$i]="$(basename $_dotnetsdk_file | sed 's/\.alias//')/$(cat $_dotnetsdk_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 $DOTNET_USER_PACKAGES | sed s=$HOME=~=g)` - for f in $(find $DOTNET_USER_PACKAGES -name "$searchGlob" \( -type d -or -type l \) -prune -exec basename {} \;); do - local active="" - [[ $PATH == *"$DOTNET_USER_PACKAGES/$f/bin"* ]] && local active=" *" - local pkgName=$(_dotnetsdk_package_runtime "$f") - local pkgVersion=$(_dotnetsdk_package_version "$f") - - local alias="" - local delim="" - for i in "${arr[@]}"; do - temp="dotnet-$pkgName.$pkgVersion" - temp2="dotnet-$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 -} - -dotnetsdk list default >/dev/null && dotnetsdk use default >/dev/null || true diff --git a/kvminstall.ps1 b/kvminstall.ps1 index 1b882f6bbeda..e0b9e16daffe 100644 --- a/kvminstall.ps1 +++ b/kvminstall.ps1 @@ -1,3 +1,7 @@ +param( + [Parameter(Mandatory=$false, Position=0)]$Branch = "master", + [Parameter(Mandatory=$false, Position=1)]$Repository = "aspnet/Home") + $tempPath = Join-Path $env:TEMP "kvminstall" $kvmPs1Path = Join-Path $tempPath "kvm.ps1" $kvmCmdPath = Join-Path $tempPath "kvm.cmd" @@ -8,8 +12,8 @@ if (!(Test-Path $tempPath)) { md $tempPath | Out-Null } $webClient = New-Object System.Net.WebClient Write-Host "Downloading KVM.ps1 to $kvmPs1Path" -$webClient.DownloadFile('https://raw.githubusercontent.com/aspnet/Home/release/kvm.ps1', $kvmPs1Path) +$webClient.DownloadFile("https://raw.githubusercontent.com/$Repository/$Branch/kvm.ps1", $kvmPs1Path) Write-Host "Downloading KVM.cmd to $kvmCmdPath" -$webClient.DownloadFile('https://raw.githubusercontent.com/aspnet/Home/release/kvm.cmd', $kvmCmdPath) +$webClient.DownloadFile("https://raw.githubusercontent.com/$Repository/$Branch/kvm.cmd", $kvmCmdPath) Write-Host "Installing KVM" & $kvmCmdPath setup \ No newline at end of file diff --git a/kvminstall.sh b/kvminstall.sh index ab98cf800130..4d1dd19b80a7 100644 --- a/kvminstall.sh +++ b/kvminstall.sh @@ -1,5 +1,8 @@ #!/bin/bash +[ -z "$KVM_REPO" ] && KVM_REPO="aspnet/Home" +[ -z "$KVM_BRANCH" ] && KVM_BRANCH="master" + _kvmsetup_has() { type "$1" > /dev/null 2>&1 return $? @@ -27,7 +30,7 @@ if ! _kvmsetup_has "curl"; then fi if [ -z "$KVM_SOURCE" ]; then - KVM_SOURCE="https://raw.githubusercontent.com/aspnet/Home/master/kvm.sh" + KVM_SOURCE="https://raw.githubusercontent.com/$KVM_REPO/$KVM_BRANCH/kvm.sh" fi # Downloading to $KVM_DIR From 9556d0d366d757a6a1b8e0d51162394b45a7dd06 Mon Sep 17 00:00:00 2001 From: anurse Date: Mon, 2 Feb 2015 14:22:46 -0800 Subject: [PATCH 12/27] change the way parameters are passed to kvminstall.ps1 --- kvminstall.ps1 | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/kvminstall.ps1 b/kvminstall.ps1 index e0b9e16daffe..5fb9eb7bd618 100644 --- a/kvminstall.ps1 +++ b/kvminstall.ps1 @@ -1,6 +1,5 @@ -param( - [Parameter(Mandatory=$false, Position=0)]$Branch = "master", - [Parameter(Mandatory=$false, Position=1)]$Repository = "aspnet/Home") +if(!$Branch) { $Branch = "release" } +if(!$Repository) { $Repository = "aspnet/Home" } $tempPath = Join-Path $env:TEMP "kvminstall" $kvmPs1Path = Join-Path $tempPath "kvm.ps1" From 4f0a9de33012bf53635a2f7965f2a837a5d0bcd3 Mon Sep 17 00:00:00 2001 From: anurse Date: Mon, 2 Feb 2015 14:26:28 -0800 Subject: [PATCH 13/27] one more try to get powershell to behave --- kvminstall.ps1 | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/kvminstall.ps1 b/kvminstall.ps1 index 5fb9eb7bd618..c29319d8bc06 100644 --- a/kvminstall.ps1 +++ b/kvminstall.ps1 @@ -1,5 +1,5 @@ -if(!$Branch) { $Branch = "release" } -if(!$Repository) { $Repository = "aspnet/Home" } +if(!$Branch) { Set-Variable Branch "release" } +if(!$Repository) { Set-Variable Repository "aspnet/Home" } $tempPath = Join-Path $env:TEMP "kvminstall" $kvmPs1Path = Join-Path $tempPath "kvm.ps1" From e22b86a28e721e4de6e46597ec41d125ba7d012c Mon Sep 17 00:00:00 2001 From: anurse Date: Mon, 2 Feb 2015 14:27:33 -0800 Subject: [PATCH 14/27] added message with source url --- kvminstall.ps1 | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/kvminstall.ps1 b/kvminstall.ps1 index c29319d8bc06..a86b951df4fb 100644 --- a/kvminstall.ps1 +++ b/kvminstall.ps1 @@ -8,11 +8,13 @@ $kvmCmdPath = Join-Path $tempPath "kvm.cmd" Write-Host "Using temporary directory: $tempPath" if (!(Test-Path $tempPath)) { md $tempPath | Out-Null } +$BaseUrl = "https://raw.githubusercontent.com/$Repository/$Branch" +Write-Host "Downloading from $BaseUrl" $webClient = New-Object System.Net.WebClient Write-Host "Downloading KVM.ps1 to $kvmPs1Path" -$webClient.DownloadFile("https://raw.githubusercontent.com/$Repository/$Branch/kvm.ps1", $kvmPs1Path) +$webClient.DownloadFile("$BaseUrl/kvm.ps1", $kvmPs1Path) Write-Host "Downloading KVM.cmd to $kvmCmdPath" -$webClient.DownloadFile("https://raw.githubusercontent.com/$Repository/$Branch/kvm.cmd", $kvmCmdPath) +$webClient.DownloadFile("$BaseUrl/kvm.cmd", $kvmCmdPath) Write-Host "Installing KVM" & $kvmCmdPath setup \ No newline at end of file From 582c86c6bb7b066d6544c6da15bdf22897114588 Mon Sep 17 00:00:00 2001 From: anurse Date: Mon, 2 Feb 2015 14:32:04 -0800 Subject: [PATCH 15/27] update command for installing dev kvm --- README.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index c442742d3a91..04dd21097c4b 100644 --- a/README.md +++ b/README.md @@ -47,10 +47,10 @@ To install KVM on Windows run the following command, which will download and run ``` -If you want to run on the bleeding edge and install the latest development version of KVM, download the `kvminstall.ps1` file locally and invoke it in powershell with the following arguments: +If you want to run on the bleeding edge and install the latest development version of KVM, run the following command: -```powershell -& C:\Path\To\kvminstall.ps1 dev +``` +@powershell -NoProfile -ExecutionPolicy unrestricted -Command "&{$Branch='dev';iex ((new-object net.webclient).DownloadString('https://raw.githubusercontent.com/aspnet/Home/release/kvminstall.ps1'))}" ``` After the script has run open a new command prompt to start using KVM. From ceac364c24ab6cdaa8ab63db7d202bb7eea5d1a0 Mon Sep 17 00:00:00 2001 From: anurse Date: Mon, 2 Feb 2015 14:34:44 -0800 Subject: [PATCH 16/27] update kvm.sh install directory --- README.md | 4 ++-- kvminstall.sh | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 04dd21097c4b..9e031cb5ce2e 100644 --- a/README.md +++ b/README.md @@ -69,13 +69,13 @@ To install KVM and the correct version of Mono on OS X using [Homebrew](http://b Installing KVM need `curl`. Do verify if that is installed on the machine. Next install KVM on Linux run the following command: ``` -curl -sSL https://raw.githubusercontent.com/aspnet/Home/release/kvminstall.sh | sh && source ~/.kre/kvm/kvm.sh +curl -sSL https://raw.githubusercontent.com/aspnet/Home/release/kvminstall.sh | sh && source ~/.k/kvm/kvm.sh ``` If you want to run on the bleeding edge and install the latest development version of KVM, use this command: ``` -curl -sSL https://raw.githubusercontent.com/aspnet/Home/release/kvminstall.sh | KVM_BRANCH=dev sh && source ~/.kre/kvm/kvm.sh +curl -sSL https://raw.githubusercontent.com/aspnet/Home/release/kvminstall.sh | KVM_BRANCH=dev sh && source ~/.k/kvm/kvm.sh ``` Note that on Linux you need to also install [Mono](http://mono-project.com) 3.4.1 or later. diff --git a/kvminstall.sh b/kvminstall.sh index 4d1dd19b80a7..0f67fb34fcb3 100644 --- a/kvminstall.sh +++ b/kvminstall.sh @@ -21,7 +21,7 @@ _kvmsetup_update_profile() { } if [ -z "$KRE_USER_HOME" ]; then - eval KRE_USER_HOME=~/.kre + eval KRE_USER_HOME=~/.k fi if ! _kvmsetup_has "curl"; then From 9231689b11304e426d4d164fc49ba1c71da750ec Mon Sep 17 00:00:00 2001 From: Andrew Nurse Date: Mon, 2 Feb 2015 14:38:19 -0800 Subject: [PATCH 17/27] spew download url from kvminstall.sh --- kvminstall.sh | 2 ++ 1 file changed, 2 insertions(+) diff --git a/kvminstall.sh b/kvminstall.sh index 0f67fb34fcb3..ccce0c0f1a78 100644 --- a/kvminstall.sh +++ b/kvminstall.sh @@ -41,6 +41,8 @@ else echo "Downloading kvm as script to '$KRE_USER_HOME/kvm'" fi +echo "Downloading kvm from '$KVM_SOURCE'" + curl -s "$KVM_SOURCE" -o "$KRE_USER_HOME/kvm/kvm.sh" || { echo >&2 "Failed to download '$KVM_SOURCE'.." return 1 From 3c85138b1033da2092cf87346dd99f50ecc9c551 Mon Sep 17 00:00:00 2001 From: Andrew Nurse Date: Mon, 2 Feb 2015 14:41:42 -0800 Subject: [PATCH 18/27] :lipstick: fix typo --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 9e031cb5ce2e..5a6cb5416763 100644 --- a/README.md +++ b/README.md @@ -66,7 +66,7 @@ To install KVM and the correct version of Mono on OS X using [Homebrew](http://b #### Linux: -Installing KVM need `curl`. Do verify if that is installed on the machine. Next install KVM on Linux run the following command: +Installing KVM requires `curl`. Do verify if that is installed on the machine. Next install KVM on Linux run the following command: ``` curl -sSL https://raw.githubusercontent.com/aspnet/Home/release/kvminstall.sh | sh && source ~/.k/kvm/kvm.sh From 54ffcdc6a94e59695324510299d5e535202b0200 Mon Sep 17 00:00:00 2001 From: "ASP.NET Push Bot" Date: Wed, 25 Mar 2015 19:01:35 -0700 Subject: [PATCH 19/27] :arrow_up: dnvm.ps1, dnvm.cmd, dnvm.sh Source: AspNet/kvm@2754edb95b051a70228f02bf3a860a6e274d373a --- dnvm.cmd | 10 + dnvm.ps1 | 1319 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ dnvm.sh | 440 ++++++++++++++++++ 3 files changed, 1769 insertions(+) create mode 100644 dnvm.cmd create mode 100644 dnvm.ps1 create mode 100644 dnvm.sh diff --git a/dnvm.cmd b/dnvm.cmd new file mode 100644 index 000000000000..6e936d7ba804 --- /dev/null +++ b/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/dnvm.ps1 b/dnvm.ps1 new file mode 100644 index 000000000000..95c3aaa6bb0a --- /dev/null +++ b/dnvm.ps1 @@ -0,0 +1,1319 @@ +#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-10348" +$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 "RuntimeShortFriendlyName" "DNX" + +Set-Variable -Option Constant "AsciiArt" @" + ___ _ ___ ____ ___ + / _ \/ |/ / | / / |/ / + / // / /| |/ / /|_/ / +/____/_/|_/ |___/_/ /_/ +"@ + +$ExitCodes = @{ + "Success" = 0 + "AliasDoesNotExist" = 1001 + "UnknownCommand" = 1002 + "InvalidArguments" = 1003 + "OtherError" = 1004 + "NoSuchPackage" = 1005 + "NoRuntimesOnFeed" = 1006 +} + +$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) + + # If the first character is non-numeric, it's a full runtime name + if(![Char]::IsDigit($Version[0])) { + $runtimeFullName = $Version + } else { + $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 ..." + try { + [xml]$xml = $wc.DownloadString($url) + } catch { + $Script:ExitCode = $ExitCodes.NoRuntimesOnFeed + throw "Unable to find any runtime packages on the feed!" + } + + $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 + try { + Apply-Proxy $wc -Proxy:$Proxy + _WriteDebug "Downloading $url ..." + + Register-ObjectEvent $wc DownloadProgressChanged -SourceIdentifier WebClient.ProgressChanged -action { + $Global:downloadData = $eventArgs + } | Out-Null + + Register-ObjectEvent $wc DownloadFileCompleted -SourceIdentifier WebClient.ProgressComplete -action { + $Global:downloadData = $eventArgs + $Global:downloadCompleted = $true + } | Out-Null + + $wc.DownloadFileAsync($url, $DestinationFile) + + while(-not $Global:downloadCompleted){ + $percent = $Global:downloadData.ProgressPercentage + $totalBytes = $Global:downloadData.TotalBytesToReceive + $receivedBytes = $Global:downloadData.BytesReceived + If ($percent -ne $null) { + Write-Progress -Activity ("Downloading $RuntimeShortFriendlyName from $url") ` + -Status ("Downloaded $($Global:downloadData.BytesReceived) of $($Global:downloadData.TotalBytesToReceive) bytes") ` + -PercentComplete $percent -Id 2 -ParentId 1 + } + } + + if($Global:downloadData.Error){ + throw "Unable to download package: {0}" -f $Global:downloadData.Error.Message + } + + Write-Progress -Activity ("Downloading $RuntimeShortFriendlyName from $url") -Id 2 -ParentId 1 -Completed + } + finally { + Remove-Variable downloadData -Scope "Global" + Remove-Variable downloadCompleted -Scope "Global" + Unregister-Event -SourceIdentifier WebClient.ProgressChanged + Unregister-Event -SourceIdentifier WebClient.ProgressComplete + $wc.Dispose() + } +} + +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 $DownloadFile $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(';')) { + if(![string]::IsNullOrWhiteSpace($portion)) { + $skip = $portion -eq "" + foreach($removePath in $removePaths) { + if(![string]::IsNullOrWhiteSpace($removePath)) { + $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 -WindowStyle Hidden +} + +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 -Persistent:$true +} + +<# +.SYNOPSIS + Installs a version of the runtime +.PARAMETER VersionNuPkgOrAlias + The version to install from the current channel, the path to a '.nupkg' file to install, 'latest' to + install the latest available version from the current channel, or an alias value to install an alternate + runtime or architecture flavor of the specified alias. +.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. +.PARAMETER Persistent + Make the installed runtime useable across all processes run by the current user +.DESCRIPTION + A proxy can also be specified by using the 'http_proxy' environment variable + +#> +function dnvm-install { + param( + [Parameter(Mandatory=$false, Position=0)] + [string]$VersionNuPkgOrAlias, + + [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, + + [Parameter(Mandatory=$false)] + [switch]$Persistent) + + if(!$VersionNuPkgOrAlias) { + _WriteOut "A version, nupkg path, or the string 'latest' must be provided." + dnvm-help install + $Script:ExitCode = $ExitCodes.InvalidArguments + return + } + + if ($VersionNuPkgOrAlias -eq "latest") { + Write-Progress -Activity "Installing runtime" "Determining latest runtime" -Id 1 + $VersionNuPkgOrAlias = Find-Latest $Runtime $Architecture + } + + $IsNuPkg = $VersionNuPkgOrAlias.EndsWith(".nupkg") + + if ($IsNuPkg) { + if(!(Test-Path $VersionNuPkgOrAlias)) { + throw "Unable to locate package file: '$VersionNuPkgOrAlias'" + } + Write-Progress -Activity "Installing runtime" "Parsing package file name" -Id 1 + $runtimeFullName = [System.IO.Path]::GetFileNameWithoutExtension($VersionNuPkgOrAlias) + $Architecture = Get-PackageArch $runtimeFullName + $Runtime = Get-PackageRuntime $runtimeFullName + } else { + $runtimeFullName = Get-RuntimeName $VersionNuPkgOrAlias -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) { + Write-Progress -Activity "Installing runtime" "Copying package" -Id 1 + _WriteDebug "Copying local nupkg $VersionNuPkgOrAlias to $DownloadFile" + Copy-Item $VersionNuPkgOrAlias $DownloadFile + } else { + # Download the package + Write-Progress -Activity "Installing runtime" "Downloading runtime" -Id 1 + _WriteDebug "Downloading version $VersionNuPkgOrAlias to $DownloadFile" + Download-Package $PackageVersion $Architecture $Runtime $DownloadFile -Proxy:$Proxy + } + + Write-Progress -Activity "Installing runtime" "Unpacking runtime" -Id 1 + 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 -Persistent:$Persistent + + if ($Runtime -eq "clr") { + if (-not $NoNative) { + if ((Is-Elevated) -or $Ngen) { + $runtimeBin = Get-RuntimePath $runtimeFullName + Write-Progress -Activity "Installing runtime" "Generating runtime native images" -Id 1 + 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..." + Write-Progress -Activity "Installing runtime" "Generating runtime native images" -Id 1 + if ($DebugPreference -eq 'SilentlyContinue') { + Start-Process $CrossGenCommand -Wait -WindowStyle Hidden + } + else { + Start-Process $CrossGenCommand -Wait -NoNewWindow + } + _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 + } + + Write-Progress -Activity "Install complete" -Id 1 -Complete +} + + +<# +.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) { + _WriteOut "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) { + _WriteOut "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." + } +} + +# Check for old KRE_HOME variable +if(Test-Path env:\KRE_HOME) { + _WriteOut -ForegroundColor Yellow "WARNING: Found a KRE_HOME environment variable. This variable has been deprecated and should be removed, or it may interfere with DNVM and the .NET Execution environment" +} + +# 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 and run it +try { + 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 + } +} catch { + Write-Error $_ + if(!$Script:ExitCode) { $Script:ExitCode = $ExitCodes.OtherError } +} + +_WriteDebug "=== End $CommandName (Exit Code $Script:ExitCode) ===" +_WriteDebug "" +exit $Script:ExitCode diff --git a/dnvm.sh b/dnvm.sh new file mode 100644 index 000000000000..b86329a0c642 --- /dev/null +++ b/dnvm.sh @@ -0,0 +1,440 @@ +# dnvm.sh +# Source this file from your .bash-profile or script to use + +# "Constants" +_DNVM_BUILDNUMBER="beta4-10348" +_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 From 9e1bcf822e65e9bb5767c64a84358254a694e8fa Mon Sep 17 00:00:00 2001 From: "ASP.NET Push Bot" Date: Fri, 27 Mar 2015 17:19:26 -0700 Subject: [PATCH 20/27] :arrow_up: dnvm.ps1, dnvm.cmd, dnvm.sh Source: AspNet/kvm@82929ba8a18be66c3f710c5c99c6249211b10877 --- dnvm.ps1 | 58 +++++++++++++++++++++++++++++++++++++------------------- dnvm.sh | 2 +- 2 files changed, 39 insertions(+), 21 deletions(-) diff --git a/dnvm.ps1 b/dnvm.ps1 index 95c3aaa6bb0a..d0cb895121ce 100644 --- a/dnvm.ps1 +++ b/dnvm.ps1 @@ -59,7 +59,7 @@ function _WriteOut { ### Constants $ProductVersion="1.0.0" -$BuildVersion="beta4-10348" +$BuildVersion="beta4-10351" $Authors="Microsoft Open Technologies, Inc." # If the Version hasn't been replaced... @@ -1178,6 +1178,40 @@ function dnvm-name { Get-RuntimeName $VersionOrAlias $Architecture $Runtime } + +# Checks if a specified file exists in the destination folder and if not, copies the file +# to the destination folder. +function Safe-Filecopy { + param( + [Parameter(Mandatory=$true, Position=0)] $Filename, + [Parameter(Mandatory=$true, Position=1)] $SourceFolder, + [Parameter(Mandatory=$true, Position=2)] $DestinationFolder) + + # Make sure the destination folder is created if it doesn't already exist. + if(!(Test-Path $DestinationFolder)) { + _WriteOut "Creating destination folder '$DestinationFolder' ... " + + New-Item -Type Directory $Destination | Out-Null + } + + $sourceFilePath = Join-Path $SourceFolder $Filename + $destFilePath = Join-Path $DestinationFolder $Filename + + if(Test-Path $sourceFilePath) { + _WriteOut "Installing '$Filename' to '$DestinationFolder' ... " + + if (Test-Path $destFilePath) { + _WriteOut " Skipping: file already exists" -ForegroundColor Yellow + } + else { + Copy-Item $sourceFilePath $destFilePath -Force + } + } + else { + _WriteOut "WARNING: Unable to install: Could not find '$Filename' in '$SourceFolder'. " + } +} + <# .SYNOPSIS Installs the version manager into your User profile directory @@ -1196,28 +1230,12 @@ function dnvm-setup { $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!" - } + # Copy script files (if necessary): + Safe-Filecopy "$CommandName.ps1" $ScriptFolder $Destination + Safe-Filecopy "$CommandName.cmd" $ScriptFolder $Destination # Configure Environment Variables # Also, clean old user home values if present - # We'll be removing any existing homes, both $PathsToRemove = @( "%USERPROFILE%\$DefaultUserDirectoryName", diff --git a/dnvm.sh b/dnvm.sh index b86329a0c642..6a4022184c51 100644 --- a/dnvm.sh +++ b/dnvm.sh @@ -2,7 +2,7 @@ # Source this file from your .bash-profile or script to use # "Constants" -_DNVM_BUILDNUMBER="beta4-10348" +_DNVM_BUILDNUMBER="beta4-10351" _DNVM_AUTHORS="Microsoft Open Technologies, Inc." _DNVM_RUNTIME_PACKAGE_NAME="dnx" _DNVM_RUNTIME_FRIENDLY_NAME=".NET Execution Environment" From a6de21aa3b5bf45647b7c74a19eca2729695affb Mon Sep 17 00:00:00 2001 From: moozzyk Date: Mon, 30 Mar 2015 15:33:55 -0700 Subject: [PATCH 21/27] Updating instructions for Mac OS --- README.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 5a6cb5416763..ad17e0ab36e1 100644 --- a/README.md +++ b/README.md @@ -57,12 +57,12 @@ After the script has run open a new command prompt to start using KVM. #### OS X: -To install KVM and the correct version of Mono on OS X using [Homebrew](http://brew.sh) follow the following steps: +To install DNVM and the correct version of Mono on OS X using [Homebrew](http://brew.sh) follow the following steps: * Install [Homebrew](http://brew.sh) if it is not already installed. * Run command `brew tap aspnet/k` to tap the ASP.NET vNext related git repositories. If you had already tapped the repo for previous releases, run `brew untap aspnet/k` to delete the old commands and tap again to get the updated brew scripts. - * Run command `brew install kvm` to install KVM. This also automatically install the latest KRE package from https://www.nuget.org/api/v2 feed. - * Run command `source kvm.sh` on your terminal if your terminal cannot understand kvm. + * Run command `brew install dnvm` to install DNVM. This also automatically install the latest KRE package from https://www.nuget.org/api/v2 feed. + * Run command `source dnvm.sh` on your terminal if your terminal cannot understand dnvm. #### Linux: From e226b069bbc3e3fbd9bee409e024e6bfd980dee0 Mon Sep 17 00:00:00 2001 From: "ASP.NET Push Bot" Date: Tue, 31 Mar 2015 16:48:09 -0700 Subject: [PATCH 22/27] :arrow_up: dnvm.ps1, dnvm.cmd, dnvm.sh Source: AspNet/kvm@ccafba65bd8d29b9f1e1cb6933e0d24f289dff3e --- dnvm.ps1 | 4 ++-- dnvm.sh | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/dnvm.ps1 b/dnvm.ps1 index d0cb895121ce..185f5635bd63 100644 --- a/dnvm.ps1 +++ b/dnvm.ps1 @@ -59,7 +59,7 @@ function _WriteOut { ### Constants $ProductVersion="1.0.0" -$BuildVersion="beta4-10351" +$BuildVersion="beta4-10354" $Authors="Microsoft Open Technologies, Inc." # If the Version hasn't been replaced... @@ -76,7 +76,7 @@ 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 "DefaultFeed" "https://www.myget.org/F/aspnetrelease/api/v2" Set-Variable -Option Constant "CrossGenCommand" "k-crossgen" Set-Variable -Option Constant "CommandPrefix" "dnvm-" Set-Variable -Option Constant "DefaultArchitecture" "x86" diff --git a/dnvm.sh b/dnvm.sh index 6a4022184c51..eb2c1bed19fb 100644 --- a/dnvm.sh +++ b/dnvm.sh @@ -2,7 +2,7 @@ # Source this file from your .bash-profile or script to use # "Constants" -_DNVM_BUILDNUMBER="beta4-10351" +_DNVM_BUILDNUMBER="beta4-10354" _DNVM_AUTHORS="Microsoft Open Technologies, Inc." _DNVM_RUNTIME_PACKAGE_NAME="dnx" _DNVM_RUNTIME_FRIENDLY_NAME=".NET Execution Environment" @@ -10,7 +10,7 @@ _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_DEFAULT_FEED="https://www.myget.org/F/aspnetrelease/api/v2" _DNVM_HOME_VAR_NAME="DNX_HOME" [ "$_DNVM_BUILDNUMBER" = "{{*" ] && _DNVM_BUILDNUMBER="HEAD" From 23437fde245ddb8433aa6996c584210750a4234e Mon Sep 17 00:00:00 2001 From: "ASP.NET Push Bot" Date: Fri, 3 Apr 2015 10:38:58 -0700 Subject: [PATCH 23/27] :arrow_up: dnvm.ps1, dnvm.cmd, dnvm.sh Source: AspNet/kvm@9da2e43a241acea3a9d13c8942dd494bbd2bf57f --- dnvm.ps1 | 9 ++++++++- dnvm.sh | 2 +- 2 files changed, 9 insertions(+), 2 deletions(-) diff --git a/dnvm.ps1 b/dnvm.ps1 index 185f5635bd63..ad1ef4949b31 100644 --- a/dnvm.ps1 +++ b/dnvm.ps1 @@ -1,5 +1,12 @@ #Requires -Version 3 +if (Test-Path env:WEBSITE_SITE_NAME) +{ + # This script is run in Azure Web Sites + # Disable progress indicator + $ProgressPreference = "SilentlyContinue" +} + $ScriptPath = $MyInvocation.MyCommand.Definition $Script:UseWriteHost = $true @@ -59,7 +66,7 @@ function _WriteOut { ### Constants $ProductVersion="1.0.0" -$BuildVersion="beta4-10354" +$BuildVersion="beta4-10356" $Authors="Microsoft Open Technologies, Inc." # If the Version hasn't been replaced... diff --git a/dnvm.sh b/dnvm.sh index eb2c1bed19fb..8a1bdc96a978 100644 --- a/dnvm.sh +++ b/dnvm.sh @@ -2,7 +2,7 @@ # Source this file from your .bash-profile or script to use # "Constants" -_DNVM_BUILDNUMBER="beta4-10354" +_DNVM_BUILDNUMBER="beta4-10356" _DNVM_AUTHORS="Microsoft Open Technologies, Inc." _DNVM_RUNTIME_PACKAGE_NAME="dnx" _DNVM_RUNTIME_FRIENDLY_NAME=".NET Execution Environment" From b415a6b6c212681f2784411654509743ce7dc07b Mon Sep 17 00:00:00 2001 From: "ASP.NET Push Bot" Date: Thu, 16 Apr 2015 14:43:06 -0700 Subject: [PATCH 24/27] :arrow_up: dnvm.ps1, dnvm.cmd, dnvm.sh Source: AspNet/kvm@d4fa7c5479bca4e54d2972f2cb65b3945cd59585 --- dnvm.ps1 | 4 ++-- dnvm.sh | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/dnvm.ps1 b/dnvm.ps1 index ad1ef4949b31..9fba71c8d4aa 100644 --- a/dnvm.ps1 +++ b/dnvm.ps1 @@ -66,7 +66,7 @@ function _WriteOut { ### Constants $ProductVersion="1.0.0" -$BuildVersion="beta4-10356" +$BuildVersion="beta4-10366" $Authors="Microsoft Open Technologies, Inc." # If the Version hasn't been replaced... @@ -83,7 +83,7 @@ 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/aspnetrelease/api/v2" +Set-Variable -Option Constant "DefaultFeed" "https://www.nuget.org/api/v2" Set-Variable -Option Constant "CrossGenCommand" "k-crossgen" Set-Variable -Option Constant "CommandPrefix" "dnvm-" Set-Variable -Option Constant "DefaultArchitecture" "x86" diff --git a/dnvm.sh b/dnvm.sh index 8a1bdc96a978..c71e85277f32 100644 --- a/dnvm.sh +++ b/dnvm.sh @@ -2,7 +2,7 @@ # Source this file from your .bash-profile or script to use # "Constants" -_DNVM_BUILDNUMBER="beta4-10356" +_DNVM_BUILDNUMBER="beta4-10366" _DNVM_AUTHORS="Microsoft Open Technologies, Inc." _DNVM_RUNTIME_PACKAGE_NAME="dnx" _DNVM_RUNTIME_FRIENDLY_NAME=".NET Execution Environment" @@ -10,7 +10,7 @@ _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/aspnetrelease/api/v2" +_DNVM_DEFAULT_FEED="https://www.nuget.org/api/v2" _DNVM_HOME_VAR_NAME="DNX_HOME" [ "$_DNVM_BUILDNUMBER" = "{{*" ] && _DNVM_BUILDNUMBER="HEAD" From 5e57d3753c2e0726bad8521a812a7c1588160d6a Mon Sep 17 00:00:00 2001 From: "ASP.NET Push Bot" Date: Wed, 27 May 2015 16:55:10 -0700 Subject: [PATCH 25/27] :arrow_up: dnvm.ps1, dnvm.cmd, dnvm.sh Source: AspNet/kvm@8d184bf6356d36fd9e1fa9f556732a2a0a2a9ad3 --- dnvm.cmd | 6 +- dnvm.ps1 | 292 +++++++++++++++++++++++----------- dnvm.sh | 471 ++++++++++++++++++++++++++++++++++++++++++------------- 3 files changed, 567 insertions(+), 202 deletions(-) diff --git a/dnvm.cmd b/dnvm.cmd index 6e936d7ba804..d2a6f5f6a320 100644 --- a/dnvm.cmd +++ b/dnvm.cmd @@ -4,7 +4,7 @@ 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%" +IF EXIST %DNVM_CMD_PATH_FILE% ( + CALL %DNVM_CMD_PATH_FILE% + DEL %DNVM_CMD_PATH_FILE% ) diff --git a/dnvm.ps1 b/dnvm.ps1 index 9fba71c8d4aa..a879128666ae 100644 --- a/dnvm.ps1 +++ b/dnvm.ps1 @@ -28,6 +28,16 @@ function _WriteOut { [Parameter(Mandatory=$false)][ConsoleColor]$BackgroundColor, [Parameter(Mandatory=$false)][switch]$NoNewLine) + if($__TestWriteTo) { + $cur = Get-Variable -Name $__TestWriteTo -ValueOnly -Scope Global -ErrorAction SilentlyContinue + $val = $cur + "$msg" + if(!$NoNewLine) { + $val += [Environment]::NewLine + } + Set-Variable -Name $__TestWriteTo -Value $val -Scope Global -Force + return + } + if(!$Script:UseWriteHost) { if(!$msg) { $msg = "" @@ -53,20 +63,11 @@ function _WriteOut { _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-10366" +$BuildVersion="beta5-10379" $Authors="Microsoft Open Technologies, Inc." # If the Version hasn't been replaced... @@ -84,7 +85,8 @@ 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.nuget.org/api/v2" -Set-Variable -Option Constant "CrossGenCommand" "k-crossgen" +Set-Variable -Option Constant "DefaultUnstableFeed" "https://www.myget.org/F/aspnetrelease/api/v2" +Set-Variable -Option Constant "CrossGenCommand" "dnx-crossgen" Set-Variable -Option Constant "CommandPrefix" "dnvm-" Set-Variable -Option Constant "DefaultArchitecture" "x86" Set-Variable -Option Constant "DefaultRuntime" "clr" @@ -97,6 +99,8 @@ Set-Variable -Option Constant "HomeEnvVar" "DNX_HOME" Set-Variable -Option Constant "RuntimeShortFriendlyName" "DNX" +Set-Variable -Option Constant "DNVMUpgradeUrl" "https://raw.githubusercontent.com/aspnet/Home/dev/dnvm.ps1" + Set-Variable -Option Constant "AsciiArt" @" ___ _ ___ ____ ___ / _ \/ |/ / | / / |/ / @@ -125,10 +129,13 @@ if(!$ColorScheme) { "Help_Optional"=[ConsoleColor]::Gray "Help_Command"=[ConsoleColor]::DarkYellow "Help_Executable"=[ConsoleColor]::DarkYellow + "Feed_Name"=[ConsoleColor]::Cyan + "Warning" = [ConsoleColor]::Yellow } } Set-Variable -Option Constant "OptionPadding" 20 +Set-Variable -Option Constant "CommandPadding" 15 # Test Control Variables if($__TeeTo) { @@ -143,6 +150,7 @@ $DeprecatedCommands = @("unalias") $RuntimeHomes = $env:DNX_HOME $UserHome = $env:DNX_USER_HOME $ActiveFeed = $env:DNX_FEED +$ActiveUnstableFeed = $env:DNX_UNSTABLE_FEED # Default Exit Code $Script:ExitCode = $ExitCodes.Success @@ -165,10 +173,6 @@ if($CmdPathFile) { _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 @@ -186,7 +190,7 @@ if(!$UserHome) { _WriteDebug "Detecting User Home..." $pf = $env:ProgramFiles if(Test-Path "env:\ProgramFiles(x86)") { - $pf32 = cat "env:\ProgramFiles(x86)" + $pf32 = Get-Content "env:\ProgramFiles(x86)" } # Canonicalize so we can do StartsWith tests @@ -214,6 +218,39 @@ $RuntimesDir = Join-Path $UserHome "runtimes" $Aliases = $null ### Helper Functions +# Checks if a specified file exists in the destination folder and if not, copies the file +# to the destination folder. +function Safe-Filecopy { + param( + [Parameter(Mandatory=$true, Position=0)] $Filename, + [Parameter(Mandatory=$true, Position=1)] $SourceFolder, + [Parameter(Mandatory=$true, Position=2)] $DestinationFolder) + + # Make sure the destination folder is created if it doesn't already exist. + if(!(Test-Path $DestinationFolder)) { + _WriteOut "Creating destination folder '$DestinationFolder' ... " + + New-Item -Type Directory $Destination | Out-Null + } + + $sourceFilePath = Join-Path $SourceFolder $Filename + $destFilePath = Join-Path $DestinationFolder $Filename + + if(Test-Path $sourceFilePath) { + _WriteOut "Installing '$Filename' to '$DestinationFolder' ... " + + if (Test-Path $destFilePath) { + _WriteOut " Skipping: file already exists" -ForegroundColor Yellow + } + else { + Copy-Item $sourceFilePath $destFilePath -Force + } + } + else { + _WriteOut "WARNING: Unable to install: Could not find '$Filename' in '$SourceFolder'. " + } +} + function GetArch($Architecture, $FallBackArch = $DefaultArchitecture) { if(![String]::IsNullOrWhiteSpace($Architecture)) { $Architecture @@ -238,13 +275,34 @@ function Write-Usage { 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 Write-Feeds { + _WriteOut + _WriteOut -ForegroundColor $ColorScheme.Help_Header "Current feed settings:" + _WriteOut -NoNewline -ForegroundColor $ColorScheme.Feed_Name "Default Stable: " + _WriteOut "$DefaultFeed" + _WriteOut -NoNewline -ForegroundColor $ColorScheme.Feed_Name "Default Unstable: " + _WriteOut "$DefaultUnstableFeed" + _WriteOut -NoNewline -ForegroundColor $ColorScheme.Feed_Name "Current Stable Override: " + if($ActiveFeed) { + _WriteOut "$ActiveFeed" + } else { + _WriteOut "" + } + _WriteOut -NoNewline -ForegroundColor $ColorScheme.Feed_Name "Current Unstable Override: " + if($ActiveUnstableFeed) { + _WriteOut "$ActiveUnstableFeed" + } else { + _WriteOut "" + } + +} + function Get-RuntimeAlias { if($Aliases -eq $null) { _WriteDebug "Scanning for aliases in $AliasesDir" @@ -403,16 +461,15 @@ function Find-Latest { param( [string]$runtime = "", [string]$architecture = "", + [Parameter(Mandatory=$true)] [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 @@ -427,9 +484,11 @@ function Find-Latest { $version = Select-Xml "//d:Version" -Namespace @{d='http://schemas.microsoft.com/ado/2007/08/dataservices'} $xml - if (![String]::IsNullOrWhiteSpace($version)) { + if($version) { _WriteDebug "Found latest version: $version" $version + } else { + throw "There are no runtimes matching the name $RuntimeId on feed $feed." } } @@ -459,11 +518,10 @@ function Download-Package( [string]$Architecture, [string]$Runtime, [string]$DestinationFile, + [Parameter(Mandatory=$true)] [string]$Feed, [string]$Proxy) { - if(!$Feed) { $Feed = $ActiveFeed } - $url = "$Feed/package/" + (Get-RuntimeId $Architecture $Runtime) + "/" + $Version _WriteOut "Downloading $runtimeFullName from $feed" @@ -494,8 +552,12 @@ function Download-Package( } } - if($Global:downloadData.Error){ - throw "Unable to download package: {0}" -f $Global:downloadData.Error.Message + if($Global:downloadData.Error) { + if($Global:downloadData.Error.Response.StatusCode -eq [System.Net.HttpStatusCode]::NotFound){ + throw "The server returned a 404 (NotFound). This is most likely caused by the feed not having the version that you typed. Check that you typed the right version and try again. Other possible causes are the feed doesn't have a $RuntimeShortFriendlyName of the right name format or some other error caused a 404 on the server." + } else { + throw "Unable to download package: {0}" -f $Global:downloadData.Error.Message + } } Write-Progress -Activity ("Downloading $RuntimeShortFriendlyName from $url") -Id 2 -ParentId 1 -Completed @@ -651,6 +713,24 @@ function Is-Elevated() { ### Commands +<# +.SYNOPSIS + Updates DNVM to the latest version. +.PARAMETER Proxy + Use the given address as a proxy when accessing remote server +#> +function dnvm-update-self { + param( + [Parameter(Mandatory=$false)] + [string]$Proxy) + + _WriteOut "Updating $CommandName from $DNVMUpgradeUrl" + $wc = New-Object System.Net.WebClient + Apply-Proxy $wc -Proxy:$Proxy + $dnvmFile = Join-Path $PSScriptRoot "dnvm.ps1" + $wc.DownloadFile($DNVMUpgradeUrl, $dnvmFile) +} + <# .SYNOPSIS Displays a list of commands, and help for specific commands @@ -675,7 +755,7 @@ function dnvm-help { if($PassThru) { $help } else { - _WriteOut -ForegroundColor $ColorScheme.Help_Header "$CommandName-$Command" + _WriteOut -ForegroundColor $ColorScheme.Help_Header "$CommandName $Command" _WriteOut " $($help.Synopsis.Trim())" _WriteOut _WriteOut -ForegroundColor $ColorScheme.Help_Header "usage:" @@ -748,6 +828,7 @@ function dnvm-help { } } else { Write-Usage + Write-Feeds _WriteOut _WriteOut -ForegroundColor $ColorScheme.Help_Header "commands: " Get-Command "$CommandPrefix*" | @@ -756,7 +837,7 @@ function dnvm-help { $name = $_.Name.Substring($CommandPrefix.Length) if($DeprecatedCommands -notcontains $name) { _WriteOut -NoNewLine " " - _WriteOut -NoNewLine -ForegroundColor $ColorScheme.Help_Command $name.PadRight(10) + _WriteOut -NoNewLine -ForegroundColor $ColorScheme.Help_Command $name.PadRight($CommandPadding) _WriteOut " $($h.Synopsis.Trim())" } } @@ -873,6 +954,8 @@ function dnvm-unalias { 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. +.PARAMETER Unstable + Upgrade from our unstable dev feed. This will give you the latest development version of the runtime. #> function dnvm-upgrade { param( @@ -901,9 +984,12 @@ function dnvm-upgrade { [switch]$NoNative, [Parameter(Mandatory=$false)] - [switch]$Ngen) + [switch]$Ngen, + + [Parameter(Mandatory=$false)] + [switch]$Unstable) - dnvm-install "latest" -Alias:$Alias -Architecture:$Architecture -Runtime:$Runtime -Force:$Force -Proxy:$Proxy -NoNative:$NoNative -Ngen:$Ngen -Persistent:$true + dnvm-install "latest" -Alias:$Alias -Architecture:$Architecture -Runtime:$Runtime -Force:$Force -Proxy:$Proxy -NoNative:$NoNative -Ngen:$Ngen -Unstable:$Unstable -Persistent:$true } <# @@ -929,9 +1015,10 @@ function dnvm-upgrade { 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. .PARAMETER Persistent Make the installed runtime useable across all processes run by the current user +.PARAMETER Unstable + Upgrade from our unstable dev feed. This will give you the latest development version of the runtime. .DESCRIPTION A proxy can also be specified by using the 'http_proxy' environment variable - #> function dnvm-install { param( @@ -966,7 +1053,28 @@ function dnvm-install { [switch]$Ngen, [Parameter(Mandatory=$false)] - [switch]$Persistent) + [switch]$Persistent, + + [Parameter(Mandatory=$false)] + [switch]$Unstable) + + $selectedFeed = "" + + if($Unstable) { + $selectedFeed = $ActiveUnstableFeed + if(!$selectedFeed) { + $selectedFeed = $DefaultUnstableFeed + } else { + _WriteOut -ForegroundColor $ColorScheme.Warning "Default unstable feed ($DefaultUnstableFeed) is being overridden by the value of the DNX_UNSTABLE_FEED environment variable ($ActiveUnstableFeed)" + } + } else { + $selectedFeed = $ActiveFeed + if(!$selectedFeed) { + $selectedFeed = $DefaultFeed + } else { + _WriteOut -ForegroundColor $ColorScheme.Warning "Default stable feed ($DefaultFeed) is being overridden by the value of the DNX_FEED environment variable ($ActiveFeed)" + } + } if(!$VersionNuPkgOrAlias) { _WriteOut "A version, nupkg path, or the string 'latest' must be provided." @@ -977,7 +1085,7 @@ function dnvm-install { if ($VersionNuPkgOrAlias -eq "latest") { Write-Progress -Activity "Installing runtime" "Determining latest runtime" -Id 1 - $VersionNuPkgOrAlias = Find-Latest $Runtime $Architecture + $VersionNuPkgOrAlias = Find-Latest $Runtime $Architecture -Feed:$selectedFeed } $IsNuPkg = $VersionNuPkgOrAlias.EndsWith(".nupkg") @@ -1011,6 +1119,7 @@ function dnvm-install { if(Test-Path $RuntimeFolder) { _WriteOut "'$runtimeFullName' is already installed." + dnvm-use $PackageVersion -Architecture:$Architecture -Runtime:$Runtime -Persistent:$Persistent } else { $Architecture = GetArch $Architecture @@ -1032,18 +1141,22 @@ function dnvm-install { # Download the package Write-Progress -Activity "Installing runtime" "Downloading runtime" -Id 1 _WriteDebug "Downloading version $VersionNuPkgOrAlias to $DownloadFile" - Download-Package $PackageVersion $Architecture $Runtime $DownloadFile -Proxy:$Proxy + + Download-Package $PackageVersion $Architecture $Runtime $DownloadFile -Proxy:$Proxy -Feed:$selectedFeed } Write-Progress -Activity "Installing runtime" "Unpacking runtime" -Id 1 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 + if(Test-Path $RuntimeFolder) { + # Ensure the runtime hasn't been installed in the time it took to download the package. + _WriteOut "'$runtimeFullName' is already installed." + } + else { + _WriteOut "Installing to $RuntimeFolder" + _WriteDebug "Moving package contents to $RuntimeFolder" + Move-Item $UnpackFolder $RuntimeFolder + } dnvm-use $PackageVersion -Architecture:$Architecture -Runtime:$Runtime -Persistent:$Persistent @@ -1103,7 +1216,7 @@ function dnvm-install { #> function dnvm-use { param( - [Parameter(Mandatory=$false, Position=0)] + [Parameter(Mandatory=$true, Position=0)] [string]$VersionOrAlias, [Alias("arch")] @@ -1120,13 +1233,6 @@ function dnvm-use { [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)) @@ -1159,63 +1265,61 @@ function dnvm-use { <# .SYNOPSIS - Gets the full name of a runtime + Locates the dnx.exe for the specified version or alias and executes it, providing the remaining arguments to dnx.exe .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) + The version of alias of the runtime to execute +.PARAMETER DnxArguments + The arguments to pass to dnx.exe #> -function dnvm-name { +function dnvm-run { param( - [Parameter(Mandatory=$false, Position=0)] + [Parameter(Mandatory=$true, Position=0)] [string]$VersionOrAlias, + [Parameter(Mandatory=$false, Position=1, ValueFromRemainingArguments=$true)] + [object[]]$DnxArguments) - [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 + $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'?" + } + $dnxExe = Join-Path $runtimeBin "dnx.exe" + if(!(Test-Path $dnxExe)) { + throw "Cannot find a dnx.exe in $runtimeBin, the installation may be corrupt. Try running 'dnvm install $VersionOrAlias -f' to reinstall it" + } + _WriteDebug "> $dnxExe $DnxArguments" + & $dnxExe @DnxArguments } - -# Checks if a specified file exists in the destination folder and if not, copies the file -# to the destination folder. -function Safe-Filecopy { +<# +.SYNOPSIS + Executes the specified command in a sub-shell where the PATH has been augmented to include the specified DNX +.PARAMETER VersionOrAlias + The version of alias of the runtime to make active in the sub-shell +.PARAMETER Command + The command to execute in the sub-shell +#> +function dnvm-exec { param( - [Parameter(Mandatory=$true, Position=0)] $Filename, - [Parameter(Mandatory=$true, Position=1)] $SourceFolder, - [Parameter(Mandatory=$true, Position=2)] $DestinationFolder) + [Parameter(Mandatory=$true, Position=0)] + [string]$VersionOrAlias, + [Parameter(Mandatory=$false, Position=1)] + [string]$Command, + [Parameter(Mandatory=$false, Position=2, ValueFromRemainingArguments=$true)] + [object[]]$Arguments) - # Make sure the destination folder is created if it doesn't already exist. - if(!(Test-Path $DestinationFolder)) { - _WriteOut "Creating destination folder '$DestinationFolder' ... " - - New-Item -Type Directory $Destination | Out-Null + $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'?" } - $sourceFilePath = Join-Path $SourceFolder $Filename - $destFilePath = Join-Path $DestinationFolder $Filename - - if(Test-Path $sourceFilePath) { - _WriteOut "Installing '$Filename' to '$DestinationFolder' ... " - - if (Test-Path $destFilePath) { - _WriteOut " Skipping: file already exists" -ForegroundColor Yellow - } - else { - Copy-Item $sourceFilePath $destFilePath -Force - } - } - else { - _WriteOut "WARNING: Unable to install: Could not find '$Filename' in '$SourceFolder'. " + $oldPath = $env:PATH + try { + $env:PATH = "$runtimeBin;$($env:PATH)" + & $Command @Arguments + } finally { + $env:PATH = $oldPath } } @@ -1265,7 +1369,7 @@ function dnvm-setup { _WriteOut "Adding $DestinationHome to Process $HomeEnvVar" $processHome = "" if(Test-Path "env:\$HomeEnvVar") { - $processHome = cat "env:\$HomeEnvVar" + $processHome = Get-Content "env:\$HomeEnvVar" } $processHome = Change-Path $processHome "%USERPROFILE%\$DefaultUserDirectoryName" $PathsToRemove Set-Content "env:\$HomeEnvVar" $processHome @@ -1335,7 +1439,7 @@ try { $Script:ExitCode = $ExitCodes.UnknownCommand } } catch { - Write-Error $_ + throw if(!$Script:ExitCode) { $Script:ExitCode = $ExitCodes.OtherError } } diff --git a/dnvm.sh b/dnvm.sh index c71e85277f32..3df30694f63b 100644 --- a/dnvm.sh +++ b/dnvm.sh @@ -2,18 +2,37 @@ # Source this file from your .bash-profile or script to use # "Constants" -_DNVM_BUILDNUMBER="beta4-10366" +_DNVM_BUILDNUMBER="beta5-10379" _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_PACKAGE_MANAGER_NAME="dnu" _DNVM_VERSION_MANAGER_NAME=".NET Version Manager" _DNVM_DEFAULT_FEED="https://www.nuget.org/api/v2" +_DNVM_DEFAULT_UNSTABLE_FEED="https://www.myget.org/F/aspnetrelease/api/v2" +_DNVM_UPDATE_LOCATION="https://raw.githubusercontent.com/aspnet/Home/dev/dnvm.sh" _DNVM_HOME_VAR_NAME="DNX_HOME" -[ "$_DNVM_BUILDNUMBER" = "{{*" ] && _DNVM_BUILDNUMBER="HEAD" +if [ "$NO_COLOR" != "1" ]; then + # ANSI Colors + RCol='\e[0m' # Text Reset + + # Regular Bold Underline High Intensity BoldHigh Intens Background High Intensity Backgrounds + Bla='\e[0;30m'; BBla='\e[1;30m'; UBla='\e[4;30m'; IBla='\e[0;90m'; BIBla='\e[1;90m'; On_Bla='\e[40m'; On_IBla='\e[0;100m'; + Red='\e[0;31m'; BRed='\e[1;31m'; URed='\e[4;31m'; IRed='\e[0;91m'; BIRed='\e[1;91m'; On_Red='\e[41m'; On_IRed='\e[0;101m'; + Gre='\e[0;32m'; BGre='\e[1;32m'; UGre='\e[4;32m'; IGre='\e[0;92m'; BIGre='\e[1;92m'; On_Gre='\e[42m'; On_IGre='\e[0;102m'; + Yel='\e[0;33m'; BYel='\e[1;33m'; UYel='\e[4;33m'; IYel='\e[0;93m'; BIYel='\e[1;93m'; On_Yel='\e[43m'; On_IYel='\e[0;103m'; + Blu='\e[0;34m'; BBlu='\e[1;34m'; UBlu='\e[4;34m'; IBlu='\e[0;94m'; BIBlu='\e[1;94m'; On_Blu='\e[44m'; On_IBlu='\e[0;104m'; + Pur='\e[0;35m'; BPur='\e[1;35m'; UPur='\e[4;35m'; IPur='\e[0;95m'; BIPur='\e[1;95m'; On_Pur='\e[45m'; On_IPur='\e[0;105m'; + Cya='\e[0;36m'; BCya='\e[1;36m'; UCya='\e[4;36m'; ICya='\e[0;96m'; BICya='\e[1;96m'; On_Cya='\e[46m'; On_ICya='\e[0;106m'; + Whi='\e[0;37m'; BWhi='\e[1;37m'; UWhi='\e[4;37m'; IWhi='\e[0;97m'; BIWhi='\e[1;97m'; On_Whi='\e[47m'; On_IWhi='\e[0;107m'; +fi + + +[[ "$_DNVM_BUILDNUMBER" = {{* ]] && _DNVM_BUILDNUMBER="HEAD" __dnvm_has() { type "$1" > /dev/null 2>&1 @@ -30,20 +49,41 @@ fi _DNVM_USER_PACKAGES="$DNX_USER_HOME/runtimes" _DNVM_ALIAS_DIR="$DNX_USER_HOME/alias" +_DNVM_DNVM_DIR="$DNX_USER_HOME/dnvm" -if [ -z "$DNX_FEED" ]; then - DNX_FEED="$_DNVM_DEFAULT_FEED" -fi +DNX_ACTIVE_FEED="" + +__dnvm_current_os() +{ + local uname=$(uname) + if [[ $uname == "Darwin" ]]; then + echo "darwin" + else + echo "linux" + fi +} __dnvm_find_latest() { - local platform="mono" + local platform=$1 + local arch=$2 + + if [ -z $platform ]; then + local platform="mono" + fi if ! __dnvm_has "curl"; then - echo "$_DNVM_COMMAND_NAME needs curl to proceed." >&2; + printf "%b\n" "${Red}$_DNVM_COMMAND_NAME needs curl to proceed. ${RCol}" >&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" + + if [[ $platform == "mono" ]]; then + #dnx-mono + local packageId="$_DNVM_RUNTIME_PACKAGE_NAME-$platform" + else + #dnx-coreclr-linux-x64 + local packageId="$_DNVM_RUNTIME_PACKAGE_NAME-$platform-$(__dnvm_current_os)-$arch" + fi + local url="$DNX_ACTIVE_FEED/GetUpdates()?packageIds=%27$packageId%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/')" @@ -77,33 +117,69 @@ __dnvm_package_runtime() { echo "$runtimeFullName" | sed "s/$_DNVM_RUNTIME_PACKAGE_NAME-\([^.-]*\).*/\1/" } +__dnvm_package_arch() { + local runtimeFullName="$1" + if [[ "$runtimeFullName" =~ $_DNVM_RUNTIME_PACKAGE_NAME-[^-.]*-[^-.]*-[^-.]*\..* ]]; + then + echo "$runtimeFullName" | sed "s/$_DNVM_RUNTIME_PACKAGE_NAME-[^-.]*-[^-.]*-\([^-.]*\)\..*/\1/" + fi +} + +__dnvm_update_self() { + local dnvmFileLocation="$_DNVM_DNVM_DIR/dnvm.sh" + if [ ! -e $dnvmFileLocation ]; then + local formattedDnvmFileLocation=`(echo $dnvmFileLocation | sed s=$HOME=~=g)` + local formattedDnvmHome=`(echo $_DNVM_DNVM_DIR | sed s=$HOME=~=g)` + printf "%b\n" "${Red}$formattedDnvmFileLocation doesn't exist. This command assumes you have installed dnvm in the usual location and are trying to update it. If you want to use update-self then dnvm.sh should be sourced from $formattedDnvmHome ${RCol}" + return 1 + fi + printf "%b\n" "${Cya}Downloading dnvm.sh from $_DNVM_UPDATE_LOCATION ${RCol}" + local httpResult=$(curl -L -D - "$_DNVM_UPDATE_LOCATION" -o "$dnvmFileLocation" -# | grep "^HTTP/1.1" | head -n 1 | sed "s/HTTP.1.1 \([0-9]*\).*/\1/") + + [[ $httpResult == "404" ]] &&printf "%b\n" "${Red}404. Unable to download DNVM from $_DNVM_UPDATE_LOCATION ${RCol}" && return 1 + [[ $httpResult != "302" && $httpResult != "200" ]] && echo "${Red}HTTP Error $httpResult fetching DNVM from $_DNVM_UPDATE_LOCATION ${RCol}" && return 1 + + source "$dnvmFileLocation" +} + __dnvm_download() { local runtimeFullName="$1" local runtimeFolder="$2" + local force="$3" local pkgName=$(__dnvm_package_name "$runtimeFullName") local pkgVersion=$(__dnvm_package_version "$runtimeFullName") - local url="$DNX_FEED/package/$pkgName/$pkgVersion" + local url="$DNX_ACTIVE_FEED/package/$pkgName/$pkgVersion" local runtimeFile="$runtimeFolder/$runtimeFullName.nupkg" + if [ -n "$force" ]; then + printf "%b\n" "${Yel}Forcing download by deleting $runtimeFolder directory ${RCol}" + rm -rf "$runtimeFolder" + fi + if [ -e "$runtimeFolder" ]; then - echo "$runtimeFullName already installed." + printf "%b\n" "${Gre}$runtimeFullName already installed. ${RCol}" return 0 fi - - echo "Downloading $runtimeFullName from $DNX_FEED" - + if ! __dnvm_has "curl"; then - echo "$_DNVM_COMMAND_NAME needs curl to proceed." >&2; + printf "%b\n" "${Red}$_DNVM_COMMAND_NAME needs curl to proceed. ${RCol}" >&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/") + echo "Downloading $runtimeFullName from $DNX_ACTIVE_FEED" + echo "Download: $url" + + local httpResult=$(curl -L -D - "$url" -o "$runtimeFile" -# | 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 + if [[ $httpResult == "404" ]]; then + printf "%b\n" "${Red}$runtimeFullName was not found in repository $DNX_ACTIVE_FEED ${RCol}" + printf "%b\n" "${Cya}This is most likely caused by the feed not having the version that you typed. Check that you typed the right version and try again. Other possible causes are the feed doesn't have a $_DNVM_RUNTIME_SHORT_NAME of the right name format or some other error caused a 404 on the server.${RCol}" + return 1 + fi + [[ $httpResult != "302" && $httpResult != "200" ]] && echo "${Red}HTTP Error $httpResult fetching $runtimeFullName from $DNX_ACTIVE_FEED ${RCol}" && return 1 __dnvm_unpack $runtimeFile $runtimeFolder return $? @@ -133,27 +209,40 @@ __dnvm_unpack() { #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 + + #Set dnx to be executable + chmod 775 "$runtimeFolder/bin/dnx" } __dnvm_requested_version_or_alias() { local versionOrAlias="$1" + local runtime="$2" + local arch="$3" 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/") + if [ -e "$_DNVM_ALIAS_DIR/$versionOrAlias.alias" ]; then + local runtimeFullName=$(cat "$_DNVM_ALIAS_DIR/$versionOrAlias.alias") + echo "$runtimeFullName" else local pkgVersion=$versionOrAlias - local pkgPlatform="mono" - fi - echo "$_DNVM_RUNTIME_PACKAGE_NAME-$pkgPlatform.$pkgVersion" + if [[ -z $runtime || "$runtime" == "mono" ]]; then + echo "$_DNVM_RUNTIME_PACKAGE_NAME-mono.$pkgVersion" + elif [[ "$runtime" == "coreclr" ]]; then + local pkgArchitecture="x64" + local pkgSystem=$(__dnvm_current_os) + + if [ "$arch" != "" ]; then + local pkgArchitecture="$arch" + fi + + echo "$_DNVM_RUNTIME_PACKAGE_NAME-coreclr-$pkgSystem-$pkgArchitecture.$pkgVersion" + fi + fi fi } @@ -163,64 +252,131 @@ __dnvm_locate_runtime_bin_from_full_name() { [ -e "$_DNVM_USER_PACKAGES/$runtimeFullName/bin" ] && echo "$_DNVM_USER_PACKAGES/$runtimeFullName/bin" && return } -__dnvm_help() { +__echo_art() { + printf "%b" "${Cya}" + echo " ___ _ ___ ____ ___" + echo " / _ \/ |/ / | / / |/ /" + echo " / // / /| |/ / /|_/ / " + echo " /____/_/|_/ |___/_/ /_/ " + printf "%b" "${RCol}" +} + +__dnvm_description() { + __echo_art echo "" echo "$_DNVM_VERSION_MANAGER_NAME - Version 1.0.0-$_DNVM_BUILDNUMBER" - [ "$_DNVM_AUTHORS" != "{{*" ] && echo "By $_DNVM_AUTHORS" + [[ "$_DNVM_AUTHORS" != {{* ]] && echo "By $_DNVM_AUTHORS" + echo "" + echo "DNVM can be used to download versions of the $_DNVM_RUNTIME_FRIENDLY_NAME and manage which version you are using." + echo "You can control the URL of the stable and unstable channel by setting the DNX_FEED and DNX_UNSTABLE_FEED variables." + echo "" + printf "%b\n" "${Yel}Current feed settings:${RCol}" + printf "%b\n" "${Cya}Default Stable:${Yel} $_DNVM_DEFAULT_FEED" + printf "%b\n" "${Cya}Default Unstable:${Yel} $_DNVM_DEFAULT_UNSTABLE_FEED" + + local dnxStableOverride="" + [[ -n $DNX_FEED ]] && dnxStableOverride="$DNX_FEED" + + printf "%b\n" "${Cya}Current Stable Override:${Yel} $dnxStableOverride" + + local dnxUnstableOverride="" + [[ -n $DNX_UNSTABLE_FEED ]] && dnxUnstableOverride="$DNX_UNSTABLE_FEED" + + printf "%b\n" "${Cya}Current Unstable Override:${Yel} $dnxUnstableOverride${RCol}" + echo "" + +} + +__dnvm_help() { + __dnvm_description + printf "%b\n" "${Cya}USAGE:${Yel} $_DNVM_COMMAND_NAME [options] ${RCol}" + echo "" + printf "%b\n" "${Yel}$_DNVM_COMMAND_NAME upgrade [-f|-force] [-u|-unstable] ${RCol}" + echo " install latest $_DNVM_RUNTIME_SHORT_NAME from feed" + echo " adds $_DNVM_RUNTIME_SHORT_NAME bin to path of current command line" + echo " set installed version as default" + echo " -f|forces force upgrade. Overwrite existing version of $_DNVM_RUNTIME_SHORT_NAME if already installed" + echo " -u|unstable use unstable feed. Installs the $_DNVM_RUNTIME_SHORT_NAME from the unstable unstable feed" + echo " -r|runtime The runtime flavor to install [clr or coreclr] (default: clr)" + echo "" + printf "%b\n" "${Yel}$_DNVM_COMMAND_NAME install |||latest [-a|-alias ] [-p|-persistent] [-f|-force] [-u|-unstable] ${RCol}" + 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 " -f|force force install. Overwrite existing version of $_DNVM_RUNTIME_SHORT_NAME if already installed" + echo " -u|unstable use unstable feed. Installs the $_DNVM_RUNTIME_SHORT_NAME from the unstable unstable feed" + echo " -r|runtime The runtime flavor to install [mono or coreclr] (default: mono)" + echo "" + echo " adds $_DNVM_RUNTIME_SHORT_NAME bin to path of current command line" + echo "" + printf "%b\n" "${Yel}$_DNVM_COMMAND_NAME use |||none [-p|-persistent] [-r|-runtime ] [-a|-arch ] ${RCol}" + 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 " -r|-runtime runtime to use (mono, coreclr)" + echo " -a|-arch architecture to use (x64)" + echo "" + printf "%b\n" "${Yel}$_DNVM_COMMAND_NAME run | ${RCol}" + echo " | the version or alias to run" + echo " arguments to be passed to $_DNVM_RUNTIME_SHORT_NAME" echo "" - echo "USAGE: $_DNVM_COMMAND_NAME [options]" + echo " runs the $_DNVM_RUNTIME_SHORT_NAME command from the specified version of the runtime without affecting the current PATH" 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" + printf "%b\n" "${Yel}$_DNVM_COMMAND_NAME exec | ${RCol}" + echo " | the version or alias to execute in" + echo " the command to run" + echo " arguments to be passed to the command" 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 " runs the specified command in the context of the specified version of the runtime without affecting the current PATH" + echo " example: $_DNVM_COMMAND_NAME exec 1.0.0-beta4 $_DNVM_PACKAGE_MANAGER_NAME build" 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" + printf "%b\n" "${Yel}$_DNVM_COMMAND_NAME list ${RCol}" + echo " list $_DNVM_RUNTIME_SHORT_NAME versions installed " echo "" - echo "$_DNVM_COMMAND_NAME list" - echo "list $_DNVM_RUNTIME_SHORT_NAME versions installed " + printf "%b\n" "${Yel}$_DNVM_COMMAND_NAME alias ${RCol}" + echo " list $_DNVM_RUNTIME_SHORT_NAME aliases which have been defined" echo "" - echo "$_DNVM_COMMAND_NAME alias" - echo "list $_DNVM_RUNTIME_SHORT_NAME aliases which have been defined" + printf "%b\n" "${Yel}$_DNVM_COMMAND_NAME alias ${RCol}" + echo " display value of the specified alias" echo "" - echo "$_DNVM_COMMAND_NAME alias " - echo "display value of the specified alias" + printf "%b\n" "${Yel}$_DNVM_COMMAND_NAME alias || ${RCol}" + 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 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" + printf "%b\n" "${Yel}$_DNVM_COMMAND_NAME unalias ${RCol}" + echo " remove the specified alias" echo "" - echo "$_DNVM_COMMAND_NAME unalias " - echo "remove the specified alias" + printf "%b\n" "${Yel}$_DNVM_COMMAND_NAME [help|-h|-help|--help] ${RCol}" + echo " displays this help text." echo "" + printf "%b\n" "${Yel}$_DNVM_COMMAND_NAME update-self ${RCol}" + echo " updates dnvm itself." } dnvm() { if [ $# -lt 1 ]; then - __dnvm_help + __dnvm_description + + printf "%b\n" "Use ${Yel}$_DNVM_COMMAND_NAME [help|-h|-help|--help] ${RCol} to display help text." + echo "" return fi case $1 in - "help" ) + "help"|"-h"|"-help"|"--help" ) __dnvm_help ;; + "update-self" ) + __dnvm_update_self + ;; + "upgrade" ) - [ $# -ne 1 ] && __dnvm_help && return - $_DNVM_COMMAND_NAME install latest -p + shift + $_DNVM_COMMAND_NAME install latest -p $@ ;; "install" ) @@ -229,6 +385,10 @@ dnvm() local persistent= local versionOrAlias= local alias= + local force= + local unstable= + local runtime="mono" + local arch="x64" while [ $# -ne 0 ] do if [[ $1 == "-p" || $1 == "-persistent" ]]; then @@ -236,61 +396,128 @@ dnvm() elif [[ $1 == "-a" || $1 == "-alias" ]]; then local alias=$2 shift + elif [[ $1 == "-f" || $1 == "-force" ]]; then + local force="-f" + elif [[ $1 == "-u" || $1 == "-unstable" ]]; then + local unstable="-u" + elif [[ $1 == "-r" || $1 == "-runtime" ]]; then + local runtime=$2 + shift + elif [[ $1 == "-arch" ]]; then + local arch=$2 + shift + + if [[ $arch != "x86" && $arch != "x64" ]]; then + printf "%b\n" "${Red}Architecture must be x86 or x64.${RCol}" + return 1 + fi + + if [[ $arch == "x86" && $runtime == "coreclr" ]]; then + printf "%b\n" "${Red}Core CLR doesn't currently have a 32 bit build. You must use x64." + return 1 + fi + elif [[ -n $1 ]]; then [[ -n $versionOrAlias ]] && echo "Invalid option $1" && __dnvm_help && return 1 local versionOrAlias=$1 fi shift done + + if [ -z $unstable ]; then + DNX_ACTIVE_FEED="$DNX_FEED" + if [ -z "$DNX_ACTIVE_FEED" ]; then + DNX_ACTIVE_FEED="$_DNVM_DEFAULT_FEED" + else + printf "%b\n" "${Yel}Default stable feed ($_DNVM_DEFAULT_FEED) is being overridden by the value of the DNX_FEED variable ($DNX_FEED). ${RCol}" + fi + else + DNX_ACTIVE_FEED="$DNX_UNSTABLE_FEED" + if [ -z "$DNX_ACTIVE_FEED" ]; then + DNX_ACTIVE_FEED="$_DNVM_DEFAULT_UNSTABLE_FEED" + else + printf "%b\n" "${Yel}Default unstable feed ($_DNVM_DEFAULT_UNSTABLE_FEED) is being overridden by the value of the DNX_UNSTABLE_FEED variable ($DNX_UNSTABLE_FEED). ${RCol}" + fi + fi + + if [[ $runtime == "mono" ]] && ! __dnvm_has "mono"; then + printf "%b\n" "${Yel}It appears you don't have Mono available. Remember to get Mono before trying to run $DNVM_RUNTIME_SHORT_NAME application. ${RCol}" >&2; + fi + 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" + echo "Determining latest version" + versionOrAlias=$(__dnvm_find_latest "$runtime" "$arch") + [[ $? == 1 ]] && echo "Error: Could not find latest version from feed $DNX_ACTIVE_FEED" && return 1 + printf "%b\n" "Latest version is ${Cya}$versionOrAlias ${RCol}" 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" + local runtimeClr=$(__dnvm_package_runtime "$runtimeFullName") + + if [ -n "$force" ]; then + printf "%b\n" "${Yel}Forcing download by deleting $runtimeFolder directory ${RCol}" + rm -rf "$runtimeFolder" + fi if [ -e "$runtimeFolder" ]; then echo "$runtimeFullName already installed" else - mkdir "$runtimeFolder" > /dev/null 2>&1 + mkdir -p "$runtimeFolder" > /dev/null 2>&1 cp -a "$versionOrAlias" "$runtimeFile" __dnvm_unpack "$runtimeFile" "$runtimeFolder" [[ $? == 1 ]] && return 1 fi - $_DNVM_COMMAND_NAME use "$runtimeVersion" "$persistent" + $_DNVM_COMMAND_NAME use "$runtimeVersion" "$persistent" -r "$runtimeClr" [[ -n $alias ]] && $_DNVM_COMMAND_NAME alias "$alias" "$runtimeVersion" else - local runtimeFullName="$(__dnvm_requested_version_or_alias $versionOrAlias)" + local runtimeFullName=$(__dnvm_requested_version_or_alias "$versionOrAlias" "$runtime" "$arch") local runtimeFolder="$_DNVM_USER_PACKAGES/$runtimeFullName" - __dnvm_download "$runtimeFullName" "$runtimeFolder" + __dnvm_download "$runtimeFullName" "$runtimeFolder" "$force" [[ $? == 1 ]] && return 1 - $_DNVM_COMMAND_NAME use "$versionOrAlias" "$persistent" + $_DNVM_COMMAND_NAME use "$versionOrAlias" "$persistent" "-runtime" "$runtime" "-arch" "$arch" [[ -n $alias ]] && $_DNVM_COMMAND_NAME alias "$alias" "$versionOrAlias" fi ;; - "use" ) - [ $# -gt 3 ] && __dnvm_help && return - [ $# -lt 2 ] && __dnvm_help && return + "use"|"run"|"exec" ) + [[ $1 == "use" && $# -lt 2 ]] && __dnvm_help && return - shift + local cmd=$1 local persistent= - while [ $# -ne 0 ] - do - if [[ $1 == "-p" || $1 == "-persistent" ]]; then - local persistent="true" - elif [[ -n $1 ]]; then - local versionOrAlias=$1 - fi + local arch= + local runtime= + + shift + if [ $cmd == "use" ]; then + local versionOrAlias= + while [ $# -ne 0 ] + do + if [[ $1 == "-p" || $1 == "-persistent" ]]; then + local persistent="true" + elif [[ $1 == "-a" || $1 == "-arch" ]]; then + local arch=$2 + shift + elif [[ $1 == "-r" || $1 == "-runtime" ]]; then + local runtime=$2 + shift + elif [[ $1 == -* ]]; then + echo "Invalid option $1" && __dnvm_help && return 1 + elif [[ -n $1 ]]; then + [[ -n $versionOrAlias ]] && echo "Invalid option $1" && __dnvm_help && return 1 + local versionOrAlias=$1 + fi + shift + done + else + local versionOrAlias=$1 shift - done + fi - if [[ $versionOrAlias == "none" ]]; then + if [[ $cmd == "use" && $versionOrAlias == "none" ]]; then echo "Removing $_DNVM_RUNTIME_SHORT_NAME from process PATH" # Strip other version from PATH PATH=$(__dnvm_strip_path "$PATH" "/bin") @@ -302,7 +529,7 @@ dnvm() return 0 fi - local runtimeFullName=$(__dnvm_requested_version_or_alias "$versionOrAlias") + local runtimeFullName=$(__dnvm_requested_version_or_alias "$versionOrAlias" "$runtime" "$arch") local runtimeBin=$(__dnvm_locate_runtime_bin_from_full_name "$runtimeFullName") if [[ -z $runtimeBin ]]; then @@ -310,25 +537,44 @@ dnvm() 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 + case $cmd in + "run") + local hostpath="$runtimeBin/dnx" + if [[ -e $hostpath ]]; then + $hostpath $@ + else + echo "Cannot find $_DNVM_RUNTIME_SHORT_NAME in $runtimeBin. It may have been corrupted. Use '$_DNVM_COMMAND_NAME install $versionOrAlias -f' to attempt to reinstall it" + fi + ;; + "exec") + ( + PATH=$(__dnvm_strip_path "$PATH" "/bin") + PATH=$(__dnvm_prepend_path "$PATH" "$runtimeBin") + $@ + ) + ;; + "use") + 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 + ;; + esac ;; "alias" ) - [[ $# -gt 3 ]] && __dnvm_help && return + [[ $# -gt 7 ]] && __dnvm_help && return [[ ! -e "$_DNVM_ALIAS_DIR/" ]] && mkdir "$_DNVM_ALIAS_DIR/" > /dev/null if [[ $# == 1 ]]; then echo "" - local format="%-20s %s\n" + local format="%-25s %s\n" printf "$format" "Alias" "Name" printf "$format" "-----" "----" if [ -d "$_DNVM_ALIAS_DIR" ]; then @@ -341,17 +587,32 @@ dnvm() echo "" return fi + shift + local name="$1" - local name="$2" - - if [[ $# == 2 ]]; then + if [[ $# == 1 ]]; 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") + shift + local versionOrAlias="$1" + shift + while [ $# -ne 0 ] + do + if [[ $1 == "-a" || $1 == "-arch" ]]; then + local arch=$2 + shift + elif [[ $1 == "-r" || $1 == "-runtime" ]]; then + local runtime=$2 + shift + fi + shift + done + + local runtimeFullName=$(__dnvm_requested_version_or_alias "$versionOrAlias" "$runtime" "$arch") [[ ! -d "$_DNVM_USER_PACKAGES/$runtimeFullName" ]] && echo "$runtimeFullName is not an installed $_DNVM_RUNTIME_SHORT_NAME version" && return 1 @@ -398,29 +659,29 @@ dnvm() done fi - local formatString="%-6s %-20s %-7s %-20s %s\n" - printf "$formatString" "Active" "Version" "Runtime" "Location" "Alias" - printf "$formatString" "------" "-------" "-------" "--------" "-----" + local formatString="%-6s %-20s %-7s %-4s %-20s %s\n" + printf "$formatString" "Active" "Version" "Runtime" "Arch" "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 pkgRuntime=$(__dnvm_package_runtime "$f") + local pkgName=$(__dnvm_package_name "$f") local pkgVersion=$(__dnvm_package_version "$f") + local pkgArch=$(__dnvm_package_arch "$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 + if [[ ${i#*/} == "$pkgName.$pkgVersion" ]]; then alias+="$delim${i%/*}" delim=", " fi done - printf "$formatString" "$active" "$pkgVersion" "$pkgName" "$formattedHome" "$alias" + printf "$formatString" "$active" "$pkgVersion" "$pkgRuntime" "$pkgArch" "$formattedHome" "$alias" [[ $# == 2 ]] && echo "" && return 0 done From d06d1b17578f40525aeba6013df96071be3ad17d Mon Sep 17 00:00:00 2001 From: "ASP.NET Push Bot" Date: Tue, 2 Jun 2015 10:43:43 -0700 Subject: [PATCH 26/27] :arrow_up: dnvm.ps1, dnvm.cmd, dnvm.sh Source: AspNet/kvm@f5c2fdf53c7eeaf2119cf983520fad0f76e7bdd7 --- dnvm.ps1 | 40 ++++++++++++++++++++++------------------ dnvm.sh | 2 +- 2 files changed, 23 insertions(+), 19 deletions(-) diff --git a/dnvm.ps1 b/dnvm.ps1 index a879128666ae..0814256de73c 100644 --- a/dnvm.ps1 +++ b/dnvm.ps1 @@ -1,4 +1,4 @@ -#Requires -Version 3 +#Requires -Version 2 if (Test-Path env:WEBSITE_SITE_NAME) { @@ -67,7 +67,7 @@ function _WriteOut { ### Constants $ProductVersion="1.0.0" -$BuildVersion="beta5-10379" +$BuildVersion="beta5-10382" $Authors="Microsoft Open Technologies, Inc." # If the Version hasn't been replaced... @@ -252,7 +252,7 @@ function Safe-Filecopy { } function GetArch($Architecture, $FallBackArch = $DefaultArchitecture) { - if(![String]::IsNullOrWhiteSpace($Architecture)) { + if(![String]::IsNullOrEmpty($Architecture)) { $Architecture } elseif($CompatArch) { $CompatArch @@ -262,7 +262,7 @@ function GetArch($Architecture, $FallBackArch = $DefaultArchitecture) { } function GetRuntime($Runtime) { - if(![String]::IsNullOrWhiteSpace($Runtime)) { + if(![String]::IsNullOrEmpty($Runtime)) { $Runtime } else { $DefaultRuntime @@ -560,7 +560,7 @@ function Download-Package( } } - Write-Progress -Activity ("Downloading $RuntimeShortFriendlyName from $url") -Id 2 -ParentId 1 -Completed + Write-Progress -Status "Done" -Activity ("Downloading $RuntimeShortFriendlyName from $url") -Id 2 -ParentId 1 -Completed } finally { Remove-Variable downloadData -Scope "Global" @@ -632,10 +632,10 @@ function Change-Path() { $newPath = $prependPath foreach($portion in $existingPaths.Split(';')) { - if(![string]::IsNullOrWhiteSpace($portion)) { + if(![string]::IsNullOrEmpty($portion)) { $skip = $portion -eq "" foreach($removePath in $removePaths) { - if(![string]::IsNullOrWhiteSpace($removePath)) { + if(![string]::IsNullOrEmpty($removePath)) { $removePrefix = if($removePath.EndsWith("\")) { $removePath } else { "$removePath\" } if ($removePath -and (($portion -eq $removePath) -or ($portion.StartsWith($removePrefix)))) { @@ -645,7 +645,7 @@ function Change-Path() { } } if (!$skip) { - if(![String]::IsNullOrWhiteSpace($newPath)) { + if(![String]::IsNullOrEmpty($newPath)) { $newPath += ";" } $newPath += $portion @@ -752,7 +752,7 @@ function dnvm-help { return } $help = Get-Help "dnvm-$Command" - if($PassThru) { + if($PassThru -Or $Host.Version.Major -lt 3) { $help } else { _WriteOut -ForegroundColor $ColorScheme.Help_Header "$CommandName $Command" @@ -1084,7 +1084,7 @@ function dnvm-install { } if ($VersionNuPkgOrAlias -eq "latest") { - Write-Progress -Activity "Installing runtime" "Determining latest runtime" -Id 1 + Write-Progress -Status "Determining Latest Runtime" -Activity "Installing runtime" -Id 1 $VersionNuPkgOrAlias = Find-Latest $Runtime $Architecture -Feed:$selectedFeed } @@ -1094,7 +1094,7 @@ function dnvm-install { if(!(Test-Path $VersionNuPkgOrAlias)) { throw "Unable to locate package file: '$VersionNuPkgOrAlias'" } - Write-Progress -Activity "Installing runtime" "Parsing package file name" -Id 1 + Write-Progress -Activity "Installing runtime" -Status "Parsing package file name" -Id 1 $runtimeFullName = [System.IO.Path]::GetFileNameWithoutExtension($VersionNuPkgOrAlias) $Architecture = Get-PackageArch $runtimeFullName $Runtime = Get-PackageRuntime $runtimeFullName @@ -1134,18 +1134,18 @@ function dnvm-install { New-Item -Type Directory $UnpackFolder | Out-Null if($IsNuPkg) { - Write-Progress -Activity "Installing runtime" "Copying package" -Id 1 + Write-Progress -Activity "Installing runtime" -Status "Copying package" -Id 1 _WriteDebug "Copying local nupkg $VersionNuPkgOrAlias to $DownloadFile" Copy-Item $VersionNuPkgOrAlias $DownloadFile } else { # Download the package - Write-Progress -Activity "Installing runtime" "Downloading runtime" -Id 1 + Write-Progress -Activity "Installing runtime" -Status "Downloading runtime" -Id 1 _WriteDebug "Downloading version $VersionNuPkgOrAlias to $DownloadFile" Download-Package $PackageVersion $Architecture $Runtime $DownloadFile -Proxy:$Proxy -Feed:$selectedFeed } - Write-Progress -Activity "Installing runtime" "Unpacking runtime" -Id 1 + Write-Progress -Activity "Installing runtime" -Status "Unpacking runtime" -Id 1 Unpack-Package $DownloadFile $UnpackFolder if(Test-Path $RuntimeFolder) { @@ -1164,7 +1164,7 @@ function dnvm-install { if (-not $NoNative) { if ((Is-Elevated) -or $Ngen) { $runtimeBin = Get-RuntimePath $runtimeFullName - Write-Progress -Activity "Installing runtime" "Generating runtime native images" -Id 1 + Write-Progress -Activity "Installing runtime" -Status "Generating runtime native images" -Id 1 Ngen-Library $runtimeBin $Architecture } else { @@ -1178,7 +1178,7 @@ function dnvm-install { } else { _WriteOut "Compiling native images for $runtimeFullName to improve startup performance..." - Write-Progress -Activity "Installing runtime" "Generating runtime native images" -Id 1 + Write-Progress -Activity "Installing runtime" -Status "Generating runtime native images" -Id 1 if ($DebugPreference -eq 'SilentlyContinue') { Start-Process $CrossGenCommand -Wait -WindowStyle Hidden } @@ -1198,7 +1198,7 @@ function dnvm-install { dnvm-alias $Alias $PackageVersion -Architecture:$Architecture -Runtime:$Runtime } - Write-Progress -Activity "Install complete" -Id 1 -Complete + Write-Progress -Status "Done" -Activity "Install complete" -Id 1 -Complete } @@ -1431,7 +1431,11 @@ if(!$cmd) { try { if(Get-Command -Name "$CommandPrefix$cmd" -ErrorAction SilentlyContinue) { _WriteDebug "& dnvm-$cmd $cmdargs" - & "dnvm-$cmd" @cmdargs + if($host.Version.Major -lt 3) { + Invoke-Command ([ScriptBlock]::Create("dnvm-$cmd $cmdargs")) + } else { + & "dnvm-$cmd" @cmdargs + } } else { _WriteOut "Unknown command: '$cmd'" diff --git a/dnvm.sh b/dnvm.sh index 3df30694f63b..e0b528902ff2 100644 --- a/dnvm.sh +++ b/dnvm.sh @@ -2,7 +2,7 @@ # Source this file from your .bash-profile or script to use # "Constants" -_DNVM_BUILDNUMBER="beta5-10379" +_DNVM_BUILDNUMBER="beta5-10382" _DNVM_AUTHORS="Microsoft Open Technologies, Inc." _DNVM_RUNTIME_PACKAGE_NAME="dnx" _DNVM_RUNTIME_FRIENDLY_NAME=".NET Execution Environment" From fdab0411767d81fb2185c738ac62fa39ac0745f9 Mon Sep 17 00:00:00 2001 From: "ASP.NET Push Bot" Date: Mon, 8 Jun 2015 08:54:04 -0700 Subject: [PATCH 27/27] :arrow_up: dnvm.ps1, dnvm.cmd, dnvm.sh Source: AspNet/kvm@dae472367a19604fd3f09e76b714a9ca8d3a4cb3 --- dnvm.ps1 | 52 ++++++++++++++++++++++++++++++++++------------------ dnvm.sh | 2 +- 2 files changed, 35 insertions(+), 19 deletions(-) diff --git a/dnvm.ps1 b/dnvm.ps1 index 0814256de73c..0ee938d380fe 100644 --- a/dnvm.ps1 +++ b/dnvm.ps1 @@ -67,7 +67,7 @@ function _WriteOut { ### Constants $ProductVersion="1.0.0" -$BuildVersion="beta5-10382" +$BuildVersion="beta5-10384" $Authors="Microsoft Open Technologies, Inc." # If the Version hasn't been replaced... @@ -85,8 +85,9 @@ 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.nuget.org/api/v2" -Set-Variable -Option Constant "DefaultUnstableFeed" "https://www.myget.org/F/aspnetrelease/api/v2" +Set-Variable -Option Constant "DefaultUnstableFeed" "https://www.myget.org/F/aspnetvnext/api/v2" Set-Variable -Option Constant "CrossGenCommand" "dnx-crossgen" +Set-Variable -Option Constant "OldCrossGenCommand" "k-crossgen" Set-Variable -Option Constant "CommandPrefix" "dnvm-" Set-Variable -Option Constant "DefaultArchitecture" "x86" Set-Variable -Option Constant "DefaultRuntime" "clr" @@ -896,31 +897,26 @@ function dnvm-list { 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 } + if($Version) { + Write-Alias $Name $Version -Architecture $Architecture -Runtime $Runtime + } elseif ($Delete) { + Delete-Alias $Name + } else { + Read-Alias $Name } } @@ -1124,7 +1120,8 @@ function dnvm-install { else { $Architecture = GetArch $Architecture $Runtime = GetRuntime $Runtime - $UnpackFolder = Join-Path $RuntimesDir "temp" + $TempFolder = Join-Path $RuntimesDir "temp" + $UnpackFolder = Join-Path $TempFolder $runtimeFullName $DownloadFile = Join-Path $UnpackFolder "$runtimeFullName.nupkg" if(Test-Path $UnpackFolder) { @@ -1155,7 +1152,19 @@ function dnvm-install { else { _WriteOut "Installing to $RuntimeFolder" _WriteDebug "Moving package contents to $RuntimeFolder" - Move-Item $UnpackFolder $RuntimeFolder + try { + Move-Item $UnpackFolder $RuntimeFolder + } catch { + if(Test-Path $RuntimeFolder) { + #Attempt to cleanup the runtime folder if it is there after a fail. + Remove-Item $RuntimeFolder -Recurse -Force + throw + } + } + #If there is nothing left in the temp folder remove it. There could be other installs happening at the same time as this. + if(-Not(Test-Path $(Join-Path $TempFolder "*"))) { + Remove-Item $TempFolder -Recurse + } } dnvm-use $PackageVersion -Architecture:$Architecture -Runtime:$Runtime -Persistent:$Persistent @@ -1179,11 +1188,18 @@ function dnvm-install { else { _WriteOut "Compiling native images for $runtimeFullName to improve startup performance..." Write-Progress -Activity "Installing runtime" -Status "Generating runtime native images" -Id 1 + + if(Get-Command $CrossGenCommand -ErrorAction SilentlyContinue) { + $crossGenCommand = $CrossGenCommand + } else { + $crossGenCommand = $OldCrossGenCommand + } + if ($DebugPreference -eq 'SilentlyContinue') { - Start-Process $CrossGenCommand -Wait -WindowStyle Hidden + Start-Process $crossGenCommand -Wait -WindowStyle Hidden } else { - Start-Process $CrossGenCommand -Wait -NoNewWindow + Start-Process $crossGenCommand -Wait -NoNewWindow } _WriteOut "Finished native image compilation." } diff --git a/dnvm.sh b/dnvm.sh index e0b528902ff2..3548b7fb6aa9 100644 --- a/dnvm.sh +++ b/dnvm.sh @@ -2,7 +2,7 @@ # Source this file from your .bash-profile or script to use # "Constants" -_DNVM_BUILDNUMBER="beta5-10382" +_DNVM_BUILDNUMBER="beta5-10384" _DNVM_AUTHORS="Microsoft Open Technologies, Inc." _DNVM_RUNTIME_PACKAGE_NAME="dnx" _DNVM_RUNTIME_FRIENDLY_NAME=".NET Execution Environment"