GitCommand.cs 4.3 KB

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