GitExecutors.cs 21 KB

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