ProjectUtils.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355
  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 { get; set; }
  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. bool dirty = false;
  64. var oldFolderNormalized = oldFolder.NormalizePath();
  65. var newFolderNormalized = newFolder.NormalizePath();
  66. string absOldFolderNormalized = Path.GetFullPath(oldFolderNormalized).NormalizePath();
  67. string absNewFolderNormalized = Path.GetFullPath(newFolderNormalized).NormalizePath();
  68. foreach (var item in root.FindAllItemsInFolder(itemType, oldFolderNormalized))
  69. {
  70. string absPathNormalized = Path.GetFullPath(item.Include).NormalizePath();
  71. string absNewIncludeNormalized = absNewFolderNormalized + absPathNormalized.Substring(absOldFolderNormalized.Length);
  72. item.Include = absNewIncludeNormalized.RelativeToPath(dir).Replace("/", "\\");
  73. dirty = true;
  74. }
  75. if (dirty)
  76. root.Save();
  77. }
  78. public static void RemoveItemsInFolderFromProjectChecked(string projectPath, string itemType, string folder)
  79. {
  80. var root = ProjectRootElement.Open(projectPath);
  81. Debug.Assert(root != null);
  82. var folderNormalized = folder.NormalizePath();
  83. var itemsToRemove = root.FindAllItemsInFolder(itemType, folderNormalized).ToList();
  84. if (itemsToRemove.Count > 0)
  85. {
  86. foreach (var item in itemsToRemove)
  87. item.Parent.RemoveChild(item);
  88. root.Save();
  89. }
  90. }
  91. private static string[] GetAllFilesRecursive(string rootDirectory, string mask)
  92. {
  93. string[] files = Directory.GetFiles(rootDirectory, mask, SearchOption.AllDirectories);
  94. // We want relative paths
  95. for (int i = 0; i < files.Length; i++)
  96. {
  97. files[i] = files[i].RelativeToPath(rootDirectory);
  98. }
  99. return files;
  100. }
  101. public static string[] GetIncludeFiles(string projectPath, string itemType)
  102. {
  103. var result = new List<string>();
  104. var existingFiles = GetAllFilesRecursive(Path.GetDirectoryName(projectPath), "*.cs");
  105. var globOptions = new GlobOptions();
  106. globOptions.Evaluation.CaseInsensitive = false;
  107. var root = ProjectRootElement.Open(projectPath);
  108. Debug.Assert(root != null);
  109. foreach (var itemGroup in root.ItemGroups)
  110. {
  111. if (itemGroup.Condition.Length != 0)
  112. continue;
  113. foreach (var item in itemGroup.Items)
  114. {
  115. if (item.ItemType != itemType)
  116. continue;
  117. string normalizedInclude = item.Include.NormalizePath();
  118. var glob = Glob.Parse(normalizedInclude, globOptions);
  119. // TODO Check somehow if path has no blob to avoid the following loop...
  120. foreach (var existingFile in existingFiles)
  121. {
  122. if (glob.IsMatch(existingFile))
  123. {
  124. result.Add(existingFile);
  125. }
  126. }
  127. }
  128. }
  129. return result.ToArray();
  130. }
  131. /// Simple function to make sure the Api assembly references are configured correctly
  132. public static void FixApiHintPath(MSBuildProject project)
  133. {
  134. var root = project.Root;
  135. void AddPropertyIfNotPresent(string name, string condition, string value)
  136. {
  137. if (root.PropertyGroups
  138. .Any(g => (g.Condition == string.Empty || g.Condition.Trim() == condition) &&
  139. g.Properties
  140. .Any(p => p.Name == name &&
  141. p.Value == value &&
  142. (p.Condition.Trim() == condition || g.Condition.Trim() == condition))))
  143. {
  144. return;
  145. }
  146. root.AddProperty(name, value).Condition = " " + condition + " ";
  147. project.HasUnsavedChanges = true;
  148. }
  149. AddPropertyIfNotPresent(name: "ApiConfiguration",
  150. condition: "'$(Configuration)' != 'ExportRelease'",
  151. value: "Debug");
  152. AddPropertyIfNotPresent(name: "ApiConfiguration",
  153. condition: "'$(Configuration)' == 'ExportRelease'",
  154. value: "Release");
  155. void SetReferenceHintPath(string referenceName, string condition, string hintPath)
  156. {
  157. foreach (var itemGroup in root.ItemGroups.Where(g =>
  158. g.Condition.Trim() == string.Empty || g.Condition.Trim() == condition))
  159. {
  160. var references = itemGroup.Items.Where(item =>
  161. item.ItemType == "Reference" &&
  162. item.Include == referenceName &&
  163. (item.Condition.Trim() == condition || itemGroup.Condition.Trim() == condition));
  164. var referencesWithHintPath = references.Where(reference =>
  165. reference.Metadata.Any(m => m.Name == "HintPath"));
  166. if (referencesWithHintPath.Any(reference => reference.Metadata
  167. .Any(m => m.Name == "HintPath" && m.Value == hintPath)))
  168. {
  169. // Found a Reference item with the right HintPath
  170. return;
  171. }
  172. var referenceWithHintPath = referencesWithHintPath.FirstOrDefault();
  173. if (referenceWithHintPath != null)
  174. {
  175. // Found a Reference item with a wrong HintPath
  176. foreach (var metadata in referenceWithHintPath.Metadata.ToList()
  177. .Where(m => m.Name == "HintPath"))
  178. {
  179. // Safe to remove as we duplicate with ToList() to loop
  180. referenceWithHintPath.RemoveChild(metadata);
  181. }
  182. referenceWithHintPath.AddMetadata("HintPath", hintPath);
  183. project.HasUnsavedChanges = true;
  184. return;
  185. }
  186. var referenceWithoutHintPath = references.FirstOrDefault();
  187. if (referenceWithoutHintPath != null)
  188. {
  189. // Found a Reference item without a HintPath
  190. referenceWithoutHintPath.AddMetadata("HintPath", hintPath);
  191. project.HasUnsavedChanges = true;
  192. return;
  193. }
  194. }
  195. // Found no Reference item at all. Add it.
  196. root.AddItem("Reference", referenceName).Condition = " " + condition + " ";
  197. project.HasUnsavedChanges = true;
  198. }
  199. const string coreProjectName = "GodotSharp";
  200. const string editorProjectName = "GodotSharpEditor";
  201. const string coreCondition = "";
  202. const string editorCondition = "'$(Configuration)' == 'Debug'";
  203. var coreHintPath = $"$(ProjectDir)/.mono/assemblies/$(ApiConfiguration)/{coreProjectName}.dll";
  204. var editorHintPath = $"$(ProjectDir)/.mono/assemblies/$(ApiConfiguration)/{editorProjectName}.dll";
  205. SetReferenceHintPath(coreProjectName, coreCondition, coreHintPath);
  206. SetReferenceHintPath(editorProjectName, editorCondition, editorHintPath);
  207. }
  208. public static void MigrateFromOldConfigNames(MSBuildProject project)
  209. {
  210. var root = project.Root;
  211. bool hasGodotProjectGeneratorVersion = false;
  212. bool foundOldConfiguration = false;
  213. foreach (var propertyGroup in root.PropertyGroups.Where(g => g.Condition == string.Empty))
  214. {
  215. if (!hasGodotProjectGeneratorVersion && propertyGroup.Properties.Any(p => p.Name == "GodotProjectGeneratorVersion"))
  216. hasGodotProjectGeneratorVersion = true;
  217. foreach (var configItem in propertyGroup.Properties
  218. .Where(p => p.Condition.Trim() == "'$(Configuration)' == ''" && p.Value == "Tools"))
  219. {
  220. configItem.Value = "Debug";
  221. foundOldConfiguration = true;
  222. project.HasUnsavedChanges = true;
  223. }
  224. }
  225. if (!hasGodotProjectGeneratorVersion)
  226. {
  227. root.PropertyGroups.First(g => g.Condition == string.Empty)?
  228. .AddProperty("GodotProjectGeneratorVersion", Assembly.GetExecutingAssembly().GetName().Version.ToString());
  229. project.HasUnsavedChanges = true;
  230. }
  231. if (!foundOldConfiguration)
  232. {
  233. var toolsConditions = new[]
  234. {
  235. "'$(Configuration)|$(Platform)' == 'Tools|AnyCPU'",
  236. "'$(Configuration)|$(Platform)' != 'Tools|AnyCPU'",
  237. "'$(Configuration)' == 'Tools'",
  238. "'$(Configuration)' != 'Tools'"
  239. };
  240. foundOldConfiguration = root.PropertyGroups
  241. .Any(g => toolsConditions.Any(c => c == g.Condition.Trim()));
  242. }
  243. if (foundOldConfiguration)
  244. {
  245. void MigrateConfigurationConditions(string oldConfiguration, string newConfiguration)
  246. {
  247. void MigrateConditions(string oldCondition, string newCondition)
  248. {
  249. foreach (var propertyGroup in root.PropertyGroups.Where(g => g.Condition.Trim() == oldCondition))
  250. {
  251. propertyGroup.Condition = " " + newCondition + " ";
  252. project.HasUnsavedChanges = true;
  253. }
  254. foreach (var propertyGroup in root.PropertyGroups)
  255. {
  256. foreach (var prop in propertyGroup.Properties.Where(p => p.Condition.Trim() == oldCondition))
  257. {
  258. prop.Condition = " " + newCondition + " ";
  259. project.HasUnsavedChanges = true;
  260. }
  261. }
  262. foreach (var itemGroup in root.ItemGroups.Where(g => g.Condition.Trim() == oldCondition))
  263. {
  264. itemGroup.Condition = " " + newCondition + " ";
  265. project.HasUnsavedChanges = true;
  266. }
  267. foreach (var itemGroup in root.ItemGroups)
  268. {
  269. foreach (var item in itemGroup.Items.Where(item => item.Condition.Trim() == oldCondition))
  270. {
  271. item.Condition = " " + newCondition + " ";
  272. project.HasUnsavedChanges = true;
  273. }
  274. }
  275. }
  276. foreach (var op in new[] {"==", "!="})
  277. {
  278. MigrateConditions($"'$(Configuration)|$(Platform)' {op} '{oldConfiguration}|AnyCPU'", $"'$(Configuration)|$(Platform)' {op} '{newConfiguration}|AnyCPU'");
  279. MigrateConditions($"'$(Configuration)' {op} '{oldConfiguration}'", $"'$(Configuration)' {op} '{newConfiguration}'");
  280. }
  281. }
  282. MigrateConfigurationConditions("Debug", "ExportDebug");
  283. MigrateConfigurationConditions("Release", "ExportRelease");
  284. MigrateConfigurationConditions("Tools", "Debug"); // Must be last
  285. }
  286. }
  287. }
  288. }