GitExecutors.cs 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591
  1. // Copyright (c) 2025 TerraByte Inc.
  2. //
  3. // A new internal class that contains the concrete implementation logic for
  4. // all Git operations. This separates the "how" from the "what" defined
  5. // in the public GitService API.
  6. using System;
  7. using System.IO;
  8. using System.Linq;
  9. using UnityEngine;
  10. using LibGit2Sharp;
  11. using System.Text;
  12. using System.Globalization;
  13. using System.ComponentModel;
  14. using UnityEngine.Scripting;
  15. using System.Threading.Tasks;
  16. using Terra.Arbitrator.Settings;
  17. using System.Collections.Generic;
  18. namespace Terra.Arbitrator.Services
  19. {
  20. /// <summary>
  21. /// A simple data container for branch information.
  22. /// </summary>
  23. [Preserve]
  24. public class BranchData
  25. {
  26. public string CurrentBranch { get; set; }
  27. public List<string> AllBranches { get; set; }
  28. }
  29. /// <summary>
  30. /// Contains the promise executor methods for all Git operations.
  31. /// This is an internal implementation detail and is not exposed publicly.
  32. /// </summary>
  33. [Preserve]
  34. internal static class GitExecutors
  35. {
  36. private static string _projectRoot;
  37. private static string ProjectRoot => _projectRoot ??= MainThreadDataCache.ProjectRoot;
  38. public static void GetBranchDataExecutor(Action<BranchData> resolve, Action<Exception> reject)
  39. {
  40. try
  41. {
  42. using var repo = new Repository(ProjectRoot);
  43. var data = new BranchData
  44. {
  45. CurrentBranch = repo.Head.FriendlyName,
  46. AllBranches = repo.Branches
  47. .Where(b => !b.FriendlyName.Contains("HEAD"))
  48. .Select(b => b.FriendlyName.Replace("origin/", ""))
  49. .Distinct()
  50. .OrderBy(name => name)
  51. .ToList()
  52. };
  53. resolve(data);
  54. }
  55. catch(Exception ex)
  56. {
  57. reject(ex);
  58. }
  59. }
  60. public static async void SwitchBranchExecutor(Action<string> resolve, Action<Exception> reject, string branchName)
  61. {
  62. try
  63. {
  64. var log = new StringBuilder();
  65. await GitCommand.RunGitAsync(log, new[] { "checkout", branchName });
  66. resolve($"Successfully switched to branch '{branchName}'.");
  67. }
  68. catch (Exception ex)
  69. {
  70. reject(ex);
  71. }
  72. }
  73. public static async void ResetAndSwitchBranchExecutor(Action<string> resolve, Action<Exception> reject, string branchName)
  74. {
  75. try
  76. {
  77. var log = new StringBuilder();
  78. await GitCommand.RunGitAsync(log, new[] { "reset", "--hard", "HEAD" });
  79. await GitCommand.RunGitAsync(log, new[] { "clean", "-fd" });
  80. await GitCommand.RunGitAsync(log, new[] { "checkout", branchName });
  81. resolve($"Discarded local changes and switched to branch '{branchName}'.");
  82. }
  83. catch (Exception ex)
  84. {
  85. reject(ex);
  86. }
  87. }
  88. /// <summary>
  89. /// Synchronous helper to get a GitChange object for a single file.
  90. /// This is public so it can be called by the GitService wrapper.
  91. /// </summary>
  92. public static GitChange GetChangeForFile(string filePath)
  93. {
  94. try
  95. {
  96. using var repo = new Repository(ProjectRoot);
  97. if (repo.Index.Conflicts.Any(c => c.Ours.Path == filePath))
  98. {
  99. return new GitChange(filePath, null, ChangeKind.Conflicted);
  100. }
  101. var statusEntry = repo.RetrieveStatus(filePath);
  102. return statusEntry switch
  103. {
  104. FileStatus.NewInWorkdir or FileStatus.NewInIndex => new GitChange(filePath, null, ChangeKind.Added),
  105. FileStatus.ModifiedInWorkdir or FileStatus.ModifiedInIndex => new GitChange(filePath, null, ChangeKind.Modified),
  106. FileStatus.DeletedFromWorkdir or FileStatus.DeletedFromIndex => new GitChange(filePath, null, ChangeKind.Deleted),
  107. FileStatus.RenamedInWorkdir or FileStatus.RenamedInIndex =>
  108. new GitChange(filePath, null, ChangeKind.Renamed),
  109. _ => null
  110. };
  111. }
  112. catch { return null; } // Suppress errors if repo is in a unique state
  113. }
  114. // --- Promise Executor Implementations ---
  115. public static async void GetUpstreamAheadByExecutor(Action<int?> resolve, Action<Exception> reject, Action<float, string> onProgress)
  116. {
  117. try
  118. {
  119. var progressReporter = new Progress<string>(line => ParseProgress(line, onProgress));
  120. await GitCommand.RunGitAsync(new StringBuilder(), new[] { "fetch", "--progress" }, progressReporter);
  121. using var repo = new Repository(ProjectRoot);
  122. resolve(repo.Head.TrackingDetails.BehindBy);
  123. }
  124. catch (Exception ex)
  125. {
  126. if (ex.Message.Contains("is not tracking a remote branch"))
  127. {
  128. resolve(null);
  129. }
  130. else
  131. {
  132. reject(ex);
  133. }
  134. }
  135. }
  136. public static void GetLocalStatusExecutor(Action<List<GitChange>> resolve, Action<Exception> reject)
  137. {
  138. try
  139. {
  140. var changes = new List<GitChange>();
  141. using var repo = new Repository(ProjectRoot);
  142. var conflictedPaths = new HashSet<string>(repo.Index.Conflicts.Select(c => c.Ours.Path));
  143. var statusOptions = new StatusOptions
  144. {
  145. IncludeUntracked = true,
  146. RecurseUntrackedDirs = true,
  147. DetectRenamesInIndex = true,
  148. DetectRenamesInWorkDir = true
  149. };
  150. foreach (var entry in repo.RetrieveStatus(statusOptions))
  151. {
  152. if (conflictedPaths.Contains(entry.FilePath))
  153. {
  154. if (changes.All(c => c.FilePath != entry.FilePath))
  155. {
  156. changes.Add(new GitChange(entry.FilePath, null, ChangeKind.Conflicted));
  157. }
  158. continue;
  159. }
  160. switch(entry.State)
  161. {
  162. case FileStatus.NewInWorkdir:
  163. case FileStatus.NewInIndex:
  164. changes.Add(new GitChange(entry.FilePath, null, ChangeKind.Added));
  165. break;
  166. case FileStatus.ModifiedInWorkdir:
  167. case FileStatus.ModifiedInIndex:
  168. changes.Add(new GitChange(entry.FilePath, null, ChangeKind.Modified));
  169. break;
  170. case FileStatus.DeletedFromWorkdir:
  171. case FileStatus.DeletedFromIndex:
  172. changes.Add(new GitChange(entry.FilePath, null, ChangeKind.Deleted));
  173. break;
  174. case FileStatus.RenamedInWorkdir:
  175. case FileStatus.RenamedInIndex:
  176. var renameDetails = entry.HeadToIndexRenameDetails ?? entry.IndexToWorkDirRenameDetails;
  177. changes.Add(renameDetails != null ? new GitChange(renameDetails.NewFilePath, renameDetails.OldFilePath, ChangeKind.Renamed)
  178. : new GitChange(entry.FilePath, "Unknown", ChangeKind.Renamed));
  179. break;
  180. }
  181. }
  182. resolve(changes);
  183. }
  184. catch (Exception ex)
  185. {
  186. reject(ex);
  187. }
  188. }
  189. public static async void CommitAndPushExecutor(Action<string> resolve, Action<Exception> reject, List<GitChange> changesToCommit, string commitMessage, string username, string email, Action<float, string> onProgress)
  190. {
  191. try
  192. {
  193. if (string.IsNullOrWhiteSpace(email))
  194. {
  195. throw new Exception("Author email is missing. Please set your email address in Project Settings > Better Git.");
  196. }
  197. using (var repo = new Repository(ProjectRoot))
  198. {
  199. var remote = repo.Network.Remotes["origin"];
  200. if (remote == null) throw new Exception("No remote named 'origin' found.");
  201. var fetchOptions = new FetchOptions { CertificateCheck = (_, _, _) => true };
  202. Commands.Fetch(repo, remote.Name, Array.Empty<string>(), fetchOptions, "Arbitrator pre-push fetch");
  203. var trackingDetails = repo.Head.TrackingDetails;
  204. if (trackingDetails.BehindBy > 0)
  205. {
  206. throw new Exception($"Push aborted. There are {trackingDetails.BehindBy.Value} incoming changes on the remote. Please pull first.");
  207. }
  208. var pathsToStage = new List<string>();
  209. foreach (var change in changesToCommit)
  210. {
  211. switch (change.Status)
  212. {
  213. case ChangeKind.Deleted:
  214. Commands.Remove(repo, change.FilePath);
  215. break;
  216. case ChangeKind.Renamed:
  217. Commands.Remove(repo, change.OldFilePath);
  218. pathsToStage.Add(change.FilePath);
  219. break;
  220. default:
  221. pathsToStage.Add(change.FilePath);
  222. break;
  223. }
  224. }
  225. if (pathsToStage.Any()) Commands.Stage(repo, pathsToStage);
  226. var status = repo.RetrieveStatus();
  227. if (!status.IsDirty) throw new Exception("No effective changes were staged to commit.");
  228. var author = new Signature(username, email, DateTimeOffset.Now);
  229. repo.Commit(commitMessage, author, author);
  230. }
  231. var progressReporter = new Progress<string>(line => ParseProgress(line, onProgress));
  232. await GitCommand.RunGitAsync(new StringBuilder(), new[] { "push", "--progress" }, progressReporter, 0, 141);
  233. resolve("Successfully committed and pushed changes!");
  234. }
  235. catch (Exception ex)
  236. {
  237. var errorMessage = ex.InnerException?.Message ?? ex.Message;
  238. reject(new Exception(errorMessage));
  239. }
  240. }
  241. private static void ParseProgress(string line, Action<float, string> onProgress)
  242. {
  243. if (onProgress == null || string.IsNullOrWhiteSpace(line)) return;
  244. line = line.Trim();
  245. var parts = line.Split(new[] { ':' }, 2);
  246. if (parts.Length < 2) return;
  247. var action = parts[0];
  248. var progressPart = parts[1];
  249. var percentIndex = progressPart.IndexOf('%');
  250. if (percentIndex == -1) return;
  251. var percentString = progressPart[..percentIndex].Trim();
  252. if (!float.TryParse(percentString, NumberStyles.Any, CultureInfo.InvariantCulture, out var percentage)) return;
  253. var progressValue = percentage / 100.0f;
  254. onProgress(progressValue, $"{action}...");
  255. }
  256. public static void ResetFileExecutor(Action<string> resolve, Action<Exception> reject, GitChange changeToReset)
  257. {
  258. try
  259. {
  260. using var repo = new Repository(ProjectRoot);
  261. switch (changeToReset.Status)
  262. {
  263. case ChangeKind.Added:
  264. {
  265. Commands.Unstage(repo, changeToReset.FilePath);
  266. var fullPath = Path.Combine(ProjectRoot, changeToReset.FilePath);
  267. if (File.Exists(fullPath))
  268. {
  269. File.Delete(fullPath);
  270. }
  271. break;
  272. }
  273. case ChangeKind.Renamed:
  274. {
  275. Commands.Unstage(repo, changeToReset.FilePath);
  276. var newFullPath = Path.Combine(ProjectRoot, changeToReset.FilePath);
  277. if (File.Exists(newFullPath)) File.Delete(newFullPath);
  278. repo.CheckoutPaths(repo.Head.Tip.Sha, new[] { changeToReset.OldFilePath }, new CheckoutOptions { CheckoutModifiers = CheckoutModifiers.Force });
  279. break;
  280. }
  281. default:
  282. repo.CheckoutPaths(repo.Head.Tip.Sha, new[] { changeToReset.FilePath }, new CheckoutOptions { CheckoutModifiers = CheckoutModifiers.Force });
  283. break;
  284. }
  285. resolve($"Successfully reset changes for '{changeToReset.FilePath}'");
  286. }
  287. catch (Exception ex)
  288. {
  289. reject(ex);
  290. }
  291. }
  292. public static async void LaunchExternalDiffExecutor(Action<string> resolve, Action<Exception> reject, GitChange change)
  293. {
  294. string fileAPath = null; // Before
  295. string fileBPath = null; // After
  296. try
  297. {
  298. using var repo = new Repository(ProjectRoot);
  299. string GetFileContentFromHead(string path)
  300. {
  301. var blob = repo.Head.Tip[path]?.Target as Blob;
  302. return blob?.GetContentText() ?? "";
  303. }
  304. string CreateTempFile(string originalPath, string content)
  305. {
  306. var tempPath = Path.Combine(Path.GetTempPath(), Guid.NewGuid() + Path.GetExtension(originalPath));
  307. File.WriteAllText(tempPath, content);
  308. return tempPath;
  309. }
  310. switch (change.Status)
  311. {
  312. case ChangeKind.Added:
  313. fileAPath = CreateTempFile(change.FilePath, "");
  314. fileBPath = Path.Combine(ProjectRoot, change.FilePath);
  315. break;
  316. case ChangeKind.Deleted:
  317. fileAPath = CreateTempFile(change.FilePath, GetFileContentFromHead(change.FilePath));
  318. fileBPath = CreateTempFile(change.FilePath, "");
  319. break;
  320. case ChangeKind.Renamed:
  321. fileAPath = CreateTempFile(change.OldFilePath, GetFileContentFromHead(change.OldFilePath));
  322. fileBPath = Path.Combine(ProjectRoot, change.FilePath);
  323. break;
  324. default: // Modified
  325. fileAPath = CreateTempFile(change.FilePath, GetFileContentFromHead(change.FilePath));
  326. fileBPath = Path.Combine(ProjectRoot, change.FilePath);
  327. break;
  328. }
  329. await GitCommand.RunVsCodeAsync(new StringBuilder(), new[] { "--diff", fileAPath, fileBPath });
  330. resolve("Launched external diff tool.");
  331. }
  332. catch(Win32Exception ex)
  333. {
  334. reject(new Exception("Could not launch VS Code. Ensure it is installed and the 'code' command is available in your system's PATH.", ex));
  335. }
  336. catch(Exception ex)
  337. {
  338. reject(ex);
  339. }
  340. finally
  341. {
  342. try
  343. {
  344. if (fileAPath != null && fileAPath.Contains(Path.GetTempPath()) && File.Exists(fileAPath)) File.Delete(fileAPath);
  345. if (fileBPath != null && fileBPath.Contains(Path.GetTempPath()) && File.Exists(fileBPath)) File.Delete(fileBPath);
  346. }
  347. catch(Exception cleanupEx)
  348. {
  349. Debug.LogError($"Failed to clean up temporary diff files: {cleanupEx.Message}");
  350. }
  351. }
  352. }
  353. public static void FileLevelConflictCheckExecutor(Action<PullAnalysisResult> resolve, Action<Exception> reject)
  354. {
  355. try
  356. {
  357. using var repo = new Repository(ProjectRoot);
  358. var result = AnalyzePullConflictsInternal(repo).Result;
  359. resolve(result);
  360. }
  361. catch (Exception ex)
  362. {
  363. reject(ex);
  364. }
  365. }
  366. private static Task<PullAnalysisResult> AnalyzePullConflictsInternal(Repository repo)
  367. {
  368. var remote = repo.Network.Remotes["origin"];
  369. if (remote == null) throw new Exception("No remote named 'origin' was found.");
  370. Commands.Fetch(repo, remote.Name, Array.Empty<string>(), new FetchOptions { CertificateCheck = (_,_,_) => true }, null);
  371. var localBranch = repo.Head;
  372. var remoteBranch = repo.Head.TrackedBranch;
  373. if (remoteBranch == null) throw new Exception("Current branch is not tracking a remote branch.");
  374. var mergeBase = repo.ObjectDatabase.FindMergeBase(localBranch.Tip, remoteBranch.Tip);
  375. if (mergeBase == null) throw new Exception("Could not find a common ancestor.");
  376. var theirChanges = new HashSet<string>(repo.Diff.Compare<TreeChanges>(mergeBase.Tree, remoteBranch.Tip.Tree).Select(c => c.Path));
  377. var ourChanges = new HashSet<string>(repo.Diff.Compare<TreeChanges>(mergeBase.Tree, localBranch.Tip.Tree).Select(c => c.Path));
  378. foreach (var statusEntry in repo.RetrieveStatus()) ourChanges.Add(statusEntry.FilePath);
  379. return Task.FromResult(new PullAnalysisResult(ourChanges.Where(theirChanges.Contains).ToList()));
  380. }
  381. public static void SafePullExecutor(Action<string> resolve, Action<Exception> reject)
  382. {
  383. try
  384. {
  385. using var repo = new Repository(ProjectRoot);
  386. var signature = new Signature("Better Git Tool", "bettergit@letsterra.com", DateTimeOffset.Now);
  387. var pullOptions = new PullOptions { FetchOptions = new FetchOptions { CertificateCheck = (_,_,_) => true } };
  388. var mergeResult = Commands.Pull(repo, signature, pullOptions);
  389. resolve(mergeResult.Status == MergeStatus.UpToDate ? "Already up-to-date." : $"Pull successful. Status: {mergeResult.Status}");
  390. }
  391. catch (Exception ex)
  392. {
  393. reject(ex);
  394. }
  395. }
  396. public static async void ForcePullExecutor(Action<string> resolve, Action<Exception> reject)
  397. {
  398. var log = new StringBuilder();
  399. var hasStashed = false;
  400. try
  401. {
  402. using (var repo = new Repository(ProjectRoot))
  403. {
  404. if (repo.RetrieveStatus().IsDirty)
  405. {
  406. await GitCommand.RunGitAsync(log, new[] { "stash", "push", "-u", "-m", "BetterGit-WIP-Pull" }, 0, 141);
  407. hasStashed = true;
  408. }
  409. }
  410. await GitCommand.RunGitAsync(log, new[] { "pull", "--no-rebase" }, 0, 1, 141);
  411. if (hasStashed)
  412. {
  413. await GitCommand.RunGitAsync(log, new[] { "stash", "pop" }, 0, 1, 141);
  414. await GitCommand.RunGitAsync(log, new[] { "stash", "drop" }, 0, 141);
  415. }
  416. resolve(log.ToString());
  417. }
  418. catch (Exception ex)
  419. {
  420. if (hasStashed)
  421. {
  422. try
  423. {
  424. await GitCommand.RunGitAsync(new StringBuilder(), new[] { "stash", "pop" }, 0, 1, 141);
  425. }
  426. catch (Exception exception)
  427. {
  428. log.AppendLine($"Fatal Error trying to pop stash after a failed pull: {exception.Message}");
  429. }
  430. }
  431. log.AppendLine("\n--- PULL FAILED ---");
  432. log.AppendLine(ex.ToString());
  433. reject(new Exception(log.ToString()));
  434. }
  435. }
  436. public static async void LaunchMergeToolExecutor(Action<string> resolve, Action<Exception> reject, GitChange change)
  437. {
  438. try
  439. {
  440. if (change.FilePath == null)
  441. {
  442. reject(new Exception("Could not find file path."));
  443. return;
  444. }
  445. var fileExtension = Path.GetExtension(change.FilePath).ToLower();
  446. if (fileExtension is ".prefab" or ".unity")
  447. {
  448. reject(new Exception("Cannot auto-resolve conflicts for binary files. Please use an external merge tool."));
  449. return;
  450. }
  451. await GitCommand.RunVsCodeAsync(new StringBuilder(), new[] { "--wait", change.FilePath }, 0, 141);
  452. var fullPath = Path.Combine(ProjectRoot, change.FilePath);
  453. var fileContent = await File.ReadAllTextAsync(fullPath);
  454. if (fileContent.Contains("<<<<<<<"))
  455. {
  456. resolve($"Conflict in '{change.FilePath}' was not resolved. Please try again.");
  457. return;
  458. }
  459. await GitCommand.RunGitAsync(new StringBuilder(), new[] { "add", change.FilePath });
  460. await GitCommand.RunGitAsync(new StringBuilder(), new[] { "reset", "HEAD", change.FilePath });
  461. resolve($"Successfully resolved conflict in '{change.FilePath}'. The file is now modified and ready for review.");
  462. }
  463. catch (Win32Exception ex)
  464. {
  465. reject(new Exception("Could not launch VS Code. Ensure it is installed and the 'code' command is available in your system's PATH.", ex));
  466. }
  467. catch (Exception ex)
  468. {
  469. reject(ex);
  470. }
  471. }
  472. public static async void UnstageAllFilesIfSafeExecutor(Action<bool> resolve, Action<Exception> reject)
  473. {
  474. try
  475. {
  476. using var repo = new Repository(ProjectRoot);
  477. if (repo.Index.Conflicts.Any())
  478. {
  479. resolve(false);
  480. return;
  481. }
  482. var stagedFiles = repo.RetrieveStatus().Count(s => s.State is
  483. FileStatus.NewInIndex or
  484. FileStatus.ModifiedInIndex or
  485. FileStatus.DeletedFromIndex or
  486. FileStatus.RenamedInIndex or
  487. FileStatus.TypeChangeInIndex);
  488. if (stagedFiles == 0)
  489. {
  490. resolve(false);
  491. return;
  492. }
  493. await GitCommand.RunGitAsync(new StringBuilder(), new[] { "reset" });
  494. resolve(true);
  495. }
  496. catch (Exception ex)
  497. {
  498. reject(ex);
  499. }
  500. }
  501. public static async void ResetAllChangesExecutor(Action<string> resolve, Action<Exception> reject)
  502. {
  503. try
  504. {
  505. var log = new StringBuilder();
  506. await GitCommand.RunGitAsync(log, new[] { "reset", "--hard", "HEAD" });
  507. await GitCommand.RunGitAsync(log, new[] { "clean", "-fd" });
  508. resolve("Successfully discarded all local changes.");
  509. }
  510. catch (Exception ex)
  511. {
  512. reject(ex);
  513. }
  514. }
  515. }
  516. }