RuntimeGraphManager.cs 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  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.Packaging;
  10. using NuGet.ProjectModel;
  11. using NuGet.RuntimeModel;
  12. namespace RepoTasks.Utilities
  13. {
  14. internal class RuntimeGraphManager
  15. {
  16. private const string RuntimeJsonFileName = "runtime.json";
  17. public RuntimeGraph Collect(LockFile lockFile)
  18. {
  19. string userPackageFolder = lockFile.PackageFolders.FirstOrDefault()?.Path;
  20. var fallBackFolders = lockFile.PackageFolders.Skip(1).Select(f => f.Path);
  21. var packageResolver = new FallbackPackagePathResolver(userPackageFolder, fallBackFolders);
  22. var graph = RuntimeGraph.Empty;
  23. foreach (var library in lockFile.Libraries)
  24. {
  25. if (string.Equals(library.Type, "package", StringComparison.OrdinalIgnoreCase))
  26. {
  27. var runtimeJson = library.Files.FirstOrDefault(f => f == RuntimeJsonFileName);
  28. if (runtimeJson != null)
  29. {
  30. var libraryPath = packageResolver.GetPackageDirectory(library.Name, library.Version);
  31. var runtimeJsonFullName = Path.Combine(libraryPath, runtimeJson);
  32. graph = RuntimeGraph.Merge(graph, JsonRuntimeFormat.ReadRuntimeGraph(runtimeJsonFullName));
  33. }
  34. }
  35. }
  36. return graph;
  37. }
  38. public IEnumerable<RuntimeFallbacks> Expand(RuntimeGraph runtimeGraph, string runtime)
  39. {
  40. var importers = FindImporters(runtimeGraph, runtime);
  41. foreach (var importer in importers)
  42. {
  43. // ExpandRuntime return runtime itself as first item so we are skiping it
  44. yield return new RuntimeFallbacks(importer, runtimeGraph.ExpandRuntime(importer).Skip(1));
  45. }
  46. }
  47. private IEnumerable<string> FindImporters(RuntimeGraph runtimeGraph, string runtime)
  48. {
  49. foreach (var runtimePair in runtimeGraph.Runtimes)
  50. {
  51. var expanded = runtimeGraph.ExpandRuntime(runtimePair.Key);
  52. if (expanded.Contains(runtime))
  53. {
  54. yield return runtimePair.Key;
  55. }
  56. }
  57. }
  58. }
  59. }