ProjectUtils.cs 17 KB

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