From 4804b8d9cd8805616c2424b4c698e528a477d9b0 Mon Sep 17 00:00:00 2001 From: Chaojie <42886212+v-chayan@users.noreply.github.com> Date: Fri, 8 May 2020 09:45:21 +0800 Subject: [PATCH] Delete task code that has been moved to the shared framework SDK in Arcade (#35405) * Delete task code that has been moved to the shared framework SDK in Arcade * Remove RegenerateReadmeTable.cs * Revert "Remove RegenerateReadmeTable.cs" This reverts commit 037f425853e5587da95404f07130e36efd6cb2e3. * BuildFPMToolPreReqs.cs is still needed for packaging Linux_x64 --- .../installer.tasks/CopyNupkgAndChangeVersion.cs | 149 --------------- .../installer.tasks/CreateFrameworkListFile.cs | 211 --------------------- .../tasks/installer.tasks/ExecWithRetries.cs | 116 ----------- .../GenerateDebRepoUploadJsonFile.cs | 44 ----- .../installer.tasks/GenerateJsonObjectString.cs | 145 -------------- .../installer.tasks/ProcessSharedFrameworkDeps.cs | 83 -------- .../tasks/installer.tasks/RuntimeGraphManager.cs | 65 ------- .../tasks/installer.tasks/RuntimeReference.cs | 63 ------ .../tasks/installer.tasks/StabilizeWixFileId.cs | 107 ----------- .../installer.tasks/ZipFileExtractToDirectory.cs | 86 --------- .../tasks/installer.tasks/ZipFileGetEntries.cs | 50 ----- 11 files changed, 1119 deletions(-) delete mode 100644 tools-local/tasks/installer.tasks/CopyNupkgAndChangeVersion.cs delete mode 100644 tools-local/tasks/installer.tasks/CreateFrameworkListFile.cs delete mode 100644 tools-local/tasks/installer.tasks/ExecWithRetries.cs delete mode 100644 tools-local/tasks/installer.tasks/GenerateDebRepoUploadJsonFile.cs delete mode 100644 tools-local/tasks/installer.tasks/GenerateJsonObjectString.cs delete mode 100644 tools-local/tasks/installer.tasks/ProcessSharedFrameworkDeps.cs delete mode 100644 tools-local/tasks/installer.tasks/RuntimeGraphManager.cs delete mode 100644 tools-local/tasks/installer.tasks/RuntimeReference.cs delete mode 100644 tools-local/tasks/installer.tasks/StabilizeWixFileId.cs delete mode 100644 tools-local/tasks/installer.tasks/ZipFileExtractToDirectory.cs delete mode 100644 tools-local/tasks/installer.tasks/ZipFileGetEntries.cs diff --git a/tools-local/tasks/installer.tasks/CopyNupkgAndChangeVersion.cs b/tools-local/tasks/installer.tasks/CopyNupkgAndChangeVersion.cs deleted file mode 100644 index 35f7a42..0000000 --- a/tools-local/tasks/installer.tasks/CopyNupkgAndChangeVersion.cs +++ /dev/null @@ -1,149 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using Microsoft.Build.Framework; -using Newtonsoft.Json.Linq; -using NuGet.Versioning; -using System; -using System.IO; -using System.IO.Compression; -using System.Linq; -using System.Xml.Linq; - -namespace Microsoft.DotNet.Build.Tasks -{ - public class CopyNupkgAndChangeVersion : BuildTask - { - [Required] - public string SourceFile { get; set; } - - [Required] - public string TargetFile { get; set; } - - [Required] - public string OriginalVersion { get; set; } - - [Required] - public string TargetVersion { get; set; } - - public string[] DependencyPackageIdsToChange { get; set; } - - public override bool Execute() - { - Directory.CreateDirectory(Path.GetDirectoryName(TargetFile)); - File.Copy(SourceFile, TargetFile, true); - - using (ZipArchive zip = ZipFile.Open(TargetFile, ZipArchiveMode.Update)) - { - RewriteNuspec(zip); - RewriteRuntimeJson(zip); - } - - return !Log.HasLoggedErrors; - } - - private void RewriteNuspec(ZipArchive zip) - { - foreach (var nuspec in zip.Entries.Where(e => e.FullName.EndsWith(".nuspec"))) - { - Rewrite(nuspec, s => - { - XDocument content = XDocument.Parse(s); - - RewriteNuspecPackageVersion(content); - RewriteNuspecDependencyVersions(content); - - return content.ToString(); - }); - } - } - - private void RewriteRuntimeJson(ZipArchive zip) - { - foreach (var runtimeJson in zip.Entries.Where(e => e.FullName == "runtime.json")) - { - Rewrite(runtimeJson, s => - { - JObject content = JObject.Parse(s); - - RewriteRuntimeJsonVersions(content); - - return content.ToString(); - }); - } - } - - private void RewriteNuspecPackageVersion(XDocument content) - { - XElement versionElement = content - .Element(CreateQualifiedName(content, "package")) - .Element(CreateQualifiedName(content, "metadata")) - .Element(CreateQualifiedName(content, "version")); - - if (versionElement.Value != OriginalVersion) - { - Log.LogError( - $"Original version is '{versionElement.Value}', " + - $"expected '{OriginalVersion}'"); - } - - versionElement.Value = TargetVersion; - } - - private void RewriteNuspecDependencyVersions(XDocument content) - { - foreach (var dependency in content - .Descendants(CreateQualifiedName(content, "dependency")) - .Where(x => - x.Attribute("version").Value == OriginalVersion && - DependencyPackageIdsToChange?.Contains(x.Attribute("id").Value) == true)) - { - dependency.Value = TargetVersion; - } - } - - private void RewriteRuntimeJsonVersions(JObject content) - { - var versionProperties = content - .Descendants() - .OfType() - .Where(p => - p.Value is JValue v && - v.Type == JTokenType.String); - - foreach (var p in versionProperties) - { - var range = VersionRange.Parse(p.Value.Value()); - - if (range.MinVersion.OriginalVersion == OriginalVersion) - { - var newRange = new VersionRange( - NuGetVersion.Parse(TargetVersion), - range.Float); - - p.Value = newRange.ToString(); - } - } - } - - private static XName CreateQualifiedName(XDocument doc, string name) - { - return doc.Root.GetDefaultNamespace().GetName(name); - } - - private static void Rewrite(ZipArchiveEntry entry, Func rewrite) - { - using (var stream = entry.Open()) - using (var reader = new StreamReader(stream)) - using (var writer = new StreamWriter(stream)) - { - var content = rewrite(reader.ReadToEnd()); - - stream.Position = 0; - stream.SetLength(0); - writer.Write(content); - } - } - } -} diff --git a/tools-local/tasks/installer.tasks/CreateFrameworkListFile.cs b/tools-local/tasks/installer.tasks/CreateFrameworkListFile.cs deleted file mode 100644 index 36a3dd5..0000000 --- a/tools-local/tasks/installer.tasks/CreateFrameworkListFile.cs +++ /dev/null @@ -1,211 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using Microsoft.Build.Framework; -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Xml.Linq; - -namespace Microsoft.DotNet.Build.Tasks -{ - public class CreateFrameworkListFile : BuildTask - { - /// - /// Files to extract basic information from and include in the list. - /// - [Required] - public ITaskItem[] Files { get; set; } - - /// - /// A list of assembly names with classification info such as Profile. A - /// Profile="%(Profile)" attribute is included in the framework list for the matching Files - /// item if %(Profile) contains text. - /// - /// If *any* FileClassifications are passed: - /// - /// *Every* file that ends up listed in the framework list must have a matching - /// FileClassification. - /// - /// Additionally, every FileClassification must find exactly one File. - /// - /// This task fails if the conditions aren't met. This ensures the classification doesn't - /// become out of date when the list of files changes. - /// - /// %(Identity): Assembly name (including ".dll"). - /// %(Profile): List of profiles that apply, semicolon-delimited. - /// %(ReferencedByDefault): Empty (default) or "true"/"false". Indicates whether this file - /// should be referenced by default when the SDK uses this framework. - /// - public ITaskItem[] FileClassifications { get; set; } - - [Required] - public string TargetFile { get; set; } - - public string[] TargetFilePrefixes { get; set; } - - /// - /// Extra attributes to place on the root node. - /// - /// %(Identity): Attribute name. - /// %(Value): Attribute value. - /// - public ITaskItem[] RootAttributes { get; set; } - - public override bool Execute() - { - XAttribute[] rootAttributes = RootAttributes - ?.Select(item => new XAttribute(item.ItemSpec, item.GetMetadata("Value"))) - .ToArray(); - - var frameworkManifest = new XElement("FileList", rootAttributes); - - Dictionary fileClassLookup = FileClassifications - ?.ToDictionary( - item => item.ItemSpec, - item => item, - StringComparer.OrdinalIgnoreCase); - - var usedFileClasses = new HashSet(); - - foreach (var f in Files - .Where(IsTargetPathIncluded) - .Select(item => new - { - Item = item, - Filename = Path.GetFileName(item.ItemSpec), - TargetPath = item.GetMetadata("TargetPath"), - AssemblyName = FileUtilities.GetAssemblyName(item.ItemSpec), - FileVersion = FileUtilities.GetFileVersion(item.ItemSpec), - IsNative = item.GetMetadata("IsNative") == "true", - IsSymbolFile = item.GetMetadata("IsSymbolFile") == "true", - IsResourceFile = item.ItemSpec - .EndsWith(".resources.dll", StringComparison.OrdinalIgnoreCase) - }) - .Where(f => - !f.IsSymbolFile && - (f.Filename.EndsWith(".dll", StringComparison.OrdinalIgnoreCase) || f.IsNative)) - // Remove duplicate files this task is given. - .GroupBy(f => f.Item.ItemSpec) - .Select(g => g.First()) - // Make order stable between builds. - .OrderBy(f => f.TargetPath, StringComparer.Ordinal) - .ThenBy(f => f.Filename, StringComparer.Ordinal)) - { - string type = "Managed"; - - if (f.IsNative) - { - type = "Native"; - } - else if (f.IsResourceFile) - { - type = "Resources"; - } - - string path = Path.Combine(f.TargetPath, f.Filename).Replace('\\', '/'); - - if (path.StartsWith("runtimes/")) - { - var pathParts = path.Split('/'); - if (pathParts.Length > 1 && pathParts[1].Contains("_")) - { - // This file is a runtime file with a "rid" containing "_". This is assumed - // to mean it's a cross-targeting tool and shouldn't be deployed in a - // self-contained app. Leave it off the list. - continue; - } - } - - var element = new XElement( - "File", - new XAttribute("Type", type), - new XAttribute("Path", path)); - - if (f.IsResourceFile) - { - element.Add( - new XAttribute("Culture", Path.GetFileName(Path.GetDirectoryName(path)))); - } - - if (f.AssemblyName != null) - { - byte[] publicKeyToken = f.AssemblyName.GetPublicKeyToken(); - string publicKeyTokenHex; - - if (publicKeyToken != null) - { - publicKeyTokenHex = BitConverter.ToString(publicKeyToken) - .ToLowerInvariant() - .Replace("-", ""); - } - else - { - Log.LogError($"No public key token found for assembly {f.Item.ItemSpec}"); - publicKeyTokenHex = ""; - } - - element.Add( - new XAttribute("AssemblyName", f.AssemblyName.Name), - new XAttribute("PublicKeyToken", publicKeyTokenHex), - new XAttribute("AssemblyVersion", f.AssemblyName.Version)); - } - else if (!f.IsNative) - { - // This file isn't managed and isn't native. Leave it off the list. - continue; - } - - element.Add(new XAttribute("FileVersion", f.FileVersion)); - - if (fileClassLookup != null) - { - if (fileClassLookup.TryGetValue(f.Filename, out ITaskItem classItem)) - { - string profile = classItem.GetMetadata("Profile"); - - if (!string.IsNullOrEmpty(profile)) - { - element.Add(new XAttribute("Profile", profile)); - } - - string referencedByDefault = classItem.GetMetadata("ReferencedByDefault"); - - if (!string.IsNullOrEmpty(referencedByDefault)) - { - element.Add(new XAttribute("ReferencedByDefault", referencedByDefault)); - } - - usedFileClasses.Add(f.Filename); - } - else - { - Log.LogError($"File matches no classification: {f.Filename}"); - } - } - - frameworkManifest.Add(element); - } - - foreach (var unused in fileClassLookup - ?.Keys.Except(usedFileClasses).OrderBy(p => p) - ?? Enumerable.Empty()) - { - Log.LogError($"Classification matches no files: {unused}"); - } - - Directory.CreateDirectory(Path.GetDirectoryName(TargetFile)); - File.WriteAllText(TargetFile, frameworkManifest.ToString()); - - return !Log.HasLoggedErrors; - } - - private bool IsTargetPathIncluded(ITaskItem item) - { - return TargetFilePrefixes - ?.Any(prefix => item.GetMetadata("TargetPath")?.StartsWith(prefix) == true) ?? true; - } - } -} diff --git a/tools-local/tasks/installer.tasks/ExecWithRetries.cs b/tools-local/tasks/installer.tasks/ExecWithRetries.cs deleted file mode 100644 index 5e57c39..0000000 --- a/tools-local/tasks/installer.tasks/ExecWithRetries.cs +++ /dev/null @@ -1,116 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -// Initially copied from https://github.com/dotnet/buildtools/blob/6736870b84e06b75e7df32bb84d442db1b2afa10/src/Microsoft.DotNet.Build.Tasks/ExecWithRetries.cs - -using Microsoft.Build.Framework; -using Microsoft.Build.Tasks; -using System; -using System.Threading; -using System.Threading.Tasks; - -namespace Microsoft.DotNet.Build.Tasks -{ - /// - /// Run a command and retry if the exit code is not 0. - /// - public class ExecWithRetries : BuildTask - { - [Required] - public string Command { get; set; } - - public string WorkingDirectory { get; set; } - - public bool IgnoreStandardErrorWarningFormat { get; set; } - - public int MaxAttempts { get; set; } = 5; - - /// - /// Base, in seconds, raised to the power of the number of retries so far. - /// - public double RetryDelayBase { get; set; } = 6; - - /// - /// A constant, in seconds, added to (base^retries) to find the delay before retrying. - /// - /// The default is -1 to make the first retry instant, because ((base^0)-1) == 0. - /// - public double RetryDelayConstant { get; set; } = -1; - - /// - /// MSBuild message importance to use when logging stdout messages from the command. Default - /// is "High". - /// - public string StandardOutputImportance { get; set; } - - /// - /// MSBuild message importance to use when logging stderr messages from the command. Default - /// is "High". - /// - public string StandardErrorImportance { get; set; } - - private CancellationTokenSource _cancelTokenSource = new CancellationTokenSource(); - - private Exec _runningExec; - - public void Cancel() - { - _runningExec?.Cancel(); - _cancelTokenSource.Cancel(); - } - - public override bool Execute() - { - for (int i = 0; i < MaxAttempts; i++) - { - _runningExec = new Exec - { - BuildEngine = BuildEngine, - Command = Command, - WorkingDirectory = WorkingDirectory, - IgnoreStandardErrorWarningFormat = IgnoreStandardErrorWarningFormat, - StandardOutputImportance = StandardOutputImportance, - StandardErrorImportance = StandardErrorImportance, - LogStandardErrorAsError = false, - IgnoreExitCode = true - }; - - if (!_runningExec.Execute()) - { - Log.LogError("Child Exec task failed to execute."); - break; - } - - int exitCode = _runningExec.ExitCode; - if (exitCode == 0) - { - return true; - } - - string message = $"Exec FAILED: exit code {exitCode} (attempt {i + 1}/{MaxAttempts})"; - - if (i + 1 == MaxAttempts || _cancelTokenSource.IsCancellationRequested) - { - Log.LogError(message); - break; - } - - TimeSpan delay = TimeSpan.FromSeconds( - Math.Pow(RetryDelayBase, i) + RetryDelayConstant); - - Log.LogMessage(MessageImportance.High, $"{message} -- Retrying after {delay}..."); - - try - { - Task.Delay(delay, _cancelTokenSource.Token).Wait(); - } - catch (AggregateException e) when (e.InnerException is TaskCanceledException) - { - break; - } - } - return false; - } - } -} diff --git a/tools-local/tasks/installer.tasks/GenerateDebRepoUploadJsonFile.cs b/tools-local/tasks/installer.tasks/GenerateDebRepoUploadJsonFile.cs deleted file mode 100644 index 51e3739..0000000 --- a/tools-local/tasks/installer.tasks/GenerateDebRepoUploadJsonFile.cs +++ /dev/null @@ -1,44 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using Microsoft.Build.Framework; -using System.IO; - - -namespace Microsoft.DotNet.Build.Tasks -{ - public partial class GenerateDebRepoUploadJsonFile : BuildTask - { - private const string _debianRevisionNumber = "1"; - [Required] - public string RepoId { get; set; } - [Required] - public string UploadJsonFilename { get; set; } - [Required] - public string PackageName { get; set; } - [Required] - public string PackageVersion { get; set; } - [Required] - public string UploadUrl { get; set; } - - public override bool Execute() - { - File.Delete(UploadJsonFilename); - - using (var fileStream = File.Create(UploadJsonFilename)) - { - using (StreamWriter sw = new StreamWriter(fileStream)) - { - sw.WriteLine("{"); - sw.WriteLine($" \"name\":\"{PackageName}\","); - sw.WriteLine($" \"version\":\"{PackageVersion}-{_debianRevisionNumber}\","); - sw.WriteLine($" \"repositoryId\":\"{RepoId}\","); - sw.WriteLine($" \"sourceUrl\":\"{UploadUrl}\""); - sw.WriteLine("}"); - } - } - return !Log.HasLoggedErrors; - } - } -} \ No newline at end of file diff --git a/tools-local/tasks/installer.tasks/GenerateJsonObjectString.cs b/tools-local/tasks/installer.tasks/GenerateJsonObjectString.cs deleted file mode 100644 index 558c4b1..0000000 --- a/tools-local/tasks/installer.tasks/GenerateJsonObjectString.cs +++ /dev/null @@ -1,145 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using Microsoft.Build.Framework; -using System; -using System.IO; -using System.Linq; -using System.Text; - -namespace Microsoft.DotNet.Build.Tasks -{ - public class GenerateJsonObjectString : BuildTask - { - private static readonly string __indent1 = new string(' ', 4); - private static readonly string __indent2 = new string(' ', 8); - - /// - /// Properties to include. If multiple properties have the same name, each property value is - /// included in an array. Only specify one value metadata: the first value is used. - /// - /// %(Identity): Name of the property. - /// %(String): String value of the property. This task adds quotes around it in the JSON. - /// %(Object): Object value of the property. Create this with a nested call to this task. - /// - [Required] - public ITaskItem[] Properties { get; set; } - - /// - /// If set, also write the output JSON string to this file. - /// - public string TargetFile { get; set; } - - [Output] - public string Json { get; set; } - - public override bool Execute() - { - var result = new StringBuilder(); - result.AppendLine("{"); - - bool firstProperty = true; - - foreach (var group in Properties.GroupBy(item => item.ItemSpec)) - { - if (firstProperty) - { - firstProperty = false; - } - else - { - result.AppendLine(","); - } - - result.Append(__indent1); - result.Append("\""); - result.Append(group.Key); - result.Append("\": "); - - if (group.Count() == 1) - { - ITaskItem item = group.First(); - WriteProperty(result, item, __indent1); - } - else - { - result.AppendLine("["); - - bool firstArrayLine = true; - - foreach (ITaskItem item in group) - { - if (firstArrayLine) - { - firstArrayLine = false; - } - else - { - result.AppendLine(","); - } - - result.Append(__indent2); - WriteProperty(result, item, __indent2); - } - - result.AppendLine(); - result.Append(__indent1); - result.Append("]"); - } - } - - result.AppendLine(); - result.AppendLine("}"); - - Json = result.ToString(); - - if (!string.IsNullOrEmpty(TargetFile)) - { - Directory.CreateDirectory(Path.GetDirectoryName(TargetFile)); - File.WriteAllText(TargetFile, Json); - } - - return !Log.HasLoggedErrors; - } - - private void WriteProperty(StringBuilder result, ITaskItem item, string indent) - { - string stringValue = item.GetMetadata("String"); - string objectValue = item.GetMetadata("Object"); - - if (!string.IsNullOrEmpty(stringValue)) - { - result.Append("\""); - result.Append(stringValue); - result.Append("\""); - } - else if (!string.IsNullOrEmpty(objectValue)) - { - bool firstObjectLine = true; - - foreach (var line in objectValue.Split( - new[] {Environment.NewLine}, - StringSplitOptions.RemoveEmptyEntries)) - { - if (firstObjectLine) - { - firstObjectLine = false; - } - else - { - result.AppendLine(); - result.Append(indent); - } - - result.Append(line); - } - } - else - { - Log.LogError($"Item '{item.ItemSpec}' has no String or Object value."); - result.Append("null"); - } - } - } -} diff --git a/tools-local/tasks/installer.tasks/ProcessSharedFrameworkDeps.cs b/tools-local/tasks/installer.tasks/ProcessSharedFrameworkDeps.cs deleted file mode 100644 index 687a8c1..0000000 --- a/tools-local/tasks/installer.tasks/ProcessSharedFrameworkDeps.cs +++ /dev/null @@ -1,83 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using Microsoft.Build.Framework; -using Microsoft.Build.Utilities; -using Microsoft.Extensions.DependencyModel; -using NuGet.Common; -using NuGet.ProjectModel; -using System; -using System.IO; -using System.Linq; - -namespace Microsoft.DotNet.Build.Tasks -{ - public partial class ProcessSharedFrameworkDeps : Task - { - [Required] - public string AssetsFilePath { get; set; } - - [Required] - public string DepsFilePath { get; set; } - - [Required] - public string[] PackagesToRemove { get; set; } - - [Required] - public string Runtime { get; set; } - - [Required] - public string BuildTasksAssemblyPath { get; set; } - - public override bool Execute() - { - EnsureInitialized(BuildTasksAssemblyPath); - - ExecuteCore(); - - return true; - } - - private void ExecuteCore() - { - DependencyContext context; - using (var depsStream = File.OpenRead(DepsFilePath)) - { - context = new DependencyContextJsonReader().Read(depsStream); - } - - LockFile lockFile = LockFileUtilities.GetLockFile(AssetsFilePath, NullLogger.Instance); - if (lockFile == null) - { - throw new ArgumentException($"Could not load a LockFile at '{AssetsFilePath}'.", nameof(AssetsFilePath)); - } - - var manager = new RuntimeGraphManager(); - var graph = manager.Collect(lockFile); - var expandedGraph = manager.Expand(graph, Runtime); - - var trimmedRuntimeLibraries = context.RuntimeLibraries; - - if (PackagesToRemove != null && PackagesToRemove.Any()) - { - trimmedRuntimeLibraries = RuntimeReference.RemoveReferences(context.RuntimeLibraries, PackagesToRemove); - } - - context = new DependencyContext( - context.Target, - context.CompilationOptions, - context.CompileLibraries, - trimmedRuntimeLibraries, - expandedGraph - ); - - using (var depsStream = File.Create(DepsFilePath)) - { - new DependencyContextWriter().Write(context, depsStream); - } - } - - partial void EnsureInitialized(string buildTasksAssemblyPath); - } -} diff --git a/tools-local/tasks/installer.tasks/RuntimeGraphManager.cs b/tools-local/tasks/installer.tasks/RuntimeGraphManager.cs deleted file mode 100644 index 2bedeef..0000000 --- a/tools-local/tasks/installer.tasks/RuntimeGraphManager.cs +++ /dev/null @@ -1,65 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using Microsoft.Extensions.DependencyModel; -using NuGet.Packaging; -using NuGet.ProjectModel; -using NuGet.RuntimeModel; -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; - -namespace Microsoft.DotNet.Build.Tasks -{ - internal class RuntimeGraphManager - { - private const string RuntimeJsonFileName = "runtime.json"; - - public RuntimeGraph Collect(LockFile lockFile) - { - string userPackageFolder = lockFile.PackageFolders.FirstOrDefault()?.Path; - var fallBackFolders = lockFile.PackageFolders.Skip(1).Select(f => f.Path); - var packageResolver = new FallbackPackagePathResolver(userPackageFolder, fallBackFolders); - - var graph = RuntimeGraph.Empty; - foreach (var library in lockFile.Libraries) - { - if (string.Equals(library.Type, "package", StringComparison.OrdinalIgnoreCase)) - { - var runtimeJson = library.Files.FirstOrDefault(f => f == RuntimeJsonFileName); - if (runtimeJson != null) - { - var libraryPath = packageResolver.GetPackageDirectory(library.Name, library.Version); - var runtimeJsonFullName = Path.Combine(libraryPath, runtimeJson); - graph = RuntimeGraph.Merge(graph, JsonRuntimeFormat.ReadRuntimeGraph(runtimeJsonFullName)); - } - } - } - return graph; - } - - public IEnumerable Expand(RuntimeGraph runtimeGraph, string runtime) - { - var importers = FindImporters(runtimeGraph, runtime); - foreach (var importer in importers) - { - // ExpandRuntime return runtime itself as first item so we are skiping it - yield return new RuntimeFallbacks(importer, runtimeGraph.ExpandRuntime(importer).Skip(1)); - } - } - - private IEnumerable FindImporters(RuntimeGraph runtimeGraph, string runtime) - { - foreach (var runtimePair in runtimeGraph.Runtimes) - { - var expanded = runtimeGraph.ExpandRuntime(runtimePair.Key); - if (expanded.Contains(runtime)) - { - yield return runtimePair.Key; - } - } - } - } -} diff --git a/tools-local/tasks/installer.tasks/RuntimeReference.cs b/tools-local/tasks/installer.tasks/RuntimeReference.cs deleted file mode 100644 index ead20e8..0000000 --- a/tools-local/tasks/installer.tasks/RuntimeReference.cs +++ /dev/null @@ -1,63 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using Microsoft.Extensions.DependencyModel; -using System; -using System.Collections.Generic; -using System.Linq; - -namespace Microsoft.DotNet.Build.Tasks -{ - internal class RuntimeReference - { - public static List RemoveReferences(IReadOnlyList runtimeLibraries, IEnumerable packages) - { - List result = new List(); - - foreach (var runtimeLib in runtimeLibraries) - { - if (string.IsNullOrEmpty(packages.FirstOrDefault(elem => runtimeLib.Name.Equals(elem, StringComparison.OrdinalIgnoreCase)))) - { - List toRemoveDependecy = new List(); - foreach (var dependency in runtimeLib.Dependencies) - { - if (!string.IsNullOrEmpty(packages.FirstOrDefault(elem => dependency.Name.Equals(elem, StringComparison.OrdinalIgnoreCase)))) - { - toRemoveDependecy.Add(dependency); - } - } - - if (toRemoveDependecy.Count > 0) - { - List modifiedDependencies = new List(); - foreach (var dependency in runtimeLib.Dependencies) - { - if (!toRemoveDependecy.Contains(dependency)) - { - modifiedDependencies.Add(dependency); - } - } - - - result.Add(new RuntimeLibrary(runtimeLib.Type, - runtimeLib.Name, - runtimeLib.Version, - runtimeLib.Hash, - runtimeLib.RuntimeAssemblyGroups, - runtimeLib.NativeLibraryGroups, - runtimeLib.ResourceAssemblies, - modifiedDependencies, - runtimeLib.Serviceable)); - - } - else if (string.IsNullOrEmpty(packages.FirstOrDefault(elem => runtimeLib.Name.Equals(elem, StringComparison.OrdinalIgnoreCase)))) - { - result.Add(runtimeLib); - } - } - } - return result; - } - } -} diff --git a/tools-local/tasks/installer.tasks/StabilizeWixFileId.cs b/tools-local/tasks/installer.tasks/StabilizeWixFileId.cs deleted file mode 100644 index 6a76df1..0000000 --- a/tools-local/tasks/installer.tasks/StabilizeWixFileId.cs +++ /dev/null @@ -1,107 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using Microsoft.Build.Framework; -using System; -using System.Diagnostics; -using System.Linq; -using System.Xml.Linq; - -namespace Microsoft.DotNet.Build.Tasks -{ - /// - /// In a WiX source file, replaces the Id of a File with some given string in order to stabilize - /// it. This allows external tooling such as signature validators to rely on a stable identifier - /// for certain files. - /// - public class StabilizeWixFileId : BuildTask - { - /// - /// File to read from. This is expected to be an output from heat.exe. - /// - /// Expected format: - /// - /// - /// - /// - /// - /// - /// - /// ... - /// - [Required] - public string SourceFile { get; set; } - - /// - /// File to write to. May be the same as SourceFile. - /// - [Required] - public string OutputFile { get; set; } - - /// - /// Set of files to stabilize. This matches the end of the "Source" attribute in the WiX - /// source file. If exactly one match isn't found in the WiX source file, this task fails. - /// - /// %(Identity): The file source to replace. - /// %(ReplacementId): The replacement for Id that won't change per-build. - /// - [Required] - public ITaskItem[] FileElementToStabilize { get; set; } - - public override bool Execute() - { - XDocument content = XDocument.Load(SourceFile); - - XNamespace rootNamespace = content.Root.GetDefaultNamespace(); - XName GetQualifiedName(string name) => rootNamespace.GetName(name); - - foreach (var file in FileElementToStabilize) - { - string replacement = file.GetMetadata("ReplacementId"); - - if (string.IsNullOrEmpty(replacement)) - { - Log.LogError($"{nameof(FileElementToStabilize)} {file.ItemSpec} has null/empty ReplacementId metadata."); - continue; - } - - XElement[] matchingFileElements = content.Element(GetQualifiedName("Wix")) - .Elements(GetQualifiedName("Fragment")) - .SelectMany(f => f.Elements(GetQualifiedName("ComponentGroup"))) - .SelectMany(cg => cg.Elements(GetQualifiedName("Component"))) - .SelectMany(c => c.Elements(GetQualifiedName("File"))) - .Where(f => f.Attribute("Source")?.Value - ?.EndsWith(file.ItemSpec, StringComparison.OrdinalIgnoreCase) == true) - .ToArray(); - - if (matchingFileElements.Length != 1) - { - Log.LogError( - $"Expected 1 match for '{file.ItemSpec}', found {matchingFileElements.Length}: " + - string.Join(", ", matchingFileElements.Select(e => e.ToString()))); - - continue; - } - - XAttribute nameAttribute = matchingFileElements[0].Attribute("Id"); - - if (nameAttribute is null) - { - Log.LogError($"Match has no Id attribute: {matchingFileElements[0]}"); - continue; - } - - Log.LogMessage( - $"Setting '{file.ItemSpec}' Id to '{replacement}' for File with Source " + - matchingFileElements[0].Attribute("Source").Value); - - nameAttribute.Value = replacement; - } - - content.Save(OutputFile); - - return !Log.HasLoggedErrors; - } - } -} diff --git a/tools-local/tasks/installer.tasks/ZipFileExtractToDirectory.cs b/tools-local/tasks/installer.tasks/ZipFileExtractToDirectory.cs deleted file mode 100644 index e03a860..0000000 --- a/tools-local/tasks/installer.tasks/ZipFileExtractToDirectory.cs +++ /dev/null @@ -1,86 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using Microsoft.Build.Framework; -using System; -using System.IO; -using System.IO.Compression; - -namespace Microsoft.DotNet.Build.Tasks -{ - public sealed class ZipFileExtractToDirectory : BuildTask - { - /// - /// The path to the archive to be extracted. - /// - [Required] - public string SourceArchive { get; set; } - - /// - /// The path of the directory to extract into. - /// - [Required] - public string DestinationDirectory { get; set; } - - /// - /// Indicates if the destination directory should be overwritten if it already exists. - /// - public bool OverwriteDestination { get; set; } - - /// - /// File entries to include in the extraction. Entries are relative - /// paths inside the archive. If null or empty, all files are extracted. - /// - public ITaskItem[] Include { get; set; } - - public override bool Execute() - { - try - { - if (Directory.Exists(DestinationDirectory)) - { - if (OverwriteDestination) - { - Log.LogMessage(MessageImportance.Low, $"'{DestinationDirectory}' already exists, trying to delete before unzipping..."); - Directory.Delete(DestinationDirectory, recursive: true); - } - else - { - Log.LogWarning($"'{DestinationDirectory}' already exists. Did you forget to set '{nameof(OverwriteDestination)}' to true?"); - } - } - - Log.LogMessage(MessageImportance.High, "Decompressing '{0}' into '{1}'...", SourceArchive, DestinationDirectory); - Directory.CreateDirectory(Path.GetDirectoryName(DestinationDirectory)); - - using (ZipArchive archive = ZipFile.OpenRead(SourceArchive)) - { - if (Include?.Length > 0) - { - foreach (ITaskItem entryItem in Include) - { - ZipArchiveEntry entry = archive.GetEntry(entryItem.ItemSpec); - string destinationPath = Path.Combine(DestinationDirectory, entryItem.ItemSpec); - - Directory.CreateDirectory(Path.GetDirectoryName(destinationPath)); - entry.ExtractToFile(destinationPath, overwrite: false); - } - } - else - { - archive.ExtractToDirectory(DestinationDirectory); - } - } - } - catch (Exception e) - { - // We have 2 log calls because we want a nice error message but we also want to capture the callstack in the log. - Log.LogError("An exception has occurred while trying to decompress '{0}' into '{1}'.", SourceArchive, DestinationDirectory); - Log.LogErrorFromException(e, /*show stack=*/ true, /*show detail=*/ true, DestinationDirectory); - return false; - } - return true; - } - } -} diff --git a/tools-local/tasks/installer.tasks/ZipFileGetEntries.cs b/tools-local/tasks/installer.tasks/ZipFileGetEntries.cs deleted file mode 100644 index 56b1e38..0000000 --- a/tools-local/tasks/installer.tasks/ZipFileGetEntries.cs +++ /dev/null @@ -1,50 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using Microsoft.Build.Framework; -using Microsoft.Build.Utilities; -using System; -using System.IO.Compression; -using System.Linq; - -namespace Microsoft.DotNet.Build.Tasks -{ - public sealed class ZipFileGetEntries : BuildTask - { - /// - /// The path to the archive. - /// - [Required] - public string TargetArchive { get; set; } - - /// - /// Generated items where each ItemSpec is the relative location of a - /// file entry in the zip archive. - /// - [Output] - public ITaskItem[] Entries { get; set; } - - public override bool Execute() - { - try - { - using (ZipArchive archive = ZipFile.OpenRead(TargetArchive)) - { - Entries = archive.Entries - // Escape '%' so encoded '+' in the nupkg stays encoded through MSBuild. - .Select(e => new TaskItem(e.FullName.Replace("%", "%25"))) - .ToArray(); - } - } - catch (Exception e) - { - // We have 2 log calls because we want a nice error message but we also want to capture the callstack in the log. - Log.LogError($"An exception has occurred while trying to read entries from '{TargetArchive}'."); - Log.LogErrorFromException(e, /*show stack=*/ true, /*show detail=*/ true, TargetArchive); - return false; - } - return true; - } - } -} -- 2.7.4