GitCommand.cs 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114
  1. // Copyright (c) 2025 TerraByte Inc.
  2. //
  3. // A new helper class that abstracts away the boilerplate of running external
  4. // command-line processes, specifically Git and VS Code, using CliWrap.
  5. using System;
  6. using CliWrap;
  7. using System.IO;
  8. using System.Linq;
  9. using UnityEngine;
  10. using System.Text;
  11. using UnityEngine.Scripting;
  12. using System.Threading.Tasks;
  13. using System.Runtime.InteropServices;
  14. namespace Terra.Arbitrator.Services
  15. {
  16. /// <summary>
  17. /// An internal helper class for executing Git commands.
  18. /// It centralizes the logic for finding executables and running them via CliWrap.
  19. /// </summary>
  20. [Preserve]
  21. internal static class GitCommand
  22. {
  23. private static string _projectRoot;
  24. private static string ProjectRoot => _projectRoot ??= Directory.GetParent(Application.dataPath)?.FullName;
  25. /// <summary>
  26. /// Runs a git command asynchronously.
  27. /// </summary>
  28. /// <param name="execPath">Executable path like git or vs code to perform terminal based command action</param>
  29. /// <param name="log">A StringBuilder to capture command output for logging.</param>
  30. /// <param name="progress">A delegate to report real-time standard error lines.</param>
  31. /// <param name="args">The arguments to pass to the git command.</param>
  32. /// <param name="acceptableExitCodes">A list of exit codes that should not be treated as errors.</param>
  33. public static async Task RunAsync(string execPath, StringBuilder log, IProgress<string> progress, string[] args, params int[] acceptableExitCodes)
  34. {
  35. var stdOutBuffer = new StringBuilder();
  36. var stdErrBuffer = new StringBuilder();
  37. var argumentsString = string.Join(" ", args);
  38. log?.AppendLine($"\n--- Executing: git {argumentsString} ---");
  39. // Pipe stderr to a delegate that both captures the full output and reports each line for progress.
  40. var stdErrPipe = PipeTarget.ToDelegate(line => {
  41. stdErrBuffer.AppendLine(line);
  42. progress?.Report(line); // Report progress for each line received.
  43. });
  44. var command = Cli.Wrap(execPath)
  45. .WithArguments(args)
  46. .WithWorkingDirectory(ProjectRoot)
  47. .WithValidation(CommandResultValidation.None) // We handle validation manually
  48. | (PipeTarget.ToDelegate(x => stdOutBuffer.Append(x)), stdErrPipe);
  49. var result = await command.ExecuteAsync();
  50. log?.AppendLine($"Exit Code: {result.ExitCode}");
  51. if (stdOutBuffer.Length > 0) log?.AppendLine($"StdOut: {stdOutBuffer}");
  52. if (stdErrBuffer.Length > 0) log?.AppendLine($"StdErr: {stdErrBuffer}");
  53. // Default to 0 if no specific codes are provided
  54. if (acceptableExitCodes.Length == 0)
  55. {
  56. acceptableExitCodes = new[] { 0 };
  57. }
  58. if (!acceptableExitCodes.Contains(result.ExitCode))
  59. {
  60. throw new Exception($"Command 'git {argumentsString}' failed with unexpected exit code {result.ExitCode}. Error: {stdErrBuffer}");
  61. }
  62. }
  63. public static Task RunGitAsync(StringBuilder log, string[] args, params int[] acceptableExitCodes)
  64. {
  65. return RunAsync(FindGitExecutable(), log, null, args, acceptableExitCodes);
  66. }
  67. public static Task RunGitAsync(StringBuilder log, string[] args, IProgress<string> progress, params int[] acceptableExitCodes)
  68. {
  69. return RunAsync(FindGitExecutable(), log, progress, args, acceptableExitCodes);
  70. }
  71. public static Task RunVsCodeAsync(StringBuilder log, string[] args, params int[] acceptableExitCodes)
  72. {
  73. return RunAsync(FindVsCodeExecutable(), log, null, args, acceptableExitCodes);
  74. }
  75. /// <summary>
  76. /// Finds the absolute path to a given executable.
  77. /// </summary>
  78. private static string FindExecutable(string name)
  79. {
  80. if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
  81. {
  82. // CliWrap handles PATH search on Windows automatically.
  83. return name;
  84. }
  85. // For macOS/Linux, we need to be more explicit due to Unity's sandboxing.
  86. string[] searchPaths = { "/usr/local/bin", "/usr/bin", "/bin", "/opt/homebrew/bin" };
  87. foreach (var path in searchPaths)
  88. {
  89. var fullPath = Path.Combine(path, name);
  90. if (File.Exists(fullPath))
  91. {
  92. return fullPath;
  93. }
  94. }
  95. throw new FileNotFoundException($"Could not find executable '{name}'. Please ensure it is installed and in your system's PATH.");
  96. }
  97. private static string FindVsCodeExecutable() => FindExecutable("code");
  98. private static string FindGitExecutable() => FindExecutable("git");
  99. }
  100. }