ArbitratorController.cs 9.6 KB

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