EditScriptCommand.cs 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. using System.IO;
  2. using UnityEditor;
  3. using UnityEngine;
  4. using LLM.Editor.Helper;
  5. using JetBrains.Annotations;
  6. namespace LLM.Editor.Commands
  7. {
  8. [System.Serializable]
  9. public class EditScriptParams
  10. {
  11. public string scriptIdentifier;
  12. public string newScriptContent;
  13. }
  14. [UsedImplicitly]
  15. public class EditScriptCommand : ICommand
  16. {
  17. private readonly EditScriptParams _params;
  18. public EditScriptCommand(string jsonParams)
  19. {
  20. _params = jsonParams?.FromJson<EditScriptParams>();
  21. }
  22. public CommandOutcome Execute(Data.CommandContext context)
  23. {
  24. if (_params == null || string.IsNullOrEmpty(_params.scriptIdentifier) || string.IsNullOrEmpty(_params.newScriptContent))
  25. {
  26. Debug.LogError("[EditScriptCommand] Invalid parameters. Script identifier and new content are required.");
  27. return CommandOutcome.Error;
  28. }
  29. var path = AssetDatabase.GUIDToAssetPath(_params.scriptIdentifier);
  30. if (string.IsNullOrEmpty(path) || !path.EndsWith(".cs"))
  31. {
  32. Debug.LogError($"[EditScriptCommand] Could not find a valid script with GUID '{_params.scriptIdentifier}'.");
  33. return CommandOutcome.Error;
  34. }
  35. try
  36. {
  37. File.WriteAllText(path, _params.newScriptContent);
  38. Debug.Log($"[EditScriptCommand] Successfully edited script at: {path}");
  39. AssetDatabase.Refresh();
  40. return CommandOutcome.Success;
  41. }
  42. catch (System.Exception e)
  43. {
  44. Debug.LogError($"[EditScriptCommand] Failed to write to file at '{path}'. Error: {e.Message}");
  45. return CommandOutcome.Error;
  46. }
  47. }
  48. }
  49. }