ArbitratorController.cs 9.6 KB

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