ArbitratorController.cs 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267
  1. // Copyright (c) 2025 TerraByte Inc.
  2. //
  3. // This script acts as the Controller for the ArbitratorWindow. It manages all
  4. // state and business logic, separating it from the UI rendering code in the window.
  5. using System;
  6. using System.Linq;
  7. using UnityEditor;
  8. using Terra.Arbitrator.Settings;
  9. using Terra.Arbitrator.Services;
  10. using Terra.Arbitrator.Promises;
  11. using System.Collections.Generic;
  12. namespace Terra.Arbitrator.GUI
  13. {
  14. public class ArbitratorController
  15. {
  16. private List<GitChange> _changes = new();
  17. public IReadOnlyList<GitChange> Changes => _changes;
  18. public string InfoMessage { get; private set; }
  19. public string ErrorMessage { get; private set; }
  20. public bool IsLoading { get; private set; }
  21. public string LoadingMessage { get; private set; } = "";
  22. private readonly Action _requestRepaint;
  23. private readonly Func<string, string, bool> _displayDialog;
  24. /// <summary>
  25. /// Initializes the controller.
  26. /// </summary>
  27. /// <param name="requestRepaint">A callback to the window's Repaint() method.</param>
  28. /// <param name="displayDialog">A callback to EditorUtility.DisplayDialog for user confirmations.</param>
  29. public ArbitratorController(Action requestRepaint, Func<string, string, bool> displayDialog)
  30. {
  31. _requestRepaint = requestRepaint;
  32. _displayDialog = displayDialog;
  33. }
  34. public void OnEnable()
  35. {
  36. if (SessionState.GetBool(BetterGitStatePersistence.ResetQueueKey, false))
  37. {
  38. SessionState.EraseString(BetterGitStatePersistence.ResetQueueKey);
  39. InfoMessage = "Multi-file reset complete. Pulling again to confirm...";
  40. Pull();
  41. }
  42. else
  43. {
  44. Refresh();
  45. }
  46. }
  47. public void Refresh()
  48. {
  49. StartOperation("Refreshing status...");
  50. UnstageStep()
  51. .Then(CompareStep)
  52. .Then(changes => _changes = changes)
  53. .Catch(HandleOperationError)
  54. .Finally(FinishOperation);
  55. }
  56. public void Pull()
  57. {
  58. if (IsLoading) return;
  59. StartOperation("Analyzing for conflicts...");
  60. GitService.AnalyzePullConflicts()
  61. .Then(analysisResult =>
  62. {
  63. if (analysisResult.HasConflicts)
  64. {
  65. FinishOperation();
  66. ConflictResolutionWindow.ShowWindow(analysisResult.ConflictingFiles, filesToActOn =>
  67. {
  68. if (filesToActOn == null) return;
  69. if (filesToActOn.Any()) ResetMultipleFiles(filesToActOn);
  70. else ForcePull();
  71. });
  72. }
  73. else
  74. {
  75. StartOperation("No conflicts found. Pulling changes...");
  76. GitService.PerformSafePull()
  77. .Then(successMessage =>
  78. {
  79. InfoMessage = successMessage;
  80. // Refresh will handle its own start/finish states
  81. Refresh();
  82. })
  83. .Catch(ex => {
  84. // If the pull fails, we need to handle the error and finish
  85. HandleOperationError(ex);
  86. FinishOperation();
  87. });
  88. }
  89. })
  90. .Catch(ex => {
  91. HandleOperationError(ex);
  92. FinishOperation();
  93. });
  94. }
  95. public void CommitAndPush(string commitMessage)
  96. {
  97. var selectedFiles = _changes.Where(c => c.IsSelectedForCommit).ToList();
  98. var username = BetterGitSettings.Username;
  99. var email = BetterGitSettings.Email;
  100. StartOperation("Staging, committing, and pushing files...");
  101. GitService.CommitAndPush(selectedFiles, commitMessage, username, email)
  102. .Then(successMessage => {
  103. InfoMessage = successMessage;
  104. Refresh();
  105. })
  106. .Catch(ex => {
  107. HandleOperationError(ex);
  108. FinishOperation();
  109. });
  110. }
  111. public void ResetFile(GitChange change)
  112. {
  113. if (IsLoading) return;
  114. var userConfirmed = _displayDialog("Confirm Reset", $"Are you sure you want to revert all local changes to '{change.FilePath}'? This action cannot be undone.");
  115. if (!userConfirmed) return;
  116. StartOperation($"Resetting {change.FilePath}...");
  117. GitService.ResetFileChanges(change)
  118. .Then(successMessage => {
  119. InfoMessage = successMessage;
  120. Refresh();
  121. })
  122. .Catch(ex => {
  123. HandleOperationError(ex);
  124. FinishOperation();
  125. });
  126. }
  127. public void DiffFile(GitChange change)
  128. {
  129. if (IsLoading) return;
  130. StartOperation($"Launching diff for {change.FilePath}...");
  131. GitService.LaunchExternalDiff(change)
  132. .Catch(HandleOperationError)
  133. .Finally(Refresh);
  134. }
  135. public void ResolveConflict(GitChange change)
  136. {
  137. if (IsLoading) return;
  138. StartOperation($"Opening merge tool for {change.FilePath}...");
  139. GitService.LaunchMergeTool(change)
  140. .Then(successMessage => { InfoMessage = successMessage; })
  141. .Catch(HandleOperationError)
  142. .Finally(Refresh);
  143. }
  144. public void ResetAll()
  145. {
  146. var userConfirmed = _displayDialog(
  147. "Confirm Reset All",
  148. "Are you sure you want to discard ALL local changes (modified, added, and untracked files)?\n\nThis action cannot be undone.");
  149. if (!userConfirmed) return;
  150. StartOperation("Discarding all local changes...");
  151. GitService.ResetAllChanges()
  152. .Then(successMessage =>
  153. {
  154. InfoMessage = successMessage;
  155. })
  156. .Catch(HandleOperationError)
  157. .Finally(Refresh);
  158. }
  159. public void SetAllSelection(bool selected)
  160. {
  161. if (_changes == null) return;
  162. foreach (var change in _changes)
  163. {
  164. if (change.Status != LibGit2Sharp.ChangeKind.Conflicted)
  165. {
  166. change.IsSelectedForCommit = selected;
  167. }
  168. }
  169. }
  170. // --- Private Methods ---
  171. private static IPromise<bool> UnstageStep()
  172. {
  173. return GitService.UnstageAllFilesIfSafe();
  174. }
  175. private IPromise<List<GitChange>> CompareStep(bool wasUnstaged)
  176. {
  177. if (wasUnstaged)
  178. {
  179. InfoMessage = "Found and unstaged files for review.";
  180. }
  181. return GitService.CompareLocalToRemote();
  182. }
  183. // --- Shared Helper Methods ---
  184. private void StartOperation(string loadingMessage)
  185. {
  186. IsLoading = true;
  187. LoadingMessage = loadingMessage;
  188. ClearMessages();
  189. _changes = null;
  190. _requestRepaint?.Invoke();
  191. }
  192. private void HandleOperationError(Exception ex)
  193. {
  194. ErrorMessage = $"Operation Failed: {ex.Message}";
  195. }
  196. private void FinishOperation()
  197. {
  198. IsLoading = false;
  199. _requestRepaint?.Invoke();
  200. }
  201. private void ClearMessages()
  202. {
  203. ErrorMessage = null;
  204. InfoMessage = null;
  205. }
  206. private void ResetMultipleFiles(List<string> filePaths)
  207. {
  208. InfoMessage = $"Starting reset for {filePaths.Count} file(s)... This may trigger script compilation.";
  209. _requestRepaint?.Invoke();
  210. SessionState.SetString("BetterGit.ResetQueue", string.Join(";", filePaths));
  211. EditorApplication.delayCall += BetterGitStatePersistence.ContinueInterruptedReset;
  212. }
  213. private void ForcePull()
  214. {
  215. StartOperation("Attempting to pull and create conflicts...");
  216. EditorApplication.LockReloadAssemblies();
  217. GitService.ForcePull()
  218. .Then(_ =>
  219. {
  220. InfoMessage = "Pull resulted in conflicts. Please resolve them below.";
  221. })
  222. .Catch(HandleOperationError)
  223. .Finally(() =>
  224. {
  225. EditorApplication.UnlockReloadAssemblies();
  226. AssetDatabase.Refresh();
  227. Refresh();
  228. });
  229. }
  230. }
  231. }