ProjectGenerator.cs 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. using System;
  2. using System.Globalization;
  3. using System.IO;
  4. using System.Text;
  5. using Microsoft.Build.Construction;
  6. using Microsoft.Build.Evaluation;
  7. using GodotTools.Shared;
  8. namespace GodotTools.ProjectEditor
  9. {
  10. public static class ProjectGenerator
  11. {
  12. public static string GodotSdkAttrValue => $"Godot.NET.Sdk/{GeneratedGodotNupkgsVersions.GodotNETSdk}";
  13. public static ProjectRootElement GenGameProject(string name)
  14. {
  15. if (name.Length == 0)
  16. throw new ArgumentException("Project name is empty.", nameof(name));
  17. var root = ProjectRootElement.Create(NewProjectFileOptions.None);
  18. root.Sdk = GodotSdkAttrValue;
  19. var mainGroup = root.AddPropertyGroup();
  20. mainGroup.AddProperty("TargetFramework", "net6.0");
  21. var net7 = mainGroup.AddProperty("TargetFramework", "net7.0");
  22. net7.Condition = " '$(GodotTargetPlatform)' == 'android' ";
  23. var net8 = mainGroup.AddProperty("TargetFramework", "net8.0");
  24. net8.Condition = " '$(GodotTargetPlatform)' == 'ios' ";
  25. mainGroup.AddProperty("EnableDynamicLoading", "true");
  26. string sanitizedName = IdentifierUtils.SanitizeQualifiedIdentifier(name, allowEmptyIdentifiers: true);
  27. // If the name is not a valid namespace, manually set RootNamespace to a sanitized one.
  28. if (sanitizedName != name)
  29. mainGroup.AddProperty("RootNamespace", sanitizedName);
  30. return root;
  31. }
  32. public static string GenAndSaveGameProject(string dir, string name)
  33. {
  34. if (name.Length == 0)
  35. throw new ArgumentException("Project name is empty.", nameof(name));
  36. string path = Path.Combine(dir, name + ".csproj");
  37. var root = GenGameProject(name);
  38. // Save (without BOM)
  39. root.Save(path, new UTF8Encoding(encoderShouldEmitUTF8Identifier: false));
  40. return Guid.NewGuid().ToString().ToUpperInvariant();
  41. }
  42. }
  43. }