SolutionInfoFactory.cs 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136
  1. // Copyright (c) .NET Foundation. All rights reserved.
  2. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
  3. using System;
  4. using System.Collections.Concurrent;
  5. using System.Collections.Generic;
  6. using System.Diagnostics;
  7. using System.Linq;
  8. using System.Threading;
  9. using System.Threading.Tasks;
  10. using Microsoft.Build.Construction;
  11. using Microsoft.Build.Evaluation;
  12. using Microsoft.Build.Framework;
  13. using Microsoft.Build.Utilities;
  14. using RepoTasks.Utilities;
  15. namespace RepoTasks.ProjectModel
  16. {
  17. internal class SolutionInfoFactory
  18. {
  19. private readonly TaskLoggingHelper _logger;
  20. private readonly IBuildEngine4 _buildEngine;
  21. public SolutionInfoFactory(TaskLoggingHelper logger, IBuildEngine4 buildEngine)
  22. {
  23. _logger = logger;
  24. _buildEngine = buildEngine;
  25. }
  26. public IReadOnlyList<SolutionInfo> Create(IEnumerable<ITaskItem> solutionItems, IDictionary<string, string> properties, string defaultConfig, CancellationToken ct)
  27. {
  28. var timer = Stopwatch.StartNew();
  29. var solutions = new ConcurrentBag<SolutionInfo>();
  30. Parallel.ForEach(solutionItems, solution =>
  31. {
  32. if (ct.IsCancellationRequested)
  33. {
  34. return;
  35. }
  36. var solutionFile = solution.ItemSpec.Replace('\\', '/');
  37. var solutionProps = new Dictionary<string, string>(properties, StringComparer.OrdinalIgnoreCase);
  38. foreach (var prop in MSBuildListSplitter.GetNamedProperties(solution.GetMetadata("AdditionalProperties")))
  39. {
  40. solutionProps[prop.Key] = prop.Value;
  41. }
  42. if (!solutionProps.TryGetValue("Configuration", out var configName))
  43. {
  44. solutionProps["Configuration"] = configName = defaultConfig;
  45. }
  46. var key = $"SlnInfo:{solutionFile}:{configName}";
  47. var obj = _buildEngine.GetRegisteredTaskObject(key, RegisteredTaskObjectLifetime.Build);
  48. if (obj is SolutionInfo cachedSlnInfo)
  49. {
  50. solutions.Add(cachedSlnInfo);
  51. return;
  52. }
  53. _logger.LogMessage($"Analyzing {solutionFile} ({configName})");
  54. var projects = new ConcurrentBag<ProjectInfo>();
  55. var projectFiles = GetProjectsForSolutionConfig(solutionFile, configName);
  56. using (var projCollection = new ProjectCollection(solutionProps) { IsBuildEnabled = false })
  57. {
  58. Parallel.ForEach(projectFiles, projectFile =>
  59. {
  60. if (ct.IsCancellationRequested)
  61. {
  62. return;
  63. }
  64. try
  65. {
  66. projects.Add(new ProjectInfoFactory(_logger).Create(projectFile, projCollection));
  67. }
  68. catch (Exception ex)
  69. {
  70. _logger.LogErrorFromException(ex);
  71. }
  72. });
  73. }
  74. bool.TryParse(solution.GetMetadata("Build"), out var shouldBuild);
  75. bool.TryParse(solution.GetMetadata("IsPatching"), out var isPatching);
  76. var solutionInfo = new SolutionInfo(
  77. solutionFile,
  78. configName,
  79. projects.ToArray(),
  80. shouldBuild,
  81. isPatching);
  82. _buildEngine.RegisterTaskObject(key, solutionInfo, RegisteredTaskObjectLifetime.Build, allowEarlyCollection: true);
  83. solutions.Add(solutionInfo);
  84. });
  85. timer.Stop();
  86. _logger.LogMessage(MessageImportance.High, $"Finished design-time build in {timer.ElapsedMilliseconds}ms");
  87. return solutions.ToArray();
  88. }
  89. private IList<string> GetProjectsForSolutionConfig(string filePath, string configName)
  90. {
  91. var sln = SolutionFile.Parse(filePath);
  92. if (string.IsNullOrEmpty(configName))
  93. {
  94. configName = sln.GetDefaultConfigurationName();
  95. }
  96. var projects = new List<string>();
  97. var config = sln.SolutionConfigurations.FirstOrDefault(c => c.ConfigurationName == configName);
  98. if (config == null)
  99. {
  100. throw new InvalidOperationException($"A solution configuration by the name of '{configName}' was not found in '{filePath}'");
  101. }
  102. foreach (var project in sln.ProjectsInOrder
  103. .Where(p =>
  104. p.ProjectType == SolutionProjectType.KnownToBeMSBuildFormat // skips solution folders
  105. && p.ProjectConfigurations.TryGetValue(config.FullName, out var projectConfig)
  106. && projectConfig.IncludeInBuild))
  107. {
  108. projects.Add(project.AbsolutePath.Replace('\\', '/'));
  109. }
  110. return projects;
  111. }
  112. }
  113. }