Forge

Jessie / forge public

Self-hosted git - made by qwen 3.8 27b

branch: main

Branches

main
GitLayerTests.cs 14.7 kB · 325 lines RawPermalinkHistory
using Forge.Git;
using Forge.Tests.Support;
using Microsoft.Extensions.Options;

namespace Forge.Tests;

/// <summary>
/// A real repository in a temp directory with the awkward cases in it: a branch with a slash,
/// annotated and lightweight tags, a binary file, a file with a space in its name, and a rename.
/// </summary>
public sealed class GitRepoFixture : IAsyncLifetime
{
    private readonly TempDir _temp = new();

    public GitCli Cli { get; private set; } = null!;
    public GitRepo Repo { get; private set; } = null!;
    public RefResolver Resolver { get; private set; } = null!;
    public string DataPath { get; private set; } = "";

    /// <summary>The .git directory of the working repository; the git layer only needs a git dir.</summary>
    public string RepoPath { get; private set; } = "";

    public string FirstSha { get; private set; } = "";
    public string SecondSha { get; private set; } = "";
    public string FeatureSha { get; private set; } = "";

    public async Task InitializeAsync()
    {
        DataPath = _temp.Sub("data");
        var options = Options.Create(new ForgeOptions { DataPath = DataPath, GitPath = TestGit.Executable });
        Cli = new GitCli(options);
        Repo = new GitRepo(Cli);
        Resolver = new RefResolver(Repo);

        var git = new TestGit(_temp.Sub("home"));
        var work = _temp.Sub("work");
        await git.MustAsync(work, "init", "--initial-branch=main", ".");

        Directory.CreateDirectory(Path.Combine(work, "src"));
        await File.WriteAllTextAsync(Path.Combine(work, "README.md"), "# Fixture\n");
        await File.WriteAllTextAsync(Path.Combine(work, "src", "a.cs"), "line one\nline two\nline three\n");
        await File.WriteAllTextAsync(Path.Combine(work, "file with space.txt"), "spaced\n");
        await File.WriteAllTextAsync(Path.Combine(work, "old.txt"), "this file will be renamed\nwithout changes\n");
        await File.WriteAllBytesAsync(Path.Combine(work, "binary.bin"), [1, 2, 0, 3, 4, 0, 255]);
        await git.MustAsync(work, "add", "-A");
        await git.MustAsync(work, "commit", "-m", "First commit", "-m", "With a body.\nOn two lines.");
        FirstSha = await git.MustAsync(work, "rev-parse", "HEAD");

        await File.WriteAllTextAsync(Path.Combine(work, "src", "a.cs"), "line one\nline 2\nline three\nline four\n");
        await git.MustAsync(work, "mv", "old.txt", "new.txt");
        await git.MustAsync(work, "add", "-A");
        await git.MustAsync(work, "commit", "-m", "Second commit");
        SecondSha = await git.MustAsync(work, "rev-parse", "HEAD");

        await git.MustAsync(work, "tag", "-a", "v1.0", "-m", "Release 1.0");
        await git.MustAsync(work, "tag", "light");

        await git.MustAsync(work, "checkout", "-b", "feature/x");
        await File.WriteAllTextAsync(Path.Combine(work, "src", "feature.txt"), "feature\n");
        await git.MustAsync(work, "add", "-A");
        await git.MustAsync(work, "commit", "-m", "Feature commit");
        FeatureSha = await git.MustAsync(work, "rev-parse", "HEAD");
        await git.MustAsync(work, "checkout", "main");

        RepoPath = Path.Combine(work, ".git");
    }

    public Task DisposeAsync()
    {
        _temp.Dispose();
        return Task.CompletedTask;
    }
}

public class GitLayerTests(GitRepoFixture fx) : IClassFixture<GitRepoFixture>
{
    [Fact]
    public async Task Version_is_reported()
    {
        var version = await fx.Cli.GetVersionAsync();
        Assert.True(version >= ForgeApp.MinimumGitVersion, $"git {version} is older than {ForgeApp.MinimumGitVersion}");
    }

    [Fact]
    public async Task Missing_git_gives_a_clear_error()
    {
        var cli = new GitCli(Options.Create(new ForgeOptions { DataPath = fx.DataPath, GitPath = "git-that-does-not-exist" }));
        var ex = await Assert.ThrowsAsync<GitException>(() => cli.GetVersionAsync());
        Assert.Contains("git-that-does-not-exist", ex.Message);
    }

    [Fact]
    public async Task Refs_list_branches_and_tags()
    {
        var refs = await fx.Repo.ListRefsAsync(fx.RepoPath);

        var main = Assert.Single(refs, r => r is { Kind: RefKind.Branch, Name: "main" });
        Assert.Equal(fx.SecondSha, main.Sha);
        Assert.Equal("Second commit", main.Subject);
        Assert.NotNull(main.Date);

        var feature = Assert.Single(refs, r => r is { Kind: RefKind.Branch, Name: "feature/x" });
        Assert.Equal(fx.FeatureSha, feature.TargetSha);

        var annotated = Assert.Single(refs, r => r is { Kind: RefKind.Tag, Name: "v1.0" });
        Assert.Equal("tag", annotated.ObjectType);
        Assert.NotEqual(fx.SecondSha, annotated.Sha);
        Assert.Equal(fx.SecondSha, annotated.TargetSha);
        Assert.Equal("Release 1.0", annotated.Subject);

        var light = Assert.Single(refs, r => r is { Kind: RefKind.Tag, Name: "light" });
        Assert.Equal(fx.SecondSha, light.Sha);
        Assert.Null(light.PeeledSha);
    }

    [Fact]
    public async Task Tree_lists_root_and_subdirectory()
    {
        var rootSha = await fx.Repo.GetRootTreeShaAsync(fx.RepoPath, fx.SecondSha);
        Assert.NotNull(rootSha);
        var root = await fx.Repo.ListTreeAsync(fx.RepoPath, rootSha);

        Assert.Equal(
            ["README.md", "binary.bin", "file with space.txt", "new.txt", "src"],
            root.Select(e => e.Name).Order(StringComparer.Ordinal));
        Assert.True(root.Single(e => e.Name == "src").IsTree);
        Assert.Equal(7, root.Single(e => e.Name == "binary.bin").Size);

        var src = await fx.Repo.GetEntryAsync(fx.RepoPath, fx.SecondSha, "src");
        Assert.True(src is { IsTree: true });
        var children = await fx.Repo.ListTreeAsync(fx.RepoPath, src.Sha);
        Assert.Equal("a.cs", Assert.Single(children).Name);
    }

    [Fact]
    public async Task Entry_lookup_handles_spaces_and_missing_paths()
    {
        var spaced = await fx.Repo.GetEntryAsync(fx.RepoPath, fx.SecondSha, "file with space.txt");
        Assert.True(spaced is { IsBlob: true, Name: "file with space.txt" });

        var nested = await fx.Repo.GetEntryAsync(fx.RepoPath, fx.SecondSha, "src/a.cs");
        Assert.Equal("a.cs", nested?.Name);

        Assert.Null(await fx.Repo.GetEntryAsync(fx.RepoPath, fx.SecondSha, "nope.txt"));
        // Pathspec magic and option-like paths are plain (missing) file names.
        Assert.Null(await fx.Repo.GetEntryAsync(fx.RepoPath, fx.SecondSha, ":(glob)**"));
        Assert.Null(await fx.Repo.GetEntryAsync(fx.RepoPath, fx.SecondSha, "--name-only"));
    }

    [Fact]
    public async Task Blob_is_read_with_size_and_cap()
    {
        var entry = await fx.Repo.GetEntryAsync(fx.RepoPath, fx.SecondSha, "src/a.cs");
        Assert.NotNull(entry);
        Assert.Equal(entry.Size, await fx.Repo.GetBlobSizeAsync(fx.RepoPath, entry.Sha));

        var blob = await fx.Repo.ReadBlobAsync(fx.RepoPath, entry.Sha, 1024);
        Assert.False(blob.Truncated);
        Assert.False(blob.IsBinary);
        Assert.Equal("line one\nline 2\nline three\nline four\n", blob.Text);

        var capped = await fx.Repo.ReadBlobAsync(fx.RepoPath, entry.Sha, 8);
        Assert.True(capped.Truncated);
        Assert.Equal("line one", capped.Text);

        var binary = await fx.Repo.GetEntryAsync(fx.RepoPath, fx.SecondSha, "binary.bin");
        Assert.True((await fx.Repo.ReadBlobAsync(fx.RepoPath, binary!.Sha, 1024)).IsBinary);
    }

    [Fact]
    public async Task Log_pages_and_filters_by_path()
    {
        var all = await fx.Repo.LogAsync(fx.RepoPath, fx.SecondSha);
        Assert.Equal([fx.SecondSha, fx.FirstSha], all.Select(c => c.Sha));
        Assert.Equal("First commit", all[1].Subject);
        Assert.Equal("With a body.\nOn two lines.", all[1].Body);
        Assert.Equal("Test Author", all[1].AuthorName);
        Assert.Equal("author@example.com", all[1].AuthorEmail);
        Assert.Equal([fx.FirstSha], all[0].Parents);

        var second = await fx.Repo.LogAsync(fx.RepoPath, fx.SecondSha, skip: 1, take: 1);
        Assert.Equal(fx.FirstSha, Assert.Single(second).Sha);

        var readme = await fx.Repo.LogAsync(fx.RepoPath, fx.SecondSha, "README.md");
        Assert.Equal(fx.FirstSha, Assert.Single(readme).Sha);

        var range = await fx.Repo.LogRangeAsync(fx.RepoPath, fx.FirstSha, fx.FeatureSha, 20);
        Assert.Equal([fx.FeatureSha, fx.SecondSha], range.Select(c => c.Sha));
    }

    [Fact]
    public async Task Commit_diff_has_stats_hunks_and_renames()
    {
        var commit = await fx.Repo.GetCommitAsync(fx.RepoPath, fx.SecondSha);
        Assert.Equal("Second commit", commit?.Subject);

        var diff = await fx.Repo.GetDiffAsync(fx.RepoPath, fx.SecondSha);

        var stat = Assert.Single(diff.Stats, s => s.Path == "src/a.cs");
        Assert.Equal((2, 1), (stat.Added, stat.Deleted));
        var renameStat = Assert.Single(diff.Stats, s => s.Path == "new.txt");
        Assert.Equal("old.txt", renameStat.OldPath);

        var modified = Assert.Single(diff.Patch.Files, f => f.NewPath == "src/a.cs");
        Assert.Equal(FileChange.Modified, modified.Change);
        var lines = modified.Hunks.SelectMany(h => h.Lines).ToList();
        Assert.Contains(new DiffLine(DiffLineKind.Deleted, 2, null, "line two"), lines);
        Assert.Contains(new DiffLine(DiffLineKind.Added, null, 2, "line 2"), lines);
        Assert.Contains(new DiffLine(DiffLineKind.Added, null, 4, "line four"), lines);

        var renamed = Assert.Single(diff.Patch.Files, f => f.Change == FileChange.Renamed);
        Assert.Equal(("old.txt", "new.txt"), (renamed.OldPath, renamed.NewPath));
    }

    [Fact]
    public async Task Root_commit_diff_marks_binary_files_and_reads_names_with_spaces()
    {
        var diff = await fx.Repo.GetDiffAsync(fx.RepoPath, fx.FirstSha);

        Assert.True(Assert.Single(diff.Stats, s => s.Path == "binary.bin").IsBinary);
        var binary = Assert.Single(diff.Patch.Files, f => f.NewPath == "binary.bin");
        Assert.True(binary.IsBinary);
        Assert.Equal(FileChange.Added, binary.Change);

        var spaced = Assert.Single(diff.Patch.Files, f => f.NewPath == "file with space.txt");
        Assert.Equal(FileChange.Added, spaced.Change);
        Assert.Equal(1, spaced.Added);
    }

    [Fact]
    public async Task Ahead_behind_counts_both_sides()
    {
        Assert.Equal((1, 0), await fx.Repo.AheadBehindAsync(fx.RepoPath, fx.SecondSha, fx.FeatureSha));
        Assert.Equal((0, 2), await fx.Repo.AheadBehindAsync(fx.RepoPath, fx.FeatureSha, fx.FirstSha));
    }

    [Fact]
    public async Task Resolver_handles_slashes_tags_shas_and_hostile_input()
    {
        var branch = await fx.Resolver.ResolveAsync(fx.RepoPath, "feature/x/src/feature.txt");
        Assert.Equal(new ResolvedRef("feature/x", ResolvedKind.Branch, fx.FeatureSha, "src/feature.txt"), branch);

        var tag = await fx.Resolver.ResolveAsync(fx.RepoPath, "v1.0/src");
        Assert.Equal(new ResolvedRef("v1.0", ResolvedKind.Tag, fx.SecondSha, "src"), tag);

        var sha = await fx.Resolver.ResolveAsync(fx.RepoPath, fx.FirstSha + "/README.md");
        Assert.Equal(new ResolvedRef(fx.FirstSha, ResolvedKind.Commit, fx.FirstSha, "README.md"), sha);

        Assert.Null(await fx.Resolver.ResolveAsync(fx.RepoPath, new string('0', 40)));
        Assert.Null(await fx.Resolver.ResolveAsync(fx.RepoPath, "missing/README.md"));

        // The checklist case: a "ref" shaped like an option must resolve to nothing and run nothing.
        var marker = Path.Combine(fx.DataPath, "pwned");
        Assert.Null(await fx.Resolver.ResolveAsync(fx.RepoPath, $"--upload-pack=touch {marker}"));
        Assert.Null(await fx.Resolver.ResolveAsync(fx.RepoPath, "--output=" + marker));
        Assert.False(File.Exists(marker));
    }

    [Fact]
    public async Task Commit_lookup_accepts_hex_only()
    {
        Assert.Equal(fx.SecondSha, await fx.Repo.ResolveCommitAsync(fx.RepoPath, fx.SecondSha[..10]));
        Assert.Null(await fx.Repo.ResolveCommitAsync(fx.RepoPath, "main"));
        Assert.Null(await fx.Repo.ResolveCommitAsync(fx.RepoPath, "--all"));
        Assert.Null(await fx.Repo.ResolveCommitAsync(fx.RepoPath, "HEAD~1"));
    }

    [Fact]
    public async Task Init_creates_a_bare_repository_on_main_with_fsck_enabled()
    {
        var path = Path.Combine(fx.DataPath, "repos", "77.git");
        Directory.CreateDirectory(Path.GetDirectoryName(path)!);

        await fx.Repo.InitBareAsync(path);

        Assert.True(File.Exists(Path.Combine(path, "HEAD")));
        Assert.Equal("main", await fx.Repo.GetHeadBranchAsync(path));
        Assert.Empty(await fx.Repo.ListRefsAsync(path));
        var config = await fx.Cli.RunAsync(path, ["config", "--get", "receive.fsckObjects"]);
        Assert.Equal("true", config.Text.Trim());
        var bare = await fx.Cli.RunAsync(path, ["rev-parse", "--is-bare-repository"]);
        Assert.Equal("true", bare.Text.Trim());
    }

    [Fact]
    public async Task Timeout_kills_the_process()
    {
        // cat-file --batch waits for stdin forever; a stream that never ends keeps it alive.
        await using var never = new NeverEndingStream();
        await Assert.ThrowsAsync<GitTimeoutException>(() =>
            fx.Cli.RunAsync(fx.RepoPath, ["cat-file", "--batch"], stdin: never, timeout: TimeSpan.FromMilliseconds(500)));
    }

    [Fact]
    public async Task Cancellation_kills_the_process()
    {
        await using var never = new NeverEndingStream();
        using var cts = new CancellationTokenSource(TimeSpan.FromMilliseconds(300));
        await Assert.ThrowsAnyAsync<OperationCanceledException>(() =>
            fx.Cli.RunAsync(fx.RepoPath, ["cat-file", "--batch"], stdin: never, ct: cts.Token));
    }

    private sealed class NeverEndingStream : Stream
    {
        public override async ValueTask<int> ReadAsync(Memory<byte> buffer, CancellationToken cancellationToken = default)
        {
            await Task.Delay(Timeout.Infinite, cancellationToken);
            return 0;
        }

        public override Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) =>
            ReadAsync(buffer.AsMemory(offset, count), cancellationToken).AsTask();

        public override int Read(byte[] buffer, int offset, int count) => throw new NotSupportedException();
        public override bool CanRead => true;
        public override bool CanSeek => false;
        public override bool CanWrite => false;
        public override long Length => throw new NotSupportedException();
        public override long Position { get => 0; set => throw new NotSupportedException(); }
        public override void Flush() { }
        public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException();
        public override void SetLength(long value) => throw new NotSupportedException();
        public override void Write(byte[] buffer, int offset, int count) => throw new NotSupportedException();
    }
}

Keyboard shortcuts

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