RuntimeGraphManager.cs 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. // Copyright (c) Microsoft Open Technologies, Inc. All rights reserved.
  2. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
  3. // Sourced from https://github.com/dotnet/core-setup/tree/be8d8e3486b2bf598ed69d39b1629a24caaba45e/tools-local/tasks, needs to be kept in sync
  4. using System;
  5. using System.Collections.Generic;
  6. using System.IO;
  7. using System.Linq;
  8. using Microsoft.Extensions.DependencyModel;
  9. using NuGet.Frameworks;
  10. using NuGet.Packaging;
  11. using NuGet.ProjectModel;
  12. using NuGet.RuntimeModel;
  13. namespace RepoTasks.Utilities
  14. {
  15. internal class RuntimeGraphManager
  16. {
  17. private const string RuntimeJsonFileName = "runtime.json";
  18. public RuntimeGraph Collect(LockFile lockFile)
  19. {
  20. string userPackageFolder = lockFile.PackageFolders.FirstOrDefault()?.Path;
  21. var fallBackFolders = lockFile.PackageFolders.Skip(1).Select(f => f.Path);
  22. var packageResolver = new FallbackPackagePathResolver(userPackageFolder, fallBackFolders);
  23. var graph = RuntimeGraph.Empty;
  24. foreach (var library in lockFile.Libraries)
  25. {
  26. if (string.Equals(library.Type, "package", StringComparison.OrdinalIgnoreCase))
  27. {
  28. var runtimeJson = library.Files.FirstOrDefault(f => f == RuntimeJsonFileName);
  29. if (runtimeJson != null)
  30. {
  31. var libraryPath = packageResolver.GetPackageDirectory(library.Name, library.Version);
  32. var runtimeJsonFullName = Path.Combine(libraryPath, runtimeJson);
  33. graph = RuntimeGraph.Merge(graph, JsonRuntimeFormat.ReadRuntimeGraph(runtimeJsonFullName));
  34. }
  35. }
  36. }
  37. return graph;
  38. }
  39. public IEnumerable<RuntimeFallbacks> Expand(RuntimeGraph runtimeGraph, string runtime)
  40. {
  41. var importers = FindImporters(runtimeGraph, runtime);
  42. foreach (var importer in importers)
  43. {
  44. // ExpandRuntime return runtime itself as first item so we are skiping it
  45. yield return new RuntimeFallbacks(importer, runtimeGraph.ExpandRuntime(importer).Skip(1));
  46. }
  47. }
  48. private IEnumerable<string> FindImporters(RuntimeGraph runtimeGraph, string runtime)
  49. {
  50. foreach (var runtimePair in runtimeGraph.Runtimes)
  51. {
  52. var expanded = runtimeGraph.ExpandRuntime(runtimePair.Key);
  53. if (expanded.Contains(runtime))
  54. {
  55. yield return runtimePair.Key;
  56. }
  57. }
  58. }
  59. }
  60. }