GitExecutors.cs 25 KB

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