ArbitratorController.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460
  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. using UnityEditor.SceneManagement;
  14. namespace Terra.Arbitrator.GUI
  15. {
  16. public enum UserAction { Proceed, SaveAndProceed, Cancel }
  17. public enum SortColumn { Commit, Status, FilePath }
  18. public class ArbitratorController
  19. {
  20. private List<GitChange> _changes = new();
  21. public IReadOnlyList<GitChange> Changes => _changes;
  22. public string InfoMessage { get; private set; }
  23. public string ErrorMessage { get; private set; }
  24. public bool IsLoading { get; private set; }
  25. public string LoadingMessage { get; private set; } = "";
  26. public bool IsInConflictState { get; private set; }
  27. public int CommitsToPull { get; private set; }
  28. public SortColumn CurrentSortColumn { get; private set; } = SortColumn.FilePath;
  29. public float OperationProgress { get; private set; }
  30. public string OperationProgressMessage { get; private set; }
  31. public IReadOnlyList<string> RemoteBranchList { get; private set; } = new List<string>();
  32. public string CurrentBranchName { get; private set; } = "master";
  33. private readonly Action _requestRepaint;
  34. private readonly Func<string, string, string, string, bool> _displayDialog;
  35. private readonly Func<UserAction> _promptForUnsavedChanges;
  36. /// <summary>
  37. /// Initializes the controller.
  38. /// </summary>
  39. /// <param name="requestRepaint">A callback to the window's Repaint() method.</param>
  40. /// <param name="displayDialog">A callback to EditorUtility.DisplayDialog for user confirmations.</param>
  41. /// <param name="promptForUnsavedChanges">A callback to EditorUtility.DisplayDialog for user confirmations.</param>
  42. public ArbitratorController(Action requestRepaint, Func<string, string, string, string, bool> displayDialog, Func<UserAction> promptForUnsavedChanges)
  43. {
  44. _requestRepaint = requestRepaint;
  45. _displayDialog = displayDialog;
  46. _promptForUnsavedChanges = promptForUnsavedChanges;
  47. }
  48. public void OnEnable()
  49. {
  50. if (SessionState.GetBool(BetterGitStatePersistence.ResetQueueKey, false))
  51. {
  52. SessionState.EraseString(BetterGitStatePersistence.ResetQueueKey);
  53. InfoMessage = "Multi-file reset complete. Pulling again to confirm...";
  54. Pull();
  55. }
  56. else
  57. {
  58. Refresh();
  59. }
  60. }
  61. public void Refresh()
  62. {
  63. StartOperation("Refreshing status...");
  64. CommitsToPull = 0;
  65. UnstageStep()
  66. .Then(CompareStep)
  67. .Then(FetchUpstreamStep)
  68. .Then(FetchBranchDataStep)
  69. .Then(FinalizeRefresh)
  70. .Catch(HandleOperationError)
  71. .Finally(FinishOperation);
  72. }
  73. public void Pull()
  74. {
  75. if (IsLoading) return;
  76. if (CancelOperationIfUnsavedScenes()) return;
  77. if (CommitsToPull > 0)
  78. {
  79. if (!_displayDialog("Confirm Pull", $"There are {CommitsToPull} incoming changes. Are you sure you want to pull?", "Yes, Pull", "Cancel"))
  80. {
  81. return;
  82. }
  83. }
  84. StartOperation("Analyzing for conflicts...");
  85. GitService.AnalyzePullConflicts()
  86. .Then(analysisResult =>
  87. {
  88. FinishOperation(); // Stop loading before showing dialog
  89. if (analysisResult.HasConflicts)
  90. {
  91. ConflictResolutionWindow.ShowWindow(this, analysisResult.ConflictingFiles);
  92. }
  93. else
  94. {
  95. PerformSafePullWithLock();
  96. }
  97. })
  98. .Catch(ex => {
  99. HandleOperationError(ex);
  100. FinishOperation();
  101. })
  102. .Finally(FinishOperation);
  103. }
  104. public void PerformSafePullWithLock()
  105. {
  106. StartOperation("Pulling changes...");
  107. EditorApplication.LockReloadAssemblies();
  108. GitService.PerformSafePull()
  109. .Then(successMessage =>
  110. {
  111. InfoMessage = successMessage;
  112. Refresh();
  113. })
  114. .Catch(ex => {
  115. HandleOperationError(ex);
  116. FinishOperation();
  117. })
  118. .Finally(EditorApplication.UnlockReloadAssemblies);
  119. }
  120. public void ResetSingleConflictingFile(string filePath, Action onResetComplete)
  121. {
  122. var change = GitService.GetChangeForFile(filePath);
  123. if (change == null)
  124. {
  125. ErrorMessage = $"Could not find file '{filePath}' to reset.";
  126. onResetComplete?.Invoke();
  127. return;
  128. }
  129. GitService.ResetFileChanges(change)
  130. .Then(successMessage =>
  131. {
  132. InfoMessage = successMessage;
  133. })
  134. .Catch(HandleOperationError)
  135. .Finally(onResetComplete);
  136. }
  137. public void CommitAndPush(string commitMessage)
  138. {
  139. var selectedFiles = _changes.Where(c => c.IsSelectedForCommit).ToList();
  140. var username = BetterGitSettings.Username;
  141. var email = BetterGitSettings.Email;
  142. StartOperation("Staging, committing, and pushing files...");
  143. GitService.CommitAndPush(selectedFiles, commitMessage, username, email, OnProgressModified)
  144. .Then(successMessage => {
  145. InfoMessage = successMessage;
  146. Refresh();
  147. })
  148. .Catch(ex => {
  149. HandleOperationError(ex);
  150. FinishOperation();
  151. });
  152. return;
  153. void OnProgressModified(float progress, string message)
  154. {
  155. OperationProgress = progress;
  156. OperationProgressMessage = message;
  157. _requestRepaint?.Invoke();
  158. }
  159. }
  160. public void SetSortColumn(SortColumn newColumn)
  161. {
  162. // If it's already the active column, do nothing.
  163. if (CurrentSortColumn == newColumn) return;
  164. CurrentSortColumn = newColumn;
  165. ApplyGrouping();
  166. _requestRepaint?.Invoke();
  167. }
  168. private void ApplyGrouping()
  169. {
  170. if (_changes == null || !_changes.Any()) return;
  171. _changes = CurrentSortColumn switch
  172. {
  173. SortColumn.Commit => _changes.OrderByDescending(c => c.IsSelectedForCommit).ThenBy(c => c.FilePath).ToList(),
  174. SortColumn.Status => _changes.OrderBy(c => GetStatusSortPriority(c.Status)).ThenBy(c => c.FilePath).ToList(),
  175. SortColumn.FilePath => _changes.OrderBy(c => c.FilePath).ToList(),
  176. _ => _changes
  177. };
  178. }
  179. private int GetStatusSortPriority(LibGit2Sharp.ChangeKind status)
  180. {
  181. return status switch
  182. {
  183. LibGit2Sharp.ChangeKind.Conflicted => -1, // Always show conflicts on top
  184. LibGit2Sharp.ChangeKind.Modified => 0,
  185. LibGit2Sharp.ChangeKind.Added => 1,
  186. LibGit2Sharp.ChangeKind.Deleted => 2,
  187. LibGit2Sharp.ChangeKind.Renamed => 3,
  188. _ => 99
  189. };
  190. }
  191. public void ResetFile(GitChange change)
  192. {
  193. if (IsLoading) return;
  194. var userConfirmed = _displayDialog("Confirm Reset", $"Are you sure you want to revert all local changes to '{change.FilePath}'? This action cannot be undone.", "Yes, Revert", "Cancel");
  195. if (!userConfirmed) return;
  196. StartOperation($"Resetting {change.FilePath}...");
  197. GitService.ResetFileChanges(change)
  198. .Then(successMessage => {
  199. InfoMessage = successMessage;
  200. Refresh();
  201. })
  202. .Catch(ex => {
  203. HandleOperationError(ex);
  204. FinishOperation();
  205. });
  206. }
  207. public void DiffFile(GitChange change)
  208. {
  209. if (IsLoading) return;
  210. StartOperation($"Launching diff for {change.FilePath}...");
  211. GitService.LaunchExternalDiff(change)
  212. .Catch(HandleOperationError)
  213. .Finally(Refresh);
  214. }
  215. public void ResolveConflict(GitChange change)
  216. {
  217. if (IsLoading) return;
  218. StartOperation($"Opening merge tool for {change.FilePath}...");
  219. var fileExtension = System.IO.Path.GetExtension(change.FilePath).ToLower();
  220. if (fileExtension is ".prefab" or ".unity")
  221. {
  222. try
  223. {
  224. GitMergeWindow.ResolveConflict(change.FilePath);
  225. }
  226. catch (Exception e)
  227. {
  228. ErrorMessage = e.Message;
  229. }
  230. Refresh();
  231. return;
  232. }
  233. GitService.LaunchMergeTool(change)
  234. .Then(successMessage => { InfoMessage = successMessage; })
  235. .Catch(HandleOperationError)
  236. .Finally(Refresh);
  237. }
  238. public void ResetSelected()
  239. {
  240. var selectedFiles = _changes.Where(c => c.IsSelectedForCommit).ToList();
  241. if (!selectedFiles.Any()) return;
  242. var fileList = string.Join("\n - ", selectedFiles.Select(f => f.FilePath));
  243. if (!_displayDialog("Confirm Reset Selected", $"Are you sure you want to revert changes for the following {selectedFiles.Count} file(s)?\n\n - {fileList}", "Yes, Revert Selected", "Cancel")) return;
  244. var pathsToReset = selectedFiles.Select(c => c.FilePath).ToList();
  245. ResetMultipleFiles(pathsToReset);
  246. }
  247. public void SetAllSelection(bool selected)
  248. {
  249. if (_changes == null) return;
  250. foreach (var change in _changes.Where(change => change.Status != LibGit2Sharp.ChangeKind.Conflicted))
  251. {
  252. change.IsSelectedForCommit = selected;
  253. }
  254. }
  255. public void SwitchToBranch(string targetBranch)
  256. {
  257. if (IsLoading || targetBranch == CurrentBranchName) return;
  258. if (Changes.Any())
  259. {
  260. if (!_displayDialog("Discard Local Changes?", $"You have local changes. To switch branches, these changes must be discarded.\n\nDiscard changes and switch to '{targetBranch}'?", "Yes, Discard and Switch", "Cancel"))
  261. {
  262. return;
  263. }
  264. StartOperation($"Discarding changes and switching to {targetBranch}...");
  265. GitService.ResetAndSwitchBranch(targetBranch)
  266. .Then(successMsg => { InfoMessage = successMsg; Refresh(); })
  267. .Catch(ex => { HandleOperationError(ex); FinishOperation(); })
  268. .Finally(() => { EditorApplication.delayCall += AssetDatabase.Refresh; });
  269. }
  270. else
  271. {
  272. if (!_displayDialog("Confirm Branch Switch", $"Are you sure you want to switch to branch '{targetBranch}'?", "Yes, Switch", "Cancel"))
  273. {
  274. return;
  275. }
  276. StartOperation($"Switching to {targetBranch}...");
  277. GitService.SwitchBranch(targetBranch)
  278. .Then(successMsg => { InfoMessage = successMsg; Refresh(); })
  279. .Catch(ex => { HandleOperationError(ex); FinishOperation(); })
  280. .Finally(() => { EditorApplication.delayCall += AssetDatabase.Refresh; });
  281. }
  282. }
  283. // --- Private Methods ---
  284. private static IPromise<bool> UnstageStep()
  285. {
  286. return GitService.UnstageAllFilesIfSafe();
  287. }
  288. private IPromise<List<GitChange>> CompareStep(bool wasUnstaged)
  289. {
  290. if (wasUnstaged)
  291. {
  292. InfoMessage = "Found and unstaged files for review.";
  293. }
  294. return GitService.CompareLocalToRemote();
  295. }
  296. private IPromise<int?> FetchUpstreamStep(List<GitChange> changes)
  297. {
  298. _changes = changes;
  299. IsInConflictState = _changes.Any(c => c.Status == LibGit2Sharp.ChangeKind.Conflicted);
  300. return IsInConflictState ? new Promise<int?>((resolve, _) => resolve(0)) : GitService.GetUpstreamAheadBy(OnProgressModified);
  301. void OnProgressModified(float progress, string message)
  302. {
  303. OperationProgress = progress;
  304. OperationProgressMessage = message;
  305. _requestRepaint?.Invoke();
  306. }
  307. }
  308. private IPromise<BranchData> FetchBranchDataStep(int? pullCount)
  309. {
  310. CommitsToPull = pullCount ?? 0;
  311. OperationProgress = 0f;
  312. OperationProgressMessage = "";
  313. return GitService.GetBranchData();
  314. }
  315. private void FinalizeRefresh(BranchData branchData)
  316. {
  317. CurrentBranchName = branchData.CurrentBranch;
  318. RemoteBranchList = branchData.AllBranches;
  319. ApplyGrouping();
  320. }
  321. // --- Shared Helper Methods ---
  322. private void StartOperation(string loadingMessage)
  323. {
  324. IsLoading = true;
  325. LoadingMessage = loadingMessage;
  326. OperationProgress = 0f;
  327. OperationProgressMessage = "";
  328. ClearMessages();
  329. _changes = null;
  330. _requestRepaint?.Invoke();
  331. }
  332. private void HandleOperationError(Exception ex)
  333. {
  334. ErrorMessage = $"Operation Failed: {ex.Message}";
  335. }
  336. private void FinishOperation()
  337. {
  338. IsLoading = false;
  339. _requestRepaint?.Invoke();
  340. }
  341. private void ClearMessages()
  342. {
  343. ErrorMessage = null;
  344. InfoMessage = null;
  345. }
  346. private void ResetMultipleFiles(List<string> filePaths)
  347. {
  348. InfoMessage = $"Starting reset for {filePaths.Count} file(s)... This may trigger script compilation.";
  349. _requestRepaint?.Invoke();
  350. SessionState.SetString("BetterGit.ResetQueue", string.Join(";", filePaths));
  351. EditorApplication.delayCall += BetterGitStatePersistence.ContinueInterruptedReset;
  352. }
  353. private void ForcePull()
  354. {
  355. StartOperation("Attempting to pull and create conflicts...");
  356. EditorApplication.LockReloadAssemblies();
  357. GitService.ForcePull()
  358. .Then(_ =>
  359. {
  360. InfoMessage = "Pull resulted in conflicts. Please resolve them below.";
  361. })
  362. .Catch(HandleOperationError)
  363. .Finally(() =>
  364. {
  365. EditorApplication.UnlockReloadAssemblies();
  366. AssetDatabase.Refresh();
  367. Refresh();
  368. });
  369. }
  370. private bool CancelOperationIfUnsavedScenes()
  371. {
  372. var isAnySceneDirty = false;
  373. for (var i = 0; i < EditorSceneManager.sceneCount; i++)
  374. {
  375. var scene = EditorSceneManager.GetSceneAt(i);
  376. if (!scene.isDirty) continue;
  377. isAnySceneDirty = true;
  378. break;
  379. }
  380. if (!isAnySceneDirty)
  381. {
  382. return false;
  383. }
  384. var userChoice = _promptForUnsavedChanges();
  385. switch (userChoice)
  386. {
  387. case UserAction.SaveAndProceed:
  388. EditorSceneManager.SaveOpenScenes();
  389. return false;
  390. case UserAction.Proceed:
  391. return false;
  392. case UserAction.Cancel:
  393. default:
  394. return true;
  395. }
  396. }
  397. }
  398. }