GitExecutors.cs 24 KB

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