ArbitratorController.cs 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630
  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. using UnityEngine;
  16. namespace Terra.Arbitrator.GUI
  17. {
  18. public enum UserAction { Proceed, SaveAndProceed, Cancel }
  19. public enum SortColumn { Commit, Status, FilePath }
  20. [Preserve]
  21. public class ArbitratorController
  22. {
  23. private List<GitChange> _changes = new();
  24. public IReadOnlyList<GitChange> Changes => _changes;
  25. public string InfoMessage { get; private set; }
  26. public string ErrorMessage { get; private set; }
  27. public bool IsLoading { get; private set; }
  28. public string LoadingMessage { get; private set; } = "";
  29. public bool IsInConflictState { get; private set; }
  30. public bool HasStash { get; private set; }
  31. public int CommitsToPull { get; private set; }
  32. public SortColumn CurrentSortColumn { get; private set; } = SortColumn.FilePath;
  33. public float OperationProgress { get; private set; }
  34. public string OperationProgressMessage { get; private set; }
  35. public IReadOnlyList<string> RemoteBranchList { get; private set; } = new List<string>();
  36. public string CurrentBranchName { get; private set; } = "master";
  37. private readonly Action _requestRepaint;
  38. private readonly Func<string, string, string, string, bool> _displayDialog;
  39. private readonly Func<UserAction> _promptForUnsavedChanges;
  40. /// <summary>
  41. /// Initializes the controller.
  42. /// </summary>
  43. /// <param name="requestRepaint">A callback to the window's Repaint() method.</param>
  44. /// <param name="displayDialog">A callback to EditorUtility.DisplayDialog for user confirmations.</param>
  45. /// <param name="promptForUnsavedChanges">A callback to EditorUtility.DisplayDialog for user confirmations.</param>
  46. public ArbitratorController(Action requestRepaint, Func<string, string, string, string, bool> displayDialog, Func<UserAction> promptForUnsavedChanges)
  47. {
  48. _requestRepaint = requestRepaint;
  49. _displayDialog = displayDialog;
  50. _promptForUnsavedChanges = promptForUnsavedChanges;
  51. }
  52. public void OnEnable()
  53. {
  54. Refresh();
  55. }
  56. public void Refresh()
  57. {
  58. StartOperation("Refreshing status...");
  59. CommitsToPull = 0;
  60. UnstageStep()
  61. .Then(CompareStep)
  62. .Then(FetchUpstreamStep)
  63. .Then(CheckForStashStep)
  64. .Then(FetchBranchDataStep)
  65. .Then(FinalizeRefresh)
  66. .Catch(HandleOperationError)
  67. .Finally(FinishOperation);
  68. }
  69. public void Pull()
  70. {
  71. if (IsLoading) return;
  72. if (CancelOperationIfUnsavedScenes()) return;
  73. if (CommitsToPull > 0)
  74. {
  75. if (!_displayDialog("Confirm Pull", $"There are {CommitsToPull} incoming changes. Are you sure you want to pull?", "Yes, Pull", "Cancel"))
  76. {
  77. return;
  78. }
  79. }
  80. StartOperation("Analyzing for conflicts...");
  81. GitService.AnalyzePullConflicts()
  82. .Then(analysisResult =>
  83. {
  84. FinishOperation();
  85. if (analysisResult.HasConflicts)
  86. {
  87. var conflictingChanges = _changes.Where(c => analysisResult.ConflictingFiles.Contains(c.FilePath)).ToList();
  88. ConflictResolutionWindow.ShowWindow(this, conflictingChanges, new PullConflictSource());
  89. }
  90. else
  91. {
  92. PerformSafePullWithLock();
  93. }
  94. })
  95. .Catch(ex => {
  96. HandleOperationError(ex);
  97. FinishOperation();
  98. })
  99. .Finally(FinishOperation);
  100. }
  101. private void PerformSafePullWithLock()
  102. {
  103. StartOperation("Pulling changes...");
  104. EditorApplication.LockReloadAssemblies();
  105. GitService.PerformSafePull()
  106. .Then(successMessage =>
  107. {
  108. InfoMessage = successMessage;
  109. Refresh();
  110. })
  111. .Catch(ex => {
  112. HandleOperationError(ex);
  113. FinishOperation();
  114. })
  115. .Finally(EditorApplication.UnlockReloadAssemblies);
  116. }
  117. public void ResolveConflictsAndPull(List<GitChange> resolutions)
  118. {
  119. StartOperation("Resolving conflicts and pulling...");
  120. EditorApplication.LockReloadAssemblies();
  121. GitService.PullAndOverwrite(resolutions)
  122. .Then(successMessage =>
  123. {
  124. InfoMessage = successMessage;
  125. })
  126. .Catch(HandleOperationError)
  127. .Finally(() =>
  128. {
  129. EditorApplication.UnlockReloadAssemblies();
  130. AssetDatabase.Refresh();
  131. Refresh();
  132. });
  133. }
  134. public void CommitAndPush(string commitMessage)
  135. {
  136. if (CancelOperationIfUnsavedScenes()) return;
  137. var selectedFiles = _changes.Where(c => c.IsSelectedForCommit).ToList();
  138. var username = BetterGitSettings.Username;
  139. var email = BetterGitSettings.Email;
  140. StartOperation("Staging, committing, and pushing files...");
  141. GitService.CommitAndPush(selectedFiles, commitMessage, username, email, OnProgressModified)
  142. .Then(successMessage => {
  143. InfoMessage = successMessage;
  144. Refresh();
  145. })
  146. .Catch(ex => {
  147. HandleOperationError(ex);
  148. FinishOperation();
  149. });
  150. return;
  151. void OnProgressModified(float progress, string message)
  152. {
  153. OperationProgress = progress;
  154. OperationProgressMessage = message;
  155. _requestRepaint?.Invoke();
  156. }
  157. }
  158. public void SetSortColumn(SortColumn newColumn)
  159. {
  160. // If it's already the active column, do nothing.
  161. if (CurrentSortColumn == newColumn) return;
  162. CurrentSortColumn = newColumn;
  163. ApplyGrouping();
  164. _requestRepaint?.Invoke();
  165. }
  166. private void ApplyGrouping()
  167. {
  168. if (_changes == null || !_changes.Any()) return;
  169. _changes = CurrentSortColumn switch
  170. {
  171. SortColumn.Commit => _changes.OrderByDescending(c => c.IsSelectedForCommit).ThenBy(c => c.FilePath).ToList(),
  172. SortColumn.Status => _changes.OrderBy(c => GetStatusSortPriority(c.Status)).ThenBy(c => c.FilePath).ToList(),
  173. SortColumn.FilePath => _changes.OrderBy(c => c.FilePath).ToList(),
  174. _ => _changes
  175. };
  176. }
  177. private static int GetStatusSortPriority(LibGit2Sharp.ChangeKind status)
  178. {
  179. return status switch
  180. {
  181. LibGit2Sharp.ChangeKind.Conflicted => -1, // Always show conflicts on top
  182. LibGit2Sharp.ChangeKind.Modified => 0,
  183. LibGit2Sharp.ChangeKind.Added => 1,
  184. LibGit2Sharp.ChangeKind.Deleted => 2,
  185. LibGit2Sharp.ChangeKind.Renamed => 3,
  186. _ => 99
  187. };
  188. }
  189. public void ResetFile(GitChange change)
  190. {
  191. if (IsLoading) return;
  192. 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");
  193. if (!userConfirmed) return;
  194. StartOperation($"Resetting {change.FilePath}...");
  195. GitService.ResetFileChanges(change)
  196. .Then(successMessage => {
  197. InfoMessage = successMessage;
  198. Refresh();
  199. })
  200. .Catch(ex => {
  201. HandleOperationError(ex);
  202. FinishOperation();
  203. });
  204. }
  205. public void DiffFile(GitChange change)
  206. {
  207. if (IsLoading) return;
  208. StartOperation($"Launching diff for {change.FilePath}...");
  209. GitService.LaunchExternalDiff(change)
  210. .Catch(HandleOperationError)
  211. .Finally(Refresh);
  212. }
  213. public void ResolveConflict(GitChange change)
  214. {
  215. if (IsLoading) return;
  216. StartOperation($"Opening merge tool for {change.FilePath}...");
  217. var fileExtension = System.IO.Path.GetExtension(change.FilePath).ToLower();
  218. if (fileExtension is ".prefab" or ".unity")
  219. {
  220. try
  221. {
  222. GitMergeWindow.ResolveConflict(change.FilePath);
  223. }
  224. catch (Exception e)
  225. {
  226. ErrorMessage = e.Message;
  227. }
  228. Refresh();
  229. return;
  230. }
  231. GitService.LaunchMergeTool(change)
  232. .Then(successMessage => { InfoMessage = successMessage; })
  233. .Catch(HandleOperationError)
  234. .Finally(Refresh);
  235. }
  236. public void ResetSelected()
  237. {
  238. var selectedFiles = _changes.Where(c => c.IsSelectedForCommit).ToList();
  239. if (!selectedFiles.Any()) return;
  240. var fileList = string.Join("\n - ", selectedFiles.Select(f => f.FilePath));
  241. 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;
  242. var pathsToReset = selectedFiles.Select(c => c.FilePath).ToList();
  243. ResetMultipleFiles(pathsToReset);
  244. }
  245. public void StashSelectedFiles()
  246. {
  247. var selectedFiles = _changes.Where(c => c.IsSelectedForCommit).ToList();
  248. if (!selectedFiles.Any())
  249. {
  250. InfoMessage = "No files selected to stash.";
  251. return;
  252. }
  253. EditorApplication.LockReloadAssemblies();
  254. StartOperation("Checking for existing stash...");
  255. GitService.HasStash()
  256. .Then(hasStash =>
  257. {
  258. FinishOperation();
  259. bool confirmed;
  260. if (hasStash)
  261. {
  262. confirmed = _displayDialog("Overwrite Stash?",
  263. "A 'Better Git Stash' already exists. Do you want to overwrite it with your currently selected files?",
  264. "Yes, Overwrite", "Cancel");
  265. }
  266. else
  267. {
  268. confirmed = _displayDialog("Create Stash?",
  269. $"Are you sure you want to stash the selected {selectedFiles.Count} file(s)?",
  270. "Yes, Stash", "Cancel");
  271. }
  272. if (!confirmed) return;
  273. StartOperation("Stashing selected files...");
  274. GitService.CreateOrOverwriteStash(selectedFiles)
  275. .Then(successMsg => { InfoMessage = successMsg; })
  276. .Catch(HandleOperationError)
  277. .Finally(Refresh);
  278. })
  279. .Catch(HandleOperationError)
  280. .Finally(() =>
  281. {
  282. FinishOperation();
  283. Refresh();
  284. EditorApplication.UnlockReloadAssemblies();
  285. AssetDatabase.Refresh();
  286. });
  287. }
  288. public void SetAllSelection(bool selected)
  289. {
  290. if (_changes == null) return;
  291. foreach (var change in _changes.Where(change => change.Status != LibGit2Sharp.ChangeKind.Conflicted))
  292. {
  293. change.IsSelectedForCommit = selected;
  294. }
  295. }
  296. public void SwitchToBranch(string targetBranch)
  297. {
  298. if (IsLoading || targetBranch == CurrentBranchName) return;
  299. if (Changes.Any())
  300. {
  301. 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"))
  302. {
  303. return;
  304. }
  305. StartOperation($"Discarding changes and switching to {targetBranch}...");
  306. GitService.ResetAndSwitchBranch(targetBranch)
  307. .Then(successMsg => { InfoMessage = successMsg; Refresh(); })
  308. .Catch(ex => { HandleOperationError(ex); FinishOperation(); })
  309. .Finally(() => { EditorApplication.delayCall += AssetDatabase.Refresh; });
  310. }
  311. else
  312. {
  313. if (!_displayDialog("Confirm Branch Switch", $"Are you sure you want to switch to branch '{targetBranch}'?", "Yes, Switch", "Cancel"))
  314. {
  315. return;
  316. }
  317. StartOperation($"Switching to {targetBranch}...");
  318. GitService.SwitchBranch(targetBranch)
  319. .Then(successMsg => { InfoMessage = successMsg; Refresh(); })
  320. .Catch(ex => { HandleOperationError(ex); FinishOperation(); })
  321. .Finally(() => { EditorApplication.delayCall += AssetDatabase.Refresh; });
  322. }
  323. }
  324. // --- Private Methods ---
  325. private static IPromise<bool> UnstageStep()
  326. {
  327. return GitService.UnstageAllFilesIfSafe();
  328. }
  329. private IPromise<List<GitChange>> CompareStep(bool wasUnstaged)
  330. {
  331. if (wasUnstaged)
  332. {
  333. InfoMessage = "Found and unstaged files for review.";
  334. }
  335. return GitService.CompareLocalToRemote();
  336. }
  337. private IPromise<int?> FetchUpstreamStep(List<GitChange> changes)
  338. {
  339. _changes = changes;
  340. IsInConflictState = _changes.Any(c => c.Status == LibGit2Sharp.ChangeKind.Conflicted);
  341. return IsInConflictState ? new Promise<int?>((resolve, _) => resolve(0)) : GitService.GetUpstreamAheadBy(OnProgressModified);
  342. void OnProgressModified(float progress, string message)
  343. {
  344. OperationProgress = progress;
  345. OperationProgressMessage = message;
  346. _requestRepaint?.Invoke();
  347. }
  348. }
  349. private IPromise<bool> CheckForStashStep(int? pullCount)
  350. {
  351. CommitsToPull = pullCount ?? 0;
  352. return GitService.HasStash();
  353. }
  354. private IPromise<BranchData> FetchBranchDataStep(bool hasStash)
  355. {
  356. HasStash = hasStash;
  357. OperationProgress = 0f;
  358. OperationProgressMessage = "";
  359. return GitService.GetBranchData();
  360. }
  361. private void FinalizeRefresh(BranchData branchData)
  362. {
  363. CurrentBranchName = branchData.CurrentBranch;
  364. RemoteBranchList = branchData.AllBranches;
  365. ApplyGrouping();
  366. }
  367. // --- Shared Helper Methods ---
  368. private void StartOperation(string loadingMessage)
  369. {
  370. IsLoading = true;
  371. LoadingMessage = loadingMessage;
  372. OperationProgress = 0f;
  373. OperationProgressMessage = "";
  374. ClearMessages();
  375. _changes = null;
  376. _requestRepaint?.Invoke();
  377. }
  378. private void HandleOperationError(Exception ex)
  379. {
  380. ErrorMessage = $"Operation Failed: {ex.Message}";
  381. Debug.LogException(ex);
  382. }
  383. private void FinishOperation()
  384. {
  385. IsLoading = false;
  386. _requestRepaint?.Invoke();
  387. }
  388. private void ClearMessages()
  389. {
  390. ErrorMessage = null;
  391. InfoMessage = null;
  392. }
  393. private void ResetMultipleFiles(List<string> filePaths)
  394. {
  395. EditorApplication.LockReloadAssemblies();
  396. StartOperation($"Resetting {filePaths.Count} file(s)...");
  397. IPromise<string> promiseChain = new Promise<string>((resolve, _) => resolve(""));
  398. foreach (var path in filePaths)
  399. {
  400. promiseChain = promiseChain.Then(_ =>
  401. {
  402. var change = GitService.GetChangeForFile(path);
  403. return change != null ? GitService.ResetFileChanges(change) : new Promise<string>((res, _) => res(""));
  404. });
  405. }
  406. promiseChain
  407. .Then(_ =>
  408. {
  409. InfoMessage = $"Successfully reset {filePaths.Count} file(s).";
  410. Refresh();
  411. })
  412. .Catch(ex =>
  413. {
  414. HandleOperationError(ex);
  415. FinishOperation();
  416. })
  417. .Finally(() =>
  418. {
  419. EditorApplication.UnlockReloadAssemblies();
  420. AssetDatabase.Refresh();
  421. });
  422. }
  423. public void ResolveConflicts(List<GitChange> resolutions, IConflictSource source)
  424. {
  425. StartOperation("Resolving conflicts...");
  426. EditorApplication.LockReloadAssemblies();
  427. source.Resolve(resolutions)
  428. .Then(successMessage =>
  429. {
  430. InfoMessage = successMessage;
  431. })
  432. .Catch(HandleOperationError)
  433. .Finally(() =>
  434. {
  435. EditorApplication.UnlockReloadAssemblies();
  436. AssetDatabase.Refresh();
  437. Refresh();
  438. });
  439. }
  440. public void ShowStashedChangesWindow()
  441. {
  442. var tempChanges = new List<GitChange>();
  443. tempChanges.AddRange(_changes);
  444. StartOperation("Loading stashed files...");
  445. GitService.GetStashedFiles()
  446. .Then(stashedFiles =>
  447. {
  448. if (stashedFiles.Any())
  449. {
  450. StashedChangesWindow.ShowWindow(this, stashedFiles);
  451. }
  452. else
  453. {
  454. InfoMessage = "No files found in the stash.";
  455. }
  456. })
  457. .Catch(HandleOperationError)
  458. .Finally(() =>
  459. {
  460. _changes = tempChanges;
  461. FinishOperation();
  462. });
  463. }
  464. public void DiscardStash()
  465. {
  466. StartOperation("Discarding stash...");
  467. GitService.DropStash()
  468. .Then(successMessage =>
  469. {
  470. InfoMessage = successMessage;
  471. })
  472. .Catch(HandleOperationError)
  473. .Finally(Refresh);
  474. }
  475. public void DiffStashedFile(GitChange change)
  476. {
  477. GitService.DiffStashedFile(change)
  478. .Catch(ex =>
  479. {
  480. var res = _displayDialog("Stash Diff Error", $"Error diffing '{change.FilePath}': {ex.Message}", "Uh-oh", "Ok");
  481. if (!res) return;
  482. Debug.Log($"Error diffing '{change.FilePath}'");
  483. Debug.LogException(ex);
  484. });
  485. }
  486. public void ApplyStash()
  487. {
  488. StartOperation("Analyzing stash for conflicts...");
  489. GitService.AnalyzeStashConflicts()
  490. .Then(analysisResult =>
  491. {
  492. Debug.Log($"Any conflicts? {analysisResult.HasConflicts}");
  493. FinishOperation();
  494. if (analysisResult.HasConflicts)
  495. {
  496. var conflictSource = new StashConflictSource();
  497. GitService.GetStashedFiles().Then(stashedFiles =>
  498. {
  499. var conflictingChanges = stashedFiles
  500. .Where(sf => analysisResult.ConflictingFiles.Contains(sf.FilePath))
  501. .ToList();
  502. Debug.Log($"Found {conflictingChanges.Count} conflicting files. Showing window.");
  503. ConflictResolutionWindow.ShowWindow(this, conflictingChanges, conflictSource);
  504. });
  505. }
  506. else
  507. {
  508. StartOperation("Applying stash...");
  509. var resolutions = new List<GitChange>();
  510. var source = new StashConflictSource();
  511. source.Resolve(resolutions)
  512. .Then(successMsg => { InfoMessage = successMsg; })
  513. .Catch(HandleOperationError)
  514. .Finally(Refresh);
  515. }
  516. })
  517. .Catch(HandleOperationError)
  518. .Finally(() =>
  519. {
  520. FinishOperation();
  521. Refresh();
  522. AssetDatabase.Refresh();
  523. });
  524. }
  525. private bool CancelOperationIfUnsavedScenes()
  526. {
  527. var isAnySceneDirty = false;
  528. for (var i = 0; i < EditorSceneManager.sceneCount; i++)
  529. {
  530. var scene = EditorSceneManager.GetSceneAt(i);
  531. if (!scene.isDirty) continue;
  532. isAnySceneDirty = true;
  533. break;
  534. }
  535. if (!isAnySceneDirty)
  536. {
  537. return false;
  538. }
  539. var userChoice = _promptForUnsavedChanges();
  540. switch (userChoice)
  541. {
  542. case UserAction.SaveAndProceed:
  543. EditorSceneManager.SaveOpenScenes();
  544. return false;
  545. case UserAction.Proceed:
  546. return false;
  547. case UserAction.Cancel:
  548. default:
  549. return true;
  550. }
  551. }
  552. }
  553. }