ArbitratorController.cs 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620
  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. });
  286. }
  287. public void SetAllSelection(bool selected)
  288. {
  289. if (_changes == null) return;
  290. foreach (var change in _changes.Where(change => change.Status != LibGit2Sharp.ChangeKind.Conflicted))
  291. {
  292. change.IsSelectedForCommit = selected;
  293. }
  294. }
  295. public void SwitchToBranch(string targetBranch)
  296. {
  297. if (IsLoading || targetBranch == CurrentBranchName) return;
  298. if (Changes.Any())
  299. {
  300. 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"))
  301. {
  302. return;
  303. }
  304. StartOperation($"Discarding changes and switching to {targetBranch}...");
  305. GitService.ResetAndSwitchBranch(targetBranch)
  306. .Then(successMsg => { InfoMessage = successMsg; Refresh(); })
  307. .Catch(ex => { HandleOperationError(ex); FinishOperation(); })
  308. .Finally(() => { EditorApplication.delayCall += AssetDatabase.Refresh; });
  309. }
  310. else
  311. {
  312. if (!_displayDialog("Confirm Branch Switch", $"Are you sure you want to switch to branch '{targetBranch}'?", "Yes, Switch", "Cancel"))
  313. {
  314. return;
  315. }
  316. StartOperation($"Switching to {targetBranch}...");
  317. GitService.SwitchBranch(targetBranch)
  318. .Then(successMsg => { InfoMessage = successMsg; Refresh(); })
  319. .Catch(ex => { HandleOperationError(ex); FinishOperation(); })
  320. .Finally(() => { EditorApplication.delayCall += AssetDatabase.Refresh; });
  321. }
  322. }
  323. // --- Private Methods ---
  324. private static IPromise<bool> UnstageStep()
  325. {
  326. return GitService.UnstageAllFilesIfSafe();
  327. }
  328. private IPromise<List<GitChange>> CompareStep(bool wasUnstaged)
  329. {
  330. if (wasUnstaged)
  331. {
  332. InfoMessage = "Found and unstaged files for review.";
  333. }
  334. return GitService.CompareLocalToRemote();
  335. }
  336. private IPromise<int?> FetchUpstreamStep(List<GitChange> changes)
  337. {
  338. _changes = changes;
  339. IsInConflictState = _changes.Any(c => c.Status == LibGit2Sharp.ChangeKind.Conflicted);
  340. return IsInConflictState ? new Promise<int?>((resolve, _) => resolve(0)) : GitService.GetUpstreamAheadBy(OnProgressModified);
  341. void OnProgressModified(float progress, string message)
  342. {
  343. OperationProgress = progress;
  344. OperationProgressMessage = message;
  345. _requestRepaint?.Invoke();
  346. }
  347. }
  348. private IPromise<bool> CheckForStashStep(int? pullCount)
  349. {
  350. CommitsToPull = pullCount ?? 0;
  351. return GitService.HasStash();
  352. }
  353. private IPromise<BranchData> FetchBranchDataStep(bool hasStash)
  354. {
  355. HasStash = hasStash;
  356. OperationProgress = 0f;
  357. OperationProgressMessage = "";
  358. return GitService.GetBranchData();
  359. }
  360. private void FinalizeRefresh(BranchData branchData)
  361. {
  362. CurrentBranchName = branchData.CurrentBranch;
  363. RemoteBranchList = branchData.AllBranches;
  364. ApplyGrouping();
  365. }
  366. // --- Shared Helper Methods ---
  367. private void StartOperation(string loadingMessage)
  368. {
  369. IsLoading = true;
  370. LoadingMessage = loadingMessage;
  371. OperationProgress = 0f;
  372. OperationProgressMessage = "";
  373. ClearMessages();
  374. _changes = null;
  375. _requestRepaint?.Invoke();
  376. }
  377. private void HandleOperationError(Exception ex)
  378. {
  379. ErrorMessage = $"Operation Failed: {ex.Message}";
  380. }
  381. private void FinishOperation()
  382. {
  383. IsLoading = false;
  384. _requestRepaint?.Invoke();
  385. }
  386. private void ClearMessages()
  387. {
  388. ErrorMessage = null;
  389. InfoMessage = null;
  390. }
  391. private void ResetMultipleFiles(List<string> filePaths)
  392. {
  393. EditorApplication.LockReloadAssemblies();
  394. StartOperation($"Resetting {filePaths.Count} file(s)...");
  395. IPromise<string> promiseChain = new Promise<string>((resolve, _) => resolve(""));
  396. foreach (var path in filePaths)
  397. {
  398. promiseChain = promiseChain.Then(_ =>
  399. {
  400. var change = GitService.GetChangeForFile(path);
  401. return change != null ? GitService.ResetFileChanges(change) : new Promise<string>((res, _) => res(""));
  402. });
  403. }
  404. promiseChain
  405. .Then(_ =>
  406. {
  407. InfoMessage = $"Successfully reset {filePaths.Count} file(s).";
  408. Refresh();
  409. })
  410. .Catch(ex =>
  411. {
  412. HandleOperationError(ex);
  413. FinishOperation();
  414. })
  415. .Finally(() =>
  416. {
  417. EditorApplication.UnlockReloadAssemblies();
  418. AssetDatabase.Refresh();
  419. });
  420. }
  421. public void ResolveConflicts(List<GitChange> resolutions, IConflictSource source)
  422. {
  423. StartOperation("Resolving conflicts...");
  424. EditorApplication.LockReloadAssemblies();
  425. source.Resolve(resolutions)
  426. .Then(successMessage =>
  427. {
  428. InfoMessage = successMessage;
  429. })
  430. .Catch(HandleOperationError)
  431. .Finally(() =>
  432. {
  433. EditorApplication.UnlockReloadAssemblies();
  434. AssetDatabase.Refresh();
  435. Refresh();
  436. });
  437. }
  438. public void ShowStashedChangesWindow()
  439. {
  440. var tempChanges = new List<GitChange>();
  441. tempChanges.AddRange(_changes);
  442. StartOperation("Loading stashed files...");
  443. GitService.GetStashedFiles()
  444. .Then(stashedFiles =>
  445. {
  446. if (stashedFiles.Any())
  447. {
  448. StashedChangesWindow.ShowWindow(this, stashedFiles);
  449. }
  450. else
  451. {
  452. InfoMessage = "No files found in the stash.";
  453. }
  454. })
  455. .Catch(HandleOperationError)
  456. .Finally(() =>
  457. {
  458. _changes = tempChanges;
  459. FinishOperation();
  460. });
  461. }
  462. public void DiscardStash()
  463. {
  464. StartOperation("Discarding stash...");
  465. GitService.DropStash()
  466. .Then(successMessage =>
  467. {
  468. InfoMessage = successMessage;
  469. })
  470. .Catch(HandleOperationError)
  471. .Finally(Refresh);
  472. }
  473. public void DiffStashedFile(GitChange change)
  474. {
  475. GitService.DiffStashedFile(change)
  476. .Catch(ex =>
  477. {
  478. var res = _displayDialog("Stash Diff Error", $"Error diffing '{change.FilePath}': {ex.Message}", "Uh-oh", "Ok");
  479. if (!res) return;
  480. Debug.Log($"Error diffing '{change.FilePath}'");
  481. Debug.LogException(ex);
  482. });
  483. }
  484. public void ApplyStash()
  485. {
  486. StartOperation("Analyzing stash for conflicts...");
  487. GitService.AnalyzeStashConflicts()
  488. .Then(analysisResult =>
  489. {
  490. FinishOperation();
  491. if (analysisResult.HasConflicts)
  492. {
  493. var conflictSource = new StashConflictSource();
  494. GitService.GetStashedFiles().Then(stashedFiles =>
  495. {
  496. var conflictingChanges = stashedFiles
  497. .Where(sf => analysisResult.ConflictingFiles.Contains(sf.FilePath))
  498. .ToList();
  499. ConflictResolutionWindow.ShowWindow(this, conflictingChanges, conflictSource);
  500. });
  501. }
  502. else
  503. {
  504. StartOperation("Applying stash...");
  505. var resolutions = new List<GitChange>();
  506. var source = new StashConflictSource();
  507. source.Resolve(resolutions)
  508. .Then(successMsg => { InfoMessage = successMsg; })
  509. .Catch(HandleOperationError)
  510. .Finally(Refresh);
  511. }
  512. })
  513. .Catch(HandleOperationError)
  514. .Finally(FinishOperation);
  515. }
  516. private bool CancelOperationIfUnsavedScenes()
  517. {
  518. var isAnySceneDirty = false;
  519. for (var i = 0; i < EditorSceneManager.sceneCount; i++)
  520. {
  521. var scene = EditorSceneManager.GetSceneAt(i);
  522. if (!scene.isDirty) continue;
  523. isAnySceneDirty = true;
  524. break;
  525. }
  526. if (!isAnySceneDirty)
  527. {
  528. return false;
  529. }
  530. var userChoice = _promptForUnsavedChanges();
  531. switch (userChoice)
  532. {
  533. case UserAction.SaveAndProceed:
  534. EditorSceneManager.SaveOpenScenes();
  535. return false;
  536. case UserAction.Proceed:
  537. return false;
  538. case UserAction.Cancel:
  539. default:
  540. return true;
  541. }
  542. }
  543. }
  544. }