ProjectUtils.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334
  1. using GodotTools.Core;
  2. using System.Collections.Generic;
  3. using System.Diagnostics;
  4. using System.IO;
  5. using System.Linq;
  6. using System.Reflection;
  7. using DotNet.Globbing;
  8. using Microsoft.Build.Construction;
  9. namespace GodotTools.ProjectEditor
  10. {
  11. public sealed class MSBuildProject
  12. {
  13. public ProjectRootElement Root { get; }
  14. public bool HasUnsavedChanges => Root.HasUnsavedChanges;
  15. public void Save() => Root.Save();
  16. public MSBuildProject(ProjectRootElement root)
  17. {
  18. Root = root;
  19. }
  20. }
  21. public static class ProjectUtils
  22. {
  23. public static MSBuildProject Open(string path)
  24. {
  25. var root = ProjectRootElement.Open(path);
  26. return root != null ? new MSBuildProject(root) : null;
  27. }
  28. public static void AddItemToProjectChecked(string projectPath, string itemType, string include)
  29. {
  30. var dir = Directory.GetParent(projectPath).FullName;
  31. var root = ProjectRootElement.Open(projectPath);
  32. Debug.Assert(root != null);
  33. var normalizedInclude = include.RelativeToPath(dir).Replace("/", "\\");
  34. if (root.AddItemChecked(itemType, normalizedInclude))
  35. root.Save();
  36. }
  37. public static void RenameItemInProjectChecked(string projectPath, string itemType, string oldInclude, string newInclude)
  38. {
  39. var dir = Directory.GetParent(projectPath).FullName;
  40. var root = ProjectRootElement.Open(projectPath);
  41. Debug.Assert(root != null);
  42. var normalizedOldInclude = oldInclude.NormalizePath();
  43. var normalizedNewInclude = newInclude.NormalizePath();
  44. var item = root.FindItemOrNullAbs(itemType, normalizedOldInclude);
  45. if (item == null)
  46. return;
  47. item.Include = normalizedNewInclude.RelativeToPath(dir).Replace("/", "\\");
  48. root.Save();
  49. }
  50. public static void RemoveItemFromProjectChecked(string projectPath, string itemType, string include)
  51. {
  52. var root = ProjectRootElement.Open(projectPath);
  53. Debug.Assert(root != null);
  54. var normalizedInclude = include.NormalizePath();
  55. if (root.RemoveItemChecked(itemType, normalizedInclude))
  56. root.Save();
  57. }
  58. public static void RenameItemsToNewFolderInProjectChecked(string projectPath, string itemType, string oldFolder, string newFolder)
  59. {
  60. var dir = Directory.GetParent(projectPath).FullName;
  61. var root = ProjectRootElement.Open(projectPath);
  62. Debug.Assert(root != null);
  63. var oldFolderNormalized = oldFolder.NormalizePath();
  64. var newFolderNormalized = newFolder.NormalizePath();
  65. string absOldFolderNormalized = Path.GetFullPath(oldFolderNormalized).NormalizePath();
  66. string absNewFolderNormalized = Path.GetFullPath(newFolderNormalized).NormalizePath();
  67. foreach (var item in root.FindAllItemsInFolder(itemType, oldFolderNormalized))
  68. {
  69. string absPathNormalized = Path.GetFullPath(item.Include).NormalizePath();
  70. string absNewIncludeNormalized = absNewFolderNormalized + absPathNormalized.Substring(absOldFolderNormalized.Length);
  71. item.Include = absNewIncludeNormalized.RelativeToPath(dir).Replace("/", "\\");
  72. }
  73. if (root.HasUnsavedChanges)
  74. root.Save();
  75. }
  76. public static void RemoveItemsInFolderFromProjectChecked(string projectPath, string itemType, string folder)
  77. {
  78. var root = ProjectRootElement.Open(projectPath);
  79. Debug.Assert(root != null);
  80. var folderNormalized = folder.NormalizePath();
  81. var itemsToRemove = root.FindAllItemsInFolder(itemType, folderNormalized).ToList();
  82. if (itemsToRemove.Count > 0)
  83. {
  84. foreach (var item in itemsToRemove)
  85. item.Parent.RemoveChild(item);
  86. root.Save();
  87. }
  88. }
  89. private static string[] GetAllFilesRecursive(string rootDirectory, string mask)
  90. {
  91. string[] files = Directory.GetFiles(rootDirectory, mask, SearchOption.AllDirectories);
  92. // We want relative paths
  93. for (int i = 0; i < files.Length; i++)
  94. {
  95. files[i] = files[i].RelativeToPath(rootDirectory);
  96. }
  97. return files;
  98. }
  99. public static string[] GetIncludeFiles(string projectPath, string itemType)
  100. {
  101. var result = new List<string>();
  102. var existingFiles = GetAllFilesRecursive(Path.GetDirectoryName(projectPath), "*.cs");
  103. var globOptions = new GlobOptions();
  104. globOptions.Evaluation.CaseInsensitive = false;
  105. var root = ProjectRootElement.Open(projectPath);
  106. Debug.Assert(root != null);
  107. foreach (var itemGroup in root.ItemGroups)
  108. {
  109. if (itemGroup.Condition.Length != 0)
  110. continue;
  111. foreach (var item in itemGroup.Items)
  112. {
  113. if (item.ItemType != itemType)
  114. continue;
  115. string normalizedInclude = item.Include.NormalizePath();
  116. var glob = Glob.Parse(normalizedInclude, globOptions);
  117. // TODO Check somehow if path has no blob to avoid the following loop...
  118. foreach (var existingFile in existingFiles)
  119. {
  120. if (glob.IsMatch(existingFile))
  121. {
  122. result.Add(existingFile);
  123. }
  124. }
  125. }
  126. }
  127. return result.ToArray();
  128. }
  129. /// Simple function to make sure the Api assembly references are configured correctly
  130. public static void FixApiHintPath(MSBuildProject project)
  131. {
  132. var root = project.Root;
  133. void AddPropertyIfNotPresent(string name, string condition, string value)
  134. {
  135. if (root.PropertyGroups
  136. .Any(g => (g.Condition == string.Empty || g.Condition.Trim() == condition) &&
  137. g.Properties
  138. .Any(p => p.Name == name &&
  139. p.Value == value &&
  140. (p.Condition.Trim() == condition || g.Condition.Trim() == condition))))
  141. {
  142. return;
  143. }
  144. root.AddProperty(name, value).Condition = " " + condition + " ";
  145. }
  146. AddPropertyIfNotPresent(name: "ApiConfiguration",
  147. condition: "'$(Configuration)' != 'ExportRelease'",
  148. value: "Debug");
  149. AddPropertyIfNotPresent(name: "ApiConfiguration",
  150. condition: "'$(Configuration)' == 'ExportRelease'",
  151. value: "Release");
  152. void SetReferenceHintPath(string referenceName, string condition, string hintPath)
  153. {
  154. foreach (var itemGroup in root.ItemGroups.Where(g =>
  155. g.Condition.Trim() == string.Empty || g.Condition.Trim() == condition))
  156. {
  157. var references = itemGroup.Items.Where(item =>
  158. item.ItemType == "Reference" &&
  159. item.Include == referenceName &&
  160. (item.Condition.Trim() == condition || itemGroup.Condition.Trim() == condition));
  161. var referencesWithHintPath = references.Where(reference =>
  162. reference.Metadata.Any(m => m.Name == "HintPath"));
  163. if (referencesWithHintPath.Any(reference => reference.Metadata
  164. .Any(m => m.Name == "HintPath" && m.Value == hintPath)))
  165. {
  166. // Found a Reference item with the right HintPath
  167. return;
  168. }
  169. var referenceWithHintPath = referencesWithHintPath.FirstOrDefault();
  170. if (referenceWithHintPath != null)
  171. {
  172. // Found a Reference item with a wrong HintPath
  173. foreach (var metadata in referenceWithHintPath.Metadata.ToList()
  174. .Where(m => m.Name == "HintPath"))
  175. {
  176. // Safe to remove as we duplicate with ToList() to loop
  177. referenceWithHintPath.RemoveChild(metadata);
  178. }
  179. referenceWithHintPath.AddMetadata("HintPath", hintPath);
  180. return;
  181. }
  182. var referenceWithoutHintPath = references.FirstOrDefault();
  183. if (referenceWithoutHintPath != null)
  184. {
  185. // Found a Reference item without a HintPath
  186. referenceWithoutHintPath.AddMetadata("HintPath", hintPath);
  187. return;
  188. }
  189. }
  190. // Found no Reference item at all. Add it.
  191. root.AddItem("Reference", referenceName).Condition = " " + condition + " ";
  192. }
  193. const string coreProjectName = "GodotSharp";
  194. const string editorProjectName = "GodotSharpEditor";
  195. const string coreCondition = "";
  196. const string editorCondition = "'$(Configuration)' == 'Debug'";
  197. var coreHintPath = $"$(ProjectDir)/.mono/assemblies/$(ApiConfiguration)/{coreProjectName}.dll";
  198. var editorHintPath = $"$(ProjectDir)/.mono/assemblies/$(ApiConfiguration)/{editorProjectName}.dll";
  199. SetReferenceHintPath(coreProjectName, coreCondition, coreHintPath);
  200. SetReferenceHintPath(editorProjectName, editorCondition, editorHintPath);
  201. }
  202. public static void MigrateFromOldConfigNames(MSBuildProject project)
  203. {
  204. var root = project.Root;
  205. bool hasGodotProjectGeneratorVersion = false;
  206. bool foundOldConfiguration = false;
  207. foreach (var propertyGroup in root.PropertyGroups.Where(g => g.Condition == string.Empty))
  208. {
  209. if (!hasGodotProjectGeneratorVersion && propertyGroup.Properties.Any(p => p.Name == "GodotProjectGeneratorVersion"))
  210. hasGodotProjectGeneratorVersion = true;
  211. foreach (var configItem in propertyGroup.Properties
  212. .Where(p => p.Condition.Trim() == "'$(Configuration)' == ''" && p.Value == "Tools"))
  213. {
  214. configItem.Value = "Debug";
  215. foundOldConfiguration = true;
  216. }
  217. }
  218. if (!hasGodotProjectGeneratorVersion)
  219. {
  220. root.PropertyGroups.First(g => g.Condition == string.Empty)?
  221. .AddProperty("GodotProjectGeneratorVersion", Assembly.GetExecutingAssembly().GetName().Version.ToString());
  222. }
  223. if (!foundOldConfiguration)
  224. {
  225. var toolsConditions = new[]
  226. {
  227. "'$(Configuration)|$(Platform)' == 'Tools|AnyCPU'",
  228. "'$(Configuration)|$(Platform)' != 'Tools|AnyCPU'",
  229. "'$(Configuration)' == 'Tools'",
  230. "'$(Configuration)' != 'Tools'"
  231. };
  232. foundOldConfiguration = root.PropertyGroups
  233. .Any(g => toolsConditions.Any(c => c == g.Condition.Trim()));
  234. }
  235. if (foundOldConfiguration)
  236. {
  237. void MigrateConfigurationConditions(string oldConfiguration, string newConfiguration)
  238. {
  239. void MigrateConditions(string oldCondition, string newCondition)
  240. {
  241. foreach (var propertyGroup in root.PropertyGroups.Where(g => g.Condition.Trim() == oldCondition))
  242. propertyGroup.Condition = " " + newCondition + " ";
  243. foreach (var propertyGroup in root.PropertyGroups)
  244. {
  245. foreach (var prop in propertyGroup.Properties.Where(p => p.Condition.Trim() == oldCondition))
  246. prop.Condition = " " + newCondition + " ";
  247. }
  248. foreach (var itemGroup in root.ItemGroups.Where(g => g.Condition.Trim() == oldCondition))
  249. itemGroup.Condition = " " + newCondition + " ";
  250. foreach (var itemGroup in root.ItemGroups)
  251. {
  252. foreach (var item in itemGroup.Items.Where(item => item.Condition.Trim() == oldCondition))
  253. item.Condition = " " + newCondition + " ";
  254. }
  255. }
  256. foreach (var op in new[] {"==", "!="})
  257. {
  258. MigrateConditions($"'$(Configuration)|$(Platform)' {op} '{oldConfiguration}|AnyCPU'", $"'$(Configuration)|$(Platform)' {op} '{newConfiguration}|AnyCPU'");
  259. MigrateConditions($"'$(Configuration)' {op} '{oldConfiguration}'", $"'$(Configuration)' {op} '{newConfiguration}'");
  260. }
  261. }
  262. MigrateConfigurationConditions("Debug", "ExportDebug");
  263. MigrateConfigurationConditions("Release", "ExportRelease");
  264. MigrateConfigurationConditions("Tools", "Debug"); // Must be last
  265. }
  266. }
  267. }
  268. }