ArbitratorController.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493
  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();
  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. private 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. if (CancelOperationIfUnsavedScenes()) return;
  142. var selectedFiles = _changes.Where(c => c.IsSelectedForCommit).ToList();
  143. var username = BetterGitSettings.Username;
  144. var email = BetterGitSettings.Email;
  145. StartOperation("Staging, committing, and pushing files...");
  146. GitService.CommitAndPush(selectedFiles, commitMessage, username, email, OnProgressModified)
  147. .Then(successMessage => {
  148. InfoMessage = successMessage;
  149. Refresh();
  150. })
  151. .Catch(ex => {
  152. HandleOperationError(ex);
  153. FinishOperation();
  154. });
  155. return;
  156. void OnProgressModified(float progress, string message)
  157. {
  158. OperationProgress = progress;
  159. OperationProgressMessage = message;
  160. _requestRepaint?.Invoke();
  161. }
  162. }
  163. public void SetSortColumn(SortColumn newColumn)
  164. {
  165. // If it's already the active column, do nothing.
  166. if (CurrentSortColumn == newColumn) return;
  167. CurrentSortColumn = newColumn;
  168. ApplyGrouping();
  169. _requestRepaint?.Invoke();
  170. }
  171. private void ApplyGrouping()
  172. {
  173. if (_changes == null || !_changes.Any()) return;
  174. _changes = CurrentSortColumn switch
  175. {
  176. SortColumn.Commit => _changes.OrderByDescending(c => c.IsSelectedForCommit).ThenBy(c => c.FilePath).ToList(),
  177. SortColumn.Status => _changes.OrderBy(c => GetStatusSortPriority(c.Status)).ThenBy(c => c.FilePath).ToList(),
  178. SortColumn.FilePath => _changes.OrderBy(c => c.FilePath).ToList(),
  179. _ => _changes
  180. };
  181. }
  182. private int GetStatusSortPriority(LibGit2Sharp.ChangeKind status)
  183. {
  184. return status switch
  185. {
  186. LibGit2Sharp.ChangeKind.Conflicted => -1, // Always show conflicts on top
  187. LibGit2Sharp.ChangeKind.Modified => 0,
  188. LibGit2Sharp.ChangeKind.Added => 1,
  189. LibGit2Sharp.ChangeKind.Deleted => 2,
  190. LibGit2Sharp.ChangeKind.Renamed => 3,
  191. _ => 99
  192. };
  193. }
  194. public void ResetFile(GitChange change)
  195. {
  196. if (IsLoading) return;
  197. 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");
  198. if (!userConfirmed) return;
  199. StartOperation($"Resetting {change.FilePath}...");
  200. GitService.ResetFileChanges(change)
  201. .Then(successMessage => {
  202. InfoMessage = successMessage;
  203. Refresh();
  204. })
  205. .Catch(ex => {
  206. HandleOperationError(ex);
  207. FinishOperation();
  208. });
  209. }
  210. public void DiffFile(GitChange change)
  211. {
  212. if (IsLoading) return;
  213. StartOperation($"Launching diff for {change.FilePath}...");
  214. GitService.LaunchExternalDiff(change)
  215. .Catch(HandleOperationError)
  216. .Finally(Refresh);
  217. }
  218. public void ResolveConflict(GitChange change)
  219. {
  220. if (IsLoading) return;
  221. StartOperation($"Opening merge tool for {change.FilePath}...");
  222. var fileExtension = System.IO.Path.GetExtension(change.FilePath).ToLower();
  223. if (fileExtension is ".prefab" or ".unity")
  224. {
  225. try
  226. {
  227. GitMergeWindow.ResolveConflict(change.FilePath);
  228. }
  229. catch (Exception e)
  230. {
  231. ErrorMessage = e.Message;
  232. }
  233. Refresh();
  234. return;
  235. }
  236. GitService.LaunchMergeTool(change)
  237. .Then(successMessage => { InfoMessage = successMessage; })
  238. .Catch(HandleOperationError)
  239. .Finally(Refresh);
  240. }
  241. public void ResetSelected()
  242. {
  243. var selectedFiles = _changes.Where(c => c.IsSelectedForCommit).ToList();
  244. if (!selectedFiles.Any()) return;
  245. var fileList = string.Join("\n - ", selectedFiles.Select(f => f.FilePath));
  246. 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;
  247. var pathsToReset = selectedFiles.Select(c => c.FilePath).ToList();
  248. ResetMultipleFiles(pathsToReset);
  249. }
  250. public void SetAllSelection(bool selected)
  251. {
  252. if (_changes == null) return;
  253. foreach (var change in _changes.Where(change => change.Status != LibGit2Sharp.ChangeKind.Conflicted))
  254. {
  255. change.IsSelectedForCommit = selected;
  256. }
  257. }
  258. public void SwitchToBranch(string targetBranch)
  259. {
  260. if (IsLoading || targetBranch == CurrentBranchName) return;
  261. if (Changes.Any())
  262. {
  263. 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"))
  264. {
  265. return;
  266. }
  267. StartOperation($"Discarding changes and switching to {targetBranch}...");
  268. GitService.ResetAndSwitchBranch(targetBranch)
  269. .Then(successMsg => { InfoMessage = successMsg; Refresh(); })
  270. .Catch(ex => { HandleOperationError(ex); FinishOperation(); })
  271. .Finally(() => { EditorApplication.delayCall += AssetDatabase.Refresh; });
  272. }
  273. else
  274. {
  275. if (!_displayDialog("Confirm Branch Switch", $"Are you sure you want to switch to branch '{targetBranch}'?", "Yes, Switch", "Cancel"))
  276. {
  277. return;
  278. }
  279. StartOperation($"Switching to {targetBranch}...");
  280. GitService.SwitchBranch(targetBranch)
  281. .Then(successMsg => { InfoMessage = successMsg; Refresh(); })
  282. .Catch(ex => { HandleOperationError(ex); FinishOperation(); })
  283. .Finally(() => { EditorApplication.delayCall += AssetDatabase.Refresh; });
  284. }
  285. }
  286. // --- Private Methods ---
  287. private static IPromise<bool> UnstageStep()
  288. {
  289. return GitService.UnstageAllFilesIfSafe();
  290. }
  291. private IPromise<List<GitChange>> CompareStep(bool wasUnstaged)
  292. {
  293. if (wasUnstaged)
  294. {
  295. InfoMessage = "Found and unstaged files for review.";
  296. }
  297. return GitService.CompareLocalToRemote();
  298. }
  299. private IPromise<int?> FetchUpstreamStep(List<GitChange> changes)
  300. {
  301. _changes = changes;
  302. IsInConflictState = _changes.Any(c => c.Status == LibGit2Sharp.ChangeKind.Conflicted);
  303. return IsInConflictState ? new Promise<int?>((resolve, _) => resolve(0)) : GitService.GetUpstreamAheadBy(OnProgressModified);
  304. void OnProgressModified(float progress, string message)
  305. {
  306. OperationProgress = progress;
  307. OperationProgressMessage = message;
  308. _requestRepaint?.Invoke();
  309. }
  310. }
  311. private IPromise<BranchData> FetchBranchDataStep(int? pullCount)
  312. {
  313. CommitsToPull = pullCount ?? 0;
  314. OperationProgress = 0f;
  315. OperationProgressMessage = "";
  316. return GitService.GetBranchData();
  317. }
  318. private void FinalizeRefresh(BranchData branchData)
  319. {
  320. CurrentBranchName = branchData.CurrentBranch;
  321. RemoteBranchList = branchData.AllBranches;
  322. ApplyGrouping();
  323. }
  324. // --- Shared Helper Methods ---
  325. private void StartOperation(string loadingMessage)
  326. {
  327. IsLoading = true;
  328. LoadingMessage = loadingMessage;
  329. OperationProgress = 0f;
  330. OperationProgressMessage = "";
  331. ClearMessages();
  332. _changes = null;
  333. _requestRepaint?.Invoke();
  334. }
  335. private void HandleOperationError(Exception ex)
  336. {
  337. ErrorMessage = $"Operation Failed: {ex.Message}";
  338. }
  339. private void FinishOperation()
  340. {
  341. IsLoading = false;
  342. _requestRepaint?.Invoke();
  343. }
  344. private void ClearMessages()
  345. {
  346. ErrorMessage = null;
  347. InfoMessage = null;
  348. }
  349. private void ResetMultipleFiles(List<string> filePaths)
  350. {
  351. var hasScripts = filePaths.Any(p => p.EndsWith(".cs", StringComparison.OrdinalIgnoreCase));
  352. if (hasScripts)
  353. {
  354. InfoMessage = $"Starting reset for {filePaths.Count} file(s)... This may trigger script compilation.";
  355. _requestRepaint?.Invoke();
  356. SessionState.SetString("BetterGit.ResetQueue", string.Join(";", filePaths));
  357. EditorApplication.delayCall += BetterGitStatePersistence.ContinueInterruptedReset;
  358. }
  359. else
  360. {
  361. StartOperation($"Resetting {filePaths.Count} file(s)...");
  362. IPromise<string> promiseChain = new Promise<string>((resolve, _) => resolve(""));
  363. foreach (var path in filePaths)
  364. {
  365. promiseChain = promiseChain.Then(_ => {
  366. var change = GitService.GetChangeForFile(path);
  367. return change != null ? GitService.ResetFileChanges(change) : new Promise<string>((res, _) => res(""));
  368. });
  369. }
  370. promiseChain
  371. .Then(successMsg => {
  372. InfoMessage = $"Successfully reset {filePaths.Count} file(s).";
  373. Refresh();
  374. })
  375. .Catch(ex => {
  376. HandleOperationError(ex);
  377. FinishOperation();
  378. });
  379. }
  380. }
  381. public void ForcePull()
  382. {
  383. StartOperation("Attempting to pull and create conflicts...");
  384. EditorApplication.LockReloadAssemblies();
  385. GitService.ForcePull()
  386. .Then(_ =>
  387. {
  388. InfoMessage = "Pull resulted in conflicts. Please resolve them below.";
  389. })
  390. .Catch(HandleOperationError)
  391. .Finally(() =>
  392. {
  393. EditorApplication.UnlockReloadAssemblies();
  394. AssetDatabase.Refresh();
  395. Refresh();
  396. });
  397. }
  398. private bool CancelOperationIfUnsavedScenes()
  399. {
  400. var isAnySceneDirty = false;
  401. for (var i = 0; i < EditorSceneManager.sceneCount; i++)
  402. {
  403. var scene = EditorSceneManager.GetSceneAt(i);
  404. if (!scene.isDirty) continue;
  405. isAnySceneDirty = true;
  406. break;
  407. }
  408. if (!isAnySceneDirty)
  409. {
  410. return false;
  411. }
  412. var userChoice = _promptForUnsavedChanges();
  413. switch (userChoice)
  414. {
  415. case UserAction.SaveAndProceed:
  416. EditorSceneManager.SaveOpenScenes();
  417. return false;
  418. case UserAction.Proceed:
  419. return false;
  420. case UserAction.Cancel:
  421. default:
  422. return true;
  423. }
  424. }
  425. }
  426. }