using System.Text; using CliWrap; using Forge.Git; namespace Forge.Tests.Support; public sealed record GitRun(int ExitCode, string StdOut, string StdErr) { public bool Ok => ExitCode == 0; } /// /// The git client used by tests, as a user's machine would run it. Isolated from the real machine: /// no system or user config, no credential helper, and no prompts, so a rejected push fails instead of hanging. /// public sealed class TestGit(string home) { public static string Executable => Environment.GetEnvironmentVariable("FORGE_TEST_GIT") ?? "git"; public async Task RunAsync(string workDir, params string[] args) { var stdout = new StringBuilder(); var stderr = new StringBuilder(); using var timeout = new CancellationTokenSource(TimeSpan.FromMinutes(2)); var result = await Cli.Wrap(Executable) .WithArguments(args) .WithWorkingDirectory(workDir) .WithEnvironmentVariables(new Dictionary { ["GIT_CONFIG_NOSYSTEM"] = "1", ["HOME"] = home, ["XDG_CONFIG_HOME"] = Path.Combine(home, ".config"), ["GIT_TERMINAL_PROMPT"] = "0", ["GCM_INTERACTIVE"] = "never", ["GIT_ASKPASS"] = null, ["SSH_ASKPASS"] = null, ["GIT_AUTHOR_NAME"] = "Test Author", ["GIT_AUTHOR_EMAIL"] = "author@example.com", ["GIT_COMMITTER_NAME"] = "Test Author", ["GIT_COMMITTER_EMAIL"] = "author@example.com", ["GIT_DIR"] = null, ["GIT_WORK_TREE"] = null, ["LC_ALL"] = "C", }) .WithStandardOutputPipe(PipeTarget.ToStringBuilder(stdout)) .WithStandardErrorPipe(PipeTarget.ToStringBuilder(stderr)) .WithValidation(CommandResultValidation.None) .ExecuteAsync(timeout.Token); return new GitRun(result.ExitCode, stdout.ToString(), stderr.ToString()); } /// Runs git and fails the test with git's own output if it exits non-zero. public async Task MustAsync(string workDir, params string[] args) { var run = await RunAsync(workDir, args); Assert.True(run.Ok, $"git {string.Join(' ', args)} failed ({run.ExitCode}):\n{run.StdOut}\n{run.StdErr}"); return run.StdOut.Trim(); } /// Creates a working repository on branch with one commit. public async Task CreateWorkRepoAsync(string path, string branch = "main", string fileName = "README.md", string content = "# Demo\n") { Directory.CreateDirectory(path); await MustAsync(path, "init", "--initial-branch=" + branch, "."); await File.WriteAllTextAsync(Path.Combine(path, fileName), content); await MustAsync(path, "add", "-A"); await MustAsync(path, "commit", "-m", "First commit"); return await MustAsync(path, "rev-parse", "HEAD"); } } public sealed class TempDir : IDisposable { public string Path { get; } = Directory.CreateTempSubdirectory("forge-test-").FullName; public string Sub(string name) { var path = System.IO.Path.Combine(Path, name); Directory.CreateDirectory(path); return path; } public void Dispose() { try { RepoPaths.DeleteDirectory(Path); } catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) { // A leftover temp directory must not fail a test run. } } }