ProjectGeneration.cs 37 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Linq;
  5. using System.Security;
  6. using System.Security.Cryptography;
  7. using System.Text;
  8. using System.Text.RegularExpressions;
  9. using Packages.Rider.Editor.Util;
  10. using UnityEditor;
  11. using UnityEditor.Compilation;
  12. using UnityEditor.PackageManager;
  13. using UnityEditorInternal;
  14. using UnityEngine;
  15. namespace Packages.Rider.Editor
  16. {
  17. public interface IGenerator
  18. {
  19. bool SyncIfNeeded(IEnumerable<string> affectedFiles, IEnumerable<string> reimportedFiles);
  20. void Sync();
  21. bool HasSolutionBeenGenerated();
  22. string SolutionFile();
  23. string ProjectDirectory { get; }
  24. void GenerateAll(bool generateAll);
  25. }
  26. public interface IFileIO
  27. {
  28. bool Exists(string fileName);
  29. string ReadAllText(string fileName);
  30. void WriteAllText(string fileName, string content);
  31. }
  32. public interface IGUIDGenerator
  33. {
  34. string ProjectGuid(string projectName, string assemblyName);
  35. string SolutionGuid(string projectName, string extension);
  36. }
  37. public interface IAssemblyNameProvider
  38. {
  39. string GetAssemblyNameFromScriptPath(string path);
  40. IEnumerable<Assembly> GetAssemblies(Func<string, bool> shouldFileBePartOfSolution);
  41. IEnumerable<string> GetAllAssetPaths();
  42. UnityEditor.PackageManager.PackageInfo FindForAssetPath(string assetPath);
  43. ResponseFileData ParseResponseFile(string responseFilePath, string projectDirectory, string[] systemReferenceDirectories);
  44. }
  45. class AssemblyNameProvider : IAssemblyNameProvider
  46. {
  47. public string GetAssemblyNameFromScriptPath(string path)
  48. {
  49. return CompilationPipeline.GetAssemblyNameFromScriptPath(path);
  50. }
  51. public IEnumerable<Assembly> GetAssemblies(Func<string, bool> shouldFileBePartOfSolution)
  52. {
  53. return CompilationPipeline.GetAssemblies()
  54. .Where(i => 0 < i.sourceFiles.Length && i.sourceFiles.Any(shouldFileBePartOfSolution));
  55. }
  56. public IEnumerable<string> GetAllAssetPaths()
  57. {
  58. return AssetDatabase.GetAllAssetPaths();
  59. }
  60. public UnityEditor.PackageManager.PackageInfo FindForAssetPath(string assetPath)
  61. {
  62. return UnityEditor.PackageManager.PackageInfo.FindForAssetPath(assetPath);
  63. }
  64. public ResponseFileData ParseResponseFile(string responseFilePath, string projectDirectory, string[] systemReferenceDirectories)
  65. {
  66. return CompilationPipeline.ParseResponseFile(
  67. responseFilePath,
  68. projectDirectory,
  69. systemReferenceDirectories
  70. );
  71. }
  72. }
  73. public class ProjectGeneration : IGenerator
  74. {
  75. enum ScriptingLanguage
  76. {
  77. None,
  78. CSharp
  79. }
  80. public static readonly string MSBuildNamespaceUri = "http://schemas.microsoft.com/developer/msbuild/2003";
  81. /// <summary>
  82. /// Map source extensions to ScriptingLanguages
  83. /// </summary>
  84. static readonly Dictionary<string, ScriptingLanguage> k_BuiltinSupportedExtensions =
  85. new Dictionary<string, ScriptingLanguage>
  86. {
  87. {"cs", ScriptingLanguage.CSharp},
  88. {"uxml", ScriptingLanguage.None},
  89. {"uss", ScriptingLanguage.None},
  90. {"shader", ScriptingLanguage.None},
  91. {"compute", ScriptingLanguage.None},
  92. {"cginc", ScriptingLanguage.None},
  93. {"hlsl", ScriptingLanguage.None},
  94. {"glslinc", ScriptingLanguage.None},
  95. {"template", ScriptingLanguage.None},
  96. {"raytrace", ScriptingLanguage.None}
  97. };
  98. string m_SolutionProjectEntryTemplate = string.Join(Environment.NewLine,
  99. @"Project(""{{{0}}}"") = ""{1}"", ""{2}"", ""{{{3}}}""",
  100. @"EndProject").Replace(" ", "\t");
  101. string m_SolutionProjectConfigurationTemplate = string.Join(Environment.NewLine,
  102. @" {{{0}}}.Debug|Any CPU.ActiveCfg = Debug|Any CPU",
  103. @" {{{0}}}.Debug|Any CPU.Build.0 = Debug|Any CPU",
  104. @" {{{0}}}.Release|Any CPU.ActiveCfg = Release|Any CPU",
  105. @" {{{0}}}.Release|Any CPU.Build.0 = Release|Any CPU").Replace(" ", "\t");
  106. static readonly string[] k_ReimportSyncExtensions = {".dll", ".asmdef"};
  107. /// <summary>
  108. /// Map ScriptingLanguages to project extensions
  109. /// </summary>
  110. /*static readonly Dictionary<ScriptingLanguage, string> k_ProjectExtensions = new Dictionary<ScriptingLanguage, string>
  111. {
  112. { ScriptingLanguage.CSharp, ".csproj" },
  113. { ScriptingLanguage.None, ".csproj" },
  114. };*/
  115. static readonly Regex k_ScriptReferenceExpression = new Regex(
  116. @"^Library.ScriptAssemblies.(?<dllname>(?<project>.*)\.dll$)",
  117. RegexOptions.Compiled | RegexOptions.IgnoreCase);
  118. string[] m_ProjectSupportedExtensions = new string[0];
  119. bool m_ShouldGenerateAll;
  120. public string ProjectDirectory { get; }
  121. public void GenerateAll(bool generateAll)
  122. {
  123. m_ShouldGenerateAll = generateAll;
  124. }
  125. readonly string m_ProjectName;
  126. readonly IAssemblyNameProvider m_AssemblyNameProvider;
  127. readonly IFileIO m_FileIOProvider;
  128. readonly IGUIDGenerator m_GUIDGenerator;
  129. internal static bool isRiderProjectGeneration; // workaround to https://github.cds.internal.unity3d.com/unity/com.unity.ide.rider/issues/28
  130. const string k_ToolsVersion = "4.0";
  131. const string k_ProductVersion = "10.0.20506";
  132. const string k_BaseDirectory = ".";
  133. const string k_TargetFrameworkVersion = "v4.7.1";
  134. const string k_TargetLanguageVersion = "latest";
  135. static readonly Regex scriptReferenceExpression = new Regex(
  136. @"^Library.ScriptAssemblies.(?<dllname>(?<project>.*)\.dll$)",
  137. RegexOptions.Compiled | RegexOptions.IgnoreCase);
  138. public ProjectGeneration() : this(Directory.GetParent(Application.dataPath).FullName)
  139. {
  140. }
  141. public ProjectGeneration(string tempDirectory) : this(tempDirectory, new AssemblyNameProvider(), new FileIOProvider(), new GUIDProvider())
  142. {
  143. }
  144. public ProjectGeneration(string tempDirectory, IAssemblyNameProvider assemblyNameProvider, IFileIO fileIoProvider, IGUIDGenerator guidGenerator)
  145. {
  146. ProjectDirectory = tempDirectory.Replace('\\', '/');
  147. m_ProjectName = Path.GetFileName(ProjectDirectory);
  148. m_AssemblyNameProvider = assemblyNameProvider;
  149. m_FileIOProvider = fileIoProvider;
  150. m_GUIDGenerator = guidGenerator;
  151. }
  152. /// <summary>
  153. /// Syncs the scripting solution if any affected files are relevant.
  154. /// </summary>
  155. /// <returns>
  156. /// Whether the solution was synced.
  157. /// </returns>
  158. /// <param name='affectedFiles'>
  159. /// A set of files whose status has changed
  160. /// </param>
  161. /// <param name="reimportedFiles">
  162. /// A set of files that got reimported
  163. /// </param>
  164. public bool SyncIfNeeded(IEnumerable<string> affectedFiles, IEnumerable<string> reimportedFiles)
  165. {
  166. SetupProjectSupportedExtensions();
  167. if (HasFilesBeenModified(affectedFiles, reimportedFiles))
  168. {
  169. Sync();
  170. return true;
  171. }
  172. return false;
  173. }
  174. bool HasFilesBeenModified(IEnumerable<string> affectedFiles, IEnumerable<string> reimportedFiles)
  175. {
  176. return affectedFiles.Any(ShouldFileBePartOfSolution) || reimportedFiles.Any(ShouldSyncOnReimportedAsset);
  177. }
  178. static bool ShouldSyncOnReimportedAsset(string asset)
  179. {
  180. return k_ReimportSyncExtensions.Contains(new FileInfo(asset).Extension);
  181. }
  182. public void Sync()
  183. {
  184. SetupProjectSupportedExtensions();
  185. var types = GetAssetPostprocessorTypes();
  186. isRiderProjectGeneration = true;
  187. bool externalCodeAlreadyGeneratedProjects = OnPreGeneratingCSProjectFiles(types);
  188. isRiderProjectGeneration = false;
  189. if (!externalCodeAlreadyGeneratedProjects)
  190. {
  191. GenerateAndWriteSolutionAndProjects(types);
  192. }
  193. OnGeneratedCSProjectFiles(types);
  194. }
  195. public bool HasSolutionBeenGenerated()
  196. {
  197. return m_FileIOProvider.Exists(SolutionFile());
  198. }
  199. void SetupProjectSupportedExtensions()
  200. {
  201. m_ProjectSupportedExtensions = EditorSettings.projectGenerationUserExtensions;
  202. }
  203. bool ShouldFileBePartOfSolution(string file)
  204. {
  205. string extension = Path.GetExtension(file);
  206. // Exclude files coming from packages except if they are internalized.
  207. if (!m_ShouldGenerateAll && IsInternalizedPackagePath(file))
  208. {
  209. return false;
  210. }
  211. // Dll's are not scripts but still need to be included..
  212. if (extension == ".dll")
  213. return true;
  214. if (file.ToLower().EndsWith(".asmdef"))
  215. return true;
  216. return IsSupportedExtension(extension);
  217. }
  218. bool IsSupportedExtension(string extension)
  219. {
  220. extension = extension.TrimStart('.');
  221. if (k_BuiltinSupportedExtensions.ContainsKey(extension))
  222. return true;
  223. if (m_ProjectSupportedExtensions.Contains(extension))
  224. return true;
  225. return false;
  226. }
  227. static ScriptingLanguage ScriptingLanguageFor(Assembly island)
  228. {
  229. return ScriptingLanguageFor(GetExtensionOfSourceFiles(island.sourceFiles));
  230. }
  231. static string GetExtensionOfSourceFiles(string[] files)
  232. {
  233. return files.Length > 0 ? GetExtensionOfSourceFile(files[0]) : "NA";
  234. }
  235. static string GetExtensionOfSourceFile(string file)
  236. {
  237. var ext = Path.GetExtension(file).ToLower();
  238. ext = ext.Substring(1); //strip dot
  239. return ext;
  240. }
  241. static ScriptingLanguage ScriptingLanguageFor(string extension)
  242. {
  243. return k_BuiltinSupportedExtensions.TryGetValue(extension.TrimStart('.'), out var result)
  244. ? result
  245. : ScriptingLanguage.None;
  246. }
  247. public void GenerateAndWriteSolutionAndProjects(Type[] types)
  248. {
  249. // Only synchronize islands that have associated source files and ones that we actually want in the project.
  250. // This also filters out DLLs coming from .asmdef files in packages.
  251. var assemblies = m_AssemblyNameProvider.GetAssemblies(ShouldFileBePartOfSolution);
  252. var allAssetProjectParts = GenerateAllAssetProjectParts();
  253. var monoIslands = assemblies.ToList();
  254. SyncSolution(monoIslands, types);
  255. var allProjectIslands = RelevantIslandsForMode(monoIslands).ToList();
  256. foreach (Assembly assembly in allProjectIslands)
  257. {
  258. var responseFileData = ParseResponseFileData(assembly);
  259. SyncProject(assembly, allAssetProjectParts, responseFileData, allProjectIslands, types);
  260. }
  261. }
  262. IEnumerable<ResponseFileData> ParseResponseFileData(Assembly assembly)
  263. {
  264. var systemReferenceDirectories =
  265. CompilationPipeline.GetSystemAssemblyDirectories(assembly.compilerOptions.ApiCompatibilityLevel);
  266. Dictionary<string, ResponseFileData> responseFilesData = assembly.compilerOptions.ResponseFiles.ToDictionary(
  267. x => x, x => m_AssemblyNameProvider.ParseResponseFile(
  268. x,
  269. ProjectDirectory,
  270. systemReferenceDirectories
  271. ));
  272. Dictionary<string, ResponseFileData> responseFilesWithErrors = responseFilesData.Where(x => x.Value.Errors.Any())
  273. .ToDictionary(x => x.Key, x => x.Value);
  274. if (responseFilesWithErrors.Any())
  275. {
  276. foreach (var error in responseFilesWithErrors)
  277. foreach (var valueError in error.Value.Errors)
  278. {
  279. Debug.LogError($"{error.Key} Parse Error : {valueError}");
  280. }
  281. }
  282. return responseFilesData.Select(x => x.Value);
  283. }
  284. Dictionary<string, string> GenerateAllAssetProjectParts()
  285. {
  286. Dictionary<string, StringBuilder> stringBuilders = new Dictionary<string, StringBuilder>();
  287. foreach (string asset in m_AssemblyNameProvider.GetAllAssetPaths())
  288. {
  289. // Exclude files coming from packages except if they are internalized.
  290. if (!m_ShouldGenerateAll && IsInternalizedPackagePath(asset))
  291. {
  292. continue;
  293. }
  294. string extension = Path.GetExtension(asset);
  295. if (IsSupportedExtension(extension) && ScriptingLanguage.None == ScriptingLanguageFor(extension))
  296. {
  297. // Find assembly the asset belongs to by adding script extension and using compilation pipeline.
  298. var assemblyName = m_AssemblyNameProvider.GetAssemblyNameFromScriptPath(asset + ".cs");
  299. if (string.IsNullOrEmpty(assemblyName))
  300. {
  301. continue;
  302. }
  303. assemblyName = FileSystemUtil.FileNameWithoutExtension(assemblyName);
  304. if (!stringBuilders.TryGetValue(assemblyName, out var projectBuilder))
  305. {
  306. projectBuilder = new StringBuilder();
  307. stringBuilders[assemblyName] = projectBuilder;
  308. }
  309. projectBuilder.Append(" <None Include=\"").Append(EscapedRelativePathFor(asset)).Append("\" />")
  310. .Append(Environment.NewLine);
  311. }
  312. }
  313. var result = new Dictionary<string, string>();
  314. foreach (var entry in stringBuilders)
  315. result[entry.Key] = entry.Value.ToString();
  316. return result;
  317. }
  318. bool IsInternalizedPackagePath(string file)
  319. {
  320. if (string.IsNullOrWhiteSpace(file))
  321. {
  322. return false;
  323. }
  324. var packageInfo = m_AssemblyNameProvider.FindForAssetPath(file);
  325. if (packageInfo == null)
  326. {
  327. return false;
  328. }
  329. var packageSource = packageInfo.source;
  330. return packageSource != PackageSource.Embedded && packageSource != PackageSource.Local;
  331. }
  332. void SyncProject(
  333. Assembly island,
  334. Dictionary<string, string> allAssetsProjectParts,
  335. IEnumerable<ResponseFileData> responseFilesData,
  336. List<Assembly> allProjectIslands,
  337. Type[] types)
  338. {
  339. SyncProjectFileIfNotChanged(ProjectFile(island),
  340. ProjectText(island, allAssetsProjectParts, responseFilesData.ToList(), allProjectIslands), types);
  341. }
  342. void SyncProjectFileIfNotChanged(string path, string newContents, Type[] types)
  343. {
  344. if (Path.GetExtension(path) == ".csproj")
  345. {
  346. newContents = OnGeneratedCSProject(path, newContents, types);
  347. }
  348. SyncFileIfNotChanged(path, newContents);
  349. }
  350. void SyncSolutionFileIfNotChanged(string path, string newContents, Type[] types)
  351. {
  352. newContents = OnGeneratedSlnSolution(path, newContents, types);
  353. SyncFileIfNotChanged(path, newContents);
  354. }
  355. static List<Type> SafeGetTypes(System.Reflection.Assembly a)
  356. {
  357. List<Type> ret;
  358. try
  359. {
  360. ret = a.GetTypes().ToList();
  361. }
  362. catch (System.Reflection.ReflectionTypeLoadException rtl)
  363. {
  364. ret = rtl.Types.ToList();
  365. }
  366. catch (Exception)
  367. {
  368. return new List<Type>();
  369. }
  370. return ret.Where(r => r != null).ToList();
  371. }
  372. static void OnGeneratedCSProjectFiles(Type[] types)
  373. {
  374. var args = new object[0];
  375. foreach (var type in types)
  376. {
  377. var method = type.GetMethod("OnGeneratedCSProjectFiles",
  378. System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic |
  379. System.Reflection.BindingFlags.Static);
  380. if (method == null)
  381. {
  382. continue;
  383. }
  384. method.Invoke(null, args);
  385. }
  386. }
  387. public static Type[] GetAssetPostprocessorTypes()
  388. {
  389. return TypeCache.GetTypesDerivedFrom<AssetPostprocessor>().ToArray(); // doesn't find types from EditorPlugin, which is fine
  390. }
  391. static bool OnPreGeneratingCSProjectFiles(Type[] types)
  392. {
  393. bool result = false;
  394. foreach (var type in types)
  395. {
  396. var args = new object[0];
  397. var method = type.GetMethod("OnPreGeneratingCSProjectFiles",
  398. System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic |
  399. System.Reflection.BindingFlags.Static);
  400. if (method == null)
  401. {
  402. continue;
  403. }
  404. var returnValue = method.Invoke(null, args);
  405. if (method.ReturnType == typeof(bool))
  406. {
  407. result |= (bool) returnValue;
  408. }
  409. }
  410. return result;
  411. }
  412. static string OnGeneratedCSProject(string path, string content, Type[] types)
  413. {
  414. foreach (var type in types)
  415. {
  416. var args = new[] {path, content};
  417. var method = type.GetMethod("OnGeneratedCSProject",
  418. System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic |
  419. System.Reflection.BindingFlags.Static);
  420. if (method == null)
  421. {
  422. continue;
  423. }
  424. var returnValue = method.Invoke(null, args);
  425. if (method.ReturnType == typeof(string))
  426. {
  427. content = (string) returnValue;
  428. }
  429. }
  430. return content;
  431. }
  432. static string OnGeneratedSlnSolution(string path, string content, Type[] types)
  433. {
  434. foreach (var type in types)
  435. {
  436. var args = new[] {path, content};
  437. var method = type.GetMethod("OnGeneratedSlnSolution",
  438. System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic |
  439. System.Reflection.BindingFlags.Static);
  440. if (method == null)
  441. {
  442. continue;
  443. }
  444. var returnValue = method.Invoke(null, args);
  445. if (method.ReturnType == typeof(string))
  446. {
  447. content = (string) returnValue;
  448. }
  449. }
  450. return content;
  451. }
  452. void SyncFileIfNotChanged(string filename, string newContents)
  453. {
  454. try
  455. {
  456. if (m_FileIOProvider.Exists(filename) && newContents == m_FileIOProvider.ReadAllText(filename))
  457. {
  458. return;
  459. }
  460. }
  461. catch (Exception exception)
  462. {
  463. Debug.LogException(exception);
  464. }
  465. m_FileIOProvider.WriteAllText(filename, newContents);
  466. }
  467. string ProjectText(Assembly assembly,
  468. Dictionary<string, string> allAssetsProjectParts,
  469. List<ResponseFileData> responseFilesData,
  470. List<Assembly> allProjectIslands)
  471. {
  472. var projectBuilder = new StringBuilder(ProjectHeader(assembly, responseFilesData));
  473. var references = new List<string>();
  474. var projectReferences = new List<Match>();
  475. foreach (string file in assembly.sourceFiles)
  476. {
  477. if (!ShouldFileBePartOfSolution(file))
  478. continue;
  479. var extension = Path.GetExtension(file).ToLower();
  480. var fullFile = EscapedRelativePathFor(file);
  481. if (".dll" != extension)
  482. {
  483. projectBuilder.Append(" <Compile Include=\"").Append(fullFile).Append("\" />").Append(Environment.NewLine);
  484. }
  485. else
  486. {
  487. references.Add(fullFile);
  488. }
  489. }
  490. // Append additional non-script files that should be included in project generation.
  491. if (allAssetsProjectParts.TryGetValue(assembly.name, out var additionalAssetsForProject))
  492. projectBuilder.Append(additionalAssetsForProject);
  493. var islandRefs = references.Union(assembly.allReferences);
  494. foreach (string reference in islandRefs)
  495. {
  496. if (reference.EndsWith("/UnityEditor.dll", StringComparison.Ordinal)
  497. || reference.EndsWith("/UnityEngine.dll", StringComparison.Ordinal)
  498. || reference.EndsWith("\\UnityEditor.dll", StringComparison.Ordinal)
  499. || reference.EndsWith("\\UnityEngine.dll", StringComparison.Ordinal))
  500. continue;
  501. var match = k_ScriptReferenceExpression.Match(reference);
  502. if (match.Success)
  503. {
  504. // assume csharp language
  505. // Add a reference to a project except if it's a reference to a script assembly
  506. // that we are not generating a project for. This will be the case for assemblies
  507. // coming from .assembly.json files in non-internalized packages.
  508. var dllName = match.Groups["dllname"].Value;
  509. if (allProjectIslands.Any(i => Path.GetFileName(i.outputPath) == dllName))
  510. {
  511. projectReferences.Add(match);
  512. continue;
  513. }
  514. }
  515. string fullReference = Path.IsPathRooted(reference) ? reference : Path.Combine(ProjectDirectory, reference);
  516. AppendReference(fullReference, projectBuilder);
  517. }
  518. var responseRefs = responseFilesData.SelectMany(x => x.FullPathReferences.Select(r => r));
  519. foreach (var reference in responseRefs)
  520. {
  521. AppendReference(reference, projectBuilder);
  522. }
  523. if (0 < projectReferences.Count)
  524. {
  525. projectBuilder.AppendLine(" </ItemGroup>");
  526. projectBuilder.AppendLine(" <ItemGroup>");
  527. foreach (Match reference in projectReferences)
  528. {
  529. var referencedProject = reference.Groups["project"].Value;
  530. projectBuilder.Append(" <ProjectReference Include=\"").Append(referencedProject)
  531. .Append(GetProjectExtension()).Append("\">").Append(Environment.NewLine);
  532. projectBuilder
  533. .Append(" <Project>{")
  534. .Append(m_GUIDGenerator.ProjectGuid(m_ProjectName, reference.Groups["project"].Value))
  535. .Append("}</Project>")
  536. .Append(Environment.NewLine);
  537. projectBuilder.Append(" <Name>").Append(referencedProject).Append("</Name>").Append(Environment.NewLine);
  538. projectBuilder.AppendLine(" </ProjectReference>");
  539. }
  540. }
  541. projectBuilder.Append(ProjectFooter());
  542. return projectBuilder.ToString();
  543. }
  544. static void AppendReference(string fullReference, StringBuilder projectBuilder)
  545. {
  546. //replace \ with / and \\ with /
  547. var escapedFullPath = SecurityElement.Escape(fullReference);
  548. escapedFullPath = escapedFullPath.Replace("\\\\", "/").Replace("\\", "/");
  549. projectBuilder.Append(" <Reference Include=\"").Append(FileSystemUtil.FileNameWithoutExtension(escapedFullPath))
  550. .Append("\">").Append(Environment.NewLine);
  551. projectBuilder.Append(" <HintPath>").Append(escapedFullPath).Append("</HintPath>").Append(Environment.NewLine);
  552. projectBuilder.Append(" </Reference>").Append(Environment.NewLine);
  553. }
  554. public string ProjectFile(Assembly assembly)
  555. {
  556. return Path.Combine(ProjectDirectory, $"{assembly.name}.csproj");
  557. }
  558. public string SolutionFile()
  559. {
  560. return Path.Combine(ProjectDirectory, $"{m_ProjectName}.sln");
  561. }
  562. string ProjectHeader(
  563. Assembly assembly,
  564. List<ResponseFileData> responseFilesData
  565. )
  566. {
  567. var otherResponseFilesData = GetOtherArgumentsFromResponseFilesData(responseFilesData);
  568. var arguments = new object[]
  569. {
  570. k_ToolsVersion, k_ProductVersion, m_GUIDGenerator.ProjectGuid(m_ProjectName, assembly.name),
  571. InternalEditorUtility.GetEngineAssemblyPath(),
  572. InternalEditorUtility.GetEditorAssemblyPath(),
  573. string.Join(";",
  574. new[] {"DEBUG", "TRACE"}.Concat(EditorUserBuildSettings.activeScriptCompilationDefines).Concat(assembly.defines)
  575. .Concat(responseFilesData.SelectMany(x => x.Defines)).Distinct().ToArray()),
  576. MSBuildNamespaceUri,
  577. assembly.name,
  578. EditorSettings.projectGenerationRootNamespace,
  579. k_TargetFrameworkVersion,
  580. GenerateLangVersion(otherResponseFilesData["langversion"]),
  581. k_BaseDirectory,
  582. assembly.compilerOptions.AllowUnsafeCode | responseFilesData.Any(x => x.Unsafe),
  583. GenerateNoWarn(otherResponseFilesData["nowarn"].Distinct().ToArray()),
  584. GenerateAnalyserItemGroup(otherResponseFilesData["analyzer"].Concat(otherResponseFilesData["a"]).SelectMany(x=>x.Split(';')).Distinct().ToArray()),
  585. GenerateAnalyserAdditionalFiles(otherResponseFilesData["additionalfile"].SelectMany(x=>x.Split(';')).Distinct().ToArray()),
  586. GenerateAnalyserRuleSet(otherResponseFilesData["ruleset"].Distinct().ToArray()),
  587. GenerateWarningLevel(otherResponseFilesData["warn"].Concat(otherResponseFilesData["w"]).Distinct()),
  588. GenerateWarningAsError(otherResponseFilesData["warnaserror"]),
  589. GenerateDocumentationFile(otherResponseFilesData["doc"])
  590. };
  591. try
  592. {
  593. return string.Format(GetProjectHeaderTemplate(), arguments);
  594. }
  595. catch (Exception)
  596. {
  597. throw new NotSupportedException(
  598. "Failed creating c# project because the c# project header did not have the correct amount of arguments, which is " +
  599. arguments.Length);
  600. }
  601. }
  602. private string GenerateDocumentationFile(IEnumerable<string> paths)
  603. {
  604. if (!paths.Any())
  605. return String.Empty;
  606. return $"{Environment.NewLine}{string.Join(Environment.NewLine, paths.Select(a => $" <DocumentationFile>{a}</DocumentationFile>"))}";
  607. }
  608. private string GenerateWarningAsError(IEnumerable<string> enumerable)
  609. {
  610. string returnValue = String.Empty;
  611. bool allWarningsAsErrors = false;
  612. List<string> warningIds = new List<string>();
  613. foreach (string s in enumerable)
  614. {
  615. if (s == "+") allWarningsAsErrors = true;
  616. else if (s == "-") allWarningsAsErrors = false;
  617. else
  618. {
  619. warningIds.Add(s);
  620. }
  621. }
  622. returnValue += $@" <TreatWarningsAsErrors>{allWarningsAsErrors}</TreatWarningsAsErrors>";
  623. if (warningIds.Any())
  624. {
  625. returnValue += $"{Environment.NewLine} <WarningsAsErrors>{string.Join(";", warningIds)}</WarningsAsErrors>";
  626. }
  627. return $"{Environment.NewLine}{returnValue}";
  628. }
  629. private string GenerateWarningLevel(IEnumerable<string> warningLevel)
  630. {
  631. var level = warningLevel.FirstOrDefault();
  632. if (!string.IsNullOrWhiteSpace(level))
  633. return level;
  634. return 4.ToString();
  635. }
  636. static string GetSolutionText()
  637. {
  638. return string.Join(Environment.NewLine,
  639. @"",
  640. @"Microsoft Visual Studio Solution File, Format Version {0}",
  641. @"# Visual Studio {1}",
  642. @"{2}",
  643. @"Global",
  644. @" GlobalSection(SolutionConfigurationPlatforms) = preSolution",
  645. @" Debug|Any CPU = Debug|Any CPU",
  646. @" Release|Any CPU = Release|Any CPU",
  647. @" EndGlobalSection",
  648. @" GlobalSection(ProjectConfigurationPlatforms) = postSolution",
  649. @"{3}",
  650. @" EndGlobalSection",
  651. @" GlobalSection(SolutionProperties) = preSolution",
  652. @" HideSolutionNode = FALSE",
  653. @" EndGlobalSection",
  654. @"EndGlobal",
  655. @"").Replace(" ", "\t");
  656. }
  657. static string GetProjectFooterTemplate()
  658. {
  659. return string.Join(Environment.NewLine,
  660. @" </ItemGroup>",
  661. @" <Import Project=""$(MSBuildToolsPath)\Microsoft.CSharp.targets"" />",
  662. @" <!-- To modify your build process, add your task inside one of the targets below and uncomment it. ",
  663. @" Other similar extension points exist, see Microsoft.Common.targets.",
  664. @" <Target Name=""BeforeBuild"">",
  665. @" </Target>",
  666. @" <Target Name=""AfterBuild"">",
  667. @" </Target>",
  668. @" -->",
  669. @"</Project>",
  670. @"");
  671. }
  672. static string GetProjectHeaderTemplate()
  673. {
  674. var header = new[]
  675. {
  676. @"<?xml version=""1.0"" encoding=""utf-8""?>",
  677. @"<Project ToolsVersion=""{0}"" DefaultTargets=""Build"" xmlns=""{6}"">",
  678. @" <PropertyGroup>",
  679. @" <LangVersion>{10}</LangVersion>",
  680. @" <_TargetFrameworkDirectories>non_empty_path_generated_by_unity.rider.package</_TargetFrameworkDirectories>",
  681. @" <_FullFrameworkReferenceAssemblyPaths>non_empty_path_generated_by_unity.rider.package</_FullFrameworkReferenceAssemblyPaths>",
  682. @" <DisableHandlePackageFileConflicts>true</DisableHandlePackageFileConflicts>{16}",
  683. @" </PropertyGroup>",
  684. @" <PropertyGroup>",
  685. @" <Configuration Condition="" '$(Configuration)' == '' "">Debug</Configuration>",
  686. @" <Platform Condition="" '$(Platform)' == '' "">AnyCPU</Platform>",
  687. @" <ProductVersion>{1}</ProductVersion>",
  688. @" <SchemaVersion>2.0</SchemaVersion>",
  689. @" <RootNamespace>{8}</RootNamespace>",
  690. @" <ProjectGuid>{{{2}}}</ProjectGuid>",
  691. @" <OutputType>Library</OutputType>",
  692. @" <AppDesignerFolder>Properties</AppDesignerFolder>",
  693. @" <AssemblyName>{7}</AssemblyName>",
  694. @" <TargetFrameworkVersion>{9}</TargetFrameworkVersion>",
  695. @" <FileAlignment>512</FileAlignment>",
  696. @" <BaseDirectory>{11}</BaseDirectory>",
  697. @" </PropertyGroup>",
  698. @" <PropertyGroup Condition="" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' "">",
  699. @" <DebugSymbols>true</DebugSymbols>",
  700. @" <DebugType>full</DebugType>",
  701. @" <Optimize>false</Optimize>",
  702. @" <OutputPath>Temp\bin\Debug\</OutputPath>",
  703. @" <DefineConstants>{5}</DefineConstants>",
  704. @" <ErrorReport>prompt</ErrorReport>",
  705. @" <WarningLevel>{17}</WarningLevel>",
  706. @" <NoWarn>0169{13}</NoWarn>",
  707. @" <AllowUnsafeBlocks>{12}</AllowUnsafeBlocks>{18}{19}",
  708. @" </PropertyGroup>",
  709. @" <PropertyGroup Condition="" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' "">",
  710. @" <DebugType>pdbonly</DebugType>",
  711. @" <Optimize>true</Optimize>",
  712. @" <OutputPath>Temp\bin\Release\</OutputPath>",
  713. @" <ErrorReport>prompt</ErrorReport>",
  714. @" <WarningLevel>{17}</WarningLevel>",
  715. @" <NoWarn>0169{13}</NoWarn>",
  716. @" <AllowUnsafeBlocks>{12}</AllowUnsafeBlocks>{18}{19}",
  717. @" </PropertyGroup>"
  718. };
  719. var forceExplicitReferences = new[]
  720. {
  721. @" <PropertyGroup>",
  722. @" <NoConfig>true</NoConfig>",
  723. @" <NoStdLib>true</NoStdLib>",
  724. @" <AddAdditionalExplicitAssemblyReferences>false</AddAdditionalExplicitAssemblyReferences>",
  725. @" <ImplicitlyExpandNETStandardFacades>false</ImplicitlyExpandNETStandardFacades>",
  726. @" <ImplicitlyExpandDesignTimeFacades>false</ImplicitlyExpandDesignTimeFacades>",
  727. @" </PropertyGroup>"
  728. };
  729. var itemGroupStart = new[]
  730. {
  731. @" <ItemGroup>"
  732. };
  733. var footer = new[]
  734. {
  735. @" <Reference Include=""UnityEngine"">",
  736. @" <HintPath>{3}</HintPath>",
  737. @" </Reference>",
  738. @" <Reference Include=""UnityEditor"">",
  739. @" <HintPath>{4}</HintPath>",
  740. @" </Reference>",
  741. @" </ItemGroup>{14}{15}",
  742. @" <ItemGroup>",
  743. @""
  744. };
  745. var pieces = header.Concat(forceExplicitReferences).Concat(itemGroupStart).Concat(footer).ToArray();
  746. return string.Join(Environment.NewLine, pieces);
  747. }
  748. void SyncSolution(IEnumerable<Assembly> islands, Type[] types)
  749. {
  750. SyncSolutionFileIfNotChanged(SolutionFile(), SolutionText(islands), types);
  751. }
  752. string SolutionText(IEnumerable<Assembly> islands)
  753. {
  754. var fileversion = "11.00";
  755. var vsversion = "2010";
  756. var relevantIslands = RelevantIslandsForMode(islands);
  757. string projectEntries = GetProjectEntries(relevantIslands);
  758. string projectConfigurations = string.Join(Environment.NewLine,
  759. relevantIslands.Select(i => GetProjectActiveConfigurations(m_GUIDGenerator.ProjectGuid(m_ProjectName, i.name))).ToArray());
  760. return string.Format(GetSolutionText(), fileversion, vsversion, projectEntries, projectConfigurations);
  761. }
  762. private static string GenerateAnalyserItemGroup(string[] paths)
  763. {
  764. // <ItemGroup>
  765. // <Analyzer Include="..\packages\Comments_analyser.1.0.6626.21356\analyzers\dotnet\cs\Comments_analyser.dll" />
  766. // <Analyzer Include="..\packages\UnityEngineAnalyzer.1.0.0.0\analyzers\dotnet\cs\UnityEngineAnalyzer.dll" />
  767. // </ItemGroup>
  768. if (!paths.Any())
  769. return string.Empty;
  770. var analyserBuilder = new StringBuilder();
  771. analyserBuilder.AppendLine(" <ItemGroup>");
  772. foreach (var path in paths)
  773. {
  774. analyserBuilder.AppendLine($" <Analyzer Include=\"{path}\" />");
  775. }
  776. analyserBuilder.AppendLine(" </ItemGroup>");
  777. return analyserBuilder.ToString();
  778. }
  779. private static ILookup<string, string> GetOtherArgumentsFromResponseFilesData(List<ResponseFileData> responseFilesData)
  780. {
  781. var paths = responseFilesData.SelectMany(x =>
  782. {
  783. return x.OtherArguments
  784. .Where(a => a.StartsWith("/") || a.StartsWith("-"))
  785. .Select(b =>
  786. {
  787. var index = b.IndexOf(":", StringComparison.Ordinal);
  788. if (index > 0 && b.Length > index)
  789. {
  790. var key = b.Substring(1, index - 1);
  791. return new KeyValuePair<string, string>(key, b.Substring(index + 1));
  792. }
  793. const string warnaserror = "warnaserror";
  794. if (b.Substring(1).StartsWith(warnaserror))
  795. {
  796. return new KeyValuePair<string,string>(warnaserror, b.Substring(warnaserror.Length+ 1) );
  797. }
  798. return default;
  799. });
  800. })
  801. .Distinct()
  802. .ToLookup(o => o.Key, pair => pair.Value);
  803. return paths;
  804. }
  805. private string GenerateLangVersion(IEnumerable<string> langVersionList)
  806. {
  807. var langVersion = langVersionList.FirstOrDefault();
  808. if (!string.IsNullOrWhiteSpace(langVersion))
  809. return langVersion;
  810. return k_TargetLanguageVersion;
  811. }
  812. private static string GenerateAnalyserRuleSet(string[] paths)
  813. {
  814. //<CodeAnalysisRuleSet>..\path\to\myrules.ruleset</CodeAnalysisRuleSet>
  815. if (!paths.Any())
  816. return string.Empty;
  817. return $"{Environment.NewLine}{string.Join(Environment.NewLine, paths.Select(a => $" <CodeAnalysisRuleSet>{a}</CodeAnalysisRuleSet>"))}";
  818. }
  819. private static string GenerateAnalyserAdditionalFiles(string[] paths)
  820. {
  821. if (!paths.Any())
  822. return string.Empty;
  823. var analyserBuilder = new StringBuilder();
  824. analyserBuilder.AppendLine(" <ItemGroup>");
  825. foreach (var path in paths)
  826. {
  827. analyserBuilder.AppendLine($" <AdditionalFiles Include=\"{path}\" />");
  828. }
  829. analyserBuilder.AppendLine(" </ItemGroup>");
  830. return analyserBuilder.ToString();
  831. }
  832. private static string GenerateNoWarn(string[] codes)
  833. {
  834. if (!codes.Any())
  835. return string.Empty;
  836. return $",{string.Join(",", codes)}";
  837. }
  838. static IEnumerable<Assembly> RelevantIslandsForMode(IEnumerable<Assembly> islands)
  839. {
  840. IEnumerable<Assembly> relevantIslands = islands.Where(i => ScriptingLanguage.CSharp == ScriptingLanguageFor(i));
  841. return relevantIslands;
  842. }
  843. /// <summary>
  844. /// Get a Project("{guid}") = "MyProject", "MyProject.unityproj", "{projectguid}"
  845. /// entry for each relevant language
  846. /// </summary>
  847. string GetProjectEntries(IEnumerable<Assembly> islands)
  848. {
  849. var projectEntries = islands.Select(i => string.Format(
  850. m_SolutionProjectEntryTemplate,
  851. m_GUIDGenerator.SolutionGuid(m_ProjectName, GetExtensionOfSourceFiles(i.sourceFiles)),
  852. i.name,
  853. Path.GetFileName(ProjectFile(i)),
  854. m_GUIDGenerator.ProjectGuid(m_ProjectName, i.name)
  855. ));
  856. return string.Join(Environment.NewLine, projectEntries.ToArray());
  857. }
  858. /// <summary>
  859. /// Generate the active configuration string for a given project guid
  860. /// </summary>
  861. string GetProjectActiveConfigurations(string projectGuid)
  862. {
  863. return string.Format(
  864. m_SolutionProjectConfigurationTemplate,
  865. projectGuid);
  866. }
  867. string EscapedRelativePathFor(string file)
  868. {
  869. var projectDir = ProjectDirectory.Replace('/', '\\');
  870. file = file.Replace('/', '\\');
  871. var path = SkipPathPrefix(file, projectDir);
  872. var packageInfo = m_AssemblyNameProvider.FindForAssetPath(path.Replace('\\', '/'));
  873. if (packageInfo != null)
  874. {
  875. // We have to normalize the path, because the PackageManagerRemapper assumes
  876. // dir seperators will be os specific.
  877. var absolutePath = Path.GetFullPath(NormalizePath(path)).Replace('/', '\\');
  878. path = SkipPathPrefix(absolutePath, projectDir);
  879. }
  880. return SecurityElement.Escape(path);
  881. }
  882. static string SkipPathPrefix(string path, string prefix)
  883. {
  884. if (path.Replace("\\", "/").StartsWith($"{prefix}/"))
  885. return path.Substring(prefix.Length + 1);
  886. return path;
  887. }
  888. static string NormalizePath(string path)
  889. {
  890. if (Path.DirectorySeparatorChar == '\\')
  891. return path.Replace('/', Path.DirectorySeparatorChar);
  892. return path.Replace('\\', Path.DirectorySeparatorChar);
  893. }
  894. static string ProjectFooter()
  895. {
  896. return GetProjectFooterTemplate();
  897. }
  898. static string GetProjectExtension()
  899. {
  900. return ".csproj";
  901. }
  902. }
  903. public static class SolutionGuidGenerator
  904. {
  905. public static string GuidForProject(string projectName)
  906. {
  907. return ComputeGuidHashFor(projectName + "salt");
  908. }
  909. public static string GuidForSolution(string projectName, string sourceFileExtension)
  910. {
  911. if (sourceFileExtension.ToLower() == "cs")
  912. // GUID for a C# class library: http://www.codeproject.com/Reference/720512/List-of-Visual-Studio-Project-Type-GUIDs
  913. return "FAE04EC0-301F-11D3-BF4B-00C04F79EFBC";
  914. return ComputeGuidHashFor(projectName);
  915. }
  916. static string ComputeGuidHashFor(string input)
  917. {
  918. var hash = MD5.Create().ComputeHash(Encoding.Default.GetBytes(input));
  919. return HashAsGuid(HashToString(hash));
  920. }
  921. static string HashAsGuid(string hash)
  922. {
  923. var guid = hash.Substring(0, 8) + "-" + hash.Substring(8, 4) + "-" + hash.Substring(12, 4) + "-" +
  924. hash.Substring(16, 4) + "-" + hash.Substring(20, 12);
  925. return guid.ToUpper();
  926. }
  927. static string HashToString(byte[] bs)
  928. {
  929. var sb = new StringBuilder();
  930. foreach (byte b in bs)
  931. sb.Append(b.ToString("x2"));
  932. return sb.ToString();
  933. }
  934. }
  935. }