GitExecutors.cs 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924
  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 const string StashMessage = "Better Git Stash";
  40. private static string GetAuthenticatedRemoteUrl()
  41. {
  42. var authUsername = BetterGitSettings.AuthUsername;
  43. var authPassword = BetterGitSettings.AuthPassword;
  44. if (string.IsNullOrEmpty(authUsername) || string.IsNullOrEmpty(authPassword))
  45. {
  46. return "origin";
  47. }
  48. using var repo = new Repository(ProjectRoot);
  49. var remote = repo.Network.Remotes["origin"];
  50. if (remote == null) throw new Exception("No remote named 'origin' found.");
  51. var originalUrl = remote.Url;
  52. var authenticatedUrl = Regex.Replace(originalUrl,
  53. "://",
  54. $"://{Uri.EscapeDataString(authUsername)}:{Uri.EscapeDataString(authPassword)}@");
  55. return authenticatedUrl;
  56. }
  57. public static void HasStashExecutor(Action<bool> resolve, Action<Exception> reject)
  58. {
  59. try
  60. {
  61. using var repo = new Repository(ProjectRoot);
  62. var stashExists = repo.Stashes.Any(s => s.Message.Contains(StashMessage));
  63. resolve(stashExists);
  64. }
  65. catch (Exception ex)
  66. {
  67. reject(ex);
  68. }
  69. }
  70. public static async void CreateOrOverwriteStashExecutor(Action<string> resolve, Action<Exception> reject, List<GitChange> changes)
  71. {
  72. try
  73. {
  74. var log = new StringBuilder();
  75. using (var repo = new Repository(ProjectRoot))
  76. {
  77. var existingStash = repo.Stashes.FirstOrDefault(s => s.Message.Contains(StashMessage));
  78. if (existingStash != null)
  79. {
  80. repo.Stashes.Remove(repo.Stashes.ToList().IndexOf(existingStash));
  81. log.AppendLine("Dropped existing 'Better Git Stash'.");
  82. }
  83. }
  84. var untrackedFiles = new List<string>();
  85. using (var repo = new Repository(ProjectRoot))
  86. {
  87. foreach (var change in changes)
  88. {
  89. var statusEntry = repo.RetrieveStatus(change.FilePath);
  90. if (statusEntry == FileStatus.NewInWorkdir)
  91. {
  92. untrackedFiles.Add(change.FilePath);
  93. }
  94. }
  95. }
  96. if (untrackedFiles.Any())
  97. {
  98. foreach (var file in untrackedFiles)
  99. {
  100. await GitCommand.RunGitAsync(log, new[] { "add", file });
  101. }
  102. log.AppendLine($"Staged {untrackedFiles.Count} untracked files.");
  103. }
  104. var allFiles = changes.Select(c => c.FilePath).ToList();
  105. if (allFiles.Any())
  106. {
  107. var stashArgs = new List<string> { "stash", "push", "-m", StashMessage, "--" };
  108. stashArgs.AddRange(allFiles);
  109. await GitCommand.RunGitAsync(log, stashArgs.ToArray());
  110. }
  111. else
  112. {
  113. throw new Exception("No files to stash.");
  114. }
  115. resolve("Successfully created new 'Better Git Stash'.");
  116. }
  117. catch (Exception ex)
  118. {
  119. Debug.LogException(ex);
  120. reject(ex);
  121. }
  122. }
  123. public static void DropStashExecutor(Action<string> resolve, Action<Exception> reject)
  124. {
  125. try
  126. {
  127. using var repo = new Repository(ProjectRoot);
  128. var stash = repo.Stashes.FirstOrDefault(s => s.Message.Contains(StashMessage));
  129. if (stash != null)
  130. {
  131. repo.Stashes.Remove(repo.Stashes.ToList().IndexOf(stash));
  132. resolve("'Better Git Stash' has been discarded.");
  133. }
  134. else
  135. {
  136. resolve("No 'Better Git Stash' found to discard.");
  137. }
  138. }
  139. catch (Exception ex)
  140. {
  141. reject(ex);
  142. }
  143. }
  144. public static void GetStashedFilesExecutor(Action<List<GitChange>> resolve, Action<Exception> reject)
  145. {
  146. try
  147. {
  148. using var repo = new Repository(ProjectRoot);
  149. var stash = repo.Stashes.FirstOrDefault(s => s.Message.Contains(StashMessage));
  150. if (stash == null)
  151. {
  152. resolve(new List<GitChange>());
  153. return;
  154. }
  155. var changes = new List<GitChange>();
  156. var stashChanges = repo.Diff.Compare<TreeChanges>(stash.Base.Tree, stash.WorkTree.Tree);
  157. foreach (var change in stashChanges)
  158. {
  159. changes.Add(new GitChange(change.Path, change.OldPath, change.Status));
  160. }
  161. var indexChanges = repo.Diff.Compare<TreeChanges>(stash.Base.Tree, stash.Index.Tree);
  162. foreach (var change in indexChanges)
  163. {
  164. if (changes.All(c => c.FilePath != change.Path))
  165. {
  166. changes.Add(new GitChange(change.Path, change.OldPath, change.Status));
  167. }
  168. }
  169. resolve(changes);
  170. }
  171. catch(Exception ex)
  172. {
  173. reject(ex);
  174. }
  175. }
  176. public static async void DiffStashedFileExecutor(Action<string> resolve, Action<Exception> reject, GitChange change)
  177. {
  178. string fileAPath = null;
  179. string fileBPath = null;
  180. try
  181. {
  182. using var repo = new Repository(ProjectRoot);
  183. var stash = repo.Stashes.FirstOrDefault(s => s.Message.Contains(StashMessage));
  184. if (stash == null) throw new Exception("'Better Git Stash' not found.");
  185. var stashedTree = stash.WorkTree.Tree;
  186. var baseTree = stash.Base.Tree;
  187. switch (change.Status)
  188. {
  189. case ChangeKind.Added:
  190. fileAPath = CreateTempFileWithContent("", "empty");
  191. fileBPath = CreateTempFileFromBlob(stashedTree[change.FilePath]?.Target as Blob, change.FilePath);
  192. break;
  193. case ChangeKind.Deleted:
  194. fileAPath = CreateTempFileFromBlob(baseTree[change.FilePath]?.Target as Blob, change.FilePath);
  195. fileBPath = CreateTempFileWithContent("", change.FilePath);
  196. break;
  197. case ChangeKind.Renamed:
  198. fileAPath = CreateTempFileFromBlob(baseTree[change.OldFilePath]?.Target as Blob, change.OldFilePath);
  199. fileBPath = Path.Combine(ProjectRoot, change.FilePath);
  200. break;
  201. default:
  202. fileAPath = CreateTempFileFromBlob(stashedTree[change.FilePath]?.Target as Blob, change.FilePath);
  203. fileBPath = Path.Combine(ProjectRoot, change.FilePath);
  204. break;
  205. }
  206. if (!File.Exists(fileBPath))
  207. {
  208. fileBPath = CreateTempFileWithContent("", Path.GetFileName(fileBPath));
  209. }
  210. await GitCommand.RunVsCodeAsync(new StringBuilder(), new[] { "--diff", fileAPath, fileBPath });
  211. resolve("Launched external diff tool.");
  212. }
  213. catch (Exception ex)
  214. {
  215. reject(ex);
  216. }
  217. finally
  218. {
  219. if (fileAPath != null && fileAPath.Contains(Path.GetTempPath())) File.Delete(fileAPath);
  220. if (fileBPath != null && fileBPath.Contains(Path.GetTempPath())) File.Delete(fileBPath);
  221. }
  222. }
  223. public static void AnalyzeStashConflictsExecutor(Action<PullAnalysisResult> resolve, Action<Exception> reject)
  224. {
  225. try
  226. {
  227. using var repo = new Repository(ProjectRoot);
  228. var stash = repo.Stashes.FirstOrDefault(s => s.Message.Contains(StashMessage));
  229. if (stash == null)
  230. {
  231. resolve(new PullAnalysisResult(new List<string>()));
  232. return;
  233. }
  234. var workTreeChanges = repo.Diff.Compare<TreeChanges>(stash.Base.Tree, stash.WorkTree.Tree).Select(c => c.Path);
  235. var indexChanges = repo.Diff.Compare<TreeChanges>(stash.Base.Tree, stash.Index.Tree).Select(c => c.Path);
  236. var stashedChanges = new HashSet<string>(workTreeChanges.Union(indexChanges));
  237. var localChanges = new HashSet<string>(repo.RetrieveStatus().Where(s => s.State != FileStatus.Ignored).Select(s => s.FilePath));
  238. var conflictingFiles = stashedChanges.Intersect(localChanges).ToList();
  239. resolve(new PullAnalysisResult(conflictingFiles));
  240. }
  241. catch (Exception ex)
  242. {
  243. reject(ex);
  244. }
  245. }
  246. public static async void ApplyStashAndOverwriteExecutor(Action<string> resolve, Action<Exception> reject, List<GitChange> resolutions)
  247. {
  248. var tempFiles = new Dictionary<string, string>();
  249. var log = new StringBuilder();
  250. try
  251. {
  252. foreach (var resolution in resolutions.Where(r => r.Resolution == GitChange.ConflictResolution.Mine))
  253. {
  254. var fullPath = Path.Combine(ProjectRoot, resolution.FilePath);
  255. if (File.Exists(fullPath))
  256. {
  257. var tempPath = Path.GetTempFileName();
  258. File.Copy(fullPath, tempPath, true);
  259. tempFiles[resolution.FilePath] = tempPath;
  260. }
  261. }
  262. using (var repo = new Repository(ProjectRoot))
  263. {
  264. var filesToReset = resolutions.Where(r => r.Resolution != GitChange.ConflictResolution.None).Select(r => r.FilePath).ToArray();
  265. if (filesToReset.Any())
  266. {
  267. repo.CheckoutPaths(repo.Head.Tip.Sha, filesToReset, new CheckoutOptions { CheckoutModifiers = CheckoutModifiers.Force });
  268. }
  269. }
  270. await GitCommand.RunGitAsync(log, new[] { "stash", "apply" });
  271. foreach (var entry in tempFiles)
  272. {
  273. var finalPath = Path.Combine(ProjectRoot, entry.Key);
  274. File.Copy(entry.Value, finalPath, true);
  275. await GitCommand.RunGitAsync(log, new[] { "add", entry.Key });
  276. }
  277. await GitCommand.RunGitAsync(log, new[] { "stash", "drop" });
  278. resolve("Stash applied successfully and has been dropped.");
  279. }
  280. catch (Exception ex)
  281. {
  282. reject(new Exception($"Failed to apply stash. You may need to resolve conflicts manually. Details: {ex.Message}"));
  283. }
  284. finally
  285. {
  286. foreach (var tempFile in tempFiles.Values.Where(File.Exists))
  287. {
  288. File.Delete(tempFile);
  289. }
  290. }
  291. }
  292. public static void GetBranchDataExecutor(Action<BranchData> resolve, Action<Exception> reject)
  293. {
  294. try
  295. {
  296. using var repo = new Repository(ProjectRoot);
  297. var data = new BranchData
  298. {
  299. CurrentBranch = repo.Head.FriendlyName,
  300. AllBranches = repo.Branches
  301. .Where(b => !b.FriendlyName.Contains("HEAD"))
  302. .Select(b => b.FriendlyName.Replace("origin/", ""))
  303. .Distinct()
  304. .OrderBy(name => name)
  305. .ToList()
  306. };
  307. resolve(data);
  308. }
  309. catch(Exception ex)
  310. {
  311. reject(ex);
  312. }
  313. }
  314. public static async void SwitchBranchExecutor(Action<string> resolve, Action<Exception> reject, string branchName)
  315. {
  316. try
  317. {
  318. var log = new StringBuilder();
  319. await GitCommand.RunGitAsync(log, new[] { "checkout", branchName });
  320. resolve($"Successfully switched to branch '{branchName}'.");
  321. }
  322. catch (Exception ex)
  323. {
  324. reject(ex);
  325. }
  326. }
  327. public static async void ResetAndSwitchBranchExecutor(Action<string> resolve, Action<Exception> reject, string branchName)
  328. {
  329. try
  330. {
  331. var log = new StringBuilder();
  332. await GitCommand.RunGitAsync(log, new[] { "reset", "--hard", "HEAD" });
  333. await GitCommand.RunGitAsync(log, new[] { "clean", "-fd" });
  334. await GitCommand.RunGitAsync(log, new[] { "checkout", branchName });
  335. resolve($"Discarded local changes and switched to branch '{branchName}'.");
  336. }
  337. catch (Exception ex)
  338. {
  339. reject(ex);
  340. }
  341. }
  342. /// <summary>
  343. /// Synchronous helper to get a GitChange object for a single file.
  344. /// This is public so it can be called by the GitService wrapper.
  345. /// </summary>
  346. public static GitChange GetChangeForFile(string filePath)
  347. {
  348. try
  349. {
  350. using var repo = new Repository(ProjectRoot);
  351. if (repo.Index.Conflicts.Any(c => c.Ours.Path == filePath))
  352. {
  353. return new GitChange(filePath, null, ChangeKind.Conflicted);
  354. }
  355. var statusEntry = repo.RetrieveStatus(filePath);
  356. return statusEntry switch
  357. {
  358. FileStatus.NewInWorkdir or FileStatus.NewInIndex => new GitChange(filePath, null, ChangeKind.Added),
  359. FileStatus.ModifiedInWorkdir or FileStatus.ModifiedInIndex => new GitChange(filePath, null, ChangeKind.Modified),
  360. FileStatus.DeletedFromWorkdir or FileStatus.DeletedFromIndex => new GitChange(filePath, null, ChangeKind.Deleted),
  361. FileStatus.RenamedInWorkdir or FileStatus.RenamedInIndex =>
  362. new GitChange(filePath, null, ChangeKind.Renamed),
  363. _ => null
  364. };
  365. }
  366. catch { return null; } // Suppress errors if repo is in a unique state
  367. }
  368. // --- Promise Executor Implementations ---
  369. public static async void GetUpstreamAheadByExecutor(Action<int?> resolve, Action<Exception> reject, Action<float, string> onProgress)
  370. {
  371. try
  372. {
  373. string refSpec;
  374. using (var tempRepo = new Repository(ProjectRoot))
  375. {
  376. var currentBranch = tempRepo.Head;
  377. if (currentBranch.TrackedBranch == null)
  378. {
  379. resolve(0);
  380. return;
  381. }
  382. var branchName = currentBranch.FriendlyName;
  383. var remoteName = currentBranch.TrackedBranch.RemoteName;
  384. refSpec = $"{branchName}:refs/remotes/{remoteName}/{branchName}";
  385. }
  386. var authenticatedUrl = GetAuthenticatedRemoteUrl();
  387. var progressReporter = new Progress<string>(line => ParseProgress(line, onProgress));
  388. await GitCommand.RunGitAsync(new StringBuilder(), new[] { "fetch", authenticatedUrl, refSpec, "--progress" }, progressReporter);
  389. using var repo = new Repository(ProjectRoot);
  390. resolve(repo.Head.TrackingDetails.BehindBy);
  391. }
  392. catch (Exception ex)
  393. {
  394. if (ex.Message.Contains("is not tracking a remote branch"))
  395. {
  396. resolve(null);
  397. }
  398. else
  399. {
  400. reject(ex);
  401. }
  402. }
  403. }
  404. public static void GetLocalStatusExecutor(Action<List<GitChange>> resolve, Action<Exception> reject)
  405. {
  406. try
  407. {
  408. var changes = new List<GitChange>();
  409. using var repo = new Repository(ProjectRoot);
  410. var conflictedPaths = new HashSet<string>(repo.Index.Conflicts.Select(c => c.Ours.Path));
  411. var statusOptions = new StatusOptions
  412. {
  413. IncludeUntracked = true,
  414. RecurseUntrackedDirs = true,
  415. DetectRenamesInIndex = true,
  416. DetectRenamesInWorkDir = true,
  417. IncludeIgnored = false,
  418. IncludeUnaltered = false
  419. };
  420. foreach (var entry in repo.RetrieveStatus(statusOptions))
  421. {
  422. if (conflictedPaths.Contains(entry.FilePath))
  423. {
  424. if (changes.All(c => c.FilePath != entry.FilePath))
  425. {
  426. changes.Add(new GitChange(entry.FilePath, null, ChangeKind.Conflicted));
  427. }
  428. continue;
  429. }
  430. switch(entry.State)
  431. {
  432. case FileStatus.ModifiedInWorkdir | FileStatus.RenamedInWorkdir:
  433. changes.Add(new GitChange(entry.FilePath, null, ChangeKind.Modified));
  434. break;
  435. case FileStatus.NewInWorkdir:
  436. case FileStatus.NewInIndex:
  437. changes.Add(new GitChange(entry.FilePath, null, ChangeKind.Added));
  438. break;
  439. case FileStatus.ModifiedInWorkdir:
  440. case FileStatus.ModifiedInIndex:
  441. changes.Add(new GitChange(entry.FilePath, null, ChangeKind.Modified));
  442. break;
  443. case FileStatus.DeletedFromWorkdir:
  444. case FileStatus.DeletedFromIndex:
  445. changes.Add(new GitChange(entry.FilePath, null, ChangeKind.Deleted));
  446. break;
  447. case FileStatus.RenamedInWorkdir:
  448. case FileStatus.RenamedInIndex:
  449. var renameDetails = entry.HeadToIndexRenameDetails ?? entry.IndexToWorkDirRenameDetails;
  450. changes.Add(renameDetails != null ? new GitChange(renameDetails.NewFilePath, renameDetails.OldFilePath, ChangeKind.Renamed)
  451. : new GitChange(entry.FilePath, "Unknown", ChangeKind.Renamed));
  452. break;
  453. }
  454. }
  455. resolve(changes);
  456. }
  457. catch (Exception ex)
  458. {
  459. reject(ex);
  460. }
  461. }
  462. public static async void CommitAndPushExecutor(Action<string> resolve, Action<Exception> reject, List<GitChange> changesToCommit, string commitMessage, string username, string email, Action<float, string> onProgress)
  463. {
  464. try
  465. {
  466. if (string.IsNullOrWhiteSpace(email))
  467. {
  468. throw new Exception("Author email is missing. Please set your email address in Project Settings > Better Git.");
  469. }
  470. var authenticatedUrl = GetAuthenticatedRemoteUrl();
  471. await GitCommand.RunGitAsync(new StringBuilder(), new[] { "fetch", authenticatedUrl });
  472. using (var repo = new Repository(ProjectRoot))
  473. {
  474. var remote = repo.Network.Remotes["origin"];
  475. if (remote == null) throw new Exception("No remote named 'origin' found.");
  476. var trackingDetails = repo.Head.TrackingDetails;
  477. if (trackingDetails.BehindBy > 0)
  478. {
  479. throw new Exception($"Push aborted. There are {trackingDetails.BehindBy.Value} incoming changes on the remote. Please pull first.");
  480. }
  481. var pathsToStage = new List<string>();
  482. foreach (var change in changesToCommit)
  483. {
  484. switch (change.Status)
  485. {
  486. case ChangeKind.Deleted:
  487. Commands.Remove(repo, change.FilePath);
  488. break;
  489. case ChangeKind.Renamed:
  490. Commands.Remove(repo, change.OldFilePath);
  491. pathsToStage.Add(change.FilePath);
  492. break;
  493. default:
  494. pathsToStage.Add(change.FilePath);
  495. break;
  496. }
  497. }
  498. if (pathsToStage.Any()) Commands.Stage(repo, pathsToStage);
  499. var status = repo.RetrieveStatus();
  500. if (!status.IsDirty) throw new Exception("No effective changes were staged to commit.");
  501. var author = new Signature(username, email, DateTimeOffset.Now);
  502. repo.Commit(commitMessage, author, author);
  503. }
  504. var progressReporter = new Progress<string>(line => ParseProgress(line, onProgress));
  505. using var tempRepo = new Repository(ProjectRoot);
  506. var currentBranch = tempRepo.Head.FriendlyName;
  507. await GitCommand.RunGitAsync(new StringBuilder(), new[] { "push", "--progress", authenticatedUrl, $"HEAD:{currentBranch}" }, progressReporter, 0, 141);
  508. resolve("Successfully committed and pushed changes!");
  509. }
  510. catch (Exception ex)
  511. {
  512. var errorMessage = ex.InnerException?.Message ?? ex.Message;
  513. reject(new Exception(errorMessage));
  514. }
  515. }
  516. private static void ParseProgress(string line, Action<float, string> onProgress)
  517. {
  518. if (onProgress == null || string.IsNullOrWhiteSpace(line)) return;
  519. line = line.Trim();
  520. var parts = line.Split(new[] { ':' }, 2);
  521. if (parts.Length < 2) return;
  522. var action = parts[0];
  523. var progressPart = parts[1];
  524. var percentIndex = progressPart.IndexOf('%');
  525. if (percentIndex == -1) return;
  526. var percentString = progressPart[..percentIndex].Trim();
  527. if (!float.TryParse(percentString, NumberStyles.Any, CultureInfo.InvariantCulture, out var percentage)) return;
  528. var progressValue = percentage / 100.0f;
  529. onProgress(progressValue, $"{action}...");
  530. }
  531. public static void ResetFileExecutor(Action<string> resolve, Action<Exception> reject, GitChange changeToReset)
  532. {
  533. try
  534. {
  535. using var repo = new Repository(ProjectRoot);
  536. switch (changeToReset.Status)
  537. {
  538. case ChangeKind.Added:
  539. {
  540. Commands.Unstage(repo, changeToReset.FilePath);
  541. var fullPath = Path.Combine(ProjectRoot, changeToReset.FilePath);
  542. if (File.Exists(fullPath))
  543. {
  544. File.Delete(fullPath);
  545. }
  546. break;
  547. }
  548. case ChangeKind.Renamed:
  549. {
  550. Commands.Unstage(repo, changeToReset.FilePath);
  551. var newFullPath = Path.Combine(ProjectRoot, changeToReset.FilePath);
  552. if (File.Exists(newFullPath)) File.Delete(newFullPath);
  553. repo.CheckoutPaths(repo.Head.Tip.Sha, new[] { changeToReset.OldFilePath }, new CheckoutOptions { CheckoutModifiers = CheckoutModifiers.Force });
  554. break;
  555. }
  556. default:
  557. repo.CheckoutPaths(repo.Head.Tip.Sha, new[] { changeToReset.FilePath }, new CheckoutOptions { CheckoutModifiers = CheckoutModifiers.Force });
  558. break;
  559. }
  560. resolve($"Successfully reset changes for '{changeToReset.FilePath}'");
  561. }
  562. catch (Exception ex)
  563. {
  564. reject(ex);
  565. }
  566. }
  567. public static async void LaunchExternalDiffExecutor(Action<string> resolve, Action<Exception> reject, GitChange change)
  568. {
  569. string fileAPath = null; // Before
  570. string fileBPath = null; // After
  571. try
  572. {
  573. using var repo = new Repository(ProjectRoot);
  574. string GetFileContentFromHead(string path)
  575. {
  576. var blob = repo.Head.Tip[path]?.Target as Blob;
  577. return blob?.GetContentText() ?? "";
  578. }
  579. string CreateTempFile(string originalPath, string content)
  580. {
  581. var tempPath = Path.Combine(Path.GetTempPath(), Guid.NewGuid() + Path.GetExtension(originalPath));
  582. File.WriteAllText(tempPath, content);
  583. return tempPath;
  584. }
  585. switch (change.Status)
  586. {
  587. case ChangeKind.Added:
  588. fileAPath = CreateTempFile(change.FilePath, "");
  589. fileBPath = Path.Combine(ProjectRoot, change.FilePath);
  590. break;
  591. case ChangeKind.Deleted:
  592. fileAPath = CreateTempFile(change.FilePath, GetFileContentFromHead(change.FilePath));
  593. fileBPath = CreateTempFile(change.FilePath, "");
  594. break;
  595. case ChangeKind.Renamed:
  596. fileAPath = CreateTempFile(change.OldFilePath, GetFileContentFromHead(change.OldFilePath));
  597. fileBPath = Path.Combine(ProjectRoot, change.FilePath);
  598. break;
  599. default: // Modified
  600. fileAPath = CreateTempFile(change.FilePath, GetFileContentFromHead(change.FilePath));
  601. fileBPath = Path.Combine(ProjectRoot, change.FilePath);
  602. break;
  603. }
  604. await GitCommand.RunVsCodeAsync(new StringBuilder(), new[] { "--diff", fileAPath, fileBPath });
  605. resolve("Launched external diff tool.");
  606. }
  607. catch(Win32Exception ex)
  608. {
  609. reject(new Exception("Could not launch VS Code. Ensure it is installed and the 'code' command is available in your system's PATH.", ex));
  610. }
  611. catch(Exception ex)
  612. {
  613. reject(ex);
  614. }
  615. finally
  616. {
  617. try
  618. {
  619. if (fileAPath != null && fileAPath.Contains(Path.GetTempPath()) && File.Exists(fileAPath)) File.Delete(fileAPath);
  620. if (fileBPath != null && fileBPath.Contains(Path.GetTempPath()) && File.Exists(fileBPath)) File.Delete(fileBPath);
  621. }
  622. catch(Exception cleanupEx)
  623. {
  624. Debug.LogError($"Failed to clean up temporary diff files: {cleanupEx.Message}");
  625. }
  626. }
  627. }
  628. public static void FileLevelConflictCheckExecutor(Action<PullAnalysisResult> resolve, Action<Exception> reject)
  629. {
  630. try
  631. {
  632. using var repo = new Repository(ProjectRoot);
  633. var result = AnalyzePullConflictsInternal(repo).Result;
  634. resolve(result);
  635. }
  636. catch (Exception ex)
  637. {
  638. reject(ex);
  639. }
  640. }
  641. private static Task<PullAnalysisResult> AnalyzePullConflictsInternal(Repository repo)
  642. {
  643. var remote = repo.Network.Remotes["origin"];
  644. if (remote == null) throw new Exception("No remote named 'origin' was found.");
  645. var localBranch = repo.Head;
  646. var remoteBranch = repo.Head.TrackedBranch;
  647. if (remoteBranch == null) throw new Exception("Current branch is not tracking a remote branch.");
  648. var mergeBase = repo.ObjectDatabase.FindMergeBase(localBranch.Tip, remoteBranch.Tip);
  649. if (mergeBase == null) throw new Exception("Could not find a common ancestor.");
  650. var theirChanges = new HashSet<string>(repo.Diff.Compare<TreeChanges>(mergeBase.Tree, remoteBranch.Tip.Tree).Select(c => c.Path));
  651. var ourChanges = new HashSet<string>(repo.Diff.Compare<TreeChanges>(mergeBase.Tree, localBranch.Tip.Tree).Select(c => c.Path));
  652. foreach (var statusEntry in repo.RetrieveStatus()) ourChanges.Add(statusEntry.FilePath);
  653. return Task.FromResult(new PullAnalysisResult(ourChanges.Where(theirChanges.Contains).ToList()));
  654. }
  655. public static async void SafePullExecutor(Action<string> resolve, Action<Exception> reject)
  656. {
  657. try
  658. {
  659. var authenticatedUrl = GetAuthenticatedRemoteUrl();
  660. var log = new StringBuilder();
  661. string currentBranchName;
  662. using (var repo = new Repository(ProjectRoot))
  663. {
  664. currentBranchName = repo.Head.FriendlyName;
  665. }
  666. await GitCommand.RunGitAsync(log, new[] { "pull", "--no-rebase", authenticatedUrl, currentBranchName }, 0, 141);
  667. resolve(log.ToString());
  668. }
  669. catch (Exception ex)
  670. {
  671. reject(ex);
  672. }
  673. }
  674. public static async void PullAndOverwriteExecutor(Action<string> resolve, Action<Exception> reject, List<GitChange> resolutions)
  675. {
  676. var tempFiles = new Dictionary<string, string>();
  677. var log = new StringBuilder();
  678. try
  679. {
  680. foreach (var resolution in resolutions.Where(r => r.Resolution == GitChange.ConflictResolution.Mine))
  681. {
  682. var fullPath = Path.Combine(ProjectRoot, resolution.FilePath);
  683. var tempPath = Path.GetTempFileName();
  684. File.Copy(fullPath, tempPath, true);
  685. tempFiles[resolution.FilePath] = tempPath;
  686. }
  687. using (var repo = new Repository(ProjectRoot))
  688. {
  689. var filesToReset = resolutions.Where(r => r.Resolution != GitChange.ConflictResolution.None).Select(r => r.FilePath).ToArray();
  690. if(filesToReset.Length > 0)
  691. {
  692. repo.CheckoutPaths(repo.Head.Tip.Sha, filesToReset, new CheckoutOptions { CheckoutModifiers = CheckoutModifiers.Force });
  693. }
  694. }
  695. await GitCommand.RunGitAsync(log, new[] { "pull", "--no-rebase" }, 0, 1, 141);
  696. foreach (var entry in tempFiles)
  697. {
  698. var finalPath = Path.Combine(ProjectRoot, entry.Key);
  699. File.Copy(entry.Value, finalPath, true);
  700. await GitCommand.RunGitAsync(log, new[] { "add", entry.Key });
  701. }
  702. var unresolvedFiles = resolutions.Where(r => r.Resolution == GitChange.ConflictResolution.None).ToList();
  703. if (unresolvedFiles.Any())
  704. {
  705. var fileList = string.Join(", ", unresolvedFiles.Select(f => f.FilePath));
  706. resolve($"Pull completed with unresolved conflicts in: {fileList}. Please resolve them manually.");
  707. }
  708. else
  709. {
  710. resolve("Pull successful. Your chosen local changes have been preserved.");
  711. }
  712. }
  713. catch (Exception ex)
  714. {
  715. reject(ex);
  716. }
  717. finally
  718. {
  719. foreach (var tempFile in tempFiles.Values.Where(File.Exists))
  720. {
  721. File.Delete(tempFile);
  722. }
  723. }
  724. }
  725. public static async void LaunchMergeToolExecutor(Action<string> resolve, Action<Exception> reject, GitChange change)
  726. {
  727. try
  728. {
  729. if (change.FilePath == null)
  730. {
  731. reject(new Exception("Could not find file path."));
  732. return;
  733. }
  734. var fileExtension = Path.GetExtension(change.FilePath).ToLower();
  735. if (fileExtension is ".prefab" or ".unity")
  736. {
  737. reject(new Exception("Cannot auto-resolve conflicts for binary files. Please use an external merge tool."));
  738. return;
  739. }
  740. await GitCommand.RunVsCodeAsync(new StringBuilder(), new[] { "--wait", change.FilePath }, 0, 141);
  741. var fullPath = Path.Combine(ProjectRoot, change.FilePath);
  742. var fileContent = await File.ReadAllTextAsync(fullPath);
  743. if (fileContent.Contains("<<<<<<<"))
  744. {
  745. resolve($"Conflict in '{change.FilePath}' was not resolved. Please try again.");
  746. return;
  747. }
  748. await GitCommand.RunGitAsync(new StringBuilder(), new[] { "add", change.FilePath });
  749. await GitCommand.RunGitAsync(new StringBuilder(), new[] { "reset", "HEAD", change.FilePath });
  750. resolve($"Successfully resolved conflict in '{change.FilePath}'. The file is now modified and ready for review.");
  751. }
  752. catch (Win32Exception ex)
  753. {
  754. reject(new Exception("Could not launch VS Code. Ensure it is installed and the 'code' command is available in your system's PATH.", ex));
  755. }
  756. catch (Exception ex)
  757. {
  758. reject(ex);
  759. }
  760. }
  761. public static async void UnstageAllFilesIfSafeExecutor(Action<bool> resolve, Action<Exception> reject)
  762. {
  763. try
  764. {
  765. using var repo = new Repository(ProjectRoot);
  766. if (repo.Index.Conflicts.Any())
  767. {
  768. resolve(false);
  769. return;
  770. }
  771. var stagedFiles = repo.RetrieveStatus().Count(s => s.State is
  772. FileStatus.NewInIndex or
  773. FileStatus.ModifiedInIndex or
  774. FileStatus.DeletedFromIndex or
  775. FileStatus.RenamedInIndex or
  776. FileStatus.TypeChangeInIndex);
  777. if (stagedFiles == 0)
  778. {
  779. resolve(false);
  780. return;
  781. }
  782. await GitCommand.RunGitAsync(new StringBuilder(), new[] { "reset" });
  783. resolve(true);
  784. }
  785. catch (Exception ex)
  786. {
  787. reject(ex);
  788. }
  789. }
  790. private static string CreateTempFileFromBlob(Blob blob, string fallbackFileName)
  791. {
  792. var content = blob?.GetContentText() ?? "";
  793. return CreateTempFileWithContent(content, fallbackFileName);
  794. }
  795. private static string CreateTempFileWithContent(string content, string originalFileName)
  796. {
  797. var tempFileName = $"{Path.GetFileName(originalFileName)}-{Path.GetRandomFileName()}";
  798. var tempPath = Path.Combine(Path.GetTempPath(), tempFileName);
  799. File.WriteAllText(tempPath, content);
  800. return tempPath;
  801. }
  802. }
  803. }