SW 중심대학 OSS GIT 서버 박건태, 이승준, 고기완, 이준호 새로운 배포
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

718 lines
31 KiB

4 years ago
  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 UnityEditor;
  10. using UnityEditor.Compilation;
  11. using UnityEditor.PackageManager;
  12. using UnityEngine;
  13. using UnityEngine.Profiling;
  14. namespace VSCodeEditor
  15. {
  16. public interface IGenerator
  17. {
  18. bool SyncIfNeeded(List<string> affectedFiles, string[] reimportedFiles);
  19. void Sync();
  20. string SolutionFile();
  21. string ProjectDirectory { get; }
  22. void GenerateAll(bool generateAll);
  23. bool SolutionExists();
  24. }
  25. public class ProjectGeneration : IGenerator
  26. {
  27. enum ScriptingLanguage
  28. {
  29. None,
  30. CSharp
  31. }
  32. public static readonly string MSBuildNamespaceUri = "http://schemas.microsoft.com/developer/msbuild/2003";
  33. const string k_WindowsNewline = "\r\n";
  34. const string k_SettingsJson = @"{
  35. ""files.exclude"":
  36. {
  37. ""**/.DS_Store"":true,
  38. ""**/.git"":true,
  39. ""**/.gitignore"":true,
  40. ""**/.gitmodules"":true,
  41. ""**/*.booproj"":true,
  42. ""**/*.pidb"":true,
  43. ""**/*.suo"":true,
  44. ""**/*.user"":true,
  45. ""**/*.userprefs"":true,
  46. ""**/*.unityproj"":true,
  47. ""**/*.dll"":true,
  48. ""**/*.exe"":true,
  49. ""**/*.pdf"":true,
  50. ""**/*.mid"":true,
  51. ""**/*.midi"":true,
  52. ""**/*.wav"":true,
  53. ""**/*.gif"":true,
  54. ""**/*.ico"":true,
  55. ""**/*.jpg"":true,
  56. ""**/*.jpeg"":true,
  57. ""**/*.png"":true,
  58. ""**/*.psd"":true,
  59. ""**/*.tga"":true,
  60. ""**/*.tif"":true,
  61. ""**/*.tiff"":true,
  62. ""**/*.3ds"":true,
  63. ""**/*.3DS"":true,
  64. ""**/*.fbx"":true,
  65. ""**/*.FBX"":true,
  66. ""**/*.lxo"":true,
  67. ""**/*.LXO"":true,
  68. ""**/*.ma"":true,
  69. ""**/*.MA"":true,
  70. ""**/*.obj"":true,
  71. ""**/*.OBJ"":true,
  72. ""**/*.asset"":true,
  73. ""**/*.cubemap"":true,
  74. ""**/*.flare"":true,
  75. ""**/*.mat"":true,
  76. ""**/*.meta"":true,
  77. ""**/*.prefab"":true,
  78. ""**/*.unity"":true,
  79. ""build/"":true,
  80. ""Build/"":true,
  81. ""Library/"":true,
  82. ""library/"":true,
  83. ""obj/"":true,
  84. ""Obj/"":true,
  85. ""ProjectSettings/"":true,
  86. ""temp/"":true,
  87. ""Temp/"":true
  88. }
  89. }";
  90. /// <summary>
  91. /// Map source extensions to ScriptingLanguages
  92. /// </summary>
  93. static readonly Dictionary<string, ScriptingLanguage> k_BuiltinSupportedExtensions = new Dictionary<string, ScriptingLanguage>
  94. {
  95. { "cs", ScriptingLanguage.CSharp },
  96. { "uxml", ScriptingLanguage.None },
  97. { "uss", ScriptingLanguage.None },
  98. { "shader", ScriptingLanguage.None },
  99. { "compute", ScriptingLanguage.None },
  100. { "cginc", ScriptingLanguage.None },
  101. { "hlsl", ScriptingLanguage.None },
  102. { "glslinc", ScriptingLanguage.None },
  103. { "template", ScriptingLanguage.None },
  104. { "raytrace", ScriptingLanguage.None }
  105. };
  106. string m_SolutionProjectEntryTemplate = string.Join("\r\n", @"Project(""{{{0}}}"") = ""{1}"", ""{2}"", ""{{{3}}}""", @"EndProject").Replace(" ", "\t");
  107. string m_SolutionProjectConfigurationTemplate = string.Join("\r\n", @" {{{0}}}.Debug|Any CPU.ActiveCfg = Debug|Any CPU", @" {{{0}}}.Debug|Any CPU.Build.0 = Debug|Any CPU", @" {{{0}}}.Release|Any CPU.ActiveCfg = Release|Any CPU", @" {{{0}}}.Release|Any CPU.Build.0 = Release|Any CPU").Replace(" ", "\t");
  108. static readonly string[] k_ReimportSyncExtensions = { ".dll", ".asmdef" };
  109. string[] m_ProjectSupportedExtensions = new string[0];
  110. public string ProjectDirectory { get; }
  111. bool m_ShouldGenerateAll;
  112. public void GenerateAll(bool generateAll)
  113. {
  114. m_ShouldGenerateAll = generateAll;
  115. }
  116. readonly string m_ProjectName;
  117. readonly IAssemblyNameProvider m_AssemblyNameProvider;
  118. readonly IFileIO m_FileIOProvider;
  119. readonly IGUIDGenerator m_GUIDProvider;
  120. const string k_ToolsVersion = "4.0";
  121. const string k_ProductVersion = "10.0.20506";
  122. const string k_BaseDirectory = ".";
  123. const string k_TargetFrameworkVersion = "v4.7.1";
  124. const string k_TargetLanguageVersion = "latest";
  125. public ProjectGeneration(string tempDirectory)
  126. : this(tempDirectory, new AssemblyNameProvider(), new FileIOProvider(), new GUIDProvider()) { }
  127. public ProjectGeneration(string tempDirectory, IAssemblyNameProvider assemblyNameProvider, IFileIO fileIO, IGUIDGenerator guidGenerator)
  128. {
  129. ProjectDirectory = tempDirectory.Replace('\\', '/');
  130. m_ProjectName = Path.GetFileName(ProjectDirectory);
  131. m_AssemblyNameProvider = assemblyNameProvider;
  132. m_FileIOProvider = fileIO;
  133. m_GUIDProvider = guidGenerator;
  134. }
  135. /// <summary>
  136. /// Syncs the scripting solution if any affected files are relevant.
  137. /// </summary>
  138. /// <returns>
  139. /// Whether the solution was synced.
  140. /// </returns>
  141. /// <param name='affectedFiles'>
  142. /// A set of files whose status has changed
  143. /// </param>
  144. /// <param name="reimportedFiles">
  145. /// A set of files that got reimported
  146. /// </param>
  147. public bool SyncIfNeeded(List<string> affectedFiles, string[] reimportedFiles)
  148. {
  149. Profiler.BeginSample("SolutionSynchronizerSync");
  150. SetupProjectSupportedExtensions();
  151. // Don't sync if we haven't synced before
  152. if (SolutionExists() && HasFilesBeenModified(affectedFiles, reimportedFiles))
  153. {
  154. var assemblies = m_AssemblyNameProvider.GetAssemblies(ShouldFileBePartOfSolution);
  155. var allProjectAssemblies = RelevantAssembliesForMode(assemblies).ToList();
  156. var allAssetProjectParts = GenerateAllAssetProjectParts();
  157. var affectedNames = affectedFiles.Select(asset => m_AssemblyNameProvider.GetAssemblyNameFromScriptPath(asset)?.Split(new [] {".dll"}, StringSplitOptions.RemoveEmptyEntries)[0]);
  158. var reimportedNames = reimportedFiles.Select(asset => m_AssemblyNameProvider.GetAssemblyNameFromScriptPath(asset)?.Split(new [] {".dll"}, StringSplitOptions.RemoveEmptyEntries)[0]);
  159. var affectedAndReimported = new HashSet<string>(affectedNames.Concat(reimportedNames));
  160. var assemblyNames = new HashSet<string>(allProjectAssemblies.Select(assembly => Path.GetFileName(assembly.outputPath)));
  161. foreach (var assembly in allProjectAssemblies)
  162. {
  163. if (!affectedAndReimported.Contains(assembly.name))
  164. continue;
  165. SyncProject(assembly, allAssetProjectParts, ParseResponseFileData(assembly), assemblyNames);
  166. }
  167. Profiler.EndSample();
  168. return true;
  169. }
  170. Profiler.EndSample();
  171. return false;
  172. }
  173. bool HasFilesBeenModified(List<string> affectedFiles, string[] reimportedFiles)
  174. {
  175. return affectedFiles.Any(ShouldFileBePartOfSolution) || reimportedFiles.Any(ShouldSyncOnReimportedAsset);
  176. }
  177. static bool ShouldSyncOnReimportedAsset(string asset)
  178. {
  179. return k_ReimportSyncExtensions.Contains(new FileInfo(asset).Extension);
  180. }
  181. public void Sync()
  182. {
  183. SetupProjectSupportedExtensions();
  184. GenerateAndWriteSolutionAndProjects();
  185. }
  186. public bool SolutionExists()
  187. {
  188. return m_FileIOProvider.Exists(SolutionFile());
  189. }
  190. void SetupProjectSupportedExtensions()
  191. {
  192. m_ProjectSupportedExtensions = EditorSettings.projectGenerationUserExtensions;
  193. }
  194. bool ShouldFileBePartOfSolution(string file)
  195. {
  196. string extension = Path.GetExtension(file);
  197. // Exclude files coming from packages except if they are internalized.
  198. if (!m_ShouldGenerateAll && IsInternalizedPackagePath(file))
  199. {
  200. return false;
  201. }
  202. // Dll's are not scripts but still need to be included..
  203. if (extension == ".dll")
  204. return true;
  205. if (file.ToLower().EndsWith(".asmdef"))
  206. return true;
  207. return IsSupportedExtension(extension);
  208. }
  209. bool IsSupportedExtension(string extension)
  210. {
  211. extension = extension.TrimStart('.');
  212. if (k_BuiltinSupportedExtensions.ContainsKey(extension))
  213. return true;
  214. if (m_ProjectSupportedExtensions.Contains(extension))
  215. return true;
  216. return false;
  217. }
  218. static ScriptingLanguage ScriptingLanguageFor(Assembly assembly)
  219. {
  220. return ScriptingLanguageFor(GetExtensionOfSourceFiles(assembly.sourceFiles));
  221. }
  222. static string GetExtensionOfSourceFiles(string[] files)
  223. {
  224. return files.Length > 0 ? GetExtensionOfSourceFile(files[0]) : "NA";
  225. }
  226. static string GetExtensionOfSourceFile(string file)
  227. {
  228. var ext = Path.GetExtension(file).ToLower();
  229. ext = ext.Substring(1); //strip dot
  230. return ext;
  231. }
  232. static ScriptingLanguage ScriptingLanguageFor(string extension)
  233. {
  234. return k_BuiltinSupportedExtensions.TryGetValue(extension.TrimStart('.'), out var result)
  235. ? result
  236. : ScriptingLanguage.None;
  237. }
  238. public void GenerateAndWriteSolutionAndProjects()
  239. {
  240. // Only synchronize assemblies that have associated source files and ones that we actually want in the project.
  241. // This also filters out DLLs coming from .asmdef files in packages.
  242. var assemblies = m_AssemblyNameProvider.GetAssemblies(ShouldFileBePartOfSolution);
  243. var allAssetProjectParts = GenerateAllAssetProjectParts();
  244. SyncSolution(assemblies);
  245. var allProjectAssemblies = RelevantAssembliesForMode(assemblies).ToList();
  246. var assemblyNames = new HashSet<string>(allProjectAssemblies.Select(assembly => Path.GetFileName(assembly.outputPath)));
  247. foreach (Assembly assembly in allProjectAssemblies)
  248. {
  249. var responseFileData = ParseResponseFileData(assembly);
  250. SyncProject(assembly, allAssetProjectParts, responseFileData, assemblyNames);
  251. }
  252. WriteVSCodeSettingsFiles();
  253. }
  254. IEnumerable<ResponseFileData> ParseResponseFileData(Assembly assembly)
  255. {
  256. var systemReferenceDirectories = CompilationPipeline.GetSystemAssemblyDirectories(assembly.compilerOptions.ApiCompatibilityLevel);
  257. Dictionary<string, ResponseFileData> responseFilesData = assembly.compilerOptions.ResponseFiles.ToDictionary(x => x, x => m_AssemblyNameProvider.ParseResponseFile(
  258. x,
  259. ProjectDirectory,
  260. systemReferenceDirectories
  261. ));
  262. Dictionary<string, ResponseFileData> responseFilesWithErrors = responseFilesData.Where(x => x.Value.Errors.Any())
  263. .ToDictionary(x => x.Key, x => x.Value);
  264. if (responseFilesWithErrors.Any())
  265. {
  266. foreach (var error in responseFilesWithErrors)
  267. foreach (var valueError in error.Value.Errors)
  268. {
  269. Debug.LogError($"{error.Key} Parse Error : {valueError}");
  270. }
  271. }
  272. return responseFilesData.Select(x => x.Value);
  273. }
  274. Dictionary<string, string> GenerateAllAssetProjectParts()
  275. {
  276. Dictionary<string, StringBuilder> stringBuilders = new Dictionary<string, StringBuilder>();
  277. foreach (string asset in m_AssemblyNameProvider.GetAllAssetPaths())
  278. {
  279. // Exclude files coming from packages except if they are internalized.
  280. // TODO: We need assets from the assembly API
  281. if (!m_ShouldGenerateAll && IsInternalizedPackagePath(asset))
  282. {
  283. continue;
  284. }
  285. string extension = Path.GetExtension(asset);
  286. if (IsSupportedExtension(extension) && ScriptingLanguage.None == ScriptingLanguageFor(extension))
  287. {
  288. // Find assembly the asset belongs to by adding script extension and using compilation pipeline.
  289. var assemblyName = m_AssemblyNameProvider.GetAssemblyNameFromScriptPath(asset);
  290. if (string.IsNullOrEmpty(assemblyName))
  291. {
  292. continue;
  293. }
  294. assemblyName = Path.GetFileNameWithoutExtension(assemblyName);
  295. if (!stringBuilders.TryGetValue(assemblyName, out var projectBuilder))
  296. {
  297. projectBuilder = new StringBuilder();
  298. stringBuilders[assemblyName] = projectBuilder;
  299. }
  300. projectBuilder.Append(" <None Include=\"").Append(EscapedRelativePathFor(asset)).Append("\" />").Append(k_WindowsNewline);
  301. }
  302. }
  303. var result = new Dictionary<string, string>();
  304. foreach (var entry in stringBuilders)
  305. result[entry.Key] = entry.Value.ToString();
  306. return result;
  307. }
  308. bool IsInternalizedPackagePath(string file)
  309. {
  310. if (string.IsNullOrWhiteSpace(file))
  311. {
  312. return false;
  313. }
  314. var packageInfo = m_AssemblyNameProvider.FindForAssetPath(file);
  315. if (packageInfo == null)
  316. {
  317. return false;
  318. }
  319. var packageSource = packageInfo.source;
  320. return packageSource != PackageSource.Embedded && packageSource != PackageSource.Local;
  321. }
  322. void SyncProject(
  323. Assembly assembly,
  324. Dictionary<string, string> allAssetsProjectParts,
  325. IEnumerable<ResponseFileData> responseFilesData,
  326. HashSet<string> assemblyNames)
  327. {
  328. SyncProjectFileIfNotChanged(ProjectFile(assembly), ProjectText(assembly, allAssetsProjectParts, responseFilesData, assemblyNames));
  329. }
  330. void SyncProjectFileIfNotChanged(string path, string newContents)
  331. {
  332. SyncFileIfNotChanged(path, newContents);
  333. }
  334. void SyncSolutionFileIfNotChanged(string path, string newContents)
  335. {
  336. SyncFileIfNotChanged(path, newContents);
  337. }
  338. void SyncFileIfNotChanged(string filename, string newContents)
  339. {
  340. if (m_FileIOProvider.Exists(filename))
  341. {
  342. var currentContents = m_FileIOProvider.ReadAllText(filename);
  343. if (currentContents == newContents)
  344. {
  345. return;
  346. }
  347. }
  348. m_FileIOProvider.WriteAllText(filename, newContents);
  349. }
  350. string ProjectText(
  351. Assembly assembly,
  352. Dictionary<string, string> allAssetsProjectParts,
  353. IEnumerable<ResponseFileData> responseFilesData,
  354. HashSet<string> assemblyNames)
  355. {
  356. var projectBuilder = new StringBuilder();
  357. ProjectHeader(assembly, responseFilesData, projectBuilder);
  358. var references = new List<string>();
  359. var projectReferences = new List<Assembly>();
  360. foreach (string file in assembly.sourceFiles)
  361. {
  362. if (!ShouldFileBePartOfSolution(file))
  363. continue;
  364. var extension = Path.GetExtension(file).ToLower();
  365. var fullFile = EscapedRelativePathFor(file);
  366. if (".dll" != extension)
  367. {
  368. projectBuilder.Append(" <Compile Include=\"").Append(fullFile).Append("\" />").Append(k_WindowsNewline);
  369. }
  370. else
  371. {
  372. references.Add(fullFile);
  373. }
  374. }
  375. // Append additional non-script files that should be included in project generation.
  376. if (allAssetsProjectParts.TryGetValue(assembly.name, out var additionalAssetsForProject))
  377. projectBuilder.Append(additionalAssetsForProject);
  378. var responseRefs = responseFilesData.SelectMany(x => x.FullPathReferences.Select(r => r));
  379. foreach (var reference in assembly.compiledAssemblyReferences.Union(responseRefs).Union(references))
  380. {
  381. string fullReference = Path.IsPathRooted(reference) ? reference : Path.Combine(ProjectDirectory, reference);
  382. AppendReference(fullReference, projectBuilder);
  383. }
  384. if (0 < assembly.assemblyReferences.Length)
  385. {
  386. projectBuilder.Append(" </ItemGroup>").Append(k_WindowsNewline);
  387. projectBuilder.Append(" <ItemGroup>").Append(k_WindowsNewline);
  388. foreach (Assembly reference in assembly.assemblyReferences)
  389. {
  390. var referencedProject = reference.outputPath;
  391. projectBuilder.Append(" <ProjectReference Include=\"").Append(reference.name).Append(GetProjectExtension()).Append("\">").Append(k_WindowsNewline);
  392. projectBuilder.Append(" <Project>{").Append(ProjectGuid(reference.name)).Append("}</Project>").Append(k_WindowsNewline);
  393. projectBuilder.Append(" <Name>").Append(reference.name).Append("</Name>").Append(k_WindowsNewline);
  394. projectBuilder.Append(" </ProjectReference>").Append(k_WindowsNewline);
  395. }
  396. }
  397. projectBuilder.Append(ProjectFooter());
  398. return projectBuilder.ToString();
  399. }
  400. static void AppendReference(string fullReference, StringBuilder projectBuilder)
  401. {
  402. //replace \ with / and \\ with /
  403. var escapedFullPath = SecurityElement.Escape(fullReference);
  404. escapedFullPath = escapedFullPath.Replace("\\\\", "/");
  405. escapedFullPath = escapedFullPath.Replace("\\", "/");
  406. projectBuilder.Append(" <Reference Include=\"").Append(Path.GetFileNameWithoutExtension(escapedFullPath)).Append("\">").Append(k_WindowsNewline);
  407. projectBuilder.Append(" <HintPath>").Append(escapedFullPath).Append("</HintPath>").Append(k_WindowsNewline);
  408. projectBuilder.Append(" </Reference>").Append(k_WindowsNewline);
  409. }
  410. public string ProjectFile(Assembly assembly)
  411. {
  412. var fileBuilder = new StringBuilder(assembly.name);
  413. fileBuilder.Append(".csproj");
  414. return Path.Combine(ProjectDirectory, fileBuilder.ToString());
  415. }
  416. public string SolutionFile()
  417. {
  418. return Path.Combine(ProjectDirectory, $"{m_ProjectName}.sln");
  419. }
  420. void ProjectHeader(
  421. Assembly assembly,
  422. IEnumerable<ResponseFileData> responseFilesData,
  423. StringBuilder builder
  424. )
  425. {
  426. // TODO: .Concat(EditorUserBuildSettings.activeScriptCompilationDefines)
  427. GetProjectHeaderTemplate(
  428. builder,
  429. ProjectGuid(assembly.name),
  430. assembly.name,
  431. string.Join(";", new[] { "DEBUG", "TRACE" }.Concat(assembly.defines).Concat(responseFilesData.SelectMany(x => x.Defines)).Distinct().ToArray()),
  432. assembly.compilerOptions.AllowUnsafeCode | responseFilesData.Any(x => x.Unsafe));
  433. }
  434. static string GetSolutionText()
  435. {
  436. return string.Join("\r\n", @"", @"Microsoft Visual Studio Solution File, Format Version {0}", @"# Visual Studio {1}", @"{2}", @"Global", @" GlobalSection(SolutionConfigurationPlatforms) = preSolution", @" Debug|Any CPU = Debug|Any CPU", @" Release|Any CPU = Release|Any CPU", @" EndGlobalSection", @" GlobalSection(ProjectConfigurationPlatforms) = postSolution", @"{3}", @" EndGlobalSection", @" GlobalSection(SolutionProperties) = preSolution", @" HideSolutionNode = FALSE", @" EndGlobalSection", @"EndGlobal", @"").Replace(" ", "\t");
  437. }
  438. static string GetProjectFooterTemplate()
  439. {
  440. return string.Join("\r\n", @" </ItemGroup>", @" <Import Project=""$(MSBuildToolsPath)\Microsoft.CSharp.targets"" />", @" <!-- To modify your build process, add your task inside one of the targets below and uncomment it.", @" Other similar extension points exist, see Microsoft.Common.targets.", @" <Target Name=""BeforeBuild"">", @" </Target>", @" <Target Name=""AfterBuild"">", @" </Target>", @" -->", @"</Project>", @"");
  441. }
  442. static void GetProjectHeaderTemplate(
  443. StringBuilder builder,
  444. string assemblyGUID,
  445. string assemblyName,
  446. string defines,
  447. bool allowUnsafe
  448. )
  449. {
  450. builder.Append(@"<?xml version=""1.0"" encoding=""utf-8""?>").Append(k_WindowsNewline);
  451. builder.Append(@"<Project ToolsVersion=""").Append(k_ToolsVersion).Append(@""" DefaultTargets=""Build"" xmlns=""").Append(MSBuildNamespaceUri).Append(@""">").Append(k_WindowsNewline);
  452. builder.Append(@" <PropertyGroup>").Append(k_WindowsNewline);
  453. builder.Append(@" <LangVersion>").Append(k_TargetLanguageVersion).Append("</LangVersion>").Append(k_WindowsNewline);
  454. builder.Append(@" </PropertyGroup>").Append(k_WindowsNewline);
  455. builder.Append(@" <PropertyGroup>").Append(k_WindowsNewline);
  456. builder.Append(@" <Configuration Condition="" '$(Configuration)' == '' "">Debug</Configuration>").Append(k_WindowsNewline);
  457. builder.Append(@" <Platform Condition="" '$(Platform)' == '' "">AnyCPU</Platform>").Append(k_WindowsNewline);
  458. builder.Append(@" <ProductVersion>").Append(k_ProductVersion).Append("</ProductVersion>").Append(k_WindowsNewline);
  459. builder.Append(@" <SchemaVersion>2.0</SchemaVersion>").Append(k_WindowsNewline);
  460. builder.Append(@" <RootNamespace>").Append(EditorSettings.projectGenerationRootNamespace).Append("</RootNamespace>").Append(k_WindowsNewline);
  461. builder.Append(@" <ProjectGuid>{").Append(assemblyGUID).Append("}</ProjectGuid>").Append(k_WindowsNewline);
  462. builder.Append(@" <OutputType>Library</OutputType>").Append(k_WindowsNewline);
  463. builder.Append(@" <AppDesignerFolder>Properties</AppDesignerFolder>").Append(k_WindowsNewline);
  464. builder.Append(@" <AssemblyName>").Append(assemblyName).Append("</AssemblyName>").Append(k_WindowsNewline);
  465. builder.Append(@" <TargetFrameworkVersion>").Append(k_TargetFrameworkVersion).Append("</TargetFrameworkVersion>").Append(k_WindowsNewline);
  466. builder.Append(@" <FileAlignment>512</FileAlignment>").Append(k_WindowsNewline);
  467. builder.Append(@" <BaseDirectory>").Append(k_BaseDirectory).Append("</BaseDirectory>").Append(k_WindowsNewline);
  468. builder.Append(@" </PropertyGroup>").Append(k_WindowsNewline);
  469. builder.Append(@" <PropertyGroup Condition="" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' "">").Append(k_WindowsNewline);
  470. builder.Append(@" <DebugSymbols>true</DebugSymbols>").Append(k_WindowsNewline);
  471. builder.Append(@" <DebugType>full</DebugType>").Append(k_WindowsNewline);
  472. builder.Append(@" <Optimize>false</Optimize>").Append(k_WindowsNewline);
  473. builder.Append(@" <OutputPath>Temp\bin\Debug\</OutputPath>").Append(k_WindowsNewline);
  474. builder.Append(@" <DefineConstants>").Append(defines).Append("</DefineConstants>").Append(k_WindowsNewline);
  475. builder.Append(@" <ErrorReport>prompt</ErrorReport>").Append(k_WindowsNewline);
  476. builder.Append(@" <WarningLevel>4</WarningLevel>").Append(k_WindowsNewline);
  477. builder.Append(@" <NoWarn>0169</NoWarn>").Append(k_WindowsNewline);
  478. builder.Append(@" <AllowUnsafeBlocks>").Append(allowUnsafe).Append("</AllowUnsafeBlocks>").Append(k_WindowsNewline);
  479. builder.Append(@" </PropertyGroup>").Append(k_WindowsNewline);
  480. builder.Append(@" <PropertyGroup Condition="" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' "">").Append(k_WindowsNewline);
  481. builder.Append(@" <DebugType>pdbonly</DebugType>").Append(k_WindowsNewline);
  482. builder.Append(@" <Optimize>true</Optimize>").Append(k_WindowsNewline);
  483. builder.Append(@" <OutputPath>Temp\bin\Release\</OutputPath>").Append(k_WindowsNewline);
  484. builder.Append(@" <ErrorReport>prompt</ErrorReport>").Append(k_WindowsNewline);
  485. builder.Append(@" <WarningLevel>4</WarningLevel>").Append(k_WindowsNewline);
  486. builder.Append(@" <NoWarn>0169</NoWarn>").Append(k_WindowsNewline);
  487. builder.Append(@" <AllowUnsafeBlocks>").Append(allowUnsafe).Append("</AllowUnsafeBlocks>").Append(k_WindowsNewline);
  488. builder.Append(@" </PropertyGroup>").Append(k_WindowsNewline);
  489. builder.Append(@" <PropertyGroup>").Append(k_WindowsNewline);
  490. builder.Append(@" <NoConfig>true</NoConfig>").Append(k_WindowsNewline);
  491. builder.Append(@" <NoStdLib>true</NoStdLib>").Append(k_WindowsNewline);
  492. builder.Append(@" <AddAdditionalExplicitAssemblyReferences>false</AddAdditionalExplicitAssemblyReferences>").Append(k_WindowsNewline);
  493. builder.Append(@" <ImplicitlyExpandNETStandardFacades>false</ImplicitlyExpandNETStandardFacades>").Append(k_WindowsNewline);
  494. builder.Append(@" <ImplicitlyExpandDesignTimeFacades>false</ImplicitlyExpandDesignTimeFacades>").Append(k_WindowsNewline);
  495. builder.Append(@" </PropertyGroup>").Append(k_WindowsNewline);
  496. builder.Append(@" <ItemGroup>").Append(k_WindowsNewline);
  497. }
  498. void SyncSolution(IEnumerable<Assembly> assemblies)
  499. {
  500. SyncSolutionFileIfNotChanged(SolutionFile(), SolutionText(assemblies));
  501. }
  502. string SolutionText(IEnumerable<Assembly> assemblies)
  503. {
  504. var fileversion = "11.00";
  505. var vsversion = "2010";
  506. var relevantAssemblies = RelevantAssembliesForMode(assemblies);
  507. string projectEntries = GetProjectEntries(relevantAssemblies);
  508. string projectConfigurations = string.Join(k_WindowsNewline, relevantAssemblies.Select(i => GetProjectActiveConfigurations(ProjectGuid(i.name))).ToArray());
  509. return string.Format(GetSolutionText(), fileversion, vsversion, projectEntries, projectConfigurations);
  510. }
  511. static IEnumerable<Assembly> RelevantAssembliesForMode(IEnumerable<Assembly> assemblies)
  512. {
  513. return assemblies.Where(i => ScriptingLanguage.CSharp == ScriptingLanguageFor(i));
  514. }
  515. /// <summary>
  516. /// Get a Project("{guid}") = "MyProject", "MyProject.csproj", "{projectguid}"
  517. /// entry for each relevant language
  518. /// </summary>
  519. string GetProjectEntries(IEnumerable<Assembly> assemblies)
  520. {
  521. var projectEntries = assemblies.Select(i => string.Format(
  522. m_SolutionProjectEntryTemplate,
  523. SolutionGuid(i),
  524. i.name,
  525. Path.GetFileName(ProjectFile(i)),
  526. ProjectGuid(i.name)
  527. ));
  528. return string.Join(k_WindowsNewline, projectEntries.ToArray());
  529. }
  530. /// <summary>
  531. /// Generate the active configuration string for a given project guid
  532. /// </summary>
  533. string GetProjectActiveConfigurations(string projectGuid)
  534. {
  535. return string.Format(
  536. m_SolutionProjectConfigurationTemplate,
  537. projectGuid);
  538. }
  539. string EscapedRelativePathFor(string file)
  540. {
  541. var projectDir = ProjectDirectory.Replace('/', '\\');
  542. file = file.Replace('/', '\\');
  543. var path = SkipPathPrefix(file, projectDir);
  544. var packageInfo = m_AssemblyNameProvider.FindForAssetPath(path.Replace('\\', '/'));
  545. if (packageInfo != null)
  546. {
  547. // We have to normalize the path, because the PackageManagerRemapper assumes
  548. // dir seperators will be os specific.
  549. var absolutePath = Path.GetFullPath(NormalizePath(path)).Replace('/', '\\');
  550. path = SkipPathPrefix(absolutePath, projectDir);
  551. }
  552. return SecurityElement.Escape(path);
  553. }
  554. static string SkipPathPrefix(string path, string prefix)
  555. {
  556. if (path.StartsWith($@"{prefix}\"))
  557. return path.Substring(prefix.Length + 1);
  558. return path;
  559. }
  560. static string NormalizePath(string path)
  561. {
  562. if (Path.DirectorySeparatorChar == '\\')
  563. return path.Replace('/', Path.DirectorySeparatorChar);
  564. return path.Replace('\\', Path.DirectorySeparatorChar);
  565. }
  566. string ProjectGuid(string assembly)
  567. {
  568. return m_GUIDProvider.ProjectGuid(m_ProjectName, assembly);
  569. }
  570. string SolutionGuid(Assembly assembly)
  571. {
  572. return m_GUIDProvider.SolutionGuid(m_ProjectName, GetExtensionOfSourceFiles(assembly.sourceFiles));
  573. }
  574. static string ProjectFooter()
  575. {
  576. return GetProjectFooterTemplate();
  577. }
  578. static string GetProjectExtension()
  579. {
  580. return ".csproj";
  581. }
  582. void WriteVSCodeSettingsFiles()
  583. {
  584. var vsCodeDirectory = Path.Combine(ProjectDirectory, ".vscode");
  585. if (!m_FileIOProvider.Exists(vsCodeDirectory))
  586. m_FileIOProvider.CreateDirectory(vsCodeDirectory);
  587. var vsCodeSettingsJson = Path.Combine(vsCodeDirectory, "settings.json");
  588. if (!m_FileIOProvider.Exists(vsCodeSettingsJson))
  589. m_FileIOProvider.WriteAllText(vsCodeSettingsJson, k_SettingsJson);
  590. }
  591. }
  592. public static class SolutionGuidGenerator
  593. {
  594. static MD5 mD5 = MD5CryptoServiceProvider.Create();
  595. public static string GuidForProject(string projectName)
  596. {
  597. return ComputeGuidHashFor(projectName + "salt");
  598. }
  599. public static string GuidForSolution(string projectName, string sourceFileExtension)
  600. {
  601. if (sourceFileExtension.ToLower() == "cs")
  602. // GUID for a C# class library: http://www.codeproject.com/Reference/720512/List-of-Visual-Studio-Project-Type-GUIDs
  603. return "FAE04EC0-301F-11D3-BF4B-00C04F79EFBC";
  604. return ComputeGuidHashFor(projectName);
  605. }
  606. static string ComputeGuidHashFor(string input)
  607. {
  608. var hash = mD5.ComputeHash(Encoding.Default.GetBytes(input));
  609. return new Guid(hash).ToString();
  610. }
  611. }
  612. }