ArbitratorController.cs 17 KB

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