summary refs log tree commit diff
path: root/LibGit/BlobObject.cs
blob: 93fd5f38f30692ac2ddc4481f38e03c60e8e7fdd (plain) (blame)
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
using System.IO.Compression;
using System.Text.Json.Serialization;
using LibGit.Extensions;
using LibGit.Interfaces;

namespace LibGit;

public class BlobObject
{
    [JsonIgnore]
    public IRepoSource RepoSource { get; }
    public string ObjectId { get; }

    public BlobObject(IRepoSource repoSource, string objectId)
    {
        RepoSource = repoSource;
        ObjectId = objectId;
    }

    private const bool _debug = false;

    public string Length { get; set; }
    public IEnumerable<byte> Data { get; set; }

    public BlobObject ReadFromZlibCompressedObjFile(Stream bytes)
    {
        if(_debug) Console.WriteLine($"Decompressing {this.GetType().Name}");
        using ZLibStream stream = new ZLibStream(bytes, CompressionMode.Decompress);
        using var result = new MemoryStream();
        stream.CopyTo(result);
        stream.Flush();
        stream.Close();
        return ReadFromDecompressedObjFile(result);
    }

    public BlobObject ReadFromDecompressedObjFile(Stream data)
    {
        if(_debug) Console.WriteLine("Parsing commit object");
        // var data = new Queue<byte>(bytes.ToArray());
        int iters = 0;
        data.Seek(0, SeekOrigin.Begin);
        if(_debug)Console.WriteLine($"Iteration {iters}: starting pos: {data.Position}/+{data.Remaining()}/{data.Length}");
        while (data.Position < data.Length)
        {
            if(_debug) Console.WriteLine($"Iteration {iters} ({data.Position}/+{data.Remaining()}/{data.Length})");
            if (data.StartsWith("tree "))
                Length = data.ReadNullTerminatedField(asciiPrefix: "tree ").AsString();

            Data = data.ReadBytes(data.Remaining());

            if (data.Remaining() > 0)
            {
                Console.WriteLine($"--Unparsed data after {++iters} iteration(s) of parsing CommitObject--");
                Console.WriteLine(this.ToJson());
                Console.WriteLine("--HexDump of remaining data--");
                data.Peek(data.Remaining()).HexDump();
                //Console.WriteLine($"Unparsed data: {Encoding.UTF8.GetString(data.ToArray())}");
            }
            if(iters > 100) throw new Exception("Too many iterations");
        }

        data.Close();
        return this;
    }

    public class TreeObjectEntry
    {
        public string Mode { get; set; }
        public string Hash { get; set; }
    }
}