ProjectUtils.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387
  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 Microsoft.Build.Construction;
  8. using Microsoft.Build.Globbing;
  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 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 = MSBuildGlob.Parse(normalizedInclude);
  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. public static void EnsureHasProjectTypeGuids(MSBuildProject project)
  130. {
  131. var root = project.Root;
  132. bool found = root.PropertyGroups.Any(pg =>
  133. string.IsNullOrEmpty(pg.Condition) && pg.Properties.Any(p => p.Name == "ProjectTypeGuids"));
  134. if (found)
  135. return;
  136. root.AddProperty("ProjectTypeGuids", ProjectGenerator.GodotDefaultProjectTypeGuids);
  137. project.HasUnsavedChanges = true;
  138. }
  139. /// Simple function to make sure the Api assembly references are configured correctly
  140. public static void FixApiHintPath(MSBuildProject project)
  141. {
  142. var root = project.Root;
  143. void AddPropertyIfNotPresent(string name, string condition, string value)
  144. {
  145. if (root.PropertyGroups
  146. .Any(g => (string.IsNullOrEmpty(g.Condition) || g.Condition.Trim() == condition) &&
  147. g.Properties
  148. .Any(p => p.Name == name &&
  149. p.Value == value &&
  150. (p.Condition.Trim() == condition || g.Condition.Trim() == condition))))
  151. {
  152. return;
  153. }
  154. root.AddProperty(name, value).Condition = " " + condition + " ";
  155. project.HasUnsavedChanges = true;
  156. }
  157. AddPropertyIfNotPresent(name: "ApiConfiguration",
  158. condition: "'$(Configuration)' != 'ExportRelease'",
  159. value: "Debug");
  160. AddPropertyIfNotPresent(name: "ApiConfiguration",
  161. condition: "'$(Configuration)' == 'ExportRelease'",
  162. value: "Release");
  163. void SetReferenceHintPath(string referenceName, string condition, string hintPath)
  164. {
  165. foreach (var itemGroup in root.ItemGroups.Where(g =>
  166. g.Condition.Trim() == string.Empty || g.Condition.Trim() == condition))
  167. {
  168. var references = itemGroup.Items.Where(item =>
  169. item.ItemType == "Reference" &&
  170. item.Include == referenceName &&
  171. (item.Condition.Trim() == condition || itemGroup.Condition.Trim() == condition));
  172. var referencesWithHintPath = references.Where(reference =>
  173. reference.Metadata.Any(m => m.Name == "HintPath"));
  174. if (referencesWithHintPath.Any(reference => reference.Metadata
  175. .Any(m => m.Name == "HintPath" && m.Value == hintPath)))
  176. {
  177. // Found a Reference item with the right HintPath
  178. return;
  179. }
  180. var referenceWithHintPath = referencesWithHintPath.FirstOrDefault();
  181. if (referenceWithHintPath != null)
  182. {
  183. // Found a Reference item with a wrong HintPath
  184. foreach (var metadata in referenceWithHintPath.Metadata.ToList()
  185. .Where(m => m.Name == "HintPath"))
  186. {
  187. // Safe to remove as we duplicate with ToList() to loop
  188. referenceWithHintPath.RemoveChild(metadata);
  189. }
  190. referenceWithHintPath.AddMetadata("HintPath", hintPath);
  191. project.HasUnsavedChanges = true;
  192. return;
  193. }
  194. var referenceWithoutHintPath = references.FirstOrDefault();
  195. if (referenceWithoutHintPath != null)
  196. {
  197. // Found a Reference item without a HintPath
  198. referenceWithoutHintPath.AddMetadata("HintPath", hintPath);
  199. project.HasUnsavedChanges = true;
  200. return;
  201. }
  202. }
  203. // Found no Reference item at all. Add it.
  204. root.AddItem("Reference", referenceName).Condition = " " + condition + " ";
  205. project.HasUnsavedChanges = true;
  206. }
  207. const string coreProjectName = "GodotSharp";
  208. const string editorProjectName = "GodotSharpEditor";
  209. const string coreCondition = "";
  210. const string editorCondition = "'$(Configuration)' == 'Debug'";
  211. var coreHintPath = $"$(ProjectDir)/.mono/assemblies/$(ApiConfiguration)/{coreProjectName}.dll";
  212. var editorHintPath = $"$(ProjectDir)/.mono/assemblies/$(ApiConfiguration)/{editorProjectName}.dll";
  213. SetReferenceHintPath(coreProjectName, coreCondition, coreHintPath);
  214. SetReferenceHintPath(editorProjectName, editorCondition, editorHintPath);
  215. }
  216. public static void MigrateFromOldConfigNames(MSBuildProject project)
  217. {
  218. var root = project.Root;
  219. bool hasGodotProjectGeneratorVersion = false;
  220. bool foundOldConfiguration = false;
  221. foreach (var propertyGroup in root.PropertyGroups.Where(g => string.IsNullOrEmpty(g.Condition)))
  222. {
  223. if (!hasGodotProjectGeneratorVersion && propertyGroup.Properties.Any(p => p.Name == "GodotProjectGeneratorVersion"))
  224. hasGodotProjectGeneratorVersion = true;
  225. foreach (var configItem in propertyGroup.Properties
  226. .Where(p => p.Condition.Trim() == "'$(Configuration)' == ''" && p.Value == "Tools"))
  227. {
  228. configItem.Value = "Debug";
  229. foundOldConfiguration = true;
  230. project.HasUnsavedChanges = true;
  231. }
  232. }
  233. if (!hasGodotProjectGeneratorVersion)
  234. {
  235. root.PropertyGroups.First(g => string.IsNullOrEmpty(g.Condition))?
  236. .AddProperty("GodotProjectGeneratorVersion", Assembly.GetExecutingAssembly().GetName().Version.ToString());
  237. project.HasUnsavedChanges = true;
  238. }
  239. if (!foundOldConfiguration)
  240. {
  241. var toolsConditions = new[]
  242. {
  243. "'$(Configuration)|$(Platform)' == 'Tools|AnyCPU'",
  244. "'$(Configuration)|$(Platform)' != 'Tools|AnyCPU'",
  245. "'$(Configuration)' == 'Tools'",
  246. "'$(Configuration)' != 'Tools'"
  247. };
  248. foundOldConfiguration = root.PropertyGroups
  249. .Any(g => toolsConditions.Any(c => c == g.Condition.Trim()));
  250. }
  251. if (foundOldConfiguration)
  252. {
  253. void MigrateConfigurationConditions(string oldConfiguration, string newConfiguration)
  254. {
  255. void MigrateConditions(string oldCondition, string newCondition)
  256. {
  257. foreach (var propertyGroup in root.PropertyGroups.Where(g => g.Condition.Trim() == oldCondition))
  258. {
  259. propertyGroup.Condition = " " + newCondition + " ";
  260. project.HasUnsavedChanges = true;
  261. }
  262. foreach (var propertyGroup in root.PropertyGroups)
  263. {
  264. foreach (var prop in propertyGroup.Properties.Where(p => p.Condition.Trim() == oldCondition))
  265. {
  266. prop.Condition = " " + newCondition + " ";
  267. project.HasUnsavedChanges = true;
  268. }
  269. }
  270. foreach (var itemGroup in root.ItemGroups.Where(g => g.Condition.Trim() == oldCondition))
  271. {
  272. itemGroup.Condition = " " + newCondition + " ";
  273. project.HasUnsavedChanges = true;
  274. }
  275. foreach (var itemGroup in root.ItemGroups)
  276. {
  277. foreach (var item in itemGroup.Items.Where(item => item.Condition.Trim() == oldCondition))
  278. {
  279. item.Condition = " " + newCondition + " ";
  280. project.HasUnsavedChanges = true;
  281. }
  282. }
  283. }
  284. foreach (var op in new[] {"==", "!="})
  285. {
  286. MigrateConditions($"'$(Configuration)|$(Platform)' {op} '{oldConfiguration}|AnyCPU'", $"'$(Configuration)|$(Platform)' {op} '{newConfiguration}|AnyCPU'");
  287. MigrateConditions($"'$(Configuration)' {op} '{oldConfiguration}'", $"'$(Configuration)' {op} '{newConfiguration}'");
  288. }
  289. }
  290. MigrateConfigurationConditions("Debug", "ExportDebug");
  291. MigrateConfigurationConditions("Release", "ExportRelease");
  292. MigrateConfigurationConditions("Tools", "Debug"); // Must be last
  293. }
  294. }
  295. public static void EnsureHasNugetNetFrameworkRefAssemblies(MSBuildProject project)
  296. {
  297. var root = project.Root;
  298. bool found = root.ItemGroups.Any(g => string.IsNullOrEmpty(g.Condition) && g.Items.Any(
  299. item => item.ItemType == "PackageReference" && item.Include == "Microsoft.NETFramework.ReferenceAssemblies"));
  300. if (found)
  301. return;
  302. var frameworkRefAssembliesItem = root.AddItem("PackageReference", "Microsoft.NETFramework.ReferenceAssemblies");
  303. // Use metadata (child nodes) instead of attributes for the PackageReference.
  304. // This is for compatibility with 3.2, where GodotTools uses an old Microsoft.Build.
  305. frameworkRefAssembliesItem.AddMetadata("Version", "1.0.0");
  306. frameworkRefAssembliesItem.AddMetadata("PrivateAssets", "All");
  307. project.HasUnsavedChanges = true;
  308. }
  309. }
  310. }