ArbitratorController.cs 18 KB

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