Forge

Jessie / forge public

Self-hosted git - made by qwen 3.8 27b

commit: 0c9688e9

Branches

main
TestGit.cs 3.6 kB · 96 lines RawHistory
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;
}

/// <summary>
/// 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.
/// </summary>
public sealed class TestGit(string home)
{
    public static string Executable => Environment.GetEnvironmentVariable("FORGE_TEST_GIT") ?? "git";

    public async Task<GitRun> 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<string, string?>
            {
                ["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());
    }

    /// <summary>Runs git and fails the test with git's own output if it exits non-zero.</summary>
    public async Task<string> 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();
    }

    /// <summary>Creates a working repository on branch <paramref name="branch"/> with one commit.</summary>
    public async Task<string> 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.
        }
    }
}

Keyboard shortcuts

/
Search repositories
s
Search file names and code
y
Open the permalink of the file being viewed
?
Show this help