From 1ccc412cafde8323cd35eff29b4fe53861484a47 Mon Sep 17 00:00:00 2001 From: Victor Hurdugaci Date: Mon, 7 Dec 2015 15:19:20 -0800 Subject: [PATCH] Support for dotnet --- KoreBuild-dotnet/KoreBuild-dotnet.nuspec | 2 +- KoreBuild-dotnet/build/BuildEnv.shade | 8 - KoreBuild-dotnet/build/Resources.cs | 0 KoreBuild-dotnet/build/Resources.tt | 195 -- KoreBuild-dotnet/build/_dnu.shade | 23 - KoreBuild-dotnet/build/_dotnet-compile.shade | 24 + KoreBuild-dotnet/build/_dotnet-pack.shade | 30 + ...pm-publish.shade => _dotnet-publish.shade} | 6 +- KoreBuild-dotnet/build/_dotnet-restore.shade | 15 + .../{_k-test.shade => _dotnet-test.shade} | 7 +- KoreBuild-dotnet/build/_dotnet.shade | 15 + KoreBuild-dotnet/build/_k-generate-resx.shade | 177 -- KoreBuild-dotnet/build/_k-restore.shade | 19 - .../build/_k-standard-goals.shade | 90 +- KoreBuild-dotnet/build/_k.shade | 28 - KoreBuild-dotnet/build/_kpm-build.shade | 52 - KoreBuild-dotnet/build/_kpm-pack.shade | 66 - KoreBuild-dotnet/build/dnvm.ps1 | 1911 ----------------- KoreBuild-dotnet/build/dnvm.sh | 1058 --------- .../build/{dnvm.cmd => install.cmd} | 10 +- KoreBuild-dotnet/build/install.ps1 | 91 + KoreBuild-dotnet/build/install.sh | 262 +++ build-template-dotnet/build.cmd | 36 +- build-template-dotnet/build.sh | 26 +- 24 files changed, 507 insertions(+), 3644 deletions(-) delete mode 100644 KoreBuild-dotnet/build/Resources.cs delete mode 100644 KoreBuild-dotnet/build/Resources.tt delete mode 100644 KoreBuild-dotnet/build/_dnu.shade create mode 100644 KoreBuild-dotnet/build/_dotnet-compile.shade create mode 100644 KoreBuild-dotnet/build/_dotnet-pack.shade rename KoreBuild-dotnet/build/{_kpm-publish.shade => _dotnet-publish.shade} (66%) create mode 100644 KoreBuild-dotnet/build/_dotnet-restore.shade rename KoreBuild-dotnet/build/{_k-test.shade => _dotnet-test.shade} (89%) create mode 100644 KoreBuild-dotnet/build/_dotnet.shade delete mode 100644 KoreBuild-dotnet/build/_k-generate-resx.shade delete mode 100644 KoreBuild-dotnet/build/_k-restore.shade delete mode 100644 KoreBuild-dotnet/build/_k.shade delete mode 100644 KoreBuild-dotnet/build/_kpm-build.shade delete mode 100644 KoreBuild-dotnet/build/_kpm-pack.shade delete mode 100644 KoreBuild-dotnet/build/dnvm.ps1 delete mode 100644 KoreBuild-dotnet/build/dnvm.sh rename KoreBuild-dotnet/build/{dnvm.cmd => install.cmd} (61%) create mode 100644 KoreBuild-dotnet/build/install.ps1 create mode 100644 KoreBuild-dotnet/build/install.sh diff --git a/KoreBuild-dotnet/KoreBuild-dotnet.nuspec b/KoreBuild-dotnet/KoreBuild-dotnet.nuspec index 874c8947c3..b17a936fb6 100644 --- a/KoreBuild-dotnet/KoreBuild-dotnet.nuspec +++ b/KoreBuild-dotnet/KoreBuild-dotnet.nuspec @@ -12,4 +12,4 @@ - \ No newline at end of file + diff --git a/KoreBuild-dotnet/build/BuildEnv.shade b/KoreBuild-dotnet/build/BuildEnv.shade index 6876084123..0d4a7145a6 100644 --- a/KoreBuild-dotnet/build/BuildEnv.shade +++ b/KoreBuild-dotnet/build/BuildEnv.shade @@ -25,12 +25,4 @@ functions return "t" + DateTime.UtcNow.ToString("yyMMddHHmmss"); } } - - bool IsBuildV2 - { - get - { - return Environment.GetEnvironmentVariable("KOREBUILD_BUILD_V2") == "1"; - } - } } \ No newline at end of file diff --git a/KoreBuild-dotnet/build/Resources.cs b/KoreBuild-dotnet/build/Resources.cs deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/KoreBuild-dotnet/build/Resources.tt b/KoreBuild-dotnet/build/Resources.tt deleted file mode 100644 index f6b0355d1d..0000000000 --- a/KoreBuild-dotnet/build/Resources.tt +++ /dev/null @@ -1,195 +0,0 @@ -<#@ template debug="true" hostspecific="true" language="C#" #> -<#@ assembly name="System.Core" #> -<#@ assembly name="System.Windows.Forms" #> -<#@ assembly name="Microsoft.VisualStudio.Shell.Interop.8.0" #> -<#@ assembly name="EnvDTE" #> -<#@ assembly name="EnvDTE80" #> -<#@ import namespace="System" #> -<#@ import namespace="System.Collections" #> -<#@ import namespace="System.Collections.Generic" #> -<#@ import namespace="System.IO" #> -<#@ import namespace="System.Linq" #> -<#@ import namespace="System.Resources" #> -<#@ import namespace="System.Text" #> -<#@ import namespace="System.Text.RegularExpressions" #> -<#@ import namespace="Microsoft.VisualStudio.Shell.Interop" #> -<#@ import namespace="EnvDTE" #> -<#@ import namespace="EnvDTE80" #> -<# - var hostServiceProvider = (IServiceProvider)Host; - var dte = (EnvDTE.DTE)hostServiceProvider.GetService(typeof(EnvDTE.DTE)); - var templateProjectItem = dte.Solution.FindProjectItem(Host.TemplateFile); - var projectDirectory = Path.GetDirectoryName(templateProjectItem.ContainingProject.FullName); - var ttDirectory = Path.Combine(projectDirectory, "Properties"); - var projectNamespace = templateProjectItem.ContainingProject.Properties.Item("DefaultNamespace").Value; - var projectName = Path.GetFileName(projectDirectory.TrimEnd('/')); - var namedParameterMatcher = new Regex(@"\{([a-z]\w+)\}", RegexOptions.IgnoreCase); - var numberParameterMatcher = new Regex(@"\{(\d+)\}"); - - foreach (var resxFile in Directory.EnumerateFiles(projectDirectory, "*.resx", SearchOption.AllDirectories)) - { - var fileName = Path.GetFileNameWithoutExtension(resxFile); - var resourceStrings = new List(); - - using (var resxReader = new ResXResourceReader(resxFile)) - { - resxReader.UseResXDataNodes = true; - - foreach (DictionaryEntry entry in resxReader) - { - var node = (ResXDataNode)entry.Value; - var value = (string)node.GetValue((System.ComponentModel.Design.ITypeResolutionService)null); - - bool usingNamedArgs = true; - var match = namedParameterMatcher.Matches(value); - if (match.Count == 0) - { - usingNamedArgs = false; - match = numberParameterMatcher.Matches(value); - } - - var arguments = match.Cast() - .Select(m => m.Groups[1].Value) - .Distinct(); - if (!usingNamedArgs) - { - arguments = arguments.OrderBy(Convert.ToInt32); - } - - resourceStrings.Add( - new ResourceData - { - Name = node.Name, - Value = value, - Arguments = arguments.ToList(), - UsingNamedArgs = usingNamedArgs - }); - } - } - - GenerationEnvironment.AppendFormat( -@"// -namespace {0} -{{ - using System.Globalization; - using System.Reflection; - using System.Resources; - - internal static class {2} - {{ - private static readonly ResourceManager _resourceManager - = new ResourceManager(""{1}.{2}"", typeof({2}).GetTypeInfo().Assembly); -", projectNamespace, projectName, fileName); - - foreach (var resourceString in resourceStrings) - { - GenerationEnvironment.AppendLine(); - RenderHeader(GenerationEnvironment, resourceString); - RenderProperty(GenerationEnvironment, resourceString); - - GenerationEnvironment.AppendLine(); - RenderHeader(GenerationEnvironment, resourceString); - RenderFormatMethod(GenerationEnvironment, resourceString); - } - - GenerationEnvironment.Append(@" - private static string GetString(string name, params string[] formatterNames) - { - var value = _resourceManager.GetString(name); - - System.Diagnostics.Debug.Assert(value != null); - - if (formatterNames != null) - { - for (var i = 0; i < formatterNames.Length; i++) - { - value = value.Replace(""{"" + formatterNames[i] + ""}"", ""{"" + i + ""}""); - } - } - - return value; - } - } -} -"); - - var outputPath = Path.Combine(ttDirectory, fileName + ".Designer.cs"); - - File.WriteAllText(outputPath, GenerationEnvironment.ToString()); - GenerationEnvironment.Length = 0; -} -#> -<#+ -private static void RenderHeader(StringBuilder builder, ResourceData resourceString) -{ - builder.Append(" /// ") - .AppendLine(); - foreach (var line in resourceString.Value.Split(new[] { Environment.NewLine }, StringSplitOptions.None)) - { - builder.AppendFormat(" /// {0}", line.Replace("<", "<").Replace(">", ">")) - .AppendLine(); - } - builder.Append(" /// ") - .AppendLine(); -} - -private static void RenderProperty(StringBuilder builder, ResourceData resourceString) -{ - builder.AppendFormat(" internal static string {0}", resourceString.Name) - .AppendLine() - .AppendLine(" {") - .AppendFormat(@" get {{ return GetString(""{0}""); }}", resourceString.Name) - .AppendLine() - .AppendLine(" }"); -} - -private static void RenderFormatMethod(StringBuilder builder, ResourceData resourceString) -{ - builder.AppendFormat(" internal static string Format{0}({1})", resourceString.Name, resourceString.Parameters) - .AppendLine() - .AppendLine(" {"); - if(resourceString.Arguments.Count > 0) - { - builder.AppendFormat(@" return string.Format(CultureInfo.CurrentCulture, GetString(""{0}""{1}), {2});", - resourceString.Name, - resourceString.UsingNamedArgs ? ", " + resourceString.FormatArguments : null, - resourceString.ArgumentNames); - } - else - { - builder.AppendFormat(@" return GetString(""{0}"");", resourceString.Name); - } - builder.AppendLine() - .AppendLine(" }"); -} - - -private class ResourceData -{ - public string Name { get; set; } - public string Value { get; set; } - public List Arguments { get; set; } - - public bool UsingNamedArgs { get; set; } - - public string FormatArguments - { - get { return string.Join(", ", Arguments.Select(a => "\"" + a + "\"")); } - } - - public string ArgumentNames - { - get { return string.Join(", ", Arguments.Select(GetArgName)); } - } - - public string Parameters - { - get { return string.Join(", ", Arguments.Select(a => "object " + GetArgName(a))); } - } - - public string GetArgName(string name) - { - return UsingNamedArgs ? name : 'p' + name; - } -} -#> \ No newline at end of file diff --git a/KoreBuild-dotnet/build/_dnu.shade b/KoreBuild-dotnet/build/_dnu.shade deleted file mode 100644 index 57cad3fdf9..0000000000 --- a/KoreBuild-dotnet/build/_dnu.shade +++ /dev/null @@ -1,23 +0,0 @@ -@{/* - -dnu - Run dnu commands in your project. Executes `dnu` command. - -command='' - The `dnu` subcommand to execute. -dnvmUse='' - Optional. The DNX framework to use. Suitable for a `dnvm exec` or `dnvm use` command. -*/} - -default dnvmUse='' -var dnvmPath = '${ Path.Combine(Directory.GetCurrentDirectory(), "packages", "KoreBuild", "build", "dnvm") }' - -exec program='cmd' commandline='/C dnu ${command}' if='!IsLinux && string.IsNullOrEmpty(dnvmUse)' - -var cmdCommand = '/S /C ""${dnvmPath}.cmd" use ${dnvmUse} && dnu ${command}"' -exec program='cmd' commandline='${ cmdCommand }' if='!IsLinux && !string.IsNullOrEmpty(dnvmUse)' - -exec program='dnu' commandline='${command}' if='IsLinux && string.IsNullOrEmpty(dnvmUse)' - -var envCommand = 'bash -c "source \"${dnvmPath}.sh\" && dnvm use ${dnvmUse} && dnu ${command}"' -exec program='/usr/bin/env' commandline='${ envCommand }' if='IsLinux && !string.IsNullOrEmpty(dnvmUse)' diff --git a/KoreBuild-dotnet/build/_dotnet-compile.shade b/KoreBuild-dotnet/build/_dotnet-compile.shade new file mode 100644 index 0000000000..c9c15dacc8 --- /dev/null +++ b/KoreBuild-dotnet/build/_dotnet-compile.shade @@ -0,0 +1,24 @@ +@{/* + +dotnet-compile + Builds a project. + +projectFile='' + Required. Path to the project.json to build. + +configuration='' + Optional. The configuration to build in. Defaults to 'Debug'. +*/} + +default configuration = 'Debug' +default compile_options=' ${E("KOREBUILD_DOTNET_COMPILE_OPTIONS")}' + +@{ + var projectFolder=Path.GetDirectoryName(projectFile); + var projectBin=Path.Combine(projectFolder, "bin", configuration); + + DeleteFolder(projectBin); + + var dotnetArgs=string.Format("compile{0} {1} --configuration {2}", compile_options, projectFolder, configuration); + Dotnet(dotnetArgs); +} \ No newline at end of file diff --git a/KoreBuild-dotnet/build/_dotnet-pack.shade b/KoreBuild-dotnet/build/_dotnet-pack.shade new file mode 100644 index 0000000000..a9b50c85c3 --- /dev/null +++ b/KoreBuild-dotnet/build/_dotnet-pack.shade @@ -0,0 +1,30 @@ +@{/* + +dotnet-pack + Builds package from project. + +projectFile='' + Required. Path to the project.json to build. + +dotnetPackOutputDir='' + Required. Base output directory. + +configuration='' + Optional. The configuration to build in. Defaults to 'Debug'. +*/} + +default configuration = 'Debug' +default pack_options=' ${E("KOREBUILD_DOTNET_PACK_OPTIONS")}' + +@{ + var projectFolder=Path.GetDirectoryName(projectFile); + var projectName=Path.GetFileName(projectFolder); + var projectBin=Path.Combine(projectFolder, "bin", configuration); + + DeleteFolder(projectBin); + + var dotnetArgs=string.Format("pack{0} {1} --configuration {2}", pack_options, projectFolder, configuration); + Dotnet(dotnetArgs); + + CopyFolder(projectBin, Path.Combine(dotnetPackOutputDir, projectName), true); +} \ No newline at end of file diff --git a/KoreBuild-dotnet/build/_kpm-publish.shade b/KoreBuild-dotnet/build/_dotnet-publish.shade similarity index 66% rename from KoreBuild-dotnet/build/_kpm-publish.shade rename to KoreBuild-dotnet/build/_dotnet-publish.shade index 833ca0d2e2..93df9b240b 100644 --- a/KoreBuild-dotnet/build/_kpm-publish.shade +++ b/KoreBuild-dotnet/build/_dotnet-publish.shade @@ -1,7 +1,7 @@ @{/* -kpm-publish - Builds project. Downloads and executes k sdk tools. +dotnet-publish + Builds project. Downloads and executes dotnet sdk tools. sourcePackagesDir='' Required. Path to packages to install (skips symbol packages) @@ -17,4 +17,4 @@ default targetPackagesDir='' .Where(p => !p.EndsWith(".symbols.nupkg")); } -dnu command='packages add ${package} ${targetPackagesDir}' each='var package in packages' +dotnet command='packages add ${package} ${targetPackagesDir}' each='var package in packages' diff --git a/KoreBuild-dotnet/build/_dotnet-restore.shade b/KoreBuild-dotnet/build/_dotnet-restore.shade new file mode 100644 index 0000000000..bd5c20a3dd --- /dev/null +++ b/KoreBuild-dotnet/build/_dotnet-restore.shade @@ -0,0 +1,15 @@ +@{/* + +dotnet-restore + Restores nuget packages required for dotnet projects. Downloads and executes dotnet sdk tools. + +restoreDir='' + Optional. The directory in which to execute the dnu restore command. +*/} + +default currentDir = '${ Directory.GetCurrentDirectory() }' +default restoreDir = '${ currentDir }' + +default restore_options=' ${ E("KOREBUILD_DOTNET_RESTORE_OPTIONS") } ${ IsLinux ? string.Empty : "--parallel" }' + +dotnet command='restore${ restore_options }' workingDir='${ restoreDir }' diff --git a/KoreBuild-dotnet/build/_k-test.shade b/KoreBuild-dotnet/build/_dotnet-test.shade similarity index 89% rename from KoreBuild-dotnet/build/_k-test.shade rename to KoreBuild-dotnet/build/_dotnet-test.shade index 55c6e08481..a771237b54 100644 --- a/KoreBuild-dotnet/build/_k-test.shade +++ b/KoreBuild-dotnet/build/_dotnet-test.shade @@ -6,7 +6,7 @@ default KOREBUILD_TEST_DNXCORE='${E("KOREBUILD_TEST_DNXCORE")}' @{/* -k-test +dotnet-test Run unit tests in your project. projectFile='' @@ -50,6 +50,7 @@ projectFile='' { var testArgs = noParallelTestProjects.Contains(projectName) ? " -parallel none" : ""; + Console.WriteLine("!!! Tests skipped for " + projectName); if (!framework.StartsWith("dnxcore", StringComparison.OrdinalIgnoreCase)) { if (IsLinux) @@ -58,11 +59,11 @@ projectFile='' testArgs = " -parallel none"; } - Dnx("test" + testArgs, projectFolder); + // Dotnet("test" + testArgs, projectFolder); } else if (!IsLinux || !string.IsNullOrEmpty(KOREBUILD_TEST_DNXCORE)) { - Dnx("test" + testArgs, projectFolder, "default -runtime coreclr"); + // Dotnet("test" + testArgs, projectFolder, "default -runtime coreclr"); } } } diff --git a/KoreBuild-dotnet/build/_dotnet.shade b/KoreBuild-dotnet/build/_dotnet.shade new file mode 100644 index 0000000000..7c2282c4c9 --- /dev/null +++ b/KoreBuild-dotnet/build/_dotnet.shade @@ -0,0 +1,15 @@ +@{/* + +dotnet + Run dotnet commands in your project. Executes `dotnet` command. + +command='' + The `dotnet` subcommand to execute. +dotnetDir='' + Optional. The directory in which to execute the `dotnet` command. +*/} + +default currentDir = '${Directory.GetCurrentDirectory()}' +default dotnetDir = '${ currentDir }' + +exec program='dotnet' commandline='${command}' workingdir='${dotnetDir}' diff --git a/KoreBuild-dotnet/build/_k-generate-resx.shade b/KoreBuild-dotnet/build/_k-generate-resx.shade deleted file mode 100644 index b499e6b0bc..0000000000 --- a/KoreBuild-dotnet/build/_k-generate-resx.shade +++ /dev/null @@ -1,177 +0,0 @@ -use namespace="System" -use namespace="System.Collections.Generic" -use namespace="System.IO" -use namespace="System.Linq" -use namespace="System.Text" -use namespace="System.Xml.Linq" - -default resxFile='' - -@{ - var projectDir = Path.GetDirectoryName(resxFile); - var outDirectory = Path.Combine(projectDir, "Properties"); - var projectName = Path.GetFileName(projectDir.TrimEnd((char)'/')); - var namedParameterMatcher = new Regex(@"\{([a-z]\w+)\}", RegexOptions.IgnoreCase); - var numberParameterMatcher = new Regex(@"\{(\d+)\}"); - var generatingEnvironment = new StringBuilder(); - - var fileName = Path.GetFileNameWithoutExtension(resxFile); - var resourceStrings = new List(); - var xml = XDocument.Load(resxFile); - - foreach (var entry in xml.Descendants("data")) - { - var name = entry.Attribute("name").Value; - var value = entry.Element("value").Value; - - bool usingNamedArgs = true; - var match = namedParameterMatcher.Matches(value); - if (match.Count == 0) - { - usingNamedArgs = false; - match = numberParameterMatcher.Matches(value); - } - - var arguments = match.Cast() - .Select(m => m.Groups[1].Value) - .Distinct(); - if (!usingNamedArgs) - { - arguments = arguments.OrderBy(Convert.ToInt32); - } - - resourceStrings.Add( - new ResourceData - { - Name = name, - Value = value, - Arguments = arguments.ToList(), - UsingNamedArgs = usingNamedArgs - }); - } - - generatingEnvironment.AppendFormat( -@"// -namespace {0} -{{ - using System.Globalization; - using System.Reflection; - using System.Resources; - - internal static class {1} - {{ - private static readonly ResourceManager _resourceManager - = new ResourceManager(""{0}.{1}"", typeof({1}).GetTypeInfo().Assembly); -", projectName, fileName); - - foreach (var resourceString in resourceStrings) - { - generatingEnvironment.AppendLine(); - RenderHeader(generatingEnvironment, resourceString); - RenderProperty(generatingEnvironment, resourceString); - - generatingEnvironment.AppendLine(); - RenderHeader(generatingEnvironment, resourceString); - RenderFormatMethod(generatingEnvironment, resourceString); - } - - generatingEnvironment.Append(@" - private static string GetString(string name, params string[] formatterNames) - { - var value = _resourceManager.GetString(name); - - System.Diagnostics.Debug.Assert(value != null); - - if (formatterNames != null) - { - for (var i = 0; i < formatterNames.Length; i++) - { - value = value.Replace(""{"" + formatterNames[i] + ""}"", ""{"" + i + ""}""); - } - } - - return value; - } - } -} -"); - - Directory.CreateDirectory(outDirectory); - var outputPath = Path.Combine(outDirectory, fileName + ".Designer.cs"); - - File.WriteAllText(outputPath, generatingEnvironment.ToString()); -} - -functions @{ - private static void RenderHeader(StringBuilder builder, ResourceData resourceString) - { - builder.Append(" /// ") - .AppendLine(); - foreach (var line in resourceString.Value.Split(new[] { '\n' }, StringSplitOptions.None)) - { - builder.AppendFormat(" /// {0}", new XText(line)) - .AppendLine(); - } - builder.Append(" /// ") - .AppendLine(); - } - - private static void RenderProperty(StringBuilder builder, ResourceData resourceString) - { - builder.AppendFormat(" internal static string {0}", resourceString.Name) - .AppendLine() - .AppendLine(" {") - .AppendFormat(@" get {{ return GetString(""{0}""); }}", resourceString.Name) - .AppendLine() - .AppendLine(" }"); - } - - private static void RenderFormatMethod(StringBuilder builder, ResourceData resourceString) - { - builder.AppendFormat(" internal static string Format{0}({1})", resourceString.Name, resourceString.Parameters) - .AppendLine() - .AppendLine(" {"); - if(resourceString.Arguments.Count > 0) - { - builder.AppendFormat(@" return string.Format(CultureInfo.CurrentCulture, GetString(""{0}""{1}), {2});", - resourceString.Name, - resourceString.UsingNamedArgs ? ", " + resourceString.FormatArguments : null, - resourceString.ArgumentNames); - } - else - { - builder.AppendFormat(@" return GetString(""{0}"");", resourceString.Name); - } - builder.AppendLine() - .AppendLine(" }"); - } - - private class ResourceData - { - public string Name { get; set; } - public string Value { get; set; } - public List Arguments { get; set; } - - public bool UsingNamedArgs { get; set; } - - public string FormatArguments - { - get { return string.Join(", ", Arguments.Select(a => "\"" + a + "\"")); } - } - - public string ArgumentNames - { - get { return string.Join(", ", Arguments.Select(GetArgName)); } - } - - public string Parameters - { - get { return string.Join(", ", Arguments.Select(a => "object " + GetArgName(a))); } - } - - public string GetArgName(string name) - { - return UsingNamedArgs ? name : 'p' + name; - } - } -} \ No newline at end of file diff --git a/KoreBuild-dotnet/build/_k-restore.shade b/KoreBuild-dotnet/build/_k-restore.shade deleted file mode 100644 index f8bae50216..0000000000 --- a/KoreBuild-dotnet/build/_k-restore.shade +++ /dev/null @@ -1,19 +0,0 @@ -@{/* - -k-restore - Restores nuget packages required for DNX projects. Downloads and executes DNX sdk tools. - -restoreDir='' - Optional. The directory in which to execute the dnu restore command. -*/} - -default currentDir = '${ Directory.GetCurrentDirectory() }' -default restoreDir = '${ currentDir }' - --// Set KOREBUILD_DNU_RESTORE_CORECLR environment variable to any value and `dnu restore` will use Core CLR. -var useCore = '${ E("KOREBUILD_DNU_RESTORE_CORECLR") }' -default restoreUse='${ string.IsNullOrEmpty(useCore) ? string.Empty : "default -runtime coreclr" }' - -default restore_options=' ${ E("KOREBUILD_DNU_RESTORE_OPTIONS") } ${ IsLinux ? string.Empty : "--parallel" }' - -dnu command='restore${ restore_options }' workingDir='${ restoreDir }' dnvmUse='${ restoreUse }' diff --git a/KoreBuild-dotnet/build/_k-standard-goals.shade b/KoreBuild-dotnet/build/_k-standard-goals.shade index f233203b28..1d537df3f7 100644 --- a/KoreBuild-dotnet/build/_k-standard-goals.shade +++ b/KoreBuild-dotnet/build/_k-standard-goals.shade @@ -36,8 +36,6 @@ default NUGET_FEED = 'https://api.nuget.org/v3/index.json' Configuration = "Debug"; E("Configuration", Configuration); } - - Log.Info("Build v2: " + IsBuildV2); } #restore-npm-modules @@ -71,7 +69,7 @@ default NUGET_FEED = 'https://api.nuget.org/v3/index.json' #deep-clean .clean-npm-modules .clean-bin-folder description='Clean folders that may cause problems for `git clean`.' #repo-initialize target='initialize' - k-restore + dotnet-restore #target-dir-clean target='clean' @{ @@ -94,16 +92,16 @@ default NUGET_FEED = 'https://api.nuget.org/v3/index.json' #ci-deep-clean .deep-clean target='clean' if='IsTeamCity' -#build-compile target='compile' if='!IsBuildV2 && Directory.Exists("src")' +#build-compile target='compile' if='Directory.Exists("src")' @{ var projectFiles = Files.Include("src/**/project.json").ToList(); if (ShouldRunInParallel) { - Parallel.ForEach(projectFiles, projectFile => DnuPack(projectFile, BUILD_DIR, Configuration)); + Parallel.ForEach(projectFiles, projectFile => DotnetPack(projectFile, BUILD_DIR, Configuration)); } else { - projectFiles.ForEach(projectFile => DnuPack(projectFile, BUILD_DIR, Configuration)); + projectFiles.ForEach(projectFile => DotnetPack(projectFile, BUILD_DIR, Configuration)); } foreach (var nupkg in Files.Include(Path.Combine(BUILD_DIR, "*/*.nupkg"))) @@ -112,45 +110,6 @@ default NUGET_FEED = 'https://api.nuget.org/v3/index.json' } } -#build-compile target='compile' if='IsBuildV2' - @{ - // If the src folder, build and create the packages - if (Directory.Exists("src")) - { - // Handle projects 1 to 3 levels down from src/, avoiding path too long errors. - DnuPack("src/*;src/*/*;src/*/*/*", BUILD_DIR, Configuration); - - foreach (var nupkg in Files.Include(Path.Combine(BUILD_DIR, "*/*.nupkg"))) - { - File.Copy(nupkg, Path.Combine(BUILD_DIR, Path.GetFileName(nupkg)), true); - } - } - - // For test and samples only check if they compile - var projectsToBuild = new List(); - if (Directory.Exists("test")) - { - // Handle projects 1 to 3 levels down from test/, avoiding path too long errors. - projectsToBuild.Add("test/*"); - projectsToBuild.Add("test/*/*"); - projectsToBuild.Add("test/*/*/*"); - } - if (Directory.Exists("samples")) - { - // Handle projects 1 to 3 levels down from samples/, avoiding path too long errors. - projectsToBuild.Add("samples/*"); - projectsToBuild.Add("samples/*/*"); - projectsToBuild.Add("samples/*/*/*"); - } - - if (projectsToBuild.Any()) - { - DnuBuild( - string.Join(";", projectsToBuild), - Configuration); - } - } - #native-compile target='compile' if='!IsLinux && Directory.Exists(Path.Combine(BASE_DIR, "src"))' var programFilesX86 = '${Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86)}' var nativeProjects ='${Files.Include(Path.Combine(BASE_DIR, "src", "**", "*.vcxproj"))}' @@ -203,7 +162,7 @@ default NUGET_FEED = 'https://api.nuget.org/v3/index.json' } #nuget-install target='install' if='Directory.Exists("src")' description='Install NuGet packages to local repo' - kpm-publish sourcePackagesDir='${BUILD_DIR}' targetPackagesDir='${E("PACKAGES_PUBLISH_DIR")}' + dotnet-publish sourcePackagesDir='${BUILD_DIR}' targetPackagesDir='${E("PACKAGES_PUBLISH_DIR")}' nuget-resilient-publish sourcePackagesDir='${BUILD_DIR}' nugetFeed='${E("NUGET_PUBLISH_FEED")}' if='!string.IsNullOrEmpty(E("NUGET_PUBLISH_FEED"))' #xunit-test target='test' if='Directory.Exists("test")' @@ -211,24 +170,24 @@ default NUGET_FEED = 'https://api.nuget.org/v3/index.json' var projectFiles = Files.Include("test/**/project.json").Exclude("**/bin/*/app/project.json").ToList(); if (ShouldRunInParallel) { - Parallel.ForEach(projectFiles, projectFile => DnxTest(projectFile, testParallel: true)); + Parallel.ForEach(projectFiles, projectFile => DotnetTest(projectFile, testParallel: true)); } else { - projectFiles.ForEach(projectFile => DnxTest(projectFile, testParallel: false)); + projectFiles.ForEach(projectFile => DotnetTest(projectFile, testParallel: false)); } } -#build-samples target='test' if='!IsBuildV2 && Directory.Exists("samples")' +#build-samples target='test' if='Directory.Exists("samples")' @{ var projectFiles = Files.Include("samples/**/project.json").ToList(); if (ShouldRunInParallel) { - Parallel.ForEach(projectFiles, projectFile => DnuBuild(projectFile, Configuration)); + Parallel.ForEach(projectFiles, projectFile => DotnetCompile(projectFile, Configuration)); } else { - projectFiles.ForEach(projectFile => DnuBuild(projectFile, Configuration)); + projectFiles.ForEach(projectFile => DotnetCompile(projectFile, Configuration)); } } @@ -260,9 +219,9 @@ default NUGET_FEED = 'https://api.nuget.org/v3/index.json' #--quiet @{ AddToE("KOREBUILD_BOWER_INSTALL_OPTIONS", "--quiet"); - AddToE("KOREBUILD_DNU_BUILD_OPTIONS", "--quiet"); - AddToE("KOREBUILD_DNU_PACK_OPTIONS", "--quiet"); - AddToE("KOREBUILD_DNU_RESTORE_OPTIONS", "--quiet"); + AddToE("KOREBUILD_DOTNET_BUILD_OPTIONS", "--quiet"); + AddToE("KOREBUILD_DOTNET_PACK_OPTIONS", "--quiet"); + AddToE("KOREBUILD_DOTNET_RESTORE_OPTIONS", "--quiet"); AddToE("KOREBUILD_NPM_INSTALL_OPTIONS", "--quiet"); Quiet = true; } @@ -370,26 +329,23 @@ functions @{ macro name='Exec' program='string' commandline='string' exec -macro name='Dnu' command='string' - dnu +macro name='Dotnet' command='string' + dotnet -macro name='Dnx' command='string' dnxDir='string' - k - -macro name='Dnx' command='string' dnxDir='string' dnvmUse='string' - k +macro name='Dotnet' command='string' dotnetDir='string' + dotnet macro name="UpdateResx" resxFile='string' k-generate-resx -macro name="DnxTest" projectFile='string' testParallel='bool' - k-test +macro name="DotnetTest" projectFile='string' testParallel='bool' + dotnet-test -macro name="DnuBuild" projectFile='string' configuration='string' - kpm-build +macro name="DotnetCompile" projectFile='string' configuration='string' + dotnet-compile -macro name="DnuPack" projectFile='string' kpmPackOutputDir='string' configuration='string' - kpm-pack +macro name="DotnetPack" projectFile='string' dotnetPackOutputDir='string' configuration='string' + dotnet-pack macro name="DeleteFolder" delete='string' directory diff --git a/KoreBuild-dotnet/build/_k.shade b/KoreBuild-dotnet/build/_k.shade deleted file mode 100644 index f95d5f81c4..0000000000 --- a/KoreBuild-dotnet/build/_k.shade +++ /dev/null @@ -1,28 +0,0 @@ -@{/* - -k - Run dnx commands in your project. Executes `dnx` command. - -command='' - The `dnx` subcommand to execute. -dnxDir='' - Optional. The directory in which to execute the `dnx` command. -dnvmUse='' - Optional. The DNX framework to use. Suitable for a `dnvm run` or `dnvm use` command. -*/} - -default currentDir = '${Directory.GetCurrentDirectory()}' -default dnxDir = '${ currentDir }' - -default dnvmUse='' -var dnvmPath = '${ Path.Combine(Directory.GetCurrentDirectory(), "packages", "KoreBuild", "build", "dnvm") }' - -exec program='cmd' commandline='/C dnx ${command}' workingdir='${dnxDir}' if='!IsLinux && string.IsNullOrEmpty(dnvmUse)' - -var cmdCommand = '/S /C ""${dnvmPath}.cmd" use ${dnvmUse} && dnx ${command}"' -exec program='cmd' commandline='${ cmdCommand }' workingdir='${dnxDir}' if='!IsLinux && !string.IsNullOrEmpty(dnvmUse)' - -exec program='dnx' commandline='${command}' workingdir='${dnxDir}' if='IsLinux && string.IsNullOrEmpty(dnvmUse)' - -var envCommand = 'bash -c "source \"${dnvmPath}.sh\" && dnvm use ${dnvmUse} && dnx ${command}"' -exec program='/usr/bin/env' commandline='${ envCommand }' workingdir='${dnxDir}' if='IsLinux && !string.IsNullOrEmpty(dnvmUse)' diff --git a/KoreBuild-dotnet/build/_kpm-build.shade b/KoreBuild-dotnet/build/_kpm-build.shade deleted file mode 100644 index ffe2aa4297..0000000000 --- a/KoreBuild-dotnet/build/_kpm-build.shade +++ /dev/null @@ -1,52 +0,0 @@ -@{/* - -kpm-build - Builds a project. - -projectFile='' - Required. Path to the project.json to build. - -configuration='' - Optional. The configuration to build in. Defaults to 'Debug'. -*/} - -default configuration = 'Debug' -default build_options=' ${E("KOREBUILD_DNU_BUILD_OPTIONS")}' - -@{ - if (IsBuildV2) - { - var projectsToPack = new List(); - foreach(var arg in projectFile.Split((char)';')) - { - if (!arg.Contains("*")) - { - projectsToPack.Add(Path.GetDirectoryName(arg)); - } - else - { - var projectFolders = Files.Include(arg + "/project.json").Select(proj => Path.GetDirectoryName(proj)); - projectsToPack.AddRange(projectFolders); - } - } - - foreach(var projFolder in projectsToPack) - { - DeleteFolder(Path.Combine(projFolder, "bin", configuration)); - } - - var projectsArg=projectFile.Replace(";", " "); - var dnuArgs=string.Format("build{0} {1} --configuration {2}", build_options, projectsArg, configuration); - Dnu(dnuArgs); - } - else - { - var projectFolder=Path.GetDirectoryName(projectFile); - var projectBin=Path.Combine(projectFolder, "bin", configuration); - - DeleteFolder(projectBin); - - var dnuArgs=string.Format("build{0} {1} --configuration {2}", build_options, projectFolder, configuration); - Dnu(dnuArgs); - } -} \ No newline at end of file diff --git a/KoreBuild-dotnet/build/_kpm-pack.shade b/KoreBuild-dotnet/build/_kpm-pack.shade deleted file mode 100644 index 029c34ae84..0000000000 --- a/KoreBuild-dotnet/build/_kpm-pack.shade +++ /dev/null @@ -1,66 +0,0 @@ -@{/* - -kpm-pack - Builds package from project. - -projectFile='' - Required. Path to the project.json to build. - -kpmPackOutputDir='' - Required. Base output directory. - -configuration='' - Optional. The configuration to build in. Defaults to 'Debug'. -*/} - -default configuration = 'Debug' -default pack_options=' ${E("KOREBUILD_DNU_PACK_OPTIONS")}' - -@{ - if (IsBuildV2) - { - var projectsToPack = new List(); - foreach(var arg in projectFile.Split((char)';')) - { - if (!arg.Contains("*")) - { - projectsToPack.Add(Path.GetDirectoryName(arg)); - } - else - { - var projectFolders = Files.Include(arg + "/project.json").Select(proj => Path.GetDirectoryName(proj)); - projectsToPack.AddRange(projectFolders); - } - } - - foreach(var projFolder in projectsToPack) - { - DeleteFolder(Path.Combine(projFolder, "bin", configuration)); - } - - var projectsArg=projectFile.Replace(";", " "); - var dnuArgs=string.Format("pack{0} {1} --configuration {2}", pack_options, projectsArg, configuration); - Dnu(dnuArgs); - - foreach(var projFolder in projectsToPack) - { - CopyFolder( - Path.Combine(projFolder, "bin", configuration), - Path.Combine(kpmPackOutputDir, Path.GetFileName(projFolder)), - true); - } - } - else - { - var projectFolder=Path.GetDirectoryName(projectFile); - var projectName=Path.GetFileName(projectFolder); - var projectBin=Path.Combine(projectFolder, "bin", configuration); - - DeleteFolder(projectBin); - - var dnuArgs=string.Format("pack{0} {1} --configuration {2}", pack_options, projectFolder, configuration); - Dnu(dnuArgs); - - CopyFolder(projectBin, Path.Combine(kpmPackOutputDir, projectName), true); - } -} \ No newline at end of file diff --git a/KoreBuild-dotnet/build/dnvm.ps1 b/KoreBuild-dotnet/build/dnvm.ps1 deleted file mode 100644 index 0b28a8b9d2..0000000000 --- a/KoreBuild-dotnet/build/dnvm.ps1 +++ /dev/null @@ -1,1911 +0,0 @@ -#Requires -Version 2 - -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 -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($__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 = "" - } - 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 - } - } -} - -### Constants -$ProductVersion="1.0.0" -$BuildVersion="rc1-15533" -$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 "DefaultGlobalDirectoryName" "Microsoft DNX" -Set-Variable -Option Constant "OldUserDirectoryNames" @(".kre", ".k") -Set-Variable -Option Constant "RuntimePackageName" "dnx" -Set-Variable -Option Constant "DefaultFeed" "https://www.myget.org/F/aspnetcidev/api/v2" -Set-Variable -Option Constant "DefaultFeedKey" "DNX_FEED" -Set-Variable -Option Constant "DefaultUnstableFeed" "https://www.myget.org/F/aspnetcidev/api/v2" -Set-Variable -Option Constant "DefaultUnstableFeedKey" "DNX_UNSTABLE_FEED" -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" -Set-Variable -Option Constant "AliasExtension" ".txt" -Set-Variable -Option Constant "DefaultOperatingSystem" "win" - -# 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 "DNVMUpgradeUrl" "https://raw.githubusercontent.com/aspnet/Home/dev/dnvm.ps1" - -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 - "Feed_Name"=[ConsoleColor]::Cyan - "Warning" = [ConsoleColor]::Yellow - "Error" = [ConsoleColor]::Red - "ActiveRuntime" = [ConsoleColor]::Cyan - } -} - -Set-Variable -Option Constant "OptionPadding" 20 -Set-Variable -Option Constant "CommandPadding" 15 - -# 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 = $(if (Test-Path "env:\$HomeEnvVar") {Get-Content "env:\$HomeEnvVar"}) -$UserHome = $env:DNX_USER_HOME -$GlobalHome = $env:DNX_GLOBAL_HOME -$ActiveFeed = $(if (Test-Path "env:\$DefaultFeedKey") {Get-Content "env:\$DefaultFeedKey"}) -$ActiveUnstableFeed = $(if (Test-Path "env:\$DefaultUnstableFeedKey") {Get-Content "env:\$DefaultUnstableFeedKey"}) - -# 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" -} - -# Determine the default installation directory (UserHome) -if(!$UserHome) { - if ($RuntimeHomes) { - _WriteDebug "Detecting User Home..." - $pf = $env:ProgramFiles - if(Test-Path "env:\ProgramFiles(x86)") { - $pf32 = Get-Content "env:\ProgramFiles(x86)" - } - - # Canonicalize so we can do StartsWith tests - if(!$pf.EndsWith("\")) { $pf += "\" } - if($pf32 -and !$pf32.EndsWith("\")) { $pf32 += "\" } - - $UserHome = $RuntimeHomes.Split(";") | 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 = "$DefaultUserHome" - } -} -$UserHome = [Environment]::ExpandEnvironmentVariables($UserHome) - -# Determine the default global installation directory (GlobalHome) -if(!$GlobalHome) { - if($env:ProgramData) { - $GlobalHome = "$env:ProgramData\$DefaultGlobalDirectoryName" - } else { - $GlobalHome = "$env:AllUsersProfile\$DefaultGlobalDirectoryName" - } -} -$GlobalHome = [Environment]::ExpandEnvironmentVariables($GlobalHome) - -# Determine where runtimes can exist (RuntimeHomes) -if(!$RuntimeHomes) { - # Set up a default value for the runtime home - $UnencodedHomes = "$UserHome;$GlobalHome" -} elseif ($RuntimeHomes.StartsWith(';')) { - _WriteOut "Ignoring invalid $HomeEnvVar; value was '$RuntimeHomes'" -ForegroundColor $ColorScheme.Warning - Clean-HomeEnv($true) - - # Use default instead. - $UnencodedHomes = "$UserHome;$GlobalHome" -} else { - $UnencodedHomes = $RuntimeHomes -} - -$UnencodedHomes = $UnencodedHomes.Split(";") -$RuntimeHomes = $UnencodedHomes | ForEach-Object { [Environment]::ExpandEnvironmentVariables($_) } -$RuntimeDirs = $RuntimeHomes | ForEach-Object { Join-Path $_ "runtimes" } - -_WriteDebug "" -_WriteDebug "=== Running $CommandName ===" -_WriteDebug "Runtime Homes: $RuntimeHomes" -_WriteDebug "User Home: $UserHome" -$AliasesDir = Join-Path $UserHome "alias" -$RuntimesDir = Join-Path $UserHome "runtimes" -$GlobalRuntimesDir = Join-Path $GlobalHome "runtimes" -$Aliases = $null - -### Helper Functions -# Remove $HomeEnv from process and user environment. -# Called when current value is invalid or after installing files to default location. -function Clean-HomeEnv { - param([switch]$SkipUserEnvironment) - - if (Test-Path "env:\$HomeEnvVar") { - _WriteOut "Removing Process $HomeEnvVar" - Set-Content "env:\$HomeEnvVar" $null - } - - if (!$SkipUserEnvironment -and [Environment]::GetEnvironmentVariable($HomeEnvVar, "User")) { - _WriteOut "Removing User $HomeEnvVar" - [Environment]::SetEnvironmentVariable($HomeEnvVar, $null, "User") - } -} - -# 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'. " - } -} - -$OSRuntimeDefaults = @{ - "win"="clr"; - "linux"="mono"; - "darwin"="mono"; -} - -$RuntimeBitnessDefaults = @{ - "clr"="x86"; - "coreclr"="x64"; -} - -function GetRuntimeInfo($Architecture, $Runtime, $OS, $Version) { - $runtimeInfo = @{ - "Architecture"="$Architecture"; - "Runtime"="$Runtime"; - "OS"="$OS"; - "Version"="$Version"; - } - - if([String]::IsNullOrEmpty($runtimeInfo.OS)) { - if($runtimeInfo.Runtime -eq "mono"){ - #If OS is empty and you are asking for mono, i.e `dnvm install latest -os mono` then we don't know what OS to pick. It could be Linux or Darwin. - #we could just arbitrarily pick one but it will probably be wrong as often as not. - #If Mono can run on Windows then this error doesn't make sense anymore. - throw "Unable to determine an operating system for a $($runtimeInfo.Runtime) runtime. You must specify which OS to use with the OS parameter." - } - $runtimeInfo.OS = $DefaultOperatingSystem - } - - if($runtimeInfo.OS -eq "osx") { - $runtimeInfo.OS = "darwin" - } - - if([String]::IsNullOrEmpty($runtimeInfo.Runtime)) { - $runtimeInfo.Runtime = $OSRuntimeDefaults.Get_Item($runtimeInfo.OS) - } - - if([String]::IsNullOrEmpty($runtimeInfo.Architecture)) { - $runtimeInfo.Architecture = $RuntimeBitnessDefaults.Get_Item($RuntimeInfo.Runtime) - } - - $runtimeObject = New-Object PSObject -Property $runtimeInfo - - $runtimeObject | Add-Member -MemberType ScriptProperty -Name RuntimeId -Value { - if($this.Runtime -eq "mono") { - "$RuntimePackageName-$($this.Runtime)".ToLowerInvariant() - } else { - "$RuntimePackageName-$($this.Runtime)-$($this.OS)-$($this.Architecture)".ToLowerInvariant() - } - } - - $runtimeObject | Add-Member -MemberType ScriptProperty -Name RuntimeName -Value { - "$($this.RuntimeId).$($this.Version)" - } - - $runtimeObject -} - -function Write-Usage { - _WriteOut -ForegroundColor $ColorScheme.Banner $AsciiArt - _WriteOut "$CommandFriendlyName v$FullVersion" - if(!$Authors.StartsWith("{{")) { - _WriteOut "By $Authors" - } - _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 "" - } - _WriteOut - _WriteOut -NoNewline " To use override feeds, set " - _WriteOut -NoNewLine -ForegroundColor $ColorScheme.Help_Executable "$DefaultFeedKey" - _WriteOut -NoNewline " and " - _WriteOut -NoNewLine -ForegroundColor $ColorScheme.Help_Executable "$DefaultUnstableFeedKey" - _WriteOut -NoNewline " environment keys respectively" - _WriteOut -} - -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 }}, @{label='Orphan';expression={-Not (Test-Path ($RuntimesDir + "\" + (Get-Content $_.FullName)))}}) - } else { - $Aliases = @() - } - } - $Aliases -} - -function IsOnPath { - param($dir) - - $env:Path.Split(';') -icontains $dir -} - -function Get-RuntimeAliasOrRuntimeInfo( - [Parameter(Mandatory=$true)][string]$Version, - [Parameter()][string]$Architecture, - [Parameter()][string]$Runtime, - [Parameter()][string]$OS) { - - $aliasPath = Join-Path $AliasesDir "$Version$AliasExtension" - - if(Test-Path $aliasPath) { - $BaseName = Get-Content $aliasPath - - if(!$Architecture) { - $Architecture = Get-PackageArch $BaseName - } - if(!$Runtime) { - $Runtime = Get-PackageRuntime $BaseName - } - $Version = Get-PackageVersion $BaseName - $OS = Get-PackageOS $BaseName - } - - GetRuntimeInfo $Architecture $Runtime $OS $Version -} - -filter List-Parts { - param($aliases, $items) - - $location = "" - - $binDir = Join-Path $_.FullName "bin" - if ((Test-Path $binDir)) { - $location = $_.Parent.FullName - } - $active = IsOnPath $binDir - - $fullAlias="" - $delim="" - - foreach($alias in $aliases) { - if($_.Name.Split('\', 2) -contains $alias.Name) { - $fullAlias += $delim + $alias.Alias + (&{if($alias.Orphan){" (missing)"}}) - $delim = ", " - } - } - - $parts1 = $_.Name.Split('.', 2) - $parts2 = $parts1[0].Split('-', 4) - - if($parts1[0] -eq "$RuntimePackageName-mono") { - $parts2 += "linux/osx" - $parts2 += "x86/x64" - } - - $aliasUsed = "" - if($items) { - $aliasUsed = $items | ForEach-Object { - if($_.Architecture -eq $parts2[3] -and $_.Runtime -eq $parts2[1] -and $_.OperatingSystem -eq $parts2[2] -and $_.Version -eq $parts1[1]) { - return $true; - } - return $false; - } - } - - if($aliasUsed -eq $true) { - $fullAlias = "" - } - - return New-Object PSObject -Property @{ - Active = $active - Version = $parts1[1] - Runtime = $parts2[1] - OperatingSystem = $parts2[2] - Architecture = $parts2[3] - Location = $location - 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, - [Parameter(Mandatory=$false)][string]$OS) - - # If the first character is non-numeric, it's a full runtime name - if(![Char]::IsDigit($Version[0])) { - $runtimeInfo = GetRuntimeInfo $(Get-PackageArch $Version) $(Get-PackageRuntime $Version) $(Get-PackageOS $Version) $(Get-PackageVersion $Version) - } else { - $runtimeInfo = GetRuntimeInfo $Architecture $Runtime $OS $Version - } - - $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 '$($runtimeInfo.RuntimeName)'" - $runtimeInfo.RuntimeName | 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-Package { - param( - $runtimeInfo, - [string]$Feed, - [string]$Proxy - ) - $url = "$Feed/Packages()?`$filter=Id eq '$($runtimeInfo.RuntimeId)' and Version eq '$($runtimeInfo.Version)'" - Invoke-NuGetWebRequest $runtimeInfo.RuntimeId $url $Proxy -} - -function Find-Latest { - param( - $runtimeInfo, - [Parameter(Mandatory=$true)] - [string]$Feed, - [string]$Proxy - ) - - _WriteOut "Determining latest version" - $RuntimeId = $runtimeInfo.RuntimeId - _WriteDebug "Latest RuntimeId: $RuntimeId" - $url = "$Feed/GetUpdates()?packageIds=%27$RuntimeId%27&versions=%270.0%27&includePrerelease=true&includeAllVersions=false" - Invoke-NuGetWebRequest $RuntimeId $url $Proxy -} - -function Invoke-NuGetWebRequest { - param ( - [string]$RuntimeId, - [string]$Url, - [string]$Proxy - ) - # 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($version) { - $downloadUrl = (Select-Xml "//d:content/@src" -Namespace @{d='http://www.w3.org/2005/Atom'} $xml).Node.value - _WriteDebug "Found $version at $downloadUrl" - @{ Version = $version; DownloadUrl = $downloadUrl } - } else { - throw "There are no runtimes matching the name $RuntimeId on feed $feed." - } -} - -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 Get-PackageOS() { - param( - [string] $runtimeFullName - ) - $runtimeFullName -replace "$RuntimePackageName-[^-]*-([^-]*)-[^.]*.*", '$1' -} - -function Download-Package() { - param( - $runtimeInfo, - [Parameter(Mandatory=$true)] - [string]$DownloadUrl, - [string]$DestinationFile, - [Parameter(Mandatory=$true)] - [string]$Feed, - [string]$Proxy - ) - - _WriteOut "Downloading $($runtimeInfo.RuntimeName) from $feed" - $wc = New-Object System.Net.WebClient - try { - Apply-Proxy $wc -Proxy:$Proxy - _WriteDebug "Downloading $DownloadUrl ..." - - 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($DownloadUrl, $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 $DownloadUrl") ` - -Status ("Downloaded $($Global:downloadData.BytesReceived) of $($Global:downloadData.TotalBytesToReceive) bytes") ` - -PercentComplete $percent -Id 2 -ParentId 1 - } - } - - 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 -Status "Done" -Activity ("Downloading $RuntimeShortFriendlyName from $DownloadUrl") -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]::IsNullOrEmpty($portion)) { - $skip = $portion -eq "" - foreach($removePath in $removePaths) { - if(![string]::IsNullOrEmpty($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]::IsNullOrEmpty($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") -} - -function Get-ScriptRoot() { - if ($PSVersionTable.PSVersion.Major -ge 3) { - return $PSScriptRoot - } - - return Split-Path $script:MyInvocation.MyCommand.Path -Parent -} - -### 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 - - $CurrentScriptRoot = Get-ScriptRoot - $dnvmFile = Join-Path $CurrentScriptRoot "dnvm.ps1" - $tempDnvmFile = Join-Path $CurrentScriptRoot "temp" - $backupFilePath = Join-Path $CurrentScriptRoot "dnvm.ps1.bak" - - $wc.DownloadFile($DNVMUpgradeUrl, $tempDnvmFile) - - if(Test-Path $backupFilePath) { - Remove-Item $backupFilePath -Force - } - - Rename-Item $dnvmFile $backupFilePath - Rename-Item $tempDnvmFile $dnvmFile -} - -<# -.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 - } - if($Host.Version.Major -lt 3) { - $help = Get-Help "dnvm-$Command" - } else { - $help = Get-Help "dnvm-$Command" -ShowWindow:$false - } - if($PassThru -Or $Host.Version.Major -lt 3) { - $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 - Write-Feeds - _WriteOut - _WriteOut -ForegroundColor $ColorScheme.Help_Header "commands: " - Get-Command "$CommandPrefix*" | - ForEach-Object { - if($Host.Version.Major -lt 3) { - $h = Get-Help $_.Name - } else { - $h = Get-Help $_.Name -ShowWindow:$false - } - $name = $_.Name.Substring($CommandPrefix.Length) - if($DeprecatedCommands -notcontains $name) { - _WriteOut -NoNewLine " " - _WriteOut -NoNewLine -ForegroundColor $ColorScheme.Help_Command $name.PadRight($CommandPadding) - _WriteOut " $($h.Synopsis.Trim())" - } - } - } -} - -filter ColorActive { - param([string] $color) - $lines = $_.Split("`n") - foreach($line in $lines) { - if($line.Contains("*")){ - _WriteOut -ForegroundColor $ColorScheme.ActiveRuntime $line - } else { - _WriteOut $line - } - } -} - -<# -.SYNOPSIS - Displays the DNVM version. -#> -function dnvm-version { - _WriteOut "$FullVersion" -} - -<# -.SYNOPSIS - Lists available runtimes -.PARAMETER Detailed - Display more detailed information on each runtime -.PARAMETER PassThru - Set this switch to return unformatted powershell objects for use in scripting -#> -function dnvm-list { - param( - [Parameter(Mandatory=$false)][switch]$PassThru, - [Parameter(Mandatory=$false)][switch]$Detailed) - $aliases = Get-RuntimeAlias - - if(-not $PassThru) { - Check-Runtimes - } - - $items = @() - $RuntimeHomes | ForEach-Object { - _WriteDebug "Scanning $_ for runtimes..." - if (Test-Path "$_\runtimes") { - $items += Get-ChildItem "$_\runtimes\$RuntimePackageName-*" | List-Parts $aliases $items - } - } - - $aliases | Where-Object {$_.Orphan} | ForEach-Object { - $items += $_ | Select-Object @{label='Name';expression={$_.Name}}, @{label='FullName';expression={Join-Path $RuntimesDir $_.Name}} | List-Parts $aliases - } - - if($PassThru) { - $items - } else { - if($items) { - #TODO: Probably a better way to do this. - if($Detailed) { - $items | - Sort-Object Version, Runtime, Architecture, OperatingSystem, Alias | - Format-Table -AutoSize -Property @{name="Active";expression={if($_.Active) { "*" } else { "" }};alignment="center"}, "Version", "Runtime", "Architecture", "OperatingSystem", "Alias", "Location" | Out-String| ColorActive - } else { - $items | - Sort-Object Version, Runtime, Architecture, OperatingSystem, Alias | - Format-Table -AutoSize -Property @{name="Active";expression={if($_.Active) { "*" } else { "" }};alignment="center"}, "Version", "Runtime", "Architecture", "OperatingSystem", "Alias" | Out-String | ColorActive - } - } else { - _WriteOut "No runtimes installed. You can run `dnvm install latest` or `dnvm upgrade` to install a runtime." - } - } -} - -<# -.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 OS - The operating system that the runtime targets -.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. - - NOTE: You cannot create an alias for a non-windows runtime. The intended use case for - an alias to help make it easier to switch the runtime, and you cannot use a non-windows - runtime on a windows machine. -#> -function dnvm-alias { - param( - [Alias("d")] - [switch]$Delete, - - [Parameter(Position=0)] - [string]$Name, - - [Parameter(Position=1)] - [string]$Version, - - [Alias("arch", "a")] - [ValidateSet("", "x86", "x64", "arm")] - [string]$Architecture = "", - - [Alias("r")] - [ValidateSet("", "clr", "coreclr", "mono")] - [Parameter(ParameterSetName="Write")] - [string]$Runtime = "", - - [ValidateSet("win", "osx", "darwin", "linux")] - [Parameter(Mandatory=$false,ParameterSetName="Write")] - [string]$OS = "") - - if($Name -like "help" -or $Name -like "/?") { - #It is unlikely that the user is trying to read an alias called help, so lets just help them out by displaying help text. - #If people need an alias called help or one that contains a `?` then we can change this to a prompt. - dnvm help alias - return - } - - if($Version) { - Write-Alias $Name $Version -Architecture $Architecture -Runtime $Runtime -OS:$OS - } elseif ($Delete) { - Delete-Alias $Name - } else { - Read-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 OS - The operating system that the runtime targets (default: win) -.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 Unstable - Upgrade from the unstable dev feed. This will give you the latest development version of the runtime. -.PARAMETER Global - Installs to configured global dnx file location (default: C:\ProgramData) -#> -function dnvm-upgrade { - param( - [Parameter(Mandatory=$false, Position=0)] - [string]$Alias = "default", - - [Alias("arch", "a")] - [ValidateSet("", "x86", "x64", "arm")] - [Parameter(Mandatory=$false)] - [string]$Architecture = "", - - [Alias("r")] - [ValidateSet("", "clr", "coreclr", "mono")] - [Parameter(Mandatory=$false)] - [string]$Runtime = "", - - [ValidateSet("", "win", "osx", "darwin", "linux")] - [Parameter(Mandatory=$false)] - [string]$OS = "", - - [Alias("f")] - [Parameter(Mandatory=$false)] - [switch]$Force, - - [Parameter(Mandatory=$false)] - [string]$Proxy, - - [Parameter(Mandatory=$false)] - [switch]$NoNative, - - [Parameter(Mandatory=$false)] - [switch]$Ngen, - - [Alias("u")] - [Parameter(Mandatory=$false)] - [switch]$Unstable, - - [Alias("g")] - [Parameter(Mandatory=$false)] - [switch]$Global) - - if($OS -ne "win" -and ![String]::IsNullOrEmpty($OS)) { - #We could remove OS as an option from upgrade, but I want to take this opporunty to educate users about the difference between install and upgrade - #It's possible we should just do install here instead. - _WriteOut -ForegroundColor $ColorScheme.Error "You cannot upgrade to a non-windows runtime. Upgrade will download the latest version of the $RuntimeShortFriendlyName and also set it as your machines default. You cannot set the default $RuntimeShortFriendlyName to a non-windows version because you cannot use it to run an application. If you want to install a non-windows $RuntimeShortFriendlyName to package with your application then use 'dnvm install latest -OS:$OS' instead. Install will download the package but not set it as your default." - $Script:ExitCode = $ExitCodes.OtherError - return - } - - dnvm-install "latest" -Alias:$Alias -Architecture:$Architecture -Runtime:$Runtime -OS:$OS -Force:$Force -Proxy:$Proxy -NoNative:$NoNative -Ngen:$Ngen -Unstable:$Unstable -Persistent:$true -Global:$Global -} - -<# -.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 OS - The operating system that the runtime targets (default: win) -.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 -.PARAMETER Unstable - Upgrade from the unstable dev feed. This will give you the latest development version of the runtime. -.PARAMETER Global - Installs to configured global dnx file location (default: C:\ProgramData) -.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", "a")] - [ValidateSet("", "x86", "x64", "arm")] - [Parameter(Mandatory=$false)] - [string]$Architecture = "", - - [Alias("r")] - [ValidateSet("", "clr", "coreclr", "mono")] - [Parameter(Mandatory=$false)] - [string]$Runtime = "", - - [ValidateSet("", "win", "osx", "darwin", "linux")] - [Parameter(Mandatory=$false)] - [string]$OS = "", - - [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, - - [Alias("p")] - [Parameter(Mandatory=$false)] - [switch]$Persistent, - - [Alias("u")] - [Parameter(Mandatory=$false)] - [switch]$Unstable, - - [Alias("g")] - [Parameter(Mandatory=$false)] - [switch]$Global) - - $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 $DefaultUnstableFeedKey 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 $DefaultFeedKey environment variable ($ActiveFeed)" - } - } - - if(!$VersionNuPkgOrAlias) { - _WriteOut "A version, nupkg path, or the string 'latest' must be provided." - dnvm-help install - $Script:ExitCode = $ExitCodes.InvalidArguments - return - } - - $IsNuPkg = $VersionNuPkgOrAlias.EndsWith(".nupkg") - - if ($IsNuPkg) { - if(!(Test-Path $VersionNuPkgOrAlias)) { - throw "Unable to locate package file: '$VersionNuPkgOrAlias'" - } - 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 - $OS = Get-PackageOS $runtimeFullName - $Version = Get-PackageVersion $runtimeFullName - } else { - $aliasPath = Join-Path $AliasesDir "$VersionNuPkgOrAlias$AliasExtension" - if(Test-Path $aliasPath) { - $BaseName = Get-Content $aliasPath - #Check empty checks let us override a given alias property when installing the same again. e.g. `dnvm install default -x64` - if([String]::IsNullOrEmpty($Architecture)) { - $Architecture = Get-PackageArch $BaseName - } - - if([String]::IsNullOrEmpty($Runtime)) { - $Runtime = Get-PackageRuntime $BaseName - } - - if([String]::IsNullOrEmpty($Version)) { - $Version = Get-PackageVersion $BaseName - } - - if([String]::IsNullOrEmpty($OS)) { - $OS = Get-PackageOS $BaseName - } - } else { - $Version = $VersionNuPkgOrAlias - } - } - - $runtimeInfo = GetRuntimeInfo $Architecture $Runtime $OS $Version - - if (!$IsNuPkg) { - if ($VersionNuPkgOrAlias -eq "latest") { - Write-Progress -Activity "Installing runtime" -Status "Determining latest runtime" -Id 1 - $findPackageResult = Find-Latest -runtimeInfo:$runtimeInfo -Feed:$selectedFeed -Proxy:$Proxy - } - else { - $findPackageResult = Find-Package -runtimeInfo:$runtimeInfo -Feed:$selectedFeed -Proxy:$Proxy - } - $Version = $findPackageResult.Version - } - - #If the version is still empty at this point then VersionOrNupkgOrAlias is an actual version. - if([String]::IsNullOrEmpty($Version)) { - $Version = $VersionNuPkgOrAlias - } - - $runtimeInfo.Version = $Version - - _WriteDebug "Preparing to install runtime '$($runtimeInfo.RuntimeName)'" - _WriteDebug "Architecture: $($runtimeInfo.Architecture)" - _WriteDebug "Runtime: $($runtimeInfo.Runtime)" - _WriteDebug "Version: $($runtimeInfo.Version)" - _WriteDebug "OS: $($runtimeInfo.OS)" - - $installDir = $RuntimesDir - if (!$Global) { - $RuntimeFolder = Join-Path $RuntimesDir $($runtimeInfo.RuntimeName) - } - else { - $installDir = $GlobalRuntimesDir - $RuntimeFolder = Join-Path $GlobalRuntimesDir $($runtimeInfo.RuntimeName) - } - - _WriteDebug "Destination: $RuntimeFolder" - - if((Test-Path $RuntimeFolder) -and $Force) { - _WriteOut "Cleaning existing installation..." - Remove-Item $RuntimeFolder -Recurse -Force - } - - $installed="" - if(Test-Path (Join-Path $RuntimesDir $($runtimeInfo.RuntimeName))) { - $installed = Join-Path $RuntimesDir $($runtimeInfo.RuntimeName) - } - if(Test-Path (Join-Path $GlobalRuntimesDir $($runtimeInfo.RuntimeName))) { - $installed = Join-Path $GlobalRuntimesDir $($runtimeInfo.RuntimeName) - } - if($installed -ne "") { - _WriteOut "'$($runtimeInfo.RuntimeName)' is already installed in $installed." - if($runtimeInfo.OS -eq "win") { - dnvm-use $runtimeInfo.Version -Architecture:$runtimeInfo.Architecture -Runtime:$runtimeInfo.Runtime -Persistent:$Persistent -OS:$runtimeInfo.OS - } - } - else { - - $Architecture = $runtimeInfo.Architecture - $Runtime = $runtimeInfo.Runtime - $OS = $runtimeInfo.OS - - $TempFolder = Join-Path $installDir "temp" - $UnpackFolder = Join-Path $TempFolder $runtimeFullName - $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" -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" -Status "Downloading runtime" -Id 1 - _WriteDebug "Downloading version $($runtimeInfo.Version) to $DownloadFile" - - Download-Package -RuntimeInfo:$runtimeInfo -DownloadUrl:$findPackageResult.DownloadUrl -DestinationFile:$DownloadFile -Proxy:$Proxy -Feed:$selectedFeed - } - - Write-Progress -Activity "Installing runtime" -Status "Unpacking runtime" -Id 1 - Unpack-Package $DownloadFile $UnpackFolder - - if(Test-Path $RuntimeFolder) { - # Ensure the runtime hasn't been installed in the time it took to download the package. - _WriteOut "'$($runtimeInfo.RuntimeName)' is already installed." - } - else { - _WriteOut "Installing to $RuntimeFolder" - _WriteDebug "Moving package contents to $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(Test-Path $(Join-Path $TempFolder "*")) { - Remove-Item $TempFolder -Recurse - } - } - - if($runtimeInfo.OS -eq "win") { - dnvm-use $runtimeInfo.Version -Architecture:$runtimeInfo.Architecture -Runtime:$runtimeInfo.Runtime -Persistent:$Persistent -OS:$runtimeInfo.OS - } - - if ($runtimeInfo.Runtime -eq "clr") { - if (-not $NoNative) { - if ((Is-Elevated) -or $Ngen) { - $runtimeBin = Get-RuntimePath $runtimeInfo.RuntimeName - Write-Progress -Activity "Installing runtime" -Status "Generating runtime native images" -Id 1 - Ngen-Library $runtimeBin $runtimeInfo.Architecture - } - else { - _WriteOut "Native image generation (ngen) is skipped. Include -Ngen switch to turn on native image generation to improve application startup time." - } - } - } - elseif ($runtimeInfo.Runtime -eq "coreclr") { - if ($NoNative -or $runtimeInfo.OS -ne "win") { - _WriteOut "Skipping native image compilation." - } - else { - _WriteOut "Compiling native images for $($runtimeInfo.RuntimeName) 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 - } - else { - Start-Process $crossGenCommand -Wait -NoNewWindow - } - _WriteOut "Finished native image compilation." - } - } - else { - _WriteOut "Unexpected platform: $($runtimeInfo.Runtime). No optimization would be performed on the package installed." - } - } - - if($Alias) { - if($runtimeInfo.OS -eq "win") { - _WriteDebug "Aliasing installed runtime to '$Alias'" - dnvm-alias $Alias $runtimeInfo.Version -Architecture:$RuntimeInfo.Architecture -Runtime:$RuntimeInfo.Runtime -OS:$RuntimeInfo.OS - } else { - _WriteOut "Unable to set an alias for a non-windows runtime. Installing non-windows runtimes on Windows are meant only for publishing, not running." - } - } - - Write-Progress -Status "Done" -Activity "Install complete" -Id 1 -Complete -} - -<# -.SYNOPSIS - Uninstalls a version of the runtime -.PARAMETER VersionOrAlias - The version to uninstall from the current channel or an alias value to uninstall an alternate - runtime or architecture flavor of the specified alias. -.PARAMETER Architecture - The processor architecture of the runtime to uninstall (default: x86) -.PARAMETER Runtime - The runtime flavor to uninstall (default: clr) -.PARAMETER OS - The operating system that the runtime targets (default: win) -#> -function dnvm-uninstall { - param( - [Parameter(Mandatory=$true, Position=0)] - [string]$VersionOrAlias, - - [Alias("arch", "a")] - [ValidateSet("", "x86", "x64", "arm")] - [Parameter(Mandatory=$false)] - [string]$Architecture = "", - - [Alias("r")] - [ValidateSet("", "clr", "coreclr", "mono")] - [Parameter(Mandatory=$false)] - [string]$Runtime = "", - - [ValidateSet("", "win", "osx", "darwin", "linux")] - [Parameter(Mandatory=$false)] - [string]$OS = "") - - $aliasPath = Join-Path $AliasesDir "$VersionOrAlias$AliasExtension" - - if(Test-Path $aliasPath) { - $BaseName = Get-Content $aliasPath - } else { - $Version = $VersionOrAlias - $runtimeInfo = GetRuntimeInfo $Architecture $Runtime $OS $Version - $BaseName = $runtimeInfo.RuntimeName - } - - $runtimeFolder="" - if(Test-Path (Join-Path $RuntimesDir $BaseName)) { - $runtimeFolder = Join-Path $RuntimesDir $BaseName - } - if(Test-Path (Join-Path $GlobalRuntimesDir $BaseName)) { - $runtimeFolder = Join-Path $GlobalRuntimesDir $BaseName - } - - if($runtimeFolder -ne "") { - Remove-Item -literalPath $runtimeFolder -Force -Recurse - _WriteOut "Removed '$($runtimeFolder)'" - } else { - _WriteOut "'$($BaseName)' is not installed" - } - - $aliases = Get-RuntimeAlias - - $result = @($aliases | Where-Object { $_.Name.EndsWith($BaseName) }) - foreach($alias in $result) { - dnvm-alias -Delete -Name $alias.Alias - } -} - -<# -.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 OS - The operating system that the runtime targets (default: win) -.PARAMETER Persistent - Make the change persistent across all processes run by the current user -#> -function dnvm-use { - param( - [Parameter(Mandatory=$true, Position=0)] - [string]$VersionOrAlias, - - [Alias("arch", "a")] - [ValidateSet("", "x86", "x64", "arm")] - [Parameter(Mandatory=$false)] - [string]$Architecture = "", - - [Alias("r")] - [ValidateSet("", "clr", "coreclr")] - [Parameter(Mandatory=$false)] - [string]$Runtime = "", - - [ValidateSet("", "win", "osx", "darwin", "linux")] - [Parameter(Mandatory=$false)] - [string]$OS = "", - - [Alias("p")] - [Parameter(Mandatory=$false)] - [switch]$Persistent) - - 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; - } - - $runtimeInfo = Get-RuntimeAliasOrRuntimeInfo -Version:$VersionOrAlias -Architecture:$Architecture -Runtime:$Runtime -OS:$OS - $runtimeFullName = $runtimeInfo.RuntimeName - $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 - Locates the dnx.exe for the specified version or alias and executes it, providing the remaining arguments to dnx.exe -.PARAMETER VersionOrAlias - The version of alias of the runtime to execute -.PARAMETER Architecture - The processor architecture of the runtime to use (default: x86, or whatever the alias specifies in the case of running an alias) -.PARAMETER Runtime - The runtime flavor of the runtime to use (default: clr, or whatever the alias specifies in the case of running an alias) -.PARAMETER DnxArguments - The arguments to pass to dnx.exe -#> -function dnvm-run { - param( - [Parameter(Mandatory=$true, Position=0)] - [string]$VersionOrAlias, - - [Alias("arch", "a")] - [ValidateSet("", "x86", "x64", "arm")] - [Parameter(Mandatory=$false)] - [string]$Architecture = "", - - [Alias("r")] - [ValidateSet("", "clr", "coreclr")] - [Parameter(Mandatory=$false)] - [string]$Runtime = "", - - [Parameter(Mandatory=$false, Position=1, ValueFromRemainingArguments=$true)] - [object[]]$DnxArguments) - - $runtimeInfo = Get-RuntimeAliasOrRuntimeInfo -Version:$VersionOrAlias -Runtime:$Runtime -Architecture:$Architecture - - $runtimeBin = Get-RuntimePath $runtimeInfo.RuntimeName - if ($runtimeBin -eq $null) { - throw "Cannot find $($runtimeInfo.Name), 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 - $Script:ExitCode = $LASTEXITCODE -} - -<# -.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 Architecture - The processor architecture of the runtime to use (default: x86, or whatever the alias specifies in the case of exec-ing an alias) -.PARAMETER Runtime - The runtime flavor of the runtime to use (default: clr, or whatever the alias specifies in the case of exec-ing an alias) -.PARAMETER Command - The command to execute in the sub-shell -#> -function dnvm-exec { - param( - [Parameter(Mandatory=$true, Position=0)] - [string]$VersionOrAlias, - [Parameter(Mandatory=$false, Position=1)] - [string]$Command, - - [Alias("arch", "a")] - [ValidateSet("", "x86", "x64", "arm")] - [Parameter(Mandatory=$false)] - [string]$Architecture = "", - - [Alias("r")] - [ValidateSet("", "clr", "coreclr")] - [Parameter(Mandatory=$false)] - [string]$Runtime = "", - [Parameter(Mandatory=$false, Position=2, ValueFromRemainingArguments=$true)] - [object[]]$Arguments) - - $runtimeInfo = Get-RuntimeAliasOrRuntimeInfo -Version:$VersionOrAlias -Runtime:$Runtime -Architecture:$Architecture - $runtimeBin = Get-RuntimePath $runtimeInfo.RuntimeName - - if ($runtimeBin -eq $null) { - throw "Cannot find $($runtimeInfo.RuntimeName), do you need to run '$CommandName install $versionOrAlias'?" - } - - $oldPath = $env:PATH - try { - $env:PATH = "$runtimeBin;$($env:PATH)" - & $Command @Arguments - } finally { - $Script:ExitCode = $LASTEXITCODE - $env:PATH = $oldPath - } -} - -<# -.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 = [Environment]::ExpandEnvironmentVariables("$DefaultUserHome") - - # Install scripts - $Destination = "$DestinationHome\bin" - _WriteOut "Installing $CommandFriendlyName to $Destination" - - $ScriptFolder = Split-Path -Parent $ScriptPath - - # 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 = @( - "$DefaultUserHome", - [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 clean up the HomeEnvVar if currently set; script installed to default location. - Clean-HomeEnv($SkipUserEnvironmentInstall) -} - -function Check-Runtimes(){ - $runtimesInstall = $false; - foreach($runtimeHomeDir in $RuntimeHomes) { - if (Test-Path "$runtimeHomeDir\runtimes") { - if(Test-Path "$runtimeHomeDir\runtimes\$RuntimePackageName-*"){ - $runtimesInstall = $true; - break; - } - } - } - - if (-not $runtimesInstall){ - $title = "Getting started" - $message = "It looks like you don't have any runtimes installed. Do you want us to install a $RuntimeShortFriendlyName to get you started?" - - $yes = New-Object System.Management.Automation.Host.ChoiceDescription "&Yes", "Install the latest runtime for you" - - $no = New-Object System.Management.Automation.Host.ChoiceDescription "&No", "Do not install the latest runtime and continue" - - $options = [System.Management.Automation.Host.ChoiceDescription[]]($yes, $no) - - $result = $host.ui.PromptForChoice($title, $message, $options, 0) - - if($result -eq 0){ - dnvm-upgrade - } - } -} - -### 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] - -$cmdargs = @() -if($args.Length -gt 1) { - # Combine arguments, ensuring any containing whitespace or parenthesis are correctly quoted - ForEach ($arg In $args[1..($args.Length-1)]) { - if ($arg -match "[\s\(\)]") { - $cmdargs += """$arg""" - } else { - $cmdargs += $arg - } - $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) { - Check-Runtimes - $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" - Invoke-Command ([ScriptBlock]::Create("dnvm-$cmd $cmdargs")) - } - else { - _WriteOut "Unknown command: '$cmd'" - dnvm-help - $Script:ExitCode = $ExitCodes.UnknownCommand - } -} catch { - throw - if(!$Script:ExitCode) { $Script:ExitCode = $ExitCodes.OtherError } -} - -_WriteDebug "=== End $CommandName (Exit Code $Script:ExitCode) ===" -_WriteDebug "" -exit $Script:ExitCode diff --git a/KoreBuild-dotnet/build/dnvm.sh b/KoreBuild-dotnet/build/dnvm.sh deleted file mode 100644 index ed4523e086..0000000000 --- a/KoreBuild-dotnet/build/dnvm.sh +++ /dev/null @@ -1,1058 +0,0 @@ -# dnvm.sh -# Source this file from your .bash-profile or script to use - -# "Constants" -_DNVM_BUILDNUMBER="rc1-15533" -_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.myget.org/F/aspnetcidev/api/v2" -_DNVM_DEFAULT_UNSTABLE_FEED="https://www.myget.org/F/aspnetcidev/api/v2" -_DNVM_UPDATE_LOCATION="https://raw.githubusercontent.com/aspnet/Home/dev/dnvm.sh" - -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 - return $? -} - -__dnvm_to_lower() { - echo "$1" | tr '[:upper:]' '[:lower:]' -} - -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 - -if [ -z "$DNX_GLOBAL_HOME" ]; then - eval DNX_GLOBAL_HOME="/usr/local/lib/dnx" -fi - -if [ -z "$DNX_HOME" ]; then - # Set to the user home value - eval DNX_HOME="$DNX_USER_HOME:$DNX_GLOBAL_HOME" -elif [[ $DNX_HOME != *"$DNX_GLOBAL_HOME"* ]]; then - eval DNX_HOME="$DNX_HOME:$DNX_GLOBAL_HOME" -fi - -_DNVM_USER_PACKAGES="$DNX_USER_HOME/runtimes" -_DNVM_GLOBAL_PACKAGES="$DNX_GLOBAL_HOME/runtimes" -_DNVM_ALIAS_DIR="$DNX_USER_HOME/alias" -_DNVM_DNVM_DIR="$DNX_USER_HOME/dnvm" - -DNX_ACTIVE_FEED="" - -__dnvm_current_os() -{ - local uname=$(uname) - if [[ $uname == "Darwin" ]]; then - echo "darwin" - else - echo "linux" - fi -} - -__dnvm_os_runtime_defaults() -{ - local os=$1 - - if [[ $os == "win" ]]; then - echo "clr" - elif [[ $os == "linux" ]]; then - echo "mono" - elif [[ $os == "darwin" ]]; then - echo "mono" - else - echo "unknown os" - fi -} - -__dnvm_runtime_bitness_defaults() -{ - local runtime=$1 - if [[ $runtime == "clr" ]]; then - echo "x86" - elif [[ $runtime == "coreclr" ]]; then - echo "x64" - else - echo "unknown runtime" - fi -} - -__dnvm_query_feed() { - local url=$1 - 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/')" - downloadUrl="$(echo $xml | sed 's/.*&2; - return 1 - fi - - 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-$os-$arch" - fi - - local url="$DNX_ACTIVE_FEED/GetUpdates()?packageIds=%27$packageId%27&versions=%270.0%27&includePrerelease=true&includeAllVersions=false" - __dnvm_query_feed $url - return $? -} - -__dnvm_find_package() { - local platform=$1 - local arch=$2 - local os=$3 - local version=$4 - - 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-$os-$arch" - fi - - local url="$DNX_ACTIVE_FEED/Packages()?\$filter=Id%20eq%27$packageId%27%20and%20Version%20eq%20%27$version%27" - __dnvm_query_feed $url - return $? -} - -__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" | sed -e "s#$_DNVM_GLOBAL_PACKAGES/[^/]*$2[^:]*:##g" -e "s#:$_DNVM_GLOBAL_PACKAGES/[^/]*$2[^:]*##g" -e "s#$_DNVM_GLOBAL_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_package_arch() { - local runtimeFullName="$1" - if [[ "$runtimeFullName" =~ $_DNVM_RUNTIME_PACKAGE_NAME-[^-.]*-[^-.]*-[^-.]*\..* ]]; - then - echo "$runtimeFullName" | sed "s/$_DNVM_RUNTIME_PACKAGE_NAME-[^-.]*-[^-.]*-\([^-.]*\)\..*/\1/" - fi -} - -__dnvm_package_os() { - local runtimeFullName="$1" - if [[ "$runtimeFullName" =~ "mono" ]]; then - echo "linux/osx" - else - 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)` - local bashSourceLocation=${BASH_SOURCE} - local scriptLocation=$bashSourceLocation - if [ -z "${bashSourceLocation}" ]; then - local scriptLocation=${(%):-%x} - fi - 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. dnvm is currently sourced from $scriptLocation ${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_promptSudo() { - local acceptSudo="$1" - local sudoMsg="$2" - - local answer= - if [ "$acceptSudo" == "0" ]; then - echo $2 - read -p "You may be prompted for your password via 'sudo' during this process. Is this Ok? (y/N) " answer - else - answer="y" - fi - if echo $answer | grep -iq "^y" ; then - return 1 - else - return 0 - fi -} - -__dnvm_download() { - local runtimeFullName="$1" - local downloadUrl="$2" - local runtimeFolder="$3" - local force="$4" - local acceptSudo="$5" - - local pkgName=$(__dnvm_package_name "$runtimeFullName") - local pkgVersion=$(__dnvm_package_version "$runtimeFullName") - 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 - printf "%b\n" "${Gre}$runtimeFullName already installed. ${RCol}" - return 0 - fi - - if ! __dnvm_has "curl"; then - printf "%b\n" "${Red}$_DNVM_COMMAND_NAME needs curl to proceed. ${RCol}" >&2; - return 1 - fi - - local useSudo= - mkdir -p "$runtimeFolder" > /dev/null 2>&1 - if [ ! -d $runtimeFolder ]; then - if ! __dnvm_promptSudo $acceptSudo "In order to install dnx globally, dnvm will have to temporarily run as root." ; then - useSudo=sudo - sudo mkdir -p "$runtimeFolder" > /dev/null 2>&1 || return 1 - else - return 1 - fi - fi - echo "Downloading $runtimeFullName from $DNX_ACTIVE_FEED" - echo "Download: $downloadUrl" - - local httpResult=$($useSudo curl -L -D - "$downloadUrl" -o "$runtimeFile" -# | grep "^HTTP/1.1" | head -n 1 | sed "s/HTTP.1.1 \([0-9]*\).*/\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 $useSudo - return $? -} - -__dnvm_unpack() { - local runtimeFile="$1" - local runtimeFolder="$2" - local useSudo=$3 - - echo "Installing to $runtimeFolder" - - if ! __dnvm_has "unzip"; then - echo "$_DNVM_COMMAND_NAME needs unzip to proceed." >&2; - return 1 - fi - - $useSudo unzip $runtimeFile -d $runtimeFolder > /dev/null 2>&1 - - [ -e "$runtimeFolder/[Content_Types].xml" ] && $useSudo rm "$runtimeFolder/[Content_Types].xml" - - [ -e "$runtimeFolder/_rels/" ] && $useSudo rm -rf "$runtimeFolder/_rels/" - - [ -e "$runtimeFolder/package/" ] && $useSudo rm -rf "$runtimeFolder/_package/" - - [ -e "$runtimeFile" ] && $useSudo rm -f "$runtimeFile" - - #Set dnx to be executable - if [[ -s "$runtimeFolder/bin/dnx" ]]; then - $useSudo chmod 775 "$runtimeFolder/bin/dnx" - fi - - #Set dnu to be executable - if [[ -s "$runtimeFolder/bin/dnu" ]]; then - $useSudo chmod 775 "$runtimeFolder/bin/dnu" - fi -} - -__dnvm_requested_version_or_alias() { - local versionOrAlias="$1" - local runtime="$2" - local arch="$3" - local os="$4" - 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") - if [[ ! -n "$runtime" && ! -n "$arch" ]]; then - echo "$runtimeFullName" - return - fi - local pkgVersion=$(__dnvm_package_version "$runtimeFullName") - fi - - if [[ ! -n "$pkgVersion" ]]; then - local pkgVersion=$versionOrAlias - fi - local pkgArchitecture="x64" - local pkgSystem=$os - - if [[ -z $runtime || "$runtime" == "mono" ]]; then - echo "$_DNVM_RUNTIME_PACKAGE_NAME-mono.$pkgVersion" - else - if [ "$arch" != "" ]; then - local pkgArchitecture="$arch" - fi - if [ "$os" == "" ]; then - local pkgSystem=$(__dnvm_current_os) - fi - - echo "$_DNVM_RUNTIME_PACKAGE_NAME-$runtime-$pkgSystem-$pkgArchitecture.$pkgVersion" - fi - fi -} - -# This will be more relevant if we support global installs -__dnvm_locate_runtime_bin_from_full_name() { - local runtimeFullName=$1 - for v in `echo $DNX_HOME | tr ":" "\n"`; do - if [ -e "$v/runtimes/$runtimeFullName/bin" ]; then - echo "$v/runtimes/$runtimeFullName/bin" && return - fi - done -} - -__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" - 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_version() { - echo "1.0.0-$_DNVM_BUILDNUMBER" -} - -__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] [-g|-global] [-y]${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|-force 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 feed" - echo " -r|-runtime runtime flavor to install [mono or coreclr] (default: mono)" - echo " -g|-global Installs the latest $_DNVM_RUNTIME_SHORT_NAME in the configured global $_DNVM_RUNTIME_SHORT_NAME file location (default: /usr/local/lib/dnx current: $DNX_GLOBAL_HOME)" - echo " -y Assume Yes to all queries and do not prompt" - echo "" - printf "%b\n" "${Yel}$_DNVM_COMMAND_NAME install |||latest [-r ] [-OS ] [-alias ] [-a|-arch ] [-p|-persistent] [-f|-force] [-u|-unstable] [-g|-global] [-y]${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 " -OS the operating system that the runtime targets (default:$(__dnvm_current_os))" - echo " -alias set alias for requested $_DNVM_RUNTIME_SHORT_NAME on install" - echo " -a|-arch architecture to use (x64)" - 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 feed" - echo " -r|-runtime runtime flavor to install [mono or coreclr] (default: mono)" - echo " -g|-global Installs to the configured global $_DNVM_RUNTIME_SHORT_NAME file location (default: /usr/local/lib/dnx current: $DNX_GLOBAL_HOME)" - echo " -y Assume Yes to all queries and do not prompt" - echo "" - echo " adds $_DNVM_RUNTIME_SHORT_NAME bin to path of current command line" - echo "" - printf "%b\n" "${Yel}$_DNVM_COMMAND_NAME uninstall [-r|-runtime ] [-a|-arch ] [-OS ]${RCol}" - echo " the version to uninstall" - echo " -r|-runtime runtime flavor to uninstall [mono or coreclr] (default: mono)" - echo " -a|-arch architecture to use (x64)" - echo " -OS the operating system that the runtime targets (default:$(__dnvm_current_os))" - echo " -y Assume Yes to all queries and do not prompt" - 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 flavor to use [mono or coreclr] (default: mono)" - 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 " runs the $_DNVM_RUNTIME_SHORT_NAME command from the specified version of the runtime without affecting the current PATH" - echo "" - 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 " 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 "" - printf "%b\n" "${Yel}$_DNVM_COMMAND_NAME list [-detailed]${RCol}" - echo " -detailed display more detailed information on each runtime" - echo "" - echo " list $_DNVM_RUNTIME_SHORT_NAME versions installed " - echo "" - printf "%b\n" "${Yel}$_DNVM_COMMAND_NAME alias ${RCol}" - echo " list $_DNVM_RUNTIME_SHORT_NAME aliases which have been defined" - echo "" - printf "%b\n" "${Yel}$_DNVM_COMMAND_NAME alias ${RCol}" - echo " display value of the specified alias" - echo "" - 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 "" - printf "%b\n" "${Yel}$_DNVM_COMMAND_NAME alias [-d|-delete] ${RCol}" - echo " remove the specified alias" - echo "" - 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 [version|-v|-version|--version] ${RCol}" - echo " print the dnvm version." - echo "" - printf "%b\n" "${Yel}$_DNVM_COMMAND_NAME update-self ${RCol}" - echo " updates dnvm itself." -} - -dnvm() -{ - if [ $# -lt 1 ]; then - __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"|"-h"|"-help"|"--help" ) - __dnvm_help - ;; - - "version"|"-v"|"-version"|"--version" ) - __dnvm_version - ;; - - "update-self" ) - __dnvm_update_self - ;; - - "upgrade" ) - shift - $_DNVM_COMMAND_NAME install latest -p $@ - ;; - - "install" ) - [ $# -lt 2 ] && __dnvm_help && return - shift - local persistent= - local versionOrAlias= - local alias= - local force= - local unstable= - local os= - local runtime= - local arch= - local global=0 - local acceptSudo=0 - while [ $# -ne 0 ] - do - if [[ $1 == "-p" || $1 == "-persistent" ]]; then - local persistent="-p" - elif [[ $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=$(__dnvm_to_lower "$2") - shift - elif [[ $1 == "-OS" ]]; then - local os=$(__dnvm_to_lower "$2") - shift - elif [[ $1 == "-y" ]]; then - local acceptSudo=1 - elif [[ $1 == "-a" || $1 == "-arch" ]]; then - local arch=$(__dnvm_to_lower "$2") - shift - - if [[ $arch != "x86" && $arch != "x64" ]]; then - printf "%b\n" "${Red}Architecture must be x86 or x64.${RCol}" - return 1 - fi - elif [[ $1 == "-g" || $1 == "-global" ]]; then - local global=1 - elif [[ -n $1 ]]; then - [[ -n $versionOrAlias ]] && echo "Invalid option $1" && __dnvm_help && return 1 - local versionOrAlias=$1 - fi - shift - done - - if [[ $arch == "x86" && $runtime == "coreclr" && $os != "win" ]]; then - printf "%b\n" "${Red}Core CLR doesn't currently have a 32 bit build. You must use x64.${RCol}" - return 1 - fi - - 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 [[ -z $os ]]; then - os=$(__dnvm_current_os) - fi - if [[ $os == "osx" ]]; then - os="darwin" - fi - - if [[ -z $runtime ]]; then - runtime=$(__dnvm_os_runtime_defaults "$os") - fi - - if [[ -z $arch ]]; then - arch=$(__dnvm_runtime_bitness_defaults "$runtime") - 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 - - local runtimeDir=$_DNVM_USER_PACKAGES - if [ $global == 1 ]; then - runtimeDir=$_DNVM_GLOBAL_PACKAGES - fi - - if [[ "$versionOrAlias" != *.nupkg ]]; then - if [[ "$versionOrAlias" == "latest" ]]; then - echo "Determining latest version" - read versionOrAlias downloadUrl < <(__dnvm_find_latest "$runtime" "$arch" "$os") - [[ $? == 1 ]] && echo "Error: Could not find latest version from feed $DNX_ACTIVE_FEED" && return 1 - printf "%b\n" "Latest version is ${Cya}$versionOrAlias ${RCol}" - else - local runtimeFullName=$(__dnvm_requested_version_or_alias "$versionOrAlias" "$runtime" "$arch" "$os") - local runtimeVersion=$(__dnvm_package_version "$runtimeFullName") - - read versionOrAlias downloadUrl < <(__dnvm_find_package "$runtime" "$arch" "$os" "$runtimeVersion") - [[ $? == 1 ]] && echo "Error: Could not find version $runtimeVersion in feed $DNX_ACTIVE_FEED" && return 1 - fi - local runtimeFullName=$(__dnvm_requested_version_or_alias "$versionOrAlias" "$runtime" "$arch" "$os") - local runtimeFolder="$runtimeDir/$runtimeFullName" - - local exist=0 - for folder in `echo $DNX_HOME | tr ":" "\n"`; do - if [ -e "$folder/runtimes/$runtimeFullName" ]; then - echo "$runtimeFullName already installed in $folder" - exist=1 - fi - done - - if [[ $exist != 1 ]]; then - __dnvm_download "$runtimeFullName" "$downloadUrl" "$runtimeFolder" "$force" "$acceptSudo" - fi - [[ $? == 1 ]] && return 1 - if [[ "$os" == $(__dnvm_current_os) ]]; then - $_DNVM_COMMAND_NAME use "$versionOrAlias" "$persistent" "-runtime" "$runtime" "-arch" "$arch" - [[ -n $alias ]] && $_DNVM_COMMAND_NAME alias "$alias" "$versionOrAlias" - fi - else - local runtimeFullName=$(basename $versionOrAlias | sed "s/\(.*\)\.nupkg/\1/") - local runtimeVersion=$(__dnvm_package_version "$runtimeFullName") - local runtimeFolder="$runtimeDir/$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 - local useSudo= - mkdir -p "$runtimeFolder" > /dev/null 2>&1 - if [ ! -d $runtimeFolder ]; then - if ! __dnvm_promptSudo $acceptSudo "In order to install dnx globally, dnvm will have to temporarily run as root." ; then - useSudo=sudo - sudo mkdir -p "$runtimeFolder" > /dev/null 2>&1 || return 1 - else - return 1 - fi - fi - cp -a "$versionOrAlias" "$runtimeFile" - __dnvm_unpack "$runtimeFile" "$runtimeFolder" $useSudo - [[ $? == 1 ]] && return 1 - fi - $_DNVM_COMMAND_NAME use "$runtimeVersion" "$persistent" -r "$runtimeClr" - [[ -n $alias ]] && $_DNVM_COMMAND_NAME alias "$alias" "$runtimeVersion" - fi - ;; - - "uninstall" ) - [[ $# -lt 2 ]] && __dnvm_help && return - shift - - local versionOrAlias= - local runtime= - local architecture= - local os= - local acceptSudo=0 - while [ $# -ne 0 ] - do - if [[ $1 == "-r" || $1 == "-runtime" ]]; then - local runtime=$(__dnvm_to_lower "$2") - shift - elif [[ $1 == "-a" || $1 == "-arch" ]]; then - local architecture=$(__dnvm_to_lower "$2") - shift - elif [[ $1 == "-OS" ]]; then - local os=$(__dnvm_to_lower "$2") - shift - elif [[ $1 == "-y" ]]; then - local acceptSudo=1 - elif [[ -n $1 ]]; then - local versionOrAlias=$1 - fi - - shift - done - - if [[ -z $os ]]; then - os=$(__dnvm_current_os) - elif [[ $os == "osx" ]]; then - os="darwin" - fi - - if [[ -z $runtime ]]; then - runtime=$(__dnvm_os_runtime_defaults "$os") - fi - - if [[ -z $architecture ]]; then - architecture=$(__dnvm_runtime_bitness_defaults "$runtime") - fi - - # dnx-coreclr-linux-x64.1.0.0-beta7-12290 - local runtimeFullName=$(__dnvm_requested_version_or_alias "$versionOrAlias" "$runtime" "$architecture" "$os") - - for folder in `echo $DNX_HOME | tr ":" "\n"`; do - if [ -e "$folder/runtimes/$runtimeFullName" ]; then - local runtimeFolder="$folder/runtimes/$runtimeFullName" - fi - done - - if [[ -e $runtimeFolder ]]; then - if [[ $runtimeFolder == *"$DNX_GLOBAL_HOME"* ]] ; then - if ! __dnvm_promptSudo $acceptSudo "In order to uninstall a global dnx, dnvm will have to temporarily run as root." ; then - local useSudo=sudo - fi - fi - $useSudo rm -r $runtimeFolder - echo "Removed $runtimeFolder" - else - echo "$runtimeFolder is not installed" - fi - - if [ -d "$_DNVM_ALIAS_DIR" ]; then - for __dnvm_file in $(find "$_DNVM_ALIAS_DIR" -name *.alias); do - if [ $(cat $__dnvm_file) == "$runtimeFullName" ]; then - rm $__dnvm_file - fi - done - fi - ;; - - "use"|"run"|"exec" ) - [[ $1 == "use" && $# -lt 2 ]] && __dnvm_help && return - - local cmd=$1 - local persistent= - local arch= - local runtime= - - local versionOrAlias= - shift - if [ $cmd == "use" ]; then - while [ $# -ne 0 ] - do - if [[ $1 == "-p" || $1 == "-persistent" ]]; then - local persistent="true" - elif [[ $1 == "-a" || $1 == "-arch" ]]; then - local arch=$(__dnvm_to_lower "$2") - shift - elif [[ $1 == "-r" || $1 == "-runtime" ]]; then - local runtime=$(__dnvm_to_lower "$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 - while [ $# -ne 0 ] - do - if [[ $1 == "-a" || $1 == "-arch" ]]; then - local arch=$(__dnvm_to_lower "$2") - shift - elif [[ $1 == "-r" || $1 == "-runtime" ]]; then - local runtime=$(__dnvm_to_lower "$2") - shift - elif [[ -n $1 ]]; then - [[ -n $versionOrAlias ]] && break - local versionOrAlias=$1 - fi - shift - done - fi - - 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") - - 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" "$runtime" "$arch" "$(__dnvm_current_os)") - 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 - - case $cmd in - "run") - local hostpath="$runtimeBin/dnx" - if [[ -e $hostpath ]]; then - $hostpath $@ - return $? - 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") - $@ - ) - return $? - ;; - "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 9 ]] && __dnvm_help && return - - [[ ! -e "$_DNVM_ALIAS_DIR/" ]] && mkdir "$_DNVM_ALIAS_DIR/" > /dev/null - - if [[ $# == 1 ]]; then - echo "" - local format="%-25s %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 - shift - - if [[ $1 == "-d" || $1 == "-delete" ]]; then - 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 - return - fi - - local name="$1" - - if [[ $# == 1 ]]; then - [[ ! -e "$_DNVM_ALIAS_DIR/$name.alias" ]] && echo "There is no alias called '$name'" && return 1 - cat "$_DNVM_ALIAS_DIR/$name.alias" - echo "" - return - fi - - shift - local versionOrAlias="$1" - shift - while [ $# -ne 0 ] - do - if [[ $1 == "-a" || $1 == "-arch" ]]; then - local arch=$(__dnvm_to_lower "$2") - shift - elif [[ $1 == "-r" || $1 == "-runtime" ]]; then - local runtime=$(__dnvm_to_lower "$2") - shift - elif [[ $1 == "-OS" ]]; then - local os=$(__dnvm_to_lower "$2") - shift - fi - shift - done - - local runtimeFullName=$(__dnvm_requested_version_or_alias "$versionOrAlias" "$runtime" "$arch" "$os") - - ([[ ! -d "$_DNVM_USER_PACKAGES/$runtimeFullName" ]] && [[ ! -d "$_DNVM_GLOBAL_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 - echo "This command has been deprecated. Use '$_DNVM_COMMAND_NAME alias -d' instead" - $_DNVM_COMMAND_NAME alias -d $name - return $? - ;; - - "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-*" - - local runtimes="" - for location in `echo $DNX_HOME | tr ":" "\n"`; do - location+="/runtimes" - if [ -d "$location" ]; then - local oruntimes="$(find $location -name "$searchGlob" \( -type d -or -type l \) -prune -exec basename {} \;)" - for v in `echo $oruntimes | tr "\n" " "`; do - runtimes+="$v:$location"$'\n' - done - fi - done - - [[ -z $runtimes ]] && echo 'No runtimes installed. You can run `dnvm install latest` or `dnvm upgrade` to install a runtime.' && return - - 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 - if [ -d "$_DNVM_ALIAS_DIR" ]; then - for __dnvm_file in $(find "$_DNVM_ALIAS_DIR" -name *.alias); do - if [ ! -d "$_DNVM_USER_PACKAGES/$(cat $__dnvm_file)" ] && [ ! -d "$_DNVM_GLOBAL_PACKAGES/$(cat $__dnvm_file)" ]; then - arr[$i]="$(basename $__dnvm_file | sed 's/\.alias//')/missing/$(cat $__dnvm_file)" - runtimes="$runtimes $(cat $__dnvm_file)" - else - arr[$i]="$(basename $__dnvm_file | sed 's/\.alias//')/$(cat $__dnvm_file)" - fi - let i+=1 - done - fi - - if [[ $2 == "-detailed" ]]; then - # Calculate widest alias - local widestAlias=5 - for f in `echo $runtimes`; do - local pkgName=$(__dnvm_package_name "$f") - local pkgVersion=$(__dnvm_package_version "$f") - local alias="" - local delim="" - for i in "${arr[@]}"; do - if [[ ${i##*/} == "$pkgName.$pkgVersion" ]]; then - alias+="$delim${i%%/*}" - delim=", " - if [[ "${i%/*}" =~ \/missing$ ]]; then - alias+=" (missing)" - fi - fi - done - if [ "${#alias}" -gt "$widestAlias" ]; then - widestAlias=${#alias} - fi - done - local formatString="%-6s %-20s %-7s %-12s %-15s %-${widestAlias}s %s\n" - printf "$formatString" "Active" "Version" "Runtime" "Architecture" "OperatingSystem" "Alias" "Location" - printf "$formatString" "------" "-------" "-------" "------------" "---------------" "-----" "--------" - else - local formatString="%-6s %-20s %-7s %-12s %-15s %s\n" - printf "$formatString" "Active" "Version" "Runtime" "Architecture" "OperatingSystem" "Alias" - printf "$formatString" "------" "-------" "-------" "------------" "---------------" "-----" - fi - - for f in `echo -e "$runtimes" | sort -t. -k2 -k3 -k4 -k1`; do - local location=`echo $f | sed 's/.*\([:]\)//'` - f=`echo $f | sed 's/\([:]\).*//'` - local formattedHome=`(echo $location | sed s=$HOME=~=g)` - local active="" - [[ $PATH == *"$location/$f/bin"* ]] && local active=" *" - 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 pkgOs=$(__dnvm_package_os "$f") - - local alias="" - local delim="" - for i in "${arr[@]}"; do - if [[ ${i##*/} == "$pkgName.$pkgVersion" ]]; then - alias+="$delim${i%%/*}" - delim=", " - if [[ "${i%/*}" =~ \/missing$ ]]; then - alias+=" (missing)" - formattedHome="" - fi - fi - done - - if [[ $2 == "-detailed" ]]; then - printf "$formatString" "$active" "$pkgVersion" "$pkgRuntime" "$pkgArch" "$pkgOs" "$alias" "$formattedHome" - else - printf "$formatString" "$active" "$pkgVersion" "$pkgRuntime" "$pkgArch" "$pkgOs" "$alias" - fi - done - - echo "" - ;; - - *) - echo "Unknown command $1" - return 1 - esac - - return 0 -} - -# Add the home location's bin directory to the path if it doesn't exist -[[ ":$PATH:" != *":$DNX_USER_HOME/bin:"* ]] && export PATH="$DNX_USER_HOME/bin:$PATH" - -# Generate the command function using the constant defined above. -$_DNVM_COMMAND_NAME alias default >/dev/null && $_DNVM_COMMAND_NAME use default >/dev/null || true diff --git a/KoreBuild-dotnet/build/dnvm.cmd b/KoreBuild-dotnet/build/install.cmd similarity index 61% rename from KoreBuild-dotnet/build/dnvm.cmd rename to KoreBuild-dotnet/build/install.cmd index e6da7be9ce..846a9b56fe 100644 --- a/KoreBuild-dotnet/build/dnvm.cmd +++ b/KoreBuild-dotnet/build/install.cmd @@ -1,10 +1,10 @@ @Echo off -for /f "delims=" %%i in ('PowerShell -NoProfile -NoLogo -ExecutionPolicy unrestricted -Command "[System.IO.Path]::GetTempFileName()"') do set DNVM_CMD_PATH_FILE=%%i.cmd +for /f "delims=" %%i in ('PowerShell -NoProfile -NoLogo -ExecutionPolicy unrestricted -Command "[System.IO.Path]::GetTempFileName()"') do set INSTALL_CMD_PATH_FILE="%%i.cmd" -PowerShell -NoProfile -NoLogo -ExecutionPolicy unrestricted -Command "[System.Threading.Thread]::CurrentThread.CurrentCulture = ''; [System.Threading.Thread]::CurrentThread.CurrentUICulture = '';$CmdPathFile='%DNVM_CMD_PATH_FILE%';& '%~dp0dnvm.ps1' %*" +PowerShell -NoProfile -NoLogo -ExecutionPolicy unrestricted -Command "[System.Threading.Thread]::CurrentThread.CurrentCulture = ''; [System.Threading.Thread]::CurrentThread.CurrentUICulture = '';$CmdPathFile='%INSTALL_CMD_PATH_FILE%';& '%~dp0install.ps1' %*" -IF EXIST %DNVM_CMD_PATH_FILE% ( - CALL %DNVM_CMD_PATH_FILE% - DEL %DNVM_CMD_PATH_FILE% +IF EXIST %INSTALL_CMD_PATH_FILE% ( + CALL %INSTALL_CMD_PATH_FILE% + DEL %INSTALL_CMD_PATH_FILE% ) diff --git a/KoreBuild-dotnet/build/install.ps1 b/KoreBuild-dotnet/build/install.ps1 new file mode 100644 index 0000000000..8c187ba5a1 --- /dev/null +++ b/KoreBuild-dotnet/build/install.ps1 @@ -0,0 +1,91 @@ +# +# Copyright (c) .NET Foundation and contributors. All rights reserved. +# Licensed under the MIT license. See LICENSE file in the project root for full license information. +# + +$ErrorActionPreference="Stop" +$ProgressPreference="SilentlyContinue" + +$Feed="https://dotnetcli.blob.core.windows.net/dotnet" +$Channel="dev" +$DotNetFileName="dotnet-win-x64.latest.zip" +$DotNetUrl="$Feed/$Channel/Binaries/Latest" + +function say($str) +{ + Write-Host "dotnet_install: $str" +} + +$InstallDir = $env:DOTNET_INSTALL_DIR +if (!$InstallDir) { + $InstallDir = "$env:LocalAppData\Microsoft\dotnet" +} + +say "Preparing to install .NET Tools to $InstallDir" + +# Check if we need to bother +$LocalFile = "$InstallDir\cli\.version" +if (Test-Path $LocalFile) +{ + $LocalData = @(cat $LocalFile) + $LocalHash = $LocalData[0].Trim() + $LocalVersion = $LocalData[1].Trim() + if ($LocalVersion -and $LocalHash) + { + $RemoteResponse = Invoke-WebRequest -UseBasicParsing "$Feed/$Channel/dnvm/latest.win.version" + $RemoteData = @([Text.Encoding]::UTF8.GetString($RemoteResponse.Content).Split()); + $RemoteHash = $RemoteData[0].Trim() + $RemoteVersion = $RemoteData[1].Trim() + + if (!$RemoteVersion -or !$RemoteHash) { + throw "Invalid response from feed" + } + + say "Latest version: $RemoteVersion" + say "Local Version: $LocalVersion" + + if($LocalHash -eq $RemoteHash) + { + say "You already have the latest version" + exit 0 + } + } +} + +# Set up the install location +if (!(Test-Path $InstallDir)) { + mkdir $InstallDir | Out-Null +} + +# De-powershell the path before passing to .NET APIs +$InstallDir = Convert-Path $InstallDir + +say "Downloading $DotNetFileName from $DotNetUrl" +$resp = Invoke-WebRequest -UseBasicParsing "$DotNetUrl/$DotNetFileName" -OutFile "$InstallDir\$DotNetFileName" + +say "Extracting zip" + +# Create the destination +if (Test-Path "$InstallDir\cli_new") { + del -rec -for "$InstallDir\cli_new" +} +mkdir "$InstallDir\cli_new" | Out-Null + +Add-Type -Assembly System.IO.Compression.FileSystem | Out-Null +[System.IO.Compression.ZipFile]::ExtractToDirectory("$InstallDir\$DotNetFileName", "$InstallDir\cli_new") + +# Replace the old installation (if any) +if (Test-Path "$InstallDir\cli") { + del -rec -for "$InstallDir\cli" +} +mv "$InstallDir\cli_new" "$InstallDir\cli" + +# Clean the zip +if (Test-Path "$InstallDir\$DotNetFileName") { + del -for "$InstallDir\$DotNetFileName" +} + +say "The .NET Tools have been installed to $InstallDir\cli!" + +# New layout +say "Add '$InstallDir\cli\bin' to your PATH to use dotnet" diff --git a/KoreBuild-dotnet/build/install.sh b/KoreBuild-dotnet/build/install.sh new file mode 100644 index 0000000000..5030b9e56d --- /dev/null +++ b/KoreBuild-dotnet/build/install.sh @@ -0,0 +1,262 @@ +#!/usr/bin/env sh +# +# Copyright (c) .NET Foundation and contributors. All rights reserved. +# Licensed under the MIT license. See LICENSE file in the project root for full license information. +# + +# Note: This script should be compatible with the dash shell used in Ubuntu. So avoid bashisms! See https://wiki.ubuntu.com/DashAsBinSh for more info + +# This is a herestring Everything from the line AFTER the "read" until the line containing ONLY "EOF" is part of the string +# The quotes around "EOF" ensure that $ is not interpreted as a variable expansion. The indentation of the herestring must be +# kept exactly consistent +LINK_SCRIPT_CONTENT=$(cat <<-"EOF" +#!/usr/bin/env bash + +SOURCE="${BASH_SOURCE[0]}" +while [ -h "$SOURCE" ]; do # resolve $SOURCE until the file is no longer a symlink + DIR="$( cd -P "$( dirname "$SOURCE" )" && pwd )" + SOURCE="$(readlink "$SOURCE")" + [[ $SOURCE != /* ]] && SOURCE="$DIR/$SOURCE" # if $SOURCE was a relative symlink, we need to resolve it relative to the path where the symlink file was located +done +DIR="$( cd -P "$( dirname "$SOURCE" )" && pwd )" + +if [ -z "$DOTNET_TOOLS" ]; then + # We should be in $PREFIX/bin, so just get the directory above us. + PREFIX="$( cd -P "$DIR/.." && pwd)" + + # The tools are in $PREFIX/share/dotnet/cli by default + DOTNET_TOOLS_DEFAULT=$PREFIX/share/dotnet/cli + + # Check the default location + if [ -d "$DOTNET_TOOLS_DEFAULT" ]; then + export DOTNET_TOOLS=$DOTNET_TOOLS_DEFAULT + else + echo "error: the .NET tools installation appears to be corrupt!" 1>&2 + echo "error: specifically, the tools could not be located in the $DOTNET_TOOLS_DEFAULT directory" 1>&2 + exit 1 + fi +fi + +MY_NAME=$(basename ${BASH_SOURCE[0]}) +MY_TARGET=$DOTNET_TOOLS/bin/$MY_NAME + +if [ ! -e "$MY_TARGET" ]; then + echo "error: the tool $MY_TARGET cannot be found" 1>&2 + exit 1 +fi + +if [ ! -x "$MY_TARGET" ]; then + echo "error: the tool $MY_TARGET is not executable" 1>&2 + exit 1 +fi + +exec "$MY_TARGET" "$@" +EOF +) + +#set default prefix (PREFIX is a fairly standard env-var, but we also want to allow the use the specific "DOTNET_INSTALL_DIR" one) +if [ ! -z "$DOTNET_INSTALL_DIR" ]; then + PREFIX=$DOTNET_INSTALL_DIR +elif [ -z "$PREFIX" ]; then + PREFIX=/usr/local +fi + +#setup some colors to use. These need to work in fairly limited shells, like the Ubuntu Docker container where there are only 8 colors. +#See if stdout is a terminal +if [ -t 1 ]; then + # see if it supports colors + ncolors=$(tput colors) + if [ -n "$ncolors" ] && [ $ncolors -ge 8 ]; then + bold="$(tput bold)" + normal="$(tput sgr0)" + black="$(tput setaf 0)" + red="$(tput setaf 1)" + green="$(tput setaf 2)" + yellow="$(tput setaf 3)" + blue="$(tput setaf 4)" + magenta="$(tput setaf 5)" + cyan="$(tput setaf 6)" + white="$(tput setaf 7)" + fi +fi + +#Standardise OS name to what is put into filenames of the tarballs. +current_os() +{ + local uname=$(uname) + if [ "$uname" = "Darwin" ]; then + echo "osx" + else + echo "linux" + fi +} + +machine_has() { + type "$1" > /dev/null 2>&1 + return $? +} + +#Not 100% sure at the moment that these checks are enough. We might need to take version into account or do something +#more complicated. This seemed like a good beginning though as it should catch the default "clean" machine case and give +#people an appropriate hint. +check_pre_reqs() { + local os=$(current_os) + local _failing=false; + + if [ "$DOTNET_INSTALL_SKIP_PREREQS" = "1" ]; then + return 0 + fi + + if [ "$os" = "linux" ]; then + [ -z "$(ldconfig -p | grep libunwind)" ] && say_err "Unable to locate libunwind. Install libunwind to continue" && _failing=true + [ -z "$(ldconfig -p | grep libssl)" ] && say_err "Unable to locate libssl. Install libssl to continue" && _failing=true + [ -z "$(ldconfig -p | grep libcurl)" ] && say_err "Unable to locate libcurl. Install libcurl to continue" && _failing=true + [ -z "$(ldconfig -p | grep libicu)" ] && say_err "Unable to locate libicu. Install libicu to continue" && _failing=true + [ -z "$(ldconfig -p | grep gettext)" ] && say_err "Unable to locate gettext. Install gettext to continue" && _failing=true + fi + + if [ "$_failing" = true ]; then + return 1 + fi +} + +say_err() { + printf "%b\n" "${red}dotnet_install: Error: $1${normal}" >&2 +} + +say() { + printf "%b\n" "dotnet_install: $1" +} + +make_link() { + local target_name=$1 + local dest=$PREFIX/bin/$target_name + say "Linking $dest -> $PREFIX/share/dotnet/cli/$target_name" + if [ -e $dest ]; then + rm $dest + fi + + [ -d "$PREFIX/bin" ] || mkdir -p $PREFIX/bin + + echo "$LINK_SCRIPT_CONTENT" > $dest + + # Make mode: rwxr-xr-x + chmod 755 $dest +} + +install_dotnet() +{ + if ! machine_has "curl"; then + printf "%b\n" "${red}curl is required to download dotnet. Install curl to proceed. ${normal}" >&2 + return 1 + fi + + say "Preparing to install .NET Tools to $PREFIX" + + if [ -e "$PREFIX/share/dotnet/cli/dotnet" ] && [ ! -w "$PREFIX/share/dotnet/cli/dotnet" ]; then + say_err "dotnet cli is already installed and not writeable. Use 'curl -sSL | sudo sh' to force install." + say_err "If you have previously installed the cli using a package manager or installer then that is why it is write protected, and you need to run sudo to install the new version." + say_err "Alternatively, removing the '$PREFIX/share/dotnet' directory completely before running the script will also resolve the issue." + return 1 + fi + + if ! check_pre_reqs; then + say_err "Ending install due to missing pre-reqs" + return 1; + fi + local os=$(current_os) + local installLocation="$PREFIX/share/dotnet" + local dotnet_url="https://dotnetcli.blob.core.windows.net/dotnet/dev/Binaries/Latest" + local dotnet_filename="dotnet-$os-x64.latest.tar.gz" + + if [ "$RELINK" = "0" ]; then + if [ "$FORCE" = "0" ]; then + # Check if we need to bother + local remoteData="$(curl -s https://dotnetcli.blob.core.windows.net/dotnet/dev/dnvm/latest.$os.version)" + [ $? != 0 ] && say_err "Unable to determine latest version." && return 1 + + local remoteVersion=$(IFS="\n" && echo $remoteData | tail -n 1) + local remoteHash=$(IFS="\n" && echo $remoteData | head -n 1) + + local localVersion=$(tail -n 1 "$installLocation/cli/.version" 2>/dev/null) + [ -z $localVersion ] && localVersion='' + local localHash=$(head -n 1 "$installLocation/cli/.version" 2>/dev/null) + + say "Latest Version: $remoteVersion" + say "Local Version: $localVersion" + + [ "$remoteHash" = "$localHash" ] && say "${green}You already have the latest version.${normal}" && return 0 + fi + + #This should noop if the directory already exists. + mkdir -p $installLocation + + say "Downloading $dotnet_filename from $dotnet_url" + + #Download file and check status code, error and return if we cannot download a cli tar. + local httpResult=$(curl -L -D - "$dotnet_url/$dotnet_filename" -o "$installLocation/$dotnet_filename" -# | grep "^HTTP/1.1" | head -n 1 | sed "s/HTTP.1.1 \([0-9]*\).*/\1/") + [ $httpResult -ne "302" ] && [ $httpResult -ne "200" ] && echo "${Red}HTTP Error $httpResult fetching the dotnet cli from $dotnet_url ${RCol}" && return 1 + + say "Extracting tarball" + #Any of these could fail for various reasons so we will check each one and end the script there if it fails. + rm -rf "$installLocation/cli_new" + mkdir "$installLocation/cli_new" + [ $? != 0 ] && say_err "failed to clean and create temporary cli directory to extract into" && return 1 + + tar -xzf "$installLocation/$dotnet_filename" -C "$installLocation/cli_new" + [ $? != 0 ] && say_err "failed to extract tar" && return 1 + + say "Moving new CLI into install location and symlinking" + + rm -rf "$installLocation/cli" + [ $? != 0 ] && say_err "Failed to clean current dotnet install" && return 1 + + mv "$installLocation/cli_new" "$installLocation/cli" + elif [ ! -e "$installLocation/cli" ]; then + say_err "${red}cannot relink dotnet, it is not installed in $PREFIX!" + return 1 + fi + + for f in $(find "$installLocation/cli" -regex ".*/dotnet[a-z\-]*$") + do + local baseFile=$(basename $f) + make_link $baseFile + done + + if [ -e "$installLocation/$dotnet_filename" ]; then + say "Cleaning $dotnet_filename" + if ! rm "$installLocation/$dotnet_filename"; then + say_err "Failed to delete tar after extracting." + return 1 + fi + fi +} + +FORCE=0 +RELINK=0 +while [ $# -ne 0 ] +do + if [ $1 = "-f" ] || [ $1 = "--force" ]; then + FORCE=1 + elif [ $1 = "-r" ] || [ $1 = "--relink" ]; then + RELINK=1 + elif [ $1 = "-?" ] || [ $1 = "-h" ] || [ $1 = "--help" ]; then + echo ".NET Tools Installer" + echo "" + echo "Usage:" + echo " $0 [-f]" + echo " $0 -r" + echo " $0 -h" + echo "" + echo "Options:" + echo " -f Force reinstallation even if you have the most recent version installed" + echo " -r Don't re-download, just recreate the links in $PREFIX/bin" + echo " -h Show this help message" + echo "" + echo "The PREFIX environment variable can be used to affect the root installation directory" + exit 0 + fi + shift +done + +install_dotnet diff --git a/build-template-dotnet/build.cmd b/build-template-dotnet/build.cmd index 553e3929a0..0ff935f8e9 100644 --- a/build-template-dotnet/build.cmd +++ b/build-template-dotnet/build.cmd @@ -2,6 +2,9 @@ cd %~dp0 SETLOCAL +SET REPO_FOLDER=%CD% +SET DOTNET_INSTALL_DIR=%REPO_FOLDER%\packages + SET NUGET_VERSION=latest SET CACHED_NUGET=%LocalAppData%\NuGet\nuget.%NUGET_VERSION%.exe SET BUILDCMD_KOREBUILD_VERSION= @@ -13,28 +16,27 @@ IF NOT EXIST %LocalAppData%\NuGet md %LocalAppData%\NuGet @powershell -NoProfile -ExecutionPolicy unrestricted -Command "$ProgressPreference = 'SilentlyContinue'; Invoke-WebRequest 'https://dist.nuget.org/win-x86-commandline/%NUGET_VERSION%/nuget.exe' -OutFile '%CACHED_NUGET%'" :copynuget -IF EXIST .nuget\nuget.exe goto restore +IF EXIST .nuget\nuget.exe goto getsake md .nuget copy %CACHED_NUGET% .nuget\nuget.exe > nul -:restore -IF EXIST packages\Sake goto getdnx -IF "%BUILDCMD_KOREBUILD_VERSION%"=="" ( - .nuget\nuget.exe install KoreBuild -ExcludeVersion -o packages -nocache -pre -) ELSE ( - .nuget\nuget.exe install KoreBuild -version %BUILDCMD_KOREBUILD_VERSION% -ExcludeVersion -o packages -nocache -pre -) +:getsake +IF EXIST packages\Sake goto skipgetsake .nuget\NuGet.exe install Sake -ExcludeVersion -Source https://www.nuget.org/api/v2/ -Out packages +:skipgetsake -:getdnx -IF "%BUILDCMD_DNX_VERSION%"=="" ( - SET BUILDCMD_DNX_VERSION=latest -) -IF "%SKIP_DNX_INSTALL%"=="" ( - CALL packages\KoreBuild\build\dnvm install %BUILDCMD_DNX_VERSION% -runtime CoreCLR -arch x86 -alias default - CALL packages\KoreBuild\build\dnvm install default -runtime CLR -arch x86 -alias default +:getkorebuild +IF EXIST packages\KoreBuild-dotnet goto skipgetkorebuild +IF "%BUILDCMD_KOREBUILD_VERSION%"=="" ( + .nuget\nuget.exe install KoreBuild-dotnet -ExcludeVersion -o packages -nocache -pre ) ELSE ( - CALL packages\KoreBuild\build\dnvm use default -runtime CLR -arch x86 + .nuget\nuget.exe install KoreBuild-dotnet -version %BUILDCMD_KOREBUILD_VERSION% -ExcludeVersion -o packages -nocache -pre ) +:skipgetkorebuild -packages\Sake\tools\Sake.exe -I packages\KoreBuild\build -f makefile.shade %* +:getdotnet +SET DOTNET_INSTALL_DIR=packages +CALL packages\KoreBuild-dotnet\build\install.cmd +SET PATH=%DOTNET_INSTALL_DIR%\cli\bin;%PATH% + +packages\Sake\tools\Sake.exe -I packages\KoreBuild-dotnet\build -f makefile.shade %* diff --git a/build-template-dotnet/build.sh b/build-template-dotnet/build.sh index da4e3fcd1c..e5b0e038b3 100644 --- a/build-template-dotnet/build.sh +++ b/build-template-dotnet/build.sh @@ -1,5 +1,15 @@ #!/usr/bin/env bash +SOURCE="${BASH_SOURCE[0]}" +while [ -h "$SOURCE" ]; do # resolve $SOURCE until the file is no longer a symlink + DIR="$( cd -P "$( dirname "$SOURCE" )" && pwd )" + SOURCE="$(readlink "$SOURCE")" + [[ $SOURCE != /* ]] && SOURCE="$DIR/$SOURCE" # if $SOURCE was a relative symlink, we need to resolve it relative to the path where the symlink file was located +done +REPO_FOLDER="$( cd -P "$( dirname "$SOURCE" )" && pwd )" + +export DOTNET_INSTALL_DIR=$REPO_FOLDER/packages/cli + if test `uname` = Darwin; then cachedir=~/Library/Caches/KBuild else @@ -25,19 +35,13 @@ if test ! -e .nuget; then fi if test ! -d packages/Sake; then - mono .nuget/nuget.exe install KoreBuild -ExcludeVersion -o packages -nocache -pre mono .nuget/nuget.exe install Sake -ExcludeVersion -Source https://www.nuget.org/api/v2/ -Out packages fi -if ! type dnvm > /dev/null 2>&1; then - source packages/KoreBuild/build/dnvm.sh +if test ! -d packages/KoreBuild-dotnet; then + mono .nuget/nuget.exe install KoreBuild-dotnet -ExcludeVersion -o packages -nocache -pre fi -if ! type dnx > /dev/null 2>&1 || [ -z "$SKIP_DNX_INSTALL" ]; then - dnvm install latest -runtime coreclr -alias default - dnvm install default -runtime mono -alias default -else - dnvm use default -runtime mono -fi - -mono packages/Sake/tools/Sake.exe -I packages/KoreBuild/build -f makefile.shade "$@" +packages/KoreBuild-dotnet/build/install.sh +export PATH=$DOTNET_INSTALL_DIR/bin/:$PATH +mono packages/Sake/tools/Sake.exe -I packages/KoreBuild-dotnet/build -f makefile.shade "$@"