|
| 1 | +using System.Threading.Tasks; |
| 2 | +using Microsoft.CodeAnalysis; |
| 3 | +using Microsoft.CodeAnalysis.MSBuild; |
| 4 | +using System.Linq; |
| 5 | +using System.Threading; |
| 6 | +using System; |
| 7 | +using System.IO; |
| 8 | +using System.Reflection; |
| 9 | +using Uno.Extensions; |
| 10 | + |
| 11 | +namespace Uno.UI.RemoteControl.Host.HotReload |
| 12 | +{ |
| 13 | + internal static class CompilationWorkspaceProvider |
| 14 | + { |
| 15 | + private static string MSBuildBasePath; |
| 16 | + |
| 17 | + public static Task<(Solution, WatchHotReloadService)> CreateWorkspaceAsync(string projectPath, IReporter reporter, CancellationToken cancellationToken) |
| 18 | + { |
| 19 | + var taskCompletionSource = new TaskCompletionSource<(Solution, WatchHotReloadService)>(TaskCreationOptions.RunContinuationsAsynchronously); |
| 20 | + CreateProject(taskCompletionSource, projectPath, reporter, cancellationToken); |
| 21 | + |
| 22 | + return taskCompletionSource.Task; |
| 23 | + } |
| 24 | + |
| 25 | + static async void CreateProject(TaskCompletionSource<(Solution, WatchHotReloadService)> taskCompletionSource, string projectPath, IReporter reporter, CancellationToken cancellationToken) |
| 26 | + { |
| 27 | + var workspace = MSBuildWorkspace.Create(); |
| 28 | + |
| 29 | + workspace.WorkspaceFailed += (_sender, diag) => |
| 30 | + { |
| 31 | + if (diag.Diagnostic.Kind == WorkspaceDiagnosticKind.Warning) |
| 32 | + { |
| 33 | + reporter.Verbose($"MSBuildWorkspace warning: {diag.Diagnostic}"); |
| 34 | + } |
| 35 | + else |
| 36 | + { |
| 37 | + if (!diag.Diagnostic.ToString().StartsWith("[Failure] Found invalid data while decoding")) |
| 38 | + { |
| 39 | + taskCompletionSource.TrySetException(new InvalidOperationException($"Failed to create MSBuildWorkspace: {diag.Diagnostic}")); |
| 40 | + } |
| 41 | + } |
| 42 | + }; |
| 43 | + |
| 44 | + await workspace.OpenProjectAsync(projectPath, cancellationToken: cancellationToken); |
| 45 | + var currentSolution = workspace.CurrentSolution; |
| 46 | + var hotReloadService = new WatchHotReloadService(workspace.Services); |
| 47 | + await hotReloadService.StartSessionAsync(currentSolution, cancellationToken); |
| 48 | + |
| 49 | + // Read the documents to memory |
| 50 | + await Task.WhenAll( |
| 51 | + currentSolution.Projects.SelectMany(p => p.Documents.Concat(p.AdditionalDocuments)).Select(d => d.GetTextAsync(cancellationToken))); |
| 52 | + |
| 53 | + // Warm up the compilation. This would help make the deltas for first edit appear much more quickly |
| 54 | + foreach (var project in currentSolution.Projects) |
| 55 | + { |
| 56 | + await project.GetCompilationAsync(cancellationToken); |
| 57 | + } |
| 58 | + |
| 59 | + taskCompletionSource.TrySetResult((currentSolution, hotReloadService)); |
| 60 | + } |
| 61 | + |
| 62 | + public static void InitializeRoslyn() |
| 63 | + { |
| 64 | + RegisterAssemblyLoader(); |
| 65 | + |
| 66 | + var pi = new System.Diagnostics.ProcessStartInfo( |
| 67 | + "cmd.exe", |
| 68 | + @"/c ""C:\Program Files (x86)\Microsoft Visual Studio\Installer\vswhere.exe"" -property installationPath" |
| 69 | + ) |
| 70 | + { |
| 71 | + RedirectStandardOutput = true, |
| 72 | + UseShellExecute = false, |
| 73 | + CreateNoWindow = true |
| 74 | + }; |
| 75 | + |
| 76 | + var process = System.Diagnostics.Process.Start(pi); |
| 77 | + process.WaitForExit(); |
| 78 | + var installPath = process.StandardOutput.ReadToEnd().Split('\r').First(); |
| 79 | + |
| 80 | + SetupMSBuildLookupPath(installPath); |
| 81 | + } |
| 82 | + |
| 83 | + private static void SetupMSBuildLookupPath(string installPath) |
| 84 | + { |
| 85 | + Environment.SetEnvironmentVariable("VSINSTALLDIR", installPath); |
| 86 | + Environment.SetEnvironmentVariable("MSBuildSDKsPath", @"C:\Program Files\dotnet\sdk\6.0.100-rc.2.21505.57\Sdks"); |
| 87 | + |
| 88 | + bool MSBuildExists() => File.Exists(Path.Combine(MSBuildBasePath, "Microsoft.Build.dll")); |
| 89 | + |
| 90 | + MSBuildBasePath = @"C:\Program Files\dotnet\sdk\6.0.100-rc.2.21505.57"; |
| 91 | + |
| 92 | + if (!MSBuildExists()) |
| 93 | + { |
| 94 | + MSBuildBasePath = Path.Combine(installPath, "MSBuild\\Current\\Bin"); |
| 95 | + if (!MSBuildExists()) |
| 96 | + { |
| 97 | + throw new InvalidOperationException($"Invalid Visual studio installation (Cannot find Microsoft.Build.dll)"); |
| 98 | + } |
| 99 | + } |
| 100 | + } |
| 101 | + |
| 102 | + |
| 103 | + private static void RegisterAssemblyLoader() |
| 104 | + { |
| 105 | + // Force assembly loader to consider siblings, when running in a separate appdomain. |
| 106 | + ResolveEventHandler localResolve = (s, e) => |
| 107 | + { |
| 108 | + if (e.Name == "Mono.Runtime") |
| 109 | + { |
| 110 | + // Roslyn 2.0 and later checks for the presence of the Mono runtime |
| 111 | + // through this check. |
| 112 | + return null; |
| 113 | + } |
| 114 | + |
| 115 | + var assembly = new AssemblyName(e.Name); |
| 116 | + var basePath = Path.GetDirectoryName(new Uri(typeof(CompilationWorkspaceProvider).Assembly.CodeBase).LocalPath); |
| 117 | + |
| 118 | + Console.WriteLine($"Searching for [{assembly}] from [{basePath}]"); |
| 119 | + |
| 120 | + // Ignore resource assemblies for now, we'll have to adjust this |
| 121 | + // when adding globalization. |
| 122 | + if (assembly.Name.EndsWith(".resources")) |
| 123 | + { |
| 124 | + return null; |
| 125 | + } |
| 126 | + |
| 127 | + // Lookup for the highest version matching assembly in the current app domain. |
| 128 | + // There may be an existing one that already matches, even though the |
| 129 | + // fusion loader did not find an exact match. |
| 130 | + var loadedAsm = ( |
| 131 | + from asm in AppDomain.CurrentDomain.GetAssemblies() |
| 132 | + where asm.GetName().Name == assembly.Name |
| 133 | + orderby asm.GetName().Version descending |
| 134 | + select asm |
| 135 | + ).ToArray(); |
| 136 | + |
| 137 | + if (loadedAsm.Length > 1) |
| 138 | + { |
| 139 | + var duplicates = loadedAsm |
| 140 | + .Skip(1) |
| 141 | + .Where(a => a.GetName().Version == loadedAsm[0].GetName().Version) |
| 142 | + .ToArray(); |
| 143 | + |
| 144 | + if (duplicates.Length != 0) |
| 145 | + { |
| 146 | + Console.WriteLine($"Selecting first occurrence of assembly [{e.Name}] which can be found at [{duplicates.Select(d => d.CodeBase).JoinBy("; ")}]"); |
| 147 | + } |
| 148 | + |
| 149 | + return loadedAsm[0]; |
| 150 | + } |
| 151 | + else if (loadedAsm.Length == 1) |
| 152 | + { |
| 153 | + return loadedAsm[0]; |
| 154 | + } |
| 155 | + |
| 156 | + Assembly LoadAssembly(string filePath) |
| 157 | + { |
| 158 | + if (File.Exists(filePath)) |
| 159 | + { |
| 160 | + try |
| 161 | + { |
| 162 | + var output = Assembly.LoadFrom(filePath); |
| 163 | + |
| 164 | + Console.WriteLine($"Loaded [{output.GetName()}] from [{output.CodeBase}]"); |
| 165 | + |
| 166 | + return output; |
| 167 | + } |
| 168 | + catch (Exception ex) |
| 169 | + { |
| 170 | + Console.WriteLine($"Failed to load [{assembly}] from [{filePath}]", ex); |
| 171 | + return null; |
| 172 | + } |
| 173 | + } |
| 174 | + else |
| 175 | + { |
| 176 | + return null; |
| 177 | + } |
| 178 | + } |
| 179 | + |
| 180 | + var paths = new[] { |
| 181 | + Path.Combine(basePath, assembly.Name + ".dll"), |
| 182 | + Path.Combine(MSBuildBasePath, assembly.Name + ".dll"), |
| 183 | + }; |
| 184 | + |
| 185 | + return paths |
| 186 | + .Select(LoadAssembly) |
| 187 | + .Where(p => p != null) |
| 188 | + .FirstOrDefault(); |
| 189 | + }; |
| 190 | + |
| 191 | + AppDomain.CurrentDomain.AssemblyResolve += localResolve; |
| 192 | + AppDomain.CurrentDomain.TypeResolve += localResolve; |
| 193 | + } |
| 194 | + |
| 195 | + } |
| 196 | +} |
0 commit comments