ProjectGeneration.cs 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020
  1. /*---------------------------------------------------------------------------------------------
  2. * Copyright (c) Unity Technologies.
  3. * Copyright (c) Microsoft Corporation. All rights reserved.
  4. * Licensed under the MIT License. See License.txt in the project root for license information.
  5. *--------------------------------------------------------------------------------------------*/
  6. using System;
  7. using System.Collections.Generic;
  8. using System.IO;
  9. using System.Linq;
  10. using SR = System.Reflection;
  11. using System.Security;
  12. using System.Security.Cryptography;
  13. using System.Text;
  14. using System.Text.RegularExpressions;
  15. using Unity.CodeEditor;
  16. using Unity.Profiling;
  17. using UnityEditor;
  18. using UnityEditor.Compilation;
  19. using UnityEngine;
  20. namespace Microsoft.Unity.VisualStudio.Editor
  21. {
  22. public enum ScriptingLanguage
  23. {
  24. None,
  25. CSharp
  26. }
  27. public interface IGenerator
  28. {
  29. bool SyncIfNeeded(IEnumerable<string> affectedFiles, IEnumerable<string> reimportedFiles);
  30. void Sync();
  31. bool HasSolutionBeenGenerated();
  32. bool IsSupportedFile(string path);
  33. string SolutionFile();
  34. string ProjectDirectory { get; }
  35. IAssemblyNameProvider AssemblyNameProvider { get; }
  36. }
  37. public class ProjectGeneration : IGenerator
  38. {
  39. public static readonly string MSBuildNamespaceUri = "http://schemas.microsoft.com/developer/msbuild/2003";
  40. public IAssemblyNameProvider AssemblyNameProvider => m_AssemblyNameProvider;
  41. public string ProjectDirectory { get; }
  42. const string k_WindowsNewline = "\r\n";
  43. const string m_SolutionProjectEntryTemplate = @"Project(""{{{0}}}"") = ""{1}"", ""{2}"", ""{{{3}}}""{4}EndProject";
  44. readonly string m_SolutionProjectConfigurationTemplate = string.Join(k_WindowsNewline,
  45. @" {{{0}}}.Debug|Any CPU.ActiveCfg = Debug|Any CPU",
  46. @" {{{0}}}.Debug|Any CPU.Build.0 = Debug|Any CPU",
  47. @" {{{0}}}.Release|Any CPU.ActiveCfg = Release|Any CPU",
  48. @" {{{0}}}.Release|Any CPU.Build.0 = Release|Any CPU").Replace(" ", "\t");
  49. static readonly string[] k_ReimportSyncExtensions = { ".dll", ".asmdef" };
  50. string[] m_ProjectSupportedExtensions = Array.Empty<string>();
  51. string[] m_BuiltinSupportedExtensions = Array.Empty<string>();
  52. readonly string m_ProjectName;
  53. readonly IAssemblyNameProvider m_AssemblyNameProvider;
  54. readonly IFileIO m_FileIOProvider;
  55. readonly IGUIDGenerator m_GUIDGenerator;
  56. bool m_ShouldGenerateAll;
  57. IVisualStudioInstallation m_CurrentInstallation;
  58. public ProjectGeneration() : this(Directory.GetParent(Application.dataPath).FullName)
  59. {
  60. }
  61. public ProjectGeneration(string tempDirectory) : this(tempDirectory, new AssemblyNameProvider(), new FileIOProvider(), new GUIDProvider())
  62. {
  63. }
  64. public ProjectGeneration(string tempDirectory, IAssemblyNameProvider assemblyNameProvider, IFileIO fileIoProvider, IGUIDGenerator guidGenerator)
  65. {
  66. ProjectDirectory = FileUtility.NormalizeWindowsToUnix(tempDirectory);
  67. m_ProjectName = Path.GetFileName(ProjectDirectory);
  68. m_AssemblyNameProvider = assemblyNameProvider;
  69. m_FileIOProvider = fileIoProvider;
  70. m_GUIDGenerator = guidGenerator;
  71. SetupProjectSupportedExtensions();
  72. }
  73. /// <summary>
  74. /// Syncs the scripting solution if any affected files are relevant.
  75. /// </summary>
  76. /// <returns>
  77. /// Whether the solution was synced.
  78. /// </returns>
  79. /// <param name='affectedFiles'>
  80. /// A set of files whose status has changed
  81. /// </param>
  82. /// <param name="reimportedFiles">
  83. /// A set of files that got reimported
  84. /// </param>
  85. public bool SyncIfNeeded(IEnumerable<string> affectedFiles, IEnumerable<string> reimportedFiles)
  86. {
  87. using (solutionSyncMarker.Auto())
  88. {
  89. // We need the exact VS version/capabilities to tweak project generation (analyzers/langversion)
  90. RefreshCurrentInstallation();
  91. SetupProjectSupportedExtensions();
  92. // See https://devblogs.microsoft.com/setup/configure-visual-studio-across-your-organization-with-vsconfig/
  93. // We create a .vsconfig file to make sure our ManagedGame workload is installed
  94. CreateVsConfigIfNotFound();
  95. // Don't sync if we haven't synced before
  96. var affected = affectedFiles as ICollection<string> ?? affectedFiles.ToArray();
  97. var reimported = reimportedFiles as ICollection<string> ?? reimportedFiles.ToArray();
  98. if (!HasFilesBeenModified(affected, reimported))
  99. {
  100. return false;
  101. }
  102. var assemblies = m_AssemblyNameProvider.GetAssemblies(ShouldFileBePartOfSolution);
  103. var allProjectAssemblies = RelevantAssembliesForMode(assemblies).ToList();
  104. SyncSolution(allProjectAssemblies);
  105. var allAssetProjectParts = GenerateAllAssetProjectParts();
  106. var affectedNames = affected
  107. .Select(asset => m_AssemblyNameProvider.GetAssemblyNameFromScriptPath(asset))
  108. .Where(name => !string.IsNullOrWhiteSpace(name)).Select(name =>
  109. name.Split(new[] {".dll"}, StringSplitOptions.RemoveEmptyEntries)[0]);
  110. var reimportedNames = reimported
  111. .Select(asset => m_AssemblyNameProvider.GetAssemblyNameFromScriptPath(asset))
  112. .Where(name => !string.IsNullOrWhiteSpace(name)).Select(name =>
  113. name.Split(new[] {".dll"}, StringSplitOptions.RemoveEmptyEntries)[0]);
  114. var affectedAndReimported = new HashSet<string>(affectedNames.Concat(reimportedNames));
  115. foreach (var assembly in allProjectAssemblies)
  116. {
  117. if (!affectedAndReimported.Contains(assembly.name))
  118. continue;
  119. SyncProject(assembly,
  120. allAssetProjectParts,
  121. responseFilesData: ParseResponseFileData(assembly).ToArray());
  122. }
  123. return true;
  124. }
  125. }
  126. private void CreateVsConfigIfNotFound()
  127. {
  128. try
  129. {
  130. var vsConfigFile = VsConfigFile();
  131. if (m_FileIOProvider.Exists(vsConfigFile))
  132. return;
  133. var content = $@"{{
  134. ""version"": ""1.0"",
  135. ""components"": [
  136. ""{Discovery.ManagedWorkload}""
  137. ]
  138. }}
  139. ";
  140. m_FileIOProvider.WriteAllText(vsConfigFile, content);
  141. }
  142. catch (IOException)
  143. {
  144. }
  145. }
  146. private bool HasFilesBeenModified(IEnumerable<string> affectedFiles, IEnumerable<string> reimportedFiles)
  147. {
  148. return affectedFiles.Any(ShouldFileBePartOfSolution) || reimportedFiles.Any(ShouldSyncOnReimportedAsset);
  149. }
  150. private static bool ShouldSyncOnReimportedAsset(string asset)
  151. {
  152. return k_ReimportSyncExtensions.Contains(new FileInfo(asset).Extension);
  153. }
  154. private void RefreshCurrentInstallation()
  155. {
  156. var editor = CodeEditor.CurrentEditor as VisualStudioEditor;
  157. editor?.TryGetVisualStudioInstallationForPath(CodeEditor.CurrentEditorInstallation, searchInstallations: true, out m_CurrentInstallation);
  158. }
  159. static ProfilerMarker solutionSyncMarker = new ProfilerMarker("SolutionSynchronizerSync");
  160. public void Sync()
  161. {
  162. // We need the exact VS version/capabilities to tweak project generation (analyzers/langversion)
  163. RefreshCurrentInstallation();
  164. SetupProjectSupportedExtensions();
  165. (m_AssemblyNameProvider as AssemblyNameProvider)?.ResetPackageInfoCache();
  166. // See https://devblogs.microsoft.com/setup/configure-visual-studio-across-your-organization-with-vsconfig/
  167. // We create a .vsconfig file to make sure our ManagedGame workload is installed
  168. CreateVsConfigIfNotFound();
  169. var externalCodeAlreadyGeneratedProjects = OnPreGeneratingCSProjectFiles();
  170. if (!externalCodeAlreadyGeneratedProjects)
  171. {
  172. GenerateAndWriteSolutionAndProjects();
  173. }
  174. OnGeneratedCSProjectFiles();
  175. }
  176. public bool HasSolutionBeenGenerated()
  177. {
  178. return m_FileIOProvider.Exists(SolutionFile());
  179. }
  180. private void SetupProjectSupportedExtensions()
  181. {
  182. m_ProjectSupportedExtensions = m_AssemblyNameProvider.ProjectSupportedExtensions;
  183. m_BuiltinSupportedExtensions = EditorSettings.projectGenerationBuiltinExtensions;
  184. }
  185. private bool ShouldFileBePartOfSolution(string file)
  186. {
  187. // Exclude files coming from packages except if they are internalized.
  188. if (m_AssemblyNameProvider.IsInternalizedPackagePath(file))
  189. {
  190. return false;
  191. }
  192. return IsSupportedFile(file);
  193. }
  194. private static string GetExtensionWithoutDot(string path)
  195. {
  196. // Prevent re-processing and information loss
  197. if (!Path.HasExtension(path))
  198. return path;
  199. return Path
  200. .GetExtension(path)
  201. .TrimStart('.')
  202. .ToLower();
  203. }
  204. public bool IsSupportedFile(string path)
  205. {
  206. var extension = GetExtensionWithoutDot(path);
  207. // Dll's are not scripts but still need to be included
  208. if (extension == "dll")
  209. return true;
  210. if (extension == "asmdef")
  211. return true;
  212. if (m_BuiltinSupportedExtensions.Contains(extension))
  213. return true;
  214. if (m_ProjectSupportedExtensions.Contains(extension))
  215. return true;
  216. return false;
  217. }
  218. private static ScriptingLanguage ScriptingLanguageFor(Assembly assembly)
  219. {
  220. var files = assembly.sourceFiles;
  221. if (files.Length == 0)
  222. return ScriptingLanguage.None;
  223. return ScriptingLanguageFor(files[0]);
  224. }
  225. internal static ScriptingLanguage ScriptingLanguageFor(string path)
  226. {
  227. return GetExtensionWithoutDot(path) == "cs" ? ScriptingLanguage.CSharp : ScriptingLanguage.None;
  228. }
  229. public void GenerateAndWriteSolutionAndProjects()
  230. {
  231. // Only synchronize assemblies that have associated source files and ones that we actually want in the project.
  232. // This also filters out DLLs coming from .asmdef files in packages.
  233. var assemblies = m_AssemblyNameProvider.GetAssemblies(ShouldFileBePartOfSolution).ToList();
  234. var allAssetProjectParts = GenerateAllAssetProjectParts();
  235. SyncSolution(assemblies);
  236. var allProjectAssemblies = RelevantAssembliesForMode(assemblies);
  237. foreach (var assembly in allProjectAssemblies)
  238. {
  239. SyncProject(assembly,
  240. allAssetProjectParts,
  241. responseFilesData: ParseResponseFileData(assembly).ToArray());
  242. }
  243. }
  244. private IEnumerable<ResponseFileData> ParseResponseFileData(Assembly assembly)
  245. {
  246. var systemReferenceDirectories = CompilationPipeline.GetSystemAssemblyDirectories(assembly.compilerOptions.ApiCompatibilityLevel);
  247. Dictionary<string, ResponseFileData> responseFilesData = assembly.compilerOptions.ResponseFiles.ToDictionary(x => x, x => m_AssemblyNameProvider.ParseResponseFile(
  248. x,
  249. ProjectDirectory,
  250. systemReferenceDirectories
  251. ));
  252. Dictionary<string, ResponseFileData> responseFilesWithErrors = responseFilesData.Where(x => x.Value.Errors.Any())
  253. .ToDictionary(x => x.Key, x => x.Value);
  254. if (responseFilesWithErrors.Any())
  255. {
  256. foreach (var error in responseFilesWithErrors)
  257. foreach (var valueError in error.Value.Errors)
  258. {
  259. Debug.LogError($"{error.Key} Parse Error : {valueError}");
  260. }
  261. }
  262. return responseFilesData.Select(x => x.Value);
  263. }
  264. private Dictionary<string, string> GenerateAllAssetProjectParts()
  265. {
  266. Dictionary<string, StringBuilder> stringBuilders = new Dictionary<string, StringBuilder>();
  267. foreach (string asset in m_AssemblyNameProvider.GetAllAssetPaths())
  268. {
  269. // Exclude files coming from packages except if they are internalized.
  270. if (m_AssemblyNameProvider.IsInternalizedPackagePath(asset))
  271. {
  272. continue;
  273. }
  274. if (IsSupportedFile(asset) && ScriptingLanguage.None == ScriptingLanguageFor(asset))
  275. {
  276. // Find assembly the asset belongs to by adding script extension and using compilation pipeline.
  277. var assemblyName = m_AssemblyNameProvider.GetAssemblyNameFromScriptPath(asset);
  278. if (string.IsNullOrEmpty(assemblyName))
  279. {
  280. continue;
  281. }
  282. assemblyName = Path.GetFileNameWithoutExtension(assemblyName);
  283. if (!stringBuilders.TryGetValue(assemblyName, out var projectBuilder))
  284. {
  285. projectBuilder = new StringBuilder();
  286. stringBuilders[assemblyName] = projectBuilder;
  287. }
  288. projectBuilder.Append(" <None Include=\"").Append(EscapedRelativePathFor(asset)).Append("\" />").Append(k_WindowsNewline);
  289. }
  290. }
  291. var result = new Dictionary<string, string>();
  292. foreach (var entry in stringBuilders)
  293. result[entry.Key] = entry.Value.ToString();
  294. return result;
  295. }
  296. private void SyncProject(
  297. Assembly assembly,
  298. Dictionary<string, string> allAssetsProjectParts,
  299. ResponseFileData[] responseFilesData)
  300. {
  301. SyncProjectFileIfNotChanged(
  302. ProjectFile(assembly),
  303. ProjectText(assembly, allAssetsProjectParts, responseFilesData));
  304. }
  305. private void SyncProjectFileIfNotChanged(string path, string newContents)
  306. {
  307. if (Path.GetExtension(path) == ".csproj")
  308. {
  309. newContents = OnGeneratedCSProject(path, newContents);
  310. }
  311. SyncFileIfNotChanged(path, newContents);
  312. }
  313. private void SyncSolutionFileIfNotChanged(string path, string newContents)
  314. {
  315. newContents = OnGeneratedSlnSolution(path, newContents);
  316. SyncFileIfNotChanged(path, newContents);
  317. }
  318. private static IEnumerable<SR.MethodInfo> GetPostProcessorCallbacks(string name)
  319. {
  320. return TypeCache
  321. .GetTypesDerivedFrom<AssetPostprocessor>()
  322. .Where(t => t.Assembly.GetName().Name != KnownAssemblies.Bridge) // never call into the bridge if loaded with the package
  323. .Select(t => t.GetMethod(name, SR.BindingFlags.Public | SR.BindingFlags.NonPublic | SR.BindingFlags.Static))
  324. .Where(m => m != null);
  325. }
  326. static void OnGeneratedCSProjectFiles()
  327. {
  328. foreach (var method in GetPostProcessorCallbacks(nameof(OnGeneratedCSProjectFiles)))
  329. {
  330. method.Invoke(null, Array.Empty<object>());
  331. }
  332. }
  333. private static bool OnPreGeneratingCSProjectFiles()
  334. {
  335. bool result = false;
  336. foreach (var method in GetPostProcessorCallbacks(nameof(OnPreGeneratingCSProjectFiles)))
  337. {
  338. var retValue = method.Invoke(null, Array.Empty<object>());
  339. if (method.ReturnType == typeof(bool))
  340. {
  341. result |= (bool)retValue;
  342. }
  343. }
  344. return result;
  345. }
  346. private static string InvokeAssetPostProcessorGenerationCallbacks(string name, string path, string content)
  347. {
  348. foreach (var method in GetPostProcessorCallbacks(name))
  349. {
  350. var args = new[] { path, content };
  351. var returnValue = method.Invoke(null, args);
  352. if (method.ReturnType == typeof(string))
  353. {
  354. // We want to chain content update between invocations
  355. content = (string)returnValue;
  356. }
  357. }
  358. return content;
  359. }
  360. private static string OnGeneratedCSProject(string path, string content)
  361. {
  362. return InvokeAssetPostProcessorGenerationCallbacks(nameof(OnGeneratedCSProject), path, content);
  363. }
  364. private static string OnGeneratedSlnSolution(string path, string content)
  365. {
  366. return InvokeAssetPostProcessorGenerationCallbacks(nameof(OnGeneratedSlnSolution), path, content);
  367. }
  368. private void SyncFileIfNotChanged(string filename, string newContents)
  369. {
  370. try
  371. {
  372. if (m_FileIOProvider.Exists(filename) && newContents == m_FileIOProvider.ReadAllText(filename))
  373. {
  374. return;
  375. }
  376. }
  377. catch (Exception exception)
  378. {
  379. Debug.LogException(exception);
  380. }
  381. m_FileIOProvider.WriteAllText(filename, newContents);
  382. }
  383. private string ProjectText(Assembly assembly,
  384. Dictionary<string, string> allAssetsProjectParts,
  385. ResponseFileData[] responseFilesData)
  386. {
  387. var projectBuilder = new StringBuilder(ProjectHeader(assembly, responseFilesData));
  388. var references = new List<string>();
  389. projectBuilder.Append(@" <ItemGroup>").Append(k_WindowsNewline);
  390. foreach (string file in assembly.sourceFiles)
  391. {
  392. if (!IsSupportedFile(file))
  393. continue;
  394. var extension = Path.GetExtension(file).ToLower();
  395. var fullFile = EscapedRelativePathFor(file);
  396. if (".dll" != extension)
  397. {
  398. projectBuilder.Append(" <Compile Include=\"").Append(fullFile).Append("\" />").Append(k_WindowsNewline);
  399. }
  400. else
  401. {
  402. references.Add(fullFile);
  403. }
  404. }
  405. projectBuilder.Append(@" </ItemGroup>").Append(k_WindowsNewline);
  406. // Append additional non-script files that should be included in project generation.
  407. if (allAssetsProjectParts.TryGetValue(assembly.name, out var additionalAssetsForProject))
  408. {
  409. projectBuilder.Append(@" <ItemGroup>").Append(k_WindowsNewline);
  410. projectBuilder.Append(additionalAssetsForProject);
  411. projectBuilder.Append(@" </ItemGroup>").Append(k_WindowsNewline);
  412. }
  413. projectBuilder.Append(@" <ItemGroup>").Append(k_WindowsNewline);
  414. var responseRefs = responseFilesData.SelectMany(x => x.FullPathReferences.Select(r => r));
  415. var internalAssemblyReferences = assembly.assemblyReferences
  416. .Where(i => !i.sourceFiles.Any(ShouldFileBePartOfSolution)).Select(i => i.outputPath);
  417. var allReferences =
  418. assembly.compiledAssemblyReferences
  419. .Union(responseRefs)
  420. .Union(references)
  421. .Union(internalAssemblyReferences);
  422. foreach (var reference in allReferences)
  423. {
  424. string fullReference = Path.IsPathRooted(reference) ? reference : Path.Combine(ProjectDirectory, reference);
  425. AppendReference(fullReference, projectBuilder);
  426. }
  427. projectBuilder.Append(@" </ItemGroup>").Append(k_WindowsNewline);
  428. if (0 < assembly.assemblyReferences.Length)
  429. {
  430. projectBuilder.Append(" <ItemGroup>").Append(k_WindowsNewline);
  431. foreach (var reference in assembly.assemblyReferences.Where(i => i.sourceFiles.Any(ShouldFileBePartOfSolution)))
  432. {
  433. // If the current assembly is a Player project, we want to project-reference the corresponding Player project
  434. var referenceName = m_AssemblyNameProvider.GetAssemblyName(assembly.outputPath, reference.name);
  435. projectBuilder.Append(" <ProjectReference Include=\"").Append(referenceName).Append(GetProjectExtension()).Append("\">").Append(k_WindowsNewline);
  436. projectBuilder.Append(" <Project>{").Append(ProjectGuid(referenceName)).Append("}</Project>").Append(k_WindowsNewline);
  437. projectBuilder.Append(" <Name>").Append(referenceName).Append("</Name>").Append(k_WindowsNewline);
  438. projectBuilder.Append(" </ProjectReference>").Append(k_WindowsNewline);
  439. }
  440. projectBuilder.Append(@" </ItemGroup>").Append(k_WindowsNewline);
  441. }
  442. projectBuilder.Append(GetProjectFooter());
  443. return projectBuilder.ToString();
  444. }
  445. private static string XmlFilename(string path)
  446. {
  447. if (string.IsNullOrEmpty(path))
  448. return path;
  449. path = path.Replace(@"%", "%25");
  450. path = path.Replace(@";", "%3b");
  451. return XmlEscape(path);
  452. }
  453. private static string XmlEscape(string s)
  454. {
  455. return SecurityElement.Escape(s);
  456. }
  457. private void AppendReference(string fullReference, StringBuilder projectBuilder)
  458. {
  459. var escapedFullPath = EscapedRelativePathFor(fullReference);
  460. projectBuilder.Append(" <Reference Include=\"").Append(Path.GetFileNameWithoutExtension(escapedFullPath)).Append("\">").Append(k_WindowsNewline);
  461. projectBuilder.Append(" <HintPath>").Append(escapedFullPath).Append("</HintPath>").Append(k_WindowsNewline);
  462. projectBuilder.Append(" </Reference>").Append(k_WindowsNewline);
  463. }
  464. public string ProjectFile(Assembly assembly)
  465. {
  466. return Path.Combine(ProjectDirectory, $"{m_AssemblyNameProvider.GetAssemblyName(assembly.outputPath, assembly.name)}.csproj");
  467. }
  468. private static readonly Regex InvalidCharactersRegexPattern = new Regex(@"\?|&|\*|""|<|>|\||#|%|\^|;" + (VisualStudioEditor.IsWindows ? "" : "|:"));
  469. public string SolutionFile()
  470. {
  471. return Path.Combine(ProjectDirectory.NormalizePathSeparators(), $"{InvalidCharactersRegexPattern.Replace(m_ProjectName, "_")}.sln");
  472. }
  473. internal string VsConfigFile()
  474. {
  475. return Path.Combine(ProjectDirectory.NormalizePathSeparators(), ".vsconfig");
  476. }
  477. internal string GetLangVersion(Assembly assembly)
  478. {
  479. var targetLanguageVersion = "latest"; // danger: latest is not the same absolute value depending on the VS version.
  480. if (m_CurrentInstallation != null)
  481. {
  482. var vsLanguageSupport = m_CurrentInstallation.LatestLanguageVersionSupported;
  483. var unityLanguageSupport = UnityInstallation.LatestLanguageVersionSupported(assembly);
  484. // Use the minimal supported version between VS and Unity, so that compilation will work in both
  485. targetLanguageVersion = (vsLanguageSupport <= unityLanguageSupport ? vsLanguageSupport : unityLanguageSupport).ToString(2); // (major, minor) only
  486. }
  487. return targetLanguageVersion;
  488. }
  489. private string ProjectHeader(
  490. Assembly assembly,
  491. ResponseFileData[] responseFilesData
  492. )
  493. {
  494. var projectType = ProjectTypeOf(assembly.name);
  495. string rulesetPath = null;
  496. var analyzers = Array.Empty<string>();
  497. if (m_CurrentInstallation != null && m_CurrentInstallation.SupportsAnalyzers)
  498. {
  499. analyzers = m_CurrentInstallation.GetAnalyzers();
  500. #if UNITY_2020_2_OR_NEWER
  501. analyzers = analyzers != null ? analyzers.Concat(assembly.compilerOptions.RoslynAnalyzerDllPaths).ToArray() : assembly.compilerOptions.RoslynAnalyzerDllPaths;
  502. rulesetPath = assembly.compilerOptions.RoslynAnalyzerRulesetPath;
  503. #endif
  504. }
  505. var projectProperties = new ProjectProperties()
  506. {
  507. ProjectGuid = ProjectGuid(assembly),
  508. LangVersion = GetLangVersion(assembly),
  509. AssemblyName = assembly.name,
  510. RootNamespace = GetRootNamespace(assembly),
  511. OutputPath = assembly.outputPath,
  512. // Analyzers
  513. Analyzers = analyzers,
  514. RulesetPath = rulesetPath,
  515. // RSP alterable
  516. Defines = assembly.defines.Concat(responseFilesData.SelectMany(x => x.Defines)).Distinct().ToArray(),
  517. Unsafe = assembly.compilerOptions.AllowUnsafeCode | responseFilesData.Any(x => x.Unsafe),
  518. // VSTU Flavoring
  519. FlavoringProjectType = projectType + ":" + (int)projectType,
  520. FlavoringBuildTarget = EditorUserBuildSettings.activeBuildTarget + ":" + (int)EditorUserBuildSettings.activeBuildTarget,
  521. FlavoringUnityVersion = Application.unityVersion,
  522. FlavoringPackageVersion = VisualStudioIntegration.PackageVersion(),
  523. };
  524. return GetProjectHeader(projectProperties);
  525. }
  526. private enum ProjectType
  527. {
  528. GamePlugins = 3,
  529. Game = 1,
  530. EditorPlugins = 7,
  531. Editor = 5,
  532. }
  533. private static ProjectType ProjectTypeOf(string fileName)
  534. {
  535. var plugins = fileName.Contains("firstpass");
  536. var editor = fileName.Contains("Editor");
  537. if (plugins && editor)
  538. return ProjectType.EditorPlugins;
  539. if (plugins)
  540. return ProjectType.GamePlugins;
  541. if (editor)
  542. return ProjectType.Editor;
  543. return ProjectType.Game;
  544. }
  545. private string GetProjectHeader(ProjectProperties properties)
  546. {
  547. var header = new[]
  548. {
  549. $@"<?xml version=""1.0"" encoding=""utf-8""?>",
  550. $@"<Project ToolsVersion=""4.0"" DefaultTargets=""Build"" xmlns=""http://schemas.microsoft.com/developer/msbuild/2003"">",
  551. $@" <PropertyGroup>",
  552. $@" <LangVersion>{properties.LangVersion}</LangVersion>",
  553. $@" </PropertyGroup>",
  554. $@" <PropertyGroup>",
  555. $@" <Configuration Condition="" '$(Configuration)' == '' "">Debug</Configuration>",
  556. $@" <Platform Condition="" '$(Platform)' == '' "">AnyCPU</Platform>",
  557. $@" <ProductVersion>10.0.20506</ProductVersion>",
  558. $@" <SchemaVersion>2.0</SchemaVersion>",
  559. $@" <RootNamespace>{properties.RootNamespace}</RootNamespace>",
  560. $@" <ProjectGuid>{{{properties.ProjectGuid}}}</ProjectGuid>",
  561. $@" <OutputType>Library</OutputType>",
  562. $@" <AppDesignerFolder>Properties</AppDesignerFolder>",
  563. $@" <AssemblyName>{properties.AssemblyName}</AssemblyName>",
  564. $@" <TargetFrameworkVersion>v4.7.1</TargetFrameworkVersion>",
  565. $@" <FileAlignment>512</FileAlignment>",
  566. $@" <BaseDirectory>.</BaseDirectory>",
  567. $@" </PropertyGroup>",
  568. $@" <PropertyGroup Condition="" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' "">",
  569. $@" <DebugSymbols>true</DebugSymbols>",
  570. $@" <DebugType>full</DebugType>",
  571. $@" <Optimize>false</Optimize>",
  572. $@" <OutputPath>{properties.OutputPath}</OutputPath>",
  573. $@" <DefineConstants>{string.Join(";", properties.Defines)}</DefineConstants>",
  574. $@" <ErrorReport>prompt</ErrorReport>",
  575. $@" <WarningLevel>4</WarningLevel>",
  576. $@" <NoWarn>0169</NoWarn>",
  577. $@" <AllowUnsafeBlocks>{properties.Unsafe}</AllowUnsafeBlocks>",
  578. $@" </PropertyGroup>",
  579. $@" <PropertyGroup Condition="" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' "">",
  580. $@" <DebugType>pdbonly</DebugType>",
  581. $@" <Optimize>true</Optimize>",
  582. $@" <OutputPath>Temp\bin\Release\</OutputPath>",
  583. $@" <ErrorReport>prompt</ErrorReport>",
  584. $@" <WarningLevel>4</WarningLevel>",
  585. $@" <NoWarn>0169</NoWarn>",
  586. $@" <AllowUnsafeBlocks>{properties.Unsafe}</AllowUnsafeBlocks>",
  587. $@" </PropertyGroup>"
  588. };
  589. var forceExplicitReferences = new[]
  590. {
  591. $@" <PropertyGroup>",
  592. $@" <NoConfig>true</NoConfig>",
  593. $@" <NoStdLib>true</NoStdLib>",
  594. $@" <AddAdditionalExplicitAssemblyReferences>false</AddAdditionalExplicitAssemblyReferences>",
  595. $@" <ImplicitlyExpandNETStandardFacades>false</ImplicitlyExpandNETStandardFacades>",
  596. $@" <ImplicitlyExpandDesignTimeFacades>false</ImplicitlyExpandDesignTimeFacades>",
  597. $@" </PropertyGroup>"
  598. };
  599. var flavoring = new[]
  600. {
  601. $@" <PropertyGroup>",
  602. $@" <ProjectTypeGuids>{{E097FAD1-6243-4DAD-9C02-E9B9EFC3FFC1}};{{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}}</ProjectTypeGuids>",
  603. $@" <UnityProjectGenerator>Package</UnityProjectGenerator>",
  604. $@" <UnityProjectGeneratorVersion>{properties.FlavoringPackageVersion}</UnityProjectGeneratorVersion>",
  605. $@" <UnityProjectType>{properties.FlavoringProjectType}</UnityProjectType>",
  606. $@" <UnityBuildTarget>{properties.FlavoringBuildTarget}</UnityBuildTarget>",
  607. $@" <UnityVersion>{properties.FlavoringUnityVersion}</UnityVersion>",
  608. $@" </PropertyGroup>"
  609. };
  610. var footer = new[]
  611. {
  612. @""
  613. };
  614. var lines = header
  615. .Concat(forceExplicitReferences)
  616. .Concat(flavoring)
  617. .ToList();
  618. if (!string.IsNullOrEmpty(properties.RulesetPath))
  619. {
  620. lines.Add(@" <PropertyGroup>");
  621. lines.Add($" <CodeAnalysisRuleSet>{properties.RulesetPath.MakeAbsolutePath().NormalizePathSeparators()}</CodeAnalysisRuleSet>");
  622. lines.Add(@" </PropertyGroup>");
  623. }
  624. if (properties.Analyzers.Any())
  625. {
  626. lines.Add(@" <ItemGroup>");
  627. foreach (var analyzer in properties.Analyzers.Distinct())
  628. {
  629. lines.Add($@" <Analyzer Include=""{analyzer.MakeAbsolutePath().NormalizePathSeparators()}"" />");
  630. }
  631. lines.Add(@" </ItemGroup>");
  632. }
  633. return string.Join(k_WindowsNewline, lines.Concat(footer));
  634. }
  635. private static string GetProjectFooter()
  636. {
  637. return string.Join(k_WindowsNewline,
  638. @" <Import Project=""$(MSBuildToolsPath)\Microsoft.CSharp.targets"" />",
  639. @" <Target Name=""GenerateTargetFrameworkMonikerAttribute"" />",
  640. @" <!-- To modify your build process, add your task inside one of the targets below and uncomment it.",
  641. @" Other similar extension points exist, see Microsoft.Common.targets.",
  642. @" <Target Name=""BeforeBuild"">",
  643. @" </Target>",
  644. @" <Target Name=""AfterBuild"">",
  645. @" </Target>",
  646. @" -->",
  647. @"</Project>",
  648. @"");
  649. }
  650. private static string GetSolutionText()
  651. {
  652. return string.Join(k_WindowsNewline,
  653. @"",
  654. @"Microsoft Visual Studio Solution File, Format Version {0}",
  655. @"# Visual Studio {1}",
  656. @"{2}",
  657. @"Global",
  658. @" GlobalSection(SolutionConfigurationPlatforms) = preSolution",
  659. @" Debug|Any CPU = Debug|Any CPU",
  660. @" Release|Any CPU = Release|Any CPU",
  661. @" EndGlobalSection",
  662. @" GlobalSection(ProjectConfigurationPlatforms) = postSolution",
  663. @"{3}",
  664. @" EndGlobalSection",
  665. @"{4}",
  666. @"EndGlobal",
  667. @"").Replace(" ", "\t");
  668. }
  669. private void SyncSolution(IEnumerable<Assembly> assemblies)
  670. {
  671. if (InvalidCharactersRegexPattern.IsMatch(ProjectDirectory))
  672. Debug.LogWarning("Project path contains special characters, which can be an issue when opening Visual Studio");
  673. var solutionFile = SolutionFile();
  674. var previousSolution = m_FileIOProvider.Exists(solutionFile) ? SolutionParser.ParseSolutionFile(solutionFile, m_FileIOProvider) : null;
  675. SyncSolutionFileIfNotChanged(solutionFile, SolutionText(assemblies, previousSolution));
  676. }
  677. private string SolutionText(IEnumerable<Assembly> assemblies, Solution previousSolution = null)
  678. {
  679. const string fileversion = "12.00";
  680. const string vsversion = "15";
  681. var relevantAssemblies = RelevantAssembliesForMode(assemblies);
  682. var generatedProjects = ToProjectEntries(relevantAssemblies).ToList();
  683. SolutionProperties[] properties = null;
  684. // First, add all projects generated by Unity to the solution
  685. var projects = new List<SolutionProjectEntry>();
  686. projects.AddRange(generatedProjects);
  687. if (previousSolution != null)
  688. {
  689. // Add all projects that were previously in the solution and that are not generated by Unity, nor generated in the project root directory
  690. var externalProjects = previousSolution.Projects
  691. .Where(p => p.IsSolutionFolderProjectFactory() || !FileUtility.IsFileInProjectRootDirectory(p.FileName))
  692. .Where(p => generatedProjects.All(gp => gp.FileName != p.FileName));
  693. projects.AddRange(externalProjects);
  694. properties = previousSolution.Properties;
  695. }
  696. string propertiesText = GetPropertiesText(properties);
  697. string projectEntriesText = GetProjectEntriesText(projects);
  698. // do not generate configurations for SolutionFolders
  699. var configurableProjects = projects.Where(p => !p.IsSolutionFolderProjectFactory());
  700. string projectConfigurationsText = string.Join(k_WindowsNewline, configurableProjects.Select(p => GetProjectActiveConfigurations(p.ProjectGuid)).ToArray());
  701. return string.Format(GetSolutionText(), fileversion, vsversion, projectEntriesText, projectConfigurationsText, propertiesText);
  702. }
  703. private static IEnumerable<Assembly> RelevantAssembliesForMode(IEnumerable<Assembly> assemblies)
  704. {
  705. return assemblies.Where(i => ScriptingLanguage.CSharp == ScriptingLanguageFor(i));
  706. }
  707. private static string GetPropertiesText(SolutionProperties[] array)
  708. {
  709. if (array == null || array.Length == 0)
  710. {
  711. // HideSolution by default
  712. array = new [] {
  713. new SolutionProperties() {
  714. Name = "SolutionProperties",
  715. Type = "preSolution",
  716. Entries = new List<KeyValuePair<string,string>>() { new KeyValuePair<string, string> ("HideSolutionNode", "FALSE") }
  717. }
  718. };
  719. }
  720. var result = new StringBuilder();
  721. for (var i = 0; i < array.Length; i++)
  722. {
  723. if (i > 0)
  724. result.Append(k_WindowsNewline);
  725. var properties = array[i];
  726. result.Append($"\tGlobalSection({properties.Name}) = {properties.Type}");
  727. result.Append(k_WindowsNewline);
  728. foreach (var entry in properties.Entries)
  729. {
  730. result.Append($"\t\t{entry.Key} = {entry.Value}");
  731. result.Append(k_WindowsNewline);
  732. }
  733. result.Append("\tEndGlobalSection");
  734. }
  735. return result.ToString();
  736. }
  737. /// <summary>
  738. /// Get a Project("{guid}") = "MyProject", "MyProject.unityproj", "{projectguid}"
  739. /// entry for each relevant language
  740. /// </summary>
  741. private string GetProjectEntriesText(IEnumerable<SolutionProjectEntry> entries)
  742. {
  743. var projectEntries = entries.Select(entry => string.Format(
  744. m_SolutionProjectEntryTemplate,
  745. entry.ProjectFactoryGuid, entry.Name, entry.FileName, entry.ProjectGuid, entry.Metadata
  746. ));
  747. return string.Join(k_WindowsNewline, projectEntries.ToArray());
  748. }
  749. private IEnumerable<SolutionProjectEntry> ToProjectEntries(IEnumerable<Assembly> assemblies)
  750. {
  751. foreach (var assembly in assemblies)
  752. yield return new SolutionProjectEntry()
  753. {
  754. ProjectFactoryGuid = SolutionGuid(assembly),
  755. Name = assembly.name,
  756. FileName = Path.GetFileName(ProjectFile(assembly)),
  757. ProjectGuid = ProjectGuid(assembly),
  758. Metadata = k_WindowsNewline
  759. };
  760. }
  761. /// <summary>
  762. /// Generate the active configuration string for a given project guid
  763. /// </summary>
  764. private string GetProjectActiveConfigurations(string projectGuid)
  765. {
  766. return string.Format(
  767. m_SolutionProjectConfigurationTemplate,
  768. projectGuid);
  769. }
  770. private string EscapedRelativePathFor(string file)
  771. {
  772. var projectDir = ProjectDirectory.NormalizePathSeparators();
  773. file = file.NormalizePathSeparators();
  774. var path = SkipPathPrefix(file, projectDir);
  775. var packageInfo = m_AssemblyNameProvider.FindForAssetPath(path.Replace('\\', '/'));
  776. if (packageInfo != null)
  777. {
  778. // We have to normalize the path, because the PackageManagerRemapper assumes
  779. // dir seperators will be os specific.
  780. var absolutePath = Path.GetFullPath(path.NormalizePathSeparators());
  781. path = SkipPathPrefix(absolutePath, projectDir);
  782. }
  783. return XmlFilename(path);
  784. }
  785. private static string SkipPathPrefix(string path, string prefix)
  786. {
  787. if (path.StartsWith($"{prefix}{Path.DirectorySeparatorChar}") && (path.Length > prefix.Length))
  788. return path.Substring(prefix.Length + 1);
  789. return path;
  790. }
  791. static string GetProjectExtension()
  792. {
  793. return ".csproj";
  794. }
  795. private string ProjectGuid(string assemblyName)
  796. {
  797. return m_GUIDGenerator.ProjectGuid(m_ProjectName, assemblyName);
  798. }
  799. private string ProjectGuid(Assembly assembly)
  800. {
  801. return ProjectGuid(m_AssemblyNameProvider.GetAssemblyName(assembly.outputPath, assembly.name));
  802. }
  803. private string SolutionGuid(Assembly assembly)
  804. {
  805. return m_GUIDGenerator.SolutionGuid(m_ProjectName, ScriptingLanguageFor(assembly));
  806. }
  807. private static string GetRootNamespace(Assembly assembly)
  808. {
  809. #if UNITY_2020_2_OR_NEWER
  810. return assembly.rootNamespace;
  811. #else
  812. return EditorSettings.projectGenerationRootNamespace;
  813. #endif
  814. }
  815. }
  816. public static class SolutionGuidGenerator
  817. {
  818. public static string GuidForProject(string projectName)
  819. {
  820. return ComputeGuidHashFor(projectName + "salt");
  821. }
  822. public static string GuidForSolution(string projectName, ScriptingLanguage language)
  823. {
  824. if (language == ScriptingLanguage.CSharp)
  825. {
  826. // GUID for a C# class library: http://www.codeproject.com/Reference/720512/List-of-Visual-Studio-Project-Type-GUIDs
  827. return "FAE04EC0-301F-11D3-BF4B-00C04F79EFBC";
  828. }
  829. return ComputeGuidHashFor(projectName);
  830. }
  831. private static string ComputeGuidHashFor(string input)
  832. {
  833. var hash = MD5.Create().ComputeHash(Encoding.Default.GetBytes(input));
  834. return HashAsGuid(HashToString(hash));
  835. }
  836. private static string HashAsGuid(string hash)
  837. {
  838. var guid = hash.Substring(0, 8) + "-" + hash.Substring(8, 4) + "-" + hash.Substring(12, 4) + "-" + hash.Substring(16, 4) + "-" + hash.Substring(20, 12);
  839. return guid.ToUpper();
  840. }
  841. private static string HashToString(byte[] bs)
  842. {
  843. var sb = new StringBuilder();
  844. foreach (byte b in bs)
  845. sb.Append(b.ToString("x2"));
  846. return sb.ToString();
  847. }
  848. }
  849. }