ProjectUtils.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471
  1. using System;
  2. using GodotTools.Core;
  3. using System.Collections.Generic;
  4. using System.Diagnostics;
  5. using System.IO;
  6. using System.Linq;
  7. using System.Text.RegularExpressions;
  8. using System.Xml;
  9. using System.Xml.Linq;
  10. using JetBrains.Annotations;
  11. using Microsoft.Build.Construction;
  12. using Microsoft.Build.Globbing;
  13. using Semver;
  14. namespace GodotTools.ProjectEditor
  15. {
  16. public sealed class MSBuildProject
  17. {
  18. internal ProjectRootElement Root { get; set; }
  19. public bool HasUnsavedChanges { get; set; }
  20. public void Save() => Root.Save();
  21. public MSBuildProject(ProjectRootElement root)
  22. {
  23. Root = root;
  24. }
  25. }
  26. public static class ProjectUtils
  27. {
  28. public static MSBuildProject Open(string path)
  29. {
  30. var root = ProjectRootElement.Open(path);
  31. return root != null ? new MSBuildProject(root) : null;
  32. }
  33. [PublicAPI]
  34. public static void AddItemToProjectChecked(string projectPath, string itemType, string include)
  35. {
  36. var dir = Directory.GetParent(projectPath).FullName;
  37. var root = ProjectRootElement.Open(projectPath);
  38. Debug.Assert(root != null);
  39. if (root.AreDefaultCompileItemsEnabled())
  40. {
  41. // No need to add. It's already included automatically by the MSBuild Sdk.
  42. // This assumes the source file is inside the project directory and not manually excluded in the csproj
  43. return;
  44. }
  45. var normalizedInclude = include.RelativeToPath(dir).Replace("/", "\\");
  46. if (root.AddItemChecked(itemType, normalizedInclude))
  47. root.Save();
  48. }
  49. public static void RenameItemInProjectChecked(string projectPath, string itemType, string oldInclude, string newInclude)
  50. {
  51. var dir = Directory.GetParent(projectPath).FullName;
  52. var root = ProjectRootElement.Open(projectPath);
  53. Debug.Assert(root != null);
  54. if (root.AreDefaultCompileItemsEnabled())
  55. {
  56. // No need to add. It's already included automatically by the MSBuild Sdk.
  57. // This assumes the source file is inside the project directory and not manually excluded in the csproj
  58. return;
  59. }
  60. var normalizedOldInclude = oldInclude.NormalizePath();
  61. var normalizedNewInclude = newInclude.NormalizePath();
  62. var item = root.FindItemOrNullAbs(itemType, normalizedOldInclude);
  63. if (item == null)
  64. return;
  65. // Check if the found item include already matches the new path
  66. var glob = MSBuildGlob.Parse(item.Include);
  67. if (glob.IsMatch(normalizedNewInclude))
  68. return;
  69. // Otherwise, if the item include uses globbing it's better to add a new item instead of modifying
  70. if (!string.IsNullOrEmpty(glob.WildcardDirectoryPart) || glob.FilenamePart.Contains("*"))
  71. {
  72. root.AddItem(itemType, normalizedNewInclude.RelativeToPath(dir).Replace("/", "\\"));
  73. root.Save();
  74. return;
  75. }
  76. item.Include = normalizedNewInclude.RelativeToPath(dir).Replace("/", "\\");
  77. root.Save();
  78. }
  79. public static void RemoveItemFromProjectChecked(string projectPath, string itemType, string include)
  80. {
  81. var root = ProjectRootElement.Open(projectPath);
  82. Debug.Assert(root != null);
  83. if (root.AreDefaultCompileItemsEnabled())
  84. {
  85. // No need to add. It's already included automatically by the MSBuild Sdk.
  86. // This assumes the source file is inside the project directory and not manually excluded in the csproj
  87. return;
  88. }
  89. var normalizedInclude = include.NormalizePath();
  90. var item = root.FindItemOrNullAbs(itemType, normalizedInclude);
  91. // Couldn't find an existing item that matches to remove
  92. if (item == null)
  93. return;
  94. var glob = MSBuildGlob.Parse(item.Include);
  95. // If the item include uses globbing don't remove it
  96. if (!string.IsNullOrEmpty(glob.WildcardDirectoryPart) || glob.FilenamePart.Contains("*"))
  97. {
  98. return;
  99. }
  100. item.Parent.RemoveChild(item);
  101. root.Save();
  102. }
  103. public static void RenameItemsToNewFolderInProjectChecked(string projectPath, string itemType, string oldFolder, string newFolder)
  104. {
  105. var dir = Directory.GetParent(projectPath).FullName;
  106. var root = ProjectRootElement.Open(projectPath);
  107. Debug.Assert(root != null);
  108. if (root.AreDefaultCompileItemsEnabled())
  109. {
  110. // No need to add. It's already included automatically by the MSBuild Sdk.
  111. // This assumes the source file is inside the project directory and not manually excluded in the csproj
  112. return;
  113. }
  114. bool dirty = false;
  115. var oldFolderNormalized = oldFolder.NormalizePath();
  116. var newFolderNormalized = newFolder.NormalizePath();
  117. string absOldFolderNormalized = Path.GetFullPath(oldFolderNormalized).NormalizePath();
  118. string absNewFolderNormalized = Path.GetFullPath(newFolderNormalized).NormalizePath();
  119. foreach (var item in root.FindAllItemsInFolder(itemType, oldFolderNormalized))
  120. {
  121. string absPathNormalized = Path.GetFullPath(item.Include).NormalizePath();
  122. string absNewIncludeNormalized = absNewFolderNormalized + absPathNormalized.Substring(absOldFolderNormalized.Length);
  123. item.Include = absNewIncludeNormalized.RelativeToPath(dir).Replace("/", "\\");
  124. dirty = true;
  125. }
  126. if (dirty)
  127. root.Save();
  128. }
  129. public static void RemoveItemsInFolderFromProjectChecked(string projectPath, string itemType, string folder)
  130. {
  131. var root = ProjectRootElement.Open(projectPath);
  132. Debug.Assert(root != null);
  133. if (root.AreDefaultCompileItemsEnabled())
  134. {
  135. // No need to add. It's already included automatically by the MSBuild Sdk.
  136. // This assumes the source file is inside the project directory and not manually excluded in the csproj
  137. return;
  138. }
  139. var folderNormalized = folder.NormalizePath();
  140. var itemsToRemove = root.FindAllItemsInFolder(itemType, folderNormalized).ToList();
  141. if (itemsToRemove.Count > 0)
  142. {
  143. foreach (var item in itemsToRemove)
  144. item.Parent.RemoveChild(item);
  145. root.Save();
  146. }
  147. }
  148. private static string[] GetAllFilesRecursive(string rootDirectory, string mask)
  149. {
  150. string[] files = Directory.GetFiles(rootDirectory, mask, SearchOption.AllDirectories);
  151. // We want relative paths
  152. for (int i = 0; i < files.Length; i++)
  153. {
  154. files[i] = files[i].RelativeToPath(rootDirectory);
  155. }
  156. return files;
  157. }
  158. public static string[] GetIncludeFiles(string projectPath, string itemType)
  159. {
  160. var result = new List<string>();
  161. var existingFiles = GetAllFilesRecursive(Path.GetDirectoryName(projectPath), "*.cs");
  162. var root = ProjectRootElement.Open(projectPath);
  163. Debug.Assert(root != null);
  164. if (root.AreDefaultCompileItemsEnabled())
  165. {
  166. var excluded = new List<string>();
  167. result.AddRange(existingFiles);
  168. foreach (var item in root.Items)
  169. {
  170. if (string.IsNullOrEmpty(item.Condition))
  171. continue;
  172. if (item.ItemType != itemType)
  173. continue;
  174. string normalizedRemove = item.Remove.NormalizePath();
  175. var glob = MSBuildGlob.Parse(normalizedRemove);
  176. excluded.AddRange(result.Where(includedFile => glob.IsMatch(includedFile)));
  177. }
  178. result.RemoveAll(f => excluded.Contains(f));
  179. }
  180. foreach (var itemGroup in root.ItemGroups)
  181. {
  182. if (itemGroup.Condition.Length != 0)
  183. continue;
  184. foreach (var item in itemGroup.Items)
  185. {
  186. if (item.ItemType != itemType)
  187. continue;
  188. string normalizedInclude = item.Include.NormalizePath();
  189. var glob = MSBuildGlob.Parse(normalizedInclude);
  190. foreach (var existingFile in existingFiles)
  191. {
  192. if (glob.IsMatch(existingFile))
  193. {
  194. result.Add(existingFile);
  195. }
  196. }
  197. }
  198. }
  199. return result.ToArray();
  200. }
  201. public static void MigrateToProjectSdksStyle(MSBuildProject project, string projectName)
  202. {
  203. var root = project.Root;
  204. if (!string.IsNullOrEmpty(root.Sdk))
  205. return;
  206. root.Sdk = $"{ProjectGenerator.GodotSdkNameToUse}/{ProjectGenerator.GodotSdkVersionToUse}";
  207. root.ToolsVersion = null;
  208. root.DefaultTargets = null;
  209. root.AddProperty("TargetFramework", "net472");
  210. // Remove obsolete properties, items and elements. We're going to be conservative
  211. // here to minimize the chances of introducing breaking changes. As such we will
  212. // only remove elements that could potentially cause issues with the Godot.NET.Sdk.
  213. void RemoveElements(IEnumerable<ProjectElement> elements)
  214. {
  215. foreach (var element in elements)
  216. element.Parent.RemoveChild(element);
  217. }
  218. // Default Configuration
  219. RemoveElements(root.PropertyGroups.SelectMany(g => g.Properties)
  220. .Where(p => p.Name == "Configuration" && p.Condition.Trim() == "'$(Configuration)' == ''" && p.Value == "Debug"));
  221. // Default Platform
  222. RemoveElements(root.PropertyGroups.SelectMany(g => g.Properties)
  223. .Where(p => p.Name == "Platform" && p.Condition.Trim() == "'$(Platform)' == ''" && p.Value == "AnyCPU"));
  224. // Simple properties
  225. var yabaiProperties = new[]
  226. {
  227. "OutputPath",
  228. "BaseIntermediateOutputPath",
  229. "IntermediateOutputPath",
  230. "TargetFrameworkVersion",
  231. "ProjectTypeGuids",
  232. "ApiConfiguration"
  233. };
  234. RemoveElements(root.PropertyGroups.SelectMany(g => g.Properties)
  235. .Where(p => yabaiProperties.Contains(p.Name)));
  236. // Configuration dependent properties
  237. var yabaiPropertiesForConfigs = new[]
  238. {
  239. "DebugSymbols",
  240. "DebugType",
  241. "Optimize",
  242. "DefineConstants",
  243. "ErrorReport",
  244. "WarningLevel",
  245. "ConsolePause"
  246. };
  247. var configNames = new[]
  248. {
  249. "ExportDebug", "ExportRelease", "Debug",
  250. "Tools", "Release" // Include old config names as well in case it's upgrading from 3.2.1 or older
  251. };
  252. foreach (var config in configNames)
  253. {
  254. var group = root.PropertyGroups
  255. .FirstOrDefault(g => g.Condition.Trim() == $"'$(Configuration)|$(Platform)' == '{config}|AnyCPU'");
  256. if (group == null)
  257. continue;
  258. RemoveElements(group.Properties.Where(p => yabaiPropertiesForConfigs.Contains(p.Name)));
  259. if (group.Count == 0)
  260. {
  261. // No more children, safe to delete the group
  262. group.Parent.RemoveChild(group);
  263. }
  264. }
  265. // Godot API References
  266. var apiAssemblies = new[] { ApiAssemblyNames.Core, ApiAssemblyNames.Editor };
  267. RemoveElements(root.ItemGroups.SelectMany(g => g.Items)
  268. .Where(i => i.ItemType == "Reference" && apiAssemblies.Contains(i.Include)));
  269. // Microsoft.NETFramework.ReferenceAssemblies PackageReference
  270. RemoveElements(root.ItemGroups.SelectMany(g => g.Items).Where(i =>
  271. i.ItemType == "PackageReference" &&
  272. i.Include.Equals("Microsoft.NETFramework.ReferenceAssemblies", StringComparison.OrdinalIgnoreCase)));
  273. // Imports
  274. var yabaiImports = new[]
  275. {
  276. "$(MSBuildBinPath)/Microsoft.CSharp.targets",
  277. "$(MSBuildBinPath)Microsoft.CSharp.targets"
  278. };
  279. RemoveElements(root.Imports.Where(import => yabaiImports.Contains(
  280. import.Project.Replace("\\", "/").Replace("//", "/"))));
  281. // 'EnableDefaultCompileItems' and 'GenerateAssemblyInfo' are kept enabled by default
  282. // on new projects, but when migrating old projects we disable them to avoid errors.
  283. root.AddProperty("EnableDefaultCompileItems", "false");
  284. root.AddProperty("GenerateAssemblyInfo", "false");
  285. // Older AssemblyInfo.cs cause the following error:
  286. // 'Properties/AssemblyInfo.cs(19,28): error CS8357:
  287. // The specified version string contains wildcards, which are not compatible with determinism.
  288. // Either remove wildcards from the version string, or disable determinism for this compilation.'
  289. // We disable deterministic builds to prevent this. The user can then fix this manually when desired
  290. // by fixing 'AssemblyVersion("1.0.*")' to not use wildcards.
  291. root.AddProperty("Deterministic", "false");
  292. project.HasUnsavedChanges = true;
  293. var xDoc = XDocument.Parse(root.RawXml);
  294. if (xDoc.Root == null)
  295. return; // Too bad, we will have to keep the xmlns/namespace and xml declaration
  296. XElement GetElement(XDocument doc, string name, string value, string parentName)
  297. {
  298. foreach (var node in doc.DescendantNodes())
  299. {
  300. if (!(node is XElement element))
  301. continue;
  302. if (element.Name.LocalName.Equals(name) && element.Value == value &&
  303. element.Parent != null && element.Parent.Name.LocalName.Equals(parentName))
  304. {
  305. return element;
  306. }
  307. }
  308. return null;
  309. }
  310. // Add comment about Microsoft.NET.Sdk properties disabled during migration
  311. GetElement(xDoc, name: "EnableDefaultCompileItems", value: "false", parentName: "PropertyGroup")
  312. .AddBeforeSelf(new XComment("The following properties were overridden during migration to prevent errors.\n" +
  313. " Enabling them may require other manual changes to the project and its files."));
  314. void RemoveNamespace(XElement element)
  315. {
  316. element.Attributes().Where(x => x.IsNamespaceDeclaration).Remove();
  317. element.Name = element.Name.LocalName;
  318. foreach (var node in element.DescendantNodes())
  319. {
  320. if (node is XElement xElement)
  321. {
  322. // Need to do the same for all children recursively as it adds it to them for some reason...
  323. RemoveNamespace(xElement);
  324. }
  325. }
  326. }
  327. // Remove xmlns/namespace
  328. RemoveNamespace(xDoc.Root);
  329. // Remove xml declaration
  330. xDoc.Nodes().FirstOrDefault(node => node.NodeType == XmlNodeType.XmlDeclaration)?.Remove();
  331. string projectFullPath = root.FullPath;
  332. root = ProjectRootElement.Create(xDoc.CreateReader());
  333. root.FullPath = projectFullPath;
  334. project.Root = root;
  335. }
  336. public static void EnsureGodotSdkIsUpToDate(MSBuildProject project)
  337. {
  338. string godotSdkAttrValue = $"{ProjectGenerator.GodotSdkNameToUse}/{ProjectGenerator.GodotSdkVersionToUse}";
  339. var root = project.Root;
  340. string rootSdk = root.Sdk?.Trim();
  341. if (!string.IsNullOrEmpty(rootSdk))
  342. {
  343. // Check if the version is already the same.
  344. if (rootSdk.Equals(godotSdkAttrValue, StringComparison.OrdinalIgnoreCase))
  345. return;
  346. // We also allow higher versions as long as the major and minor are the same.
  347. var semVerToUse = SemVersion.Parse(ProjectGenerator.GodotSdkVersionToUse);
  348. var godotSdkAttrLaxValueRegex = new Regex($@"^{ProjectGenerator.GodotSdkNameToUse}/(?<ver>.*)$");
  349. var match = godotSdkAttrLaxValueRegex.Match(rootSdk);
  350. if (match.Success &&
  351. SemVersion.TryParse(match.Groups["ver"].Value, out var semVerDetected) &&
  352. semVerDetected.Major == semVerToUse.Major &&
  353. semVerDetected.Minor == semVerToUse.Minor &&
  354. semVerDetected > semVerToUse)
  355. {
  356. return;
  357. }
  358. }
  359. root.Sdk = godotSdkAttrValue;
  360. project.HasUnsavedChanges = true;
  361. }
  362. }
  363. }