GitExecutors.cs 24 KB

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