ProjectGeneration.cs 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Linq;
  5. using System.Security;
  6. using System.Text;
  7. using System.Text.RegularExpressions;
  8. using System.Threading;
  9. using System.Threading.Tasks;
  10. using SingularityGroup.HotReload;
  11. using SingularityGroup.HotReload.Editor.Util;
  12. using SingularityGroup.HotReload.Newtonsoft.Json;
  13. using UnityEditor;
  14. using UnityEditor.Compilation;
  15. using UnityEditor.PackageManager;
  16. using UnityEditorInternal;
  17. using Assembly = UnityEditor.Compilation.Assembly;
  18. using PackageInfo = UnityEditor.PackageManager.PackageInfo;
  19. #if UNITY_2019_1_OR_NEWER
  20. using System.Reflection;
  21. #endif
  22. namespace SingularityGroup.HotReload.Editor.ProjectGeneration {
  23. class ProjectGeneration {
  24. private enum ScriptingLanguage {
  25. None,
  26. CSharp
  27. }
  28. [Serializable]
  29. class Config {
  30. public string projectExclusionRegex;
  31. public HashSet<string> projectBlacklist;
  32. public HashSet<string> polyfillSourceFiles;
  33. public bool excludeAllAnalyzers;
  34. public bool useBuiltInProjectGeneration;
  35. }
  36. public static readonly string MSBuildNamespaceUri = "http://schemas.microsoft.com/developer/msbuild/2003";
  37. /// <summary>
  38. /// Map source extensions to ScriptingLanguages
  39. /// </summary>
  40. private static readonly Dictionary<string, ScriptingLanguage> k_BuiltinSupportedExtensions =
  41. new Dictionary<string, ScriptingLanguage> {
  42. { "cs", ScriptingLanguage.CSharp },
  43. { "uxml", ScriptingLanguage.None },
  44. { "uss", ScriptingLanguage.None },
  45. { "shader", ScriptingLanguage.None },
  46. { "compute", ScriptingLanguage.None },
  47. { "cginc", ScriptingLanguage.None },
  48. { "hlsl", ScriptingLanguage.None },
  49. { "glslinc", ScriptingLanguage.None },
  50. { "template", ScriptingLanguage.None },
  51. { "raytrace", ScriptingLanguage.None },
  52. { "json", ScriptingLanguage.None },
  53. { "rsp", ScriptingLanguage.None },
  54. { "asmdef", ScriptingLanguage.None },
  55. { "asmref", ScriptingLanguage.None },
  56. { "xaml", ScriptingLanguage.None },
  57. { "tt", ScriptingLanguage.None },
  58. { "t4", ScriptingLanguage.None },
  59. { "ttinclude", ScriptingLanguage.None }
  60. };
  61. private string m_SolutionProjectEntryTemplate = string.Join(Environment.NewLine,
  62. @"Project(""{{{0}}}"") = ""{1}"", ""{2}"", ""{{{3}}}""",
  63. @"EndProject").Replace(" ", "\t");
  64. private string m_SolutionProjectConfigurationTemplate = string.Join(Environment.NewLine,
  65. @" {{{0}}}.Debug|Any CPU.ActiveCfg = Debug|Any CPU",
  66. @" {{{0}}}.Debug|Any CPU.Build.0 = Debug|Any CPU").Replace(" ", "\t");
  67. private string[] m_ProjectSupportedExtensions = new string[0];
  68. private readonly string m_ProjectName;
  69. private readonly string m_ProjectDirectory;
  70. private readonly string m_SolutionDirectory;
  71. private readonly IFileIO m_FileIOProvider;
  72. private readonly IGUIDGenerator m_GUIDGenerator;
  73. private static readonly SemaphoreSlim gate = new SemaphoreSlim(1, 1);
  74. private const string k_ToolsVersion = "4.0";
  75. private const string k_ProductVersion = "10.0.20506";
  76. private const string k_BaseDirectory = ".";
  77. #if !UNITY_2020_2_OR_NEWER
  78. private const string k_TargetLanguageVersion = "latest";
  79. #endif
  80. // ReSharper disable once CollectionNeverUpdated.Local
  81. private readonly Dictionary<string, UnityEditor.PackageManager.PackageInfo> m_PackageInfoCache =
  82. new Dictionary<string, UnityEditor.PackageManager.PackageInfo>();
  83. private Assembly[] m_AllEditorAssemblies;
  84. private Assembly[] m_AllPlayerAssemblies;
  85. private string[] m_AllAssetPaths;
  86. private string m_EngineAssemblyPath;
  87. private string m_EditorAssemblyPath;
  88. private bool m_SuppressCommonWarnings;
  89. private string m_FallbackRootNamespace;
  90. private IHotReloadProjectGenerationPostProcessor[] m_PostProcessors;
  91. public static bool IsSyncing => gate.CurrentCount == 0;
  92. internal const string tempDir = PackageConst.LibraryCachePath + "/Solution";
  93. public static string GetUnityProjectDirectory(string dataPath) => new DirectoryInfo(dataPath).Parent.FullName;
  94. public static string GetSolutionFilePath(string dataPath) => Path.Combine(tempDir, Path.GetFileName(GetUnityProjectDirectory(dataPath)) + ".sln");
  95. public static Task GenerateSlnAndCsprojFiles(string dataPath) {
  96. if (!IsSyncing) {
  97. return GenerateAsync(dataPath);
  98. }
  99. return Task.CompletedTask;
  100. }
  101. public static Task EnsureSlnAndCsprojFiles(string dataPath) {
  102. if (File.Exists(GetSolutionFilePath(dataPath))) {
  103. return Task.CompletedTask;
  104. }
  105. return GenerateAsync(dataPath);
  106. }
  107. private static Task GenerateAsync(string dataPath) {
  108. Directory.CreateDirectory(tempDir);
  109. var gen = new ProjectGeneration(tempDir, GetUnityProjectDirectory(dataPath));
  110. return gen.Sync();
  111. }
  112. public ProjectGeneration(string solutionDirectory, string unityProjectDirectory) {
  113. m_ProjectDirectory = unityProjectDirectory;
  114. m_SolutionDirectory = solutionDirectory;
  115. m_ProjectName = Path.GetFileName(unityProjectDirectory);
  116. m_FileIOProvider = new FileIOProvider();
  117. m_GUIDGenerator = new GUIDProvider();
  118. }
  119. public async Task Sync() {
  120. await ThreadUtility.SwitchToThreadPool();
  121. var config = LoadConfig();
  122. if (config.useBuiltInProjectGeneration) {
  123. return;
  124. }
  125. await ThreadUtility.SwitchToMainThread();
  126. await gate.WaitAsync();
  127. try {
  128. //Cache all data that is accessed via unity API on the unity main thread.
  129. m_AllAssetPaths = AssetDatabase.GetAllAssetPaths();
  130. m_ProjectSupportedExtensions = EditorSettings.projectGenerationUserExtensions;
  131. m_EngineAssemblyPath = InternalEditorUtility.GetEngineAssemblyPath();
  132. m_EditorAssemblyPath = InternalEditorUtility.GetEditorAssemblyPath();
  133. m_FallbackRootNamespace = EditorSettings.projectGenerationRootNamespace;
  134. m_SuppressCommonWarnings =
  135. #if UNITY_2020_1_OR_NEWER
  136. PlayerSettings.suppressCommonWarnings;
  137. #else
  138. false;
  139. #endif
  140. //Do the remaining work on a separate thread
  141. await Task.WhenAll(
  142. BuildPackageInfoCache(),
  143. BuildEditorAssemblies(),
  144. BuildPostProcessors()
  145. );
  146. await GenerateAndWriteSolutionAndProjects(config);
  147. } finally {
  148. gate.Release();
  149. }
  150. }
  151. private Config LoadConfig() {
  152. var configPath = Path.Combine(m_ProjectDirectory, PackageConst.ConfigFileName);
  153. Config config;
  154. if(File.Exists(configPath)) {
  155. config = JsonConvert.DeserializeObject<Config>(File.ReadAllText(configPath));
  156. } else {
  157. config = new Config();
  158. }
  159. return config;
  160. }
  161. private bool ShouldFileBePartOfSolution(string file) {
  162. // Exclude files coming from packages except if they are internalized.
  163. if (IsInternalizedPackagePath(file)) {
  164. return false;
  165. }
  166. return HasValidExtension(file);
  167. }
  168. public bool HasValidExtension(string file) {
  169. var extension = Path.GetExtension(file);
  170. // Dll's are not scripts but still need to be included..
  171. if (file.Equals(".dll", StringComparison.OrdinalIgnoreCase))
  172. return true;
  173. return IsSupportedExtension(extension);
  174. }
  175. private bool IsSupportedExtension(string extension) {
  176. extension = extension.TrimStart('.');
  177. return k_BuiltinSupportedExtensions.ContainsKey(extension) || m_ProjectSupportedExtensions.Contains(extension);
  178. }
  179. async Task GenerateAndWriteSolutionAndProjects(Config config) {
  180. await ThreadUtility.SwitchToThreadPool();
  181. var projectExclusionRegex = config.projectExclusionRegex != null ? new Regex(config.projectExclusionRegex, RegexOptions.Compiled | RegexOptions.Singleline) : null;
  182. var projectBlacklist = config.projectBlacklist ?? new HashSet<string>();
  183. var polyfillSourceFiles = config.polyfillSourceFiles ?? new HashSet<string>();
  184. var filteredProjects = new HashSet<string>();
  185. var runtimeDependenciesBuilder = new List<string>();
  186. runtimeDependenciesBuilder.Add(typeof(HarmonyLib.DetourApi).Assembly.Location);
  187. # if UNITY_2019_4_OR_NEWER
  188. runtimeDependenciesBuilder.Add(typeof(Helper2019).Assembly.Location);
  189. #endif
  190. # if UNITY_2020_3_OR_NEWER
  191. runtimeDependenciesBuilder.Add(typeof(Helper2020).Assembly.Location);
  192. #endif
  193. # if UNITY_2022_2_OR_NEWER
  194. runtimeDependenciesBuilder.Add(typeof(Helper2022).Assembly.Location);
  195. #endif
  196. var runtimeDependencies = runtimeDependenciesBuilder.ToArray();
  197. // Only synchronize islands that have associated source files and ones that we actually want in the project.
  198. // This also filters out DLLs coming from .asmdef files in packages.
  199. var assemblies = GetAssemblies(ShouldFileBePartOfSolution).ToArray();
  200. var projectParts = new List<ProjectPart>();
  201. foreach (var assembly in assemblies) {
  202. if(projectExclusionRegex != null && projectExclusionRegex.IsMatch(assembly.name)) {
  203. filteredProjects.Add(assembly.name);
  204. continue;
  205. }
  206. var part = new ProjectPart(assembly.name, assembly, "", m_FallbackRootNamespace, polyfillSourceFiles);
  207. string projectPath;
  208. # if (UNITY_2021_3_OR_NEWER)
  209. projectPath = Path.GetRelativePath(m_ProjectDirectory, ProjectFile(part)).Replace('\\', '/');
  210. # else
  211. projectPath = ProjectFile(part).Replace('\\', '/').Replace(m_ProjectDirectory.Replace('\\', '/'), "");
  212. #endif
  213. if(projectBlacklist.Contains(projectPath)) {
  214. filteredProjects.Add(assembly.name);
  215. continue;
  216. }
  217. projectParts.Add(part);
  218. }
  219. SyncSolution(projectParts.ToArray());
  220. await ThreadUtility.SwitchToMainThread();
  221. var responseFiles = new List<ResponseFileData>[projectParts.Count];
  222. for (var i = 0; i < projectParts.Count; i++) {
  223. responseFiles[i] = projectParts[i].ParseResponseFileData(m_ProjectDirectory).ToList();
  224. }
  225. await ThreadUtility.SwitchToThreadPool();
  226. for (var i = 0; i < projectParts.Count; i++) {
  227. SyncProject(projectParts[i], responseFiles[i], filteredProjects, runtimeDependencies, config);
  228. }
  229. foreach (var pp in m_PostProcessors) {
  230. try {
  231. pp.OnGeneratedCSProjectFilesThreaded();
  232. } catch (Exception ex) {
  233. Log.Warning("Post processor '{0}' threw exception when calling OnGeneratedCSProjectFilesThreaded:\n{1}", pp, ex);
  234. }
  235. }
  236. }
  237. private void SyncProject(
  238. ProjectPart island,
  239. List<ResponseFileData> responseFileData,
  240. HashSet<string> filteredProjects,
  241. string[] runtimeDependencies,
  242. Config config) {
  243. SyncProjectFileIfNotChanged(
  244. ProjectFile(island),
  245. ProjectText(island, responseFileData, filteredProjects, runtimeDependencies, config));
  246. }
  247. private void SyncProjectFileIfNotChanged(string path, string newContents) {
  248. foreach (var pp in m_PostProcessors) {
  249. try {
  250. newContents = pp.OnGeneratedCSProjectThreaded(path, newContents);
  251. } catch (Exception ex) {
  252. Log.Warning("Post processor '{0}' failed when processing project '{1}':\n{2}", pp, path, ex);
  253. }
  254. }
  255. SyncFileIfNotChanged(path, newContents);
  256. }
  257. private void SyncSolutionFileIfNotChanged(string path, string newContents) {
  258. foreach (var pp in m_PostProcessors) {
  259. try {
  260. newContents = pp.OnGeneratedSlnSolutionThreaded(path, newContents);
  261. } catch (Exception ex) {
  262. Log.Warning("Post processor '{0}' failed when processing solution '{1}':\n{2}", pp, path, ex);
  263. }
  264. }
  265. SyncFileIfNotChanged(path, newContents);
  266. }
  267. private void SyncFileIfNotChanged(string path, string newContents) {
  268. try {
  269. if (m_FileIOProvider.Exists(path) && newContents == m_FileIOProvider.ReadAllText(path)) {
  270. return;
  271. }
  272. } catch (Exception exception) {
  273. Log.Exception(exception);
  274. }
  275. m_FileIOProvider.WriteAllText(path, newContents);
  276. }
  277. private string ProjectText(ProjectPart assembly, List<ResponseFileData> responseFilesData, HashSet<string> filteredProjects, string[] runtimeDependencies, Config config) {
  278. var projectBuilder = new StringBuilder(ProjectHeader(assembly, responseFilesData, config));
  279. foreach (var file in assembly.SourceFiles) {
  280. var fullFile = m_FileIOProvider.EscapedRelativePathFor(file, m_SolutionDirectory);
  281. projectBuilder.Append(" <Compile Include=\"").Append(fullFile).Append("\" />").Append(Environment.NewLine);
  282. }
  283. projectBuilder.Append(assembly.AssetsProjectPart);
  284. var responseRefs = responseFilesData.SelectMany(x => x.FullPathReferences.Select(r => r));
  285. var internalAssemblyReferences = assembly.AssemblyReferences
  286. .Where(reference => filteredProjects.Contains(reference.name) || !reference.sourceFiles.Any(ShouldFileBePartOfSolution)).Select(i => i.outputPath);
  287. var allReferences =
  288. assembly.CompiledAssemblyReferences
  289. .Union(responseRefs)
  290. .Union(internalAssemblyReferences).ToArray();
  291. foreach (var reference in allReferences) {
  292. var fullReference = Path.IsPathRooted(reference) ? reference : Path.Combine(m_ProjectDirectory, reference);
  293. AppendReference(fullReference, projectBuilder);
  294. }
  295. foreach (var path in runtimeDependencies) {
  296. AppendReference(path, projectBuilder);
  297. }
  298. if (assembly.AssemblyReferences.Length > 0) {
  299. projectBuilder.Append(" </ItemGroup>").Append(Environment.NewLine);
  300. projectBuilder.Append(" <ItemGroup>").Append(Environment.NewLine);
  301. foreach (var reference in assembly.AssemblyReferences.Where(i => !filteredProjects.Contains(i.name) && i.sourceFiles.Any(ShouldFileBePartOfSolution))) {
  302. var name = GetProjectName(reference.name, reference.defines);
  303. projectBuilder.Append(" <ProjectReference Include=\"").Append(name).Append(".csproj").Append("\">")
  304. .Append(Environment.NewLine);
  305. projectBuilder.Append(" <Project>{").Append(ProjectGuid(name)).Append("}</Project>").Append(Environment.NewLine);
  306. projectBuilder.Append(" <Name>").Append(name).Append("</Name>").Append(Environment.NewLine);
  307. projectBuilder.Append(" </ProjectReference>").Append(Environment.NewLine);
  308. }
  309. }
  310. projectBuilder.Append(ProjectFooter());
  311. return projectBuilder.ToString();
  312. }
  313. private static void AppendReference(string fullReference, StringBuilder projectBuilder) {
  314. var escapedFullPath = SecurityElement.Escape(fullReference);
  315. escapedFullPath = escapedFullPath.NormalizePath();
  316. projectBuilder.Append(" <Reference Include=\"").Append(FileSystemUtil.FileNameWithoutExtension(escapedFullPath))
  317. .Append("\">").Append(Environment.NewLine);
  318. projectBuilder.Append(" <HintPath>").Append(escapedFullPath).Append("</HintPath>").Append(Environment.NewLine);
  319. projectBuilder.Append(" </Reference>").Append(Environment.NewLine);
  320. }
  321. private string ProjectFile(ProjectPart projectPart) {
  322. return Path.Combine(m_SolutionDirectory, $"{GetProjectName(projectPart.Name, projectPart.Defines)}.csproj");
  323. }
  324. public string SolutionFile() {
  325. return Path.Combine(m_SolutionDirectory, $"{m_ProjectName}.sln");
  326. }
  327. private string ProjectHeader(
  328. ProjectPart assembly,
  329. List<ResponseFileData> responseFilesData,
  330. Config config
  331. ) {
  332. var otherResponseFilesData = GetOtherArgumentsFromResponseFilesData(responseFilesData);
  333. var arguments = new object[] {
  334. k_ToolsVersion,
  335. k_ProductVersion,
  336. ProjectGuid(GetProjectName(assembly.Name, assembly.Defines)),
  337. m_EngineAssemblyPath,
  338. m_EditorAssemblyPath,
  339. string.Join(";", assembly.Defines.Concat(responseFilesData.SelectMany(x => x.Defines)).Distinct().ToArray()),
  340. MSBuildNamespaceUri,
  341. assembly.Name,
  342. assembly.OutputPath,
  343. assembly.RootNamespace,
  344. "",
  345. GenerateLangVersion(otherResponseFilesData["langversion"], assembly),
  346. k_BaseDirectory,
  347. assembly.CompilerOptions.AllowUnsafeCode | responseFilesData.Any(x => x.Unsafe),
  348. GenerateNoWarn(otherResponseFilesData["nowarn"].Distinct().ToList()),
  349. config.excludeAllAnalyzers ? "" : GenerateAnalyserItemGroup(RetrieveRoslynAnalyzers(assembly, otherResponseFilesData)),
  350. config.excludeAllAnalyzers ? "" : GenerateAnalyserAdditionalFiles(otherResponseFilesData["additionalfile"].SelectMany(x=>x.Split(';')).Distinct().ToArray()),
  351. config.excludeAllAnalyzers ? "" : GenerateRoslynAnalyzerRulesetPath(assembly, otherResponseFilesData),
  352. GenerateWarningLevel(otherResponseFilesData["warn"].Concat(otherResponseFilesData["w"]).Distinct()),
  353. GenerateWarningAsError(otherResponseFilesData["warnaserror"], otherResponseFilesData["warnaserror-"],
  354. otherResponseFilesData["warnaserror+"]),
  355. GenerateDocumentationFile(otherResponseFilesData["doc"].ToArray()),
  356. GenerateNullable(otherResponseFilesData["nullable"])
  357. };
  358. try {
  359. return string.Format(GetProjectHeaderTemplate(), arguments);
  360. } catch (Exception) {
  361. throw new NotSupportedException(
  362. "Failed creating c# project because the c# project header did not have the correct amount of arguments, which is " +
  363. arguments.Length);
  364. }
  365. }
  366. string[] RetrieveRoslynAnalyzers(ProjectPart assembly, ILookup<string, string> otherResponseFilesData) {
  367. var otherAnalyzers = otherResponseFilesData["a"] ?? Array.Empty<string>();
  368. #if UNITY_2020_2_OR_NEWER
  369. return otherResponseFilesData["analyzer"].Concat(otherAnalyzers)
  370. .SelectMany(x=>x.Split(';'))
  371. // #if !ROSLYN_ANALYZER_FIX
  372. // .Concat(GetRoslynAnalyzerPaths())
  373. // #else
  374. .Concat(assembly.CompilerOptions.RoslynAnalyzerDllPaths ?? Array.Empty<string>())
  375. // #endif
  376. .Select(MakeAbsolutePath)
  377. .Distinct()
  378. .ToArray();
  379. #else
  380. return otherResponseFilesData["analyzer"].Concat(otherAnalyzers)
  381. .SelectMany(x=>x.Split(';'))
  382. .Distinct()
  383. .Select(MakeAbsolutePath)
  384. .ToArray();
  385. #endif
  386. }
  387. private static string GenerateAnalyserItemGroup(string[] paths) {
  388. // <ItemGroup>
  389. // <Analyzer Include="..\packages\Comments_analyser.1.0.6626.21356\analyzers\dotnet\cs\Comments_analyser.dll" />
  390. // <Analyzer Include="..\packages\UnityEngineAnalyzer.1.0.0.0\analyzers\dotnet\cs\UnityEngineAnalyzer.dll" />
  391. // </ItemGroup>
  392. if (!paths.Any())
  393. return string.Empty;
  394. var analyserBuilder = new StringBuilder();
  395. analyserBuilder.AppendLine(" <ItemGroup>");
  396. foreach (var path in paths) {
  397. analyserBuilder.AppendLine($" <Analyzer Include=\"{path.NormalizePath()}\" />");
  398. }
  399. analyserBuilder.AppendLine(" </ItemGroup>");
  400. return analyserBuilder.ToString();
  401. }
  402. private string GenerateRoslynAnalyzerRulesetPath(ProjectPart assembly, ILookup<string, string> otherResponseFilesData) {
  403. #if UNITY_2020_2_OR_NEWER
  404. return GenerateAnalyserRuleSet(otherResponseFilesData["ruleset"].Append(assembly.CompilerOptions.RoslynAnalyzerRulesetPath)
  405. .Where(a => !string.IsNullOrEmpty(a)).Distinct().Select(x => MakeAbsolutePath(x).NormalizePath()).ToArray());
  406. #else
  407. return GenerateAnalyserRuleSet(otherResponseFilesData["ruleset"].Distinct().Select(x => MakeAbsolutePath(x).NormalizePath()).ToArray());
  408. #endif
  409. }
  410. private static string GenerateAnalyserRuleSet(string[] paths) {
  411. //<CodeAnalysisRuleSet>..\path\to\myrules.ruleset</CodeAnalysisRuleSet>
  412. if (!paths.Any())
  413. return string.Empty;
  414. return
  415. $"{Environment.NewLine}{string.Join(Environment.NewLine, paths.Select(a => $" <CodeAnalysisRuleSet>{a}</CodeAnalysisRuleSet>"))}";
  416. }
  417. private static string MakeAbsolutePath(string path) {
  418. return Path.IsPathRooted(path) ? path : Path.GetFullPath(path);
  419. }
  420. private string GenerateNullable(IEnumerable<string> enumerable) {
  421. var val = enumerable.FirstOrDefault();
  422. if (string.IsNullOrWhiteSpace(val))
  423. return string.Empty;
  424. return $"{Environment.NewLine} <Nullable>{val}</Nullable>";
  425. }
  426. private static string GenerateDocumentationFile(string[] paths) {
  427. if (!paths.Any())
  428. return String.Empty;
  429. return $"{Environment.NewLine}{string.Join(Environment.NewLine, paths.Select(a => $" <DocumentationFile>{a}</DocumentationFile>"))}";
  430. }
  431. private static string GenerateWarningAsError(IEnumerable<string> args, IEnumerable<string> argsMinus, IEnumerable<string> argsPlus) {
  432. var returnValue = String.Empty;
  433. var allWarningsAsErrors = false;
  434. var warningIds = new List<string>();
  435. foreach (var s in args) {
  436. if (s == "+" || s == string.Empty) allWarningsAsErrors = true;
  437. else if (s == "-") allWarningsAsErrors = false;
  438. else {
  439. warningIds.Add(s);
  440. }
  441. }
  442. warningIds.AddRange(argsPlus);
  443. returnValue += $@" <TreatWarningsAsErrors>{allWarningsAsErrors}</TreatWarningsAsErrors>";
  444. if (warningIds.Any()) {
  445. returnValue += $"{Environment.NewLine} <WarningsAsErrors>{string.Join(";", warningIds)}</WarningsAsErrors>";
  446. }
  447. if (argsMinus.Any())
  448. returnValue += $"{Environment.NewLine} <WarningsNotAsErrors>{string.Join(";", argsMinus)}</WarningsNotAsErrors>";
  449. return $"{Environment.NewLine}{returnValue}";
  450. }
  451. private static string GenerateWarningLevel(IEnumerable<string> warningLevel) {
  452. var level = warningLevel.FirstOrDefault();
  453. if (!string.IsNullOrWhiteSpace(level))
  454. return level;
  455. return 4.ToString();
  456. }
  457. private static string GetSolutionText() {
  458. return string.Join(Environment.NewLine,
  459. @"",
  460. @"Microsoft Visual Studio Solution File, Format Version {0}",
  461. @"# Visual Studio {1}",
  462. @"{2}",
  463. @"Global",
  464. @" GlobalSection(SolutionConfigurationPlatforms) = preSolution",
  465. @" Debug|Any CPU = Debug|Any CPU",
  466. @" EndGlobalSection",
  467. @" GlobalSection(ProjectConfigurationPlatforms) = postSolution",
  468. @"{3}",
  469. @" EndGlobalSection",
  470. @" GlobalSection(SolutionProperties) = preSolution",
  471. @" HideSolutionNode = FALSE",
  472. @" EndGlobalSection",
  473. @"EndGlobal",
  474. @"").Replace(" ", "\t");
  475. }
  476. private static string GetProjectFooterTemplate() {
  477. return string.Join(Environment.NewLine,
  478. @" </ItemGroup>",
  479. @" <Import Project=""$(MSBuildToolsPath)\Microsoft.CSharp.targets"" />",
  480. @" <!-- To modify your build process, add your task inside one of the targets below and uncomment it.",
  481. @" Other similar extension points exist, see Microsoft.Common.targets.",
  482. @" <Target Name=""BeforeBuild"">",
  483. @" </Target>",
  484. @" <Target Name=""AfterBuild"">",
  485. @" </Target>",
  486. @" -->",
  487. @"</Project>",
  488. @"");
  489. }
  490. private static string GetProjectHeaderTemplate() {
  491. var header = new[] {
  492. @"<?xml version=""1.0"" encoding=""utf-8""?>",
  493. @"<Project ToolsVersion=""{0}"" DefaultTargets=""Build"" xmlns=""{6}"">",
  494. @" <PropertyGroup>",
  495. @" <LangVersion>{11}</LangVersion>",
  496. @" <_TargetFrameworkDirectories>non_empty_path_generated_by_unity.rider.package</_TargetFrameworkDirectories>",
  497. @" <_FullFrameworkReferenceAssemblyPaths>non_empty_path_generated_by_unity.rider.package</_FullFrameworkReferenceAssemblyPaths>",
  498. @" <DisableHandlePackageFileConflicts>true</DisableHandlePackageFileConflicts>{17}",
  499. @" </PropertyGroup>",
  500. @" <PropertyGroup>",
  501. @" <Configuration Condition="" '$(Configuration)' == '' "">Debug</Configuration>",
  502. @" <Platform Condition="" '$(Platform)' == '' "">AnyCPU</Platform>",
  503. @" <ProductVersion>{1}</ProductVersion>",
  504. @" <SchemaVersion>2.0</SchemaVersion>",
  505. @" <RootNamespace>{9}</RootNamespace>",
  506. @" <ProjectGuid>{{{2}}}</ProjectGuid>",
  507. @" <ProjectTypeGuids>{{E097FAD1-6243-4DAD-9C02-E9B9EFC3FFC1}};{{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}}</ProjectTypeGuids>",
  508. @" <OutputType>Library</OutputType>",
  509. @" <AppDesignerFolder>Properties</AppDesignerFolder>",
  510. @" <AssemblyName>{7}</AssemblyName>",
  511. @" <TargetFrameworkVersion>v4.7.1</TargetFrameworkVersion>",
  512. @" <FileAlignment>512</FileAlignment>",
  513. @" <BaseDirectory>{12}</BaseDirectory>",
  514. @" </PropertyGroup>",
  515. @" <PropertyGroup>",
  516. @" <DebugSymbols>true</DebugSymbols>",
  517. @" <DebugType>full</DebugType>",
  518. @" <Optimize>false</Optimize>",
  519. @" <OutputPath>{8}</OutputPath>",
  520. @" <DefineConstants>{5}</DefineConstants>",
  521. @" <ErrorReport>prompt</ErrorReport>",
  522. @" <WarningLevel>{18}</WarningLevel>",
  523. @" <NoWarn>{14}</NoWarn>",
  524. @" <AllowUnsafeBlocks>{13}</AllowUnsafeBlocks>{19}{20}{21}",
  525. @" </PropertyGroup>"
  526. };
  527. var forceExplicitReferences = new[] {
  528. @" <PropertyGroup>",
  529. @" <NoConfig>true</NoConfig>",
  530. @" <NoStdLib>true</NoStdLib>",
  531. @" <AddAdditionalExplicitAssemblyReferences>false</AddAdditionalExplicitAssemblyReferences>",
  532. @" <ImplicitlyExpandNETStandardFacades>false</ImplicitlyExpandNETStandardFacades>",
  533. @" <ImplicitlyExpandDesignTimeFacades>false</ImplicitlyExpandDesignTimeFacades>",
  534. @" </PropertyGroup>"
  535. };
  536. var footer = new[] {
  537. @"{15}{16} <ItemGroup>",
  538. @""
  539. };
  540. var pieces = header.Concat(forceExplicitReferences).Concat(footer).ToArray();
  541. return string.Join(Environment.NewLine, pieces);
  542. }
  543. private void SyncSolution(ProjectPart[] islands) {
  544. SyncSolutionFileIfNotChanged(SolutionFile(), SolutionText(islands));
  545. }
  546. private string SolutionText(ProjectPart[] islands) {
  547. var fileversion = "11.00";
  548. var vsversion = "2010";
  549. var projectEntries = GetProjectEntries(islands);
  550. var projectConfigurations = string.Join(Environment.NewLine,
  551. islands.Select(i => GetProjectActiveConfigurations(ProjectGuid(GetProjectName(i.Name, i.Defines)))).ToArray());
  552. return string.Format(GetSolutionText(), fileversion, vsversion, projectEntries, projectConfigurations);
  553. }
  554. private static ILookup<string, string> GetOtherArgumentsFromResponseFilesData(List<ResponseFileData> responseFilesData) {
  555. var paths = responseFilesData.SelectMany(x => {
  556. return x.OtherArguments
  557. .Where(a => a.StartsWith("/", StringComparison.Ordinal) || a.StartsWith("-", StringComparison.Ordinal))
  558. .Select(b => {
  559. var index = b.IndexOf(":", StringComparison.Ordinal);
  560. if (index > 0 && b.Length > index) {
  561. var key = b.Substring(1, index - 1);
  562. return new KeyValuePair<string, string>(key.ToLowerInvariant(), b.Substring(index + 1));
  563. }
  564. const string warnaserror = "warnaserror";
  565. if (b.Substring(1).StartsWith(warnaserror, StringComparison.Ordinal)) {
  566. return new KeyValuePair<string, string>(warnaserror, b.Substring(warnaserror.Length + 1));
  567. }
  568. const string nullable = "nullable";
  569. if (b.Substring(1).StartsWith(nullable)) {
  570. var res = b.Substring(nullable.Length + 1);
  571. if (string.IsNullOrWhiteSpace(res) || res.Equals("+"))
  572. res = "enable";
  573. else if (res.Equals("-"))
  574. res = "disable";
  575. return new KeyValuePair<string, string>(nullable, res);
  576. }
  577. return default(KeyValuePair<string, string>);
  578. });
  579. })
  580. .Distinct()
  581. .ToLookup(o => o.Key, pair => pair.Value);
  582. return paths;
  583. }
  584. private string GenerateLangVersion(IEnumerable<string> langVersionList, ProjectPart assembly) {
  585. var langVersion = langVersionList.FirstOrDefault();
  586. if (!string.IsNullOrWhiteSpace(langVersion))
  587. return langVersion;
  588. #if UNITY_2020_2_OR_NEWER
  589. return assembly.CompilerOptions.LanguageVersion;
  590. #else
  591. return k_TargetLanguageVersion;
  592. #endif
  593. }
  594. private static string GenerateAnalyserAdditionalFiles(string[] paths) {
  595. if (!paths.Any())
  596. return string.Empty;
  597. var analyserBuilder = new StringBuilder();
  598. analyserBuilder.AppendLine(" <ItemGroup>");
  599. foreach (var path in paths) {
  600. analyserBuilder.AppendLine($" <AdditionalFiles Include=\"{path}\" />");
  601. }
  602. analyserBuilder.AppendLine(" </ItemGroup>");
  603. return analyserBuilder.ToString();
  604. }
  605. public string GenerateNoWarn(List<string> codes) {
  606. if (m_SuppressCommonWarnings)
  607. codes.AddRange(new[] { "0169", "0649" });
  608. if (!codes.Any())
  609. return string.Empty;
  610. return string.Join(",", codes.Distinct());
  611. }
  612. private string GetProjectEntries(ProjectPart[] islands) {
  613. var projectEntries = islands.Select(i => string.Format(
  614. m_SolutionProjectEntryTemplate,
  615. SolutionGuidGenerator.GuidForSolution(),
  616. i.Name,
  617. Path.GetFileName(ProjectFile(i)),
  618. ProjectGuid(GetProjectName(i.Name, i.Defines))
  619. ));
  620. return string.Join(Environment.NewLine, projectEntries.ToArray());
  621. }
  622. /// <summary>
  623. /// Generate the active configuration string for a given project guid
  624. /// </summary>
  625. private string GetProjectActiveConfigurations(string projectGuid) {
  626. return string.Format(
  627. m_SolutionProjectConfigurationTemplate,
  628. projectGuid);
  629. }
  630. private static string ProjectFooter() {
  631. return GetProjectFooterTemplate();
  632. }
  633. private string ProjectGuid(string name) {
  634. return m_GUIDGenerator.ProjectGuid(m_ProjectName + name);
  635. }
  636. public ProjectGenerationFlag ProjectGenerationFlag => ProjectGenerationFlag.Local | ProjectGenerationFlag.Embedded;
  637. public string GetAssemblyNameFromScriptPath(string path) {
  638. return CompilationPipeline.GetAssemblyNameFromScriptPath(path);
  639. }
  640. public IEnumerable<Assembly> GetAssemblies(Func<string, bool> shouldFileBePartOfSolution) {
  641. return m_AllEditorAssemblies.Where(a => a.sourceFiles.Any(shouldFileBePartOfSolution));
  642. }
  643. private Task BuildEditorAssemblies() {
  644. var assemblies = CompilationPipeline.GetAssemblies(AssembliesType.Editor);
  645. return Task.Run(() => {
  646. var result = new Assembly[assemblies.Length];
  647. for (var i = 0; i < assemblies.Length; i++) {
  648. var assembly = assemblies[i];
  649. var outputPath = $@"Temp\Bin\Debug\{assembly.name}\";
  650. result[i] = new Assembly(assembly.name, outputPath, assembly.sourceFiles,
  651. assembly.defines,
  652. assembly.assemblyReferences, assembly.compiledAssemblyReferences,
  653. assembly.flags, assembly.compilerOptions
  654. #if UNITY_2020_2_OR_NEWER
  655. , assembly.rootNamespace
  656. #endif
  657. );
  658. }
  659. m_AllEditorAssemblies = result;
  660. });
  661. }
  662. public string GetProjectName(string name, string[] defines) {
  663. if (!ProjectGenerationFlag.HasFlag(ProjectGenerationFlag.PlayerAssemblies))
  664. return name;
  665. return !defines.Contains("UNITY_EDITOR") ? name + ".Player" : name;
  666. }
  667. private static string ResolvePotentialParentPackageAssetPath(string assetPath) {
  668. const string packagesPrefix = "packages/";
  669. if (!assetPath.StartsWith(packagesPrefix, StringComparison.OrdinalIgnoreCase)) {
  670. return null;
  671. }
  672. var followupSeparator = assetPath.IndexOf('/', packagesPrefix.Length);
  673. if (followupSeparator == -1) {
  674. return assetPath.ToLowerInvariant();
  675. }
  676. return assetPath.Substring(0, followupSeparator).ToLowerInvariant();
  677. }
  678. public UnityEditor.PackageManager.PackageInfo FindForAssetPath(string assetPath) {
  679. var parentPackageAssetPath = ResolvePotentialParentPackageAssetPath(assetPath);
  680. if (parentPackageAssetPath == null) {
  681. return null;
  682. }
  683. PackageInfo cachedPackageInfo;
  684. if (m_PackageInfoCache.TryGetValue(parentPackageAssetPath, out cachedPackageInfo)) {
  685. return cachedPackageInfo;
  686. }
  687. return null;
  688. }
  689. async Task BuildPackageInfoCache() {
  690. #if UNITY_2019_4_OR_NEWER
  691. m_PackageInfoCache.Clear();
  692. var parentAssetPaths = new HashSet<string>();
  693. await Task.Run(() => {
  694. for (var i = 0; i < m_AllAssetPaths.Length; i++) {
  695. if (string.IsNullOrWhiteSpace(m_AllAssetPaths[i])) {
  696. continue;
  697. }
  698. var parentPackageAssetPath = ResolvePotentialParentPackageAssetPath(m_AllAssetPaths[i]);
  699. if (parentPackageAssetPath == null) {
  700. continue;
  701. }
  702. parentAssetPaths.Add(parentPackageAssetPath);
  703. }
  704. });
  705. foreach (var parentAssetPath in parentAssetPaths) {
  706. var result = UnityEditor.PackageManager.PackageInfo.FindForAssetPath(parentAssetPath);
  707. m_PackageInfoCache.Add(parentAssetPath, result);
  708. }
  709. #else
  710. //keep compiler happy
  711. await Task.CompletedTask;
  712. #endif
  713. }
  714. async Task BuildPostProcessors() {
  715. #if UNITY_2019_1_OR_NEWER
  716. var types = TypeCache.GetTypesDerivedFrom<IHotReloadProjectGenerationPostProcessor>();
  717. m_PostProcessors = await Task.Run(() => {
  718. var postProcessors = new List<IHotReloadProjectGenerationPostProcessor>(types.Count);
  719. foreach (var type in types) {
  720. try {
  721. var instance = (IHotReloadProjectGenerationPostProcessor)Activator.CreateInstance(type);
  722. postProcessors.Add(instance);
  723. } catch (MissingMethodException) {
  724. Log.Warning("The type '{0}' was expected to have a public default constructor but it didn't", type.FullName);
  725. } catch (TargetInvocationException ex) {
  726. Log.Warning("Exception occurred when invoking default constructor of '{0}':\n{1}", type.FullName, ex.InnerException);
  727. } catch (Exception ex) {
  728. Log.Warning("Unknown exception encountered when trying to create post processor '{0}':\n{1}", type.FullName, ex);
  729. }
  730. }
  731. postProcessors.Sort((x, y) => x.CallbackOrder.CompareTo(y.CallbackOrder));
  732. return postProcessors.ToArray();
  733. });
  734. foreach (var postProcessor in m_PostProcessors) {
  735. postProcessor.InitializeOnMainThread();
  736. }
  737. #else
  738. m_PostProcessors = new IHotReloadProjectGenerationPostProcessor[0];
  739. //keep compiler happy
  740. await Task.CompletedTask;
  741. #endif
  742. }
  743. public bool IsInternalizedPackagePath(string path) {
  744. if (string.IsNullOrWhiteSpace(path)) {
  745. return false;
  746. }
  747. var packageInfo = FindForAssetPath(path);
  748. if (packageInfo == null) {
  749. return false;
  750. }
  751. var packageSource = packageInfo.source;
  752. switch (packageSource) {
  753. case PackageSource.Embedded:
  754. case PackageSource.Local:
  755. return false;
  756. default:
  757. return true;
  758. }
  759. }
  760. }
  761. }