SolutionInfoFactory.cs 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134
  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, 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 = "Debug";
  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. var solutionInfo = new SolutionInfo(
  76. solutionFile,
  77. configName,
  78. projects.ToArray(),
  79. shouldBuild);
  80. _buildEngine.RegisterTaskObject(key, solutionInfo, RegisteredTaskObjectLifetime.Build, allowEarlyCollection: true);
  81. solutions.Add(solutionInfo);
  82. });
  83. timer.Stop();
  84. _logger.LogMessage(MessageImportance.High, $"Finished design-time build in {timer.ElapsedMilliseconds}ms");
  85. return solutions.ToArray();
  86. }
  87. private IList<string> GetProjectsForSolutionConfig(string filePath, string configName)
  88. {
  89. var sln = SolutionFile.Parse(filePath);
  90. if (string.IsNullOrEmpty(configName))
  91. {
  92. configName = sln.GetDefaultConfigurationName();
  93. }
  94. var projects = new List<string>();
  95. var config = sln.SolutionConfigurations.FirstOrDefault(c => c.ConfigurationName == configName);
  96. if (config == null)
  97. {
  98. throw new InvalidOperationException($"A solution configuration by the name of '{configName}' was not found in '{filePath}'");
  99. }
  100. foreach (var project in sln.ProjectsInOrder
  101. .Where(p =>
  102. p.ProjectType == SolutionProjectType.KnownToBeMSBuildFormat // skips solution folders
  103. && p.ProjectConfigurations.TryGetValue(config.FullName, out var projectConfig)
  104. && projectConfig.IncludeInBuild))
  105. {
  106. projects.Add(project.AbsolutePath.Replace('\\', '/'));
  107. }
  108. return projects;
  109. }
  110. }
  111. }