ProjectGeneration.cs 33 KB

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