ArbitratorController.cs 18 KB

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