ProjectUtils.cs 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. using System.Collections.Generic;
  2. using System.IO;
  3. using DotNet.Globbing;
  4. using Microsoft.Build.Construction;
  5. namespace GodotSharpTools.Project
  6. {
  7. public static class ProjectUtils
  8. {
  9. public static void AddItemToProjectChecked(string projectPath, string itemType, string include)
  10. {
  11. var dir = Directory.GetParent(projectPath).FullName;
  12. var root = ProjectRootElement.Open(projectPath);
  13. var normalizedInclude = include.RelativeToPath(dir).Replace("/", "\\");
  14. if (root.AddItemChecked(itemType, normalizedInclude))
  15. root.Save();
  16. }
  17. private static string[] GetAllFilesRecursive(string rootDirectory, string mask)
  18. {
  19. string[] files = Directory.GetFiles(rootDirectory, mask, SearchOption.AllDirectories);
  20. // We want relative paths
  21. for (int i = 0; i < files.Length; i++) {
  22. files[i] = files[i].RelativeToPath(rootDirectory);
  23. }
  24. return files;
  25. }
  26. public static string[] GetIncludeFiles(string projectPath, string itemType)
  27. {
  28. var result = new List<string>();
  29. var existingFiles = GetAllFilesRecursive(Path.GetDirectoryName(projectPath), "*.cs");
  30. GlobOptions globOptions = new GlobOptions();
  31. globOptions.Evaluation.CaseInsensitive = false;
  32. var root = ProjectRootElement.Open(projectPath);
  33. foreach (var itemGroup in root.ItemGroups)
  34. {
  35. if (itemGroup.Condition.Length != 0)
  36. continue;
  37. foreach (var item in itemGroup.Items)
  38. {
  39. if (item.ItemType != itemType)
  40. continue;
  41. string normalizedInclude = item.Include.NormalizePath();
  42. var glob = Glob.Parse(normalizedInclude, globOptions);
  43. // TODO Check somehow if path has no blog to avoid the following loop...
  44. foreach (var existingFile in existingFiles)
  45. {
  46. if (glob.IsMatch(existingFile))
  47. {
  48. result.Add(existingFile);
  49. }
  50. }
  51. }
  52. }
  53. return result.ToArray();
  54. }
  55. }
  56. }