summaryrefslogtreecommitdiff
path: root/src/marlin.core/functional/GitBinaryClient.cs
blob: b2751c03fcf03333b148a3424d27dccbddfd8641 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
namespace marlin.core.functional;

using System.Diagnostics;

public class GitBinaryClient : IGitClient
{
    private readonly IGitCredential? _credential;

    public GitBinaryClient(IGitCredential? credential = null)
    {
        this._credential = credential;
    }

    public async Task<Dictionary<string, string>> GetRemoteRefs(string remote)
    {
        string stdout = await this.RunAsync(
            authenticate: true,
            "ls-remote", "--heads", "--tags", remote);

        return ParseRefs(stdout);
    }

    public async Task Init(string repoPath)
    {
        Directory.CreateDirectory(repoPath);
        await this.RunAsync(authenticate: false, "init", "--bare", repoPath);
    }

    public async Task FetchTrees(string repoPath, string remote, IEnumerable<string> refs, bool skipBlobs = false)
    {
        var refList = refs as IReadOnlyCollection<string> ?? refs.ToArray();
        if (refList.Count == 0)
            return;

        var args = new List<string> { "-C", repoPath, "fetch" };
        if (skipBlobs)
            args.Add("--filter=blob:none");
        args.Add(remote);
        args.AddRange(refList);

        await this.RunAsync(authenticate: true, args.ToArray());
    }

    public async Task Checkout(string repoPath, string remote, string branch, string commit)
    {
        await this.RunAsync(authenticate: true, "clone", "--revision", branch, remote, repoPath);
        // await this.RunAsync(authenticate: true, "clone", "--branch", branch, remote, repoPath);
        await this.RunAsync(authenticate: false, "-C", repoPath, "checkout", commit);
    }

    public async Task<string[]> ListTree(string repoPath, string hash, string filterPath = ".")
    {
        string stdout = await this.RunAsync(
            authenticate: false,
            "-C", repoPath, "ls-tree", "-r", "--name-only", hash, "--", filterPath);

        return stdout.Split('\n', StringSplitOptions.RemoveEmptyEntries);
    }

    public Task<byte[]> CatFile(string repoPath, string hash, string fileName)
    {
        return this.RunRawAsync(
            authenticate: false,
            "-C", repoPath, "show", $"{hash}:{fileName}");
    }

    private Task<string> RunAsync(bool authenticate, params string[] arguments) =>
        this.RunAsync(authenticate, async stream =>
        {
            using var reader = new StreamReader(stream);
            return await reader.ReadToEndAsync();
        }, arguments);

    private Task<byte[]> RunRawAsync(bool authenticate, params string[] arguments) =>
        this.RunAsync(authenticate, async stream =>
        {
            using var buffer = new MemoryStream();
            await stream.CopyToAsync(buffer);
            return buffer.ToArray();
        }, arguments);

    private async Task<T> RunAsync<T>(bool authenticate, Func<Stream, Task<T>> readStdout, string[] arguments)
    {
        var psi = new ProcessStartInfo("git")
        {
            RedirectStandardOutput = true,
            RedirectStandardError = true,
            UseShellExecute = false,
            CreateNoWindow = true,
        };

        foreach (string arg in arguments)
            psi.ArgumentList.Add(arg);

        psi.Environment["GIT_TERMINAL_PROMPT"] = "0";

        IAsyncDisposable? credentialScope = authenticate && this._credential != null
            ? await this._credential.ApplyAsync(psi)
            : null;

        try
        {
            using var process = Process.Start(psi)
                ?? throw new InvalidOperationException("Failed to start git process.");

            Task<T> stdoutTask = readStdout(process.StandardOutput.BaseStream);
            Task<string> stderrTask = process.StandardError.ReadToEndAsync();

            await process.WaitForExitAsync();
            T stdout = await stdoutTask;
            string stderr = await stderrTask;

            if (process.ExitCode != 0)
                throw new GitCommandException(string.Join(' ', arguments), process.ExitCode, stderr);

            return stdout;
        }
        finally
        {
            if (credentialScope != null)
                await credentialScope.DisposeAsync();
        }
    }

    private static Dictionary<string, string> ParseRefs(string stdout)
    {
        var result = new Dictionary<string, string>();

        foreach (string line in stdout.Split('\n', StringSplitOptions.RemoveEmptyEntries))
        {
            string[] parts = line.Split('\t');
            if (parts.Length != 2)
                continue; // ignore a malformed line rather than throw over one bad entry

            if (parts[1].EndsWith("^{}", StringComparison.Ordinal))
                continue; // peeled tag marker from ls-remote, not a real ref/refspec

            result[parts[1]] = parts[0];
        }

        return result;
    }
}