navid/veins / 5abea8f29f2cbc7750fce6321d3044f50f1b84095af70fff71cb34c0664abfa0 / xveins/src/git/git_object.cpp

git_object.cpp

← xveins/src/git · 39103 bytes · raw · download

#include "git/git_internal.h"

#include <openssl/evp.h>
#include <zlib.h>

#include <algorithm>
#include <cstring>
#include <map>
#include <mutex>
#include <string_view>

namespace vn::git {

namespace {

std::uint32_t be32(Bytes data, std::size_t off) {
    return (static_cast<std::uint32_t>(data[off]) << 24) |
           (static_cast<std::uint32_t>(data[off + 1]) << 16) |
           (static_cast<std::uint32_t>(data[off + 2]) << 8) |
           static_cast<std::uint32_t>(data[off + 3]);
}

std::uint64_t be64(Bytes data, std::size_t off) {
    return (static_cast<std::uint64_t>(be32(data, off)) << 32) |
           static_cast<std::uint64_t>(be32(data, off + 4));
}

Oid sha1(Bytes data) {
    Oid out{};
    unsigned int len = 0;
    static const std::uint8_t empty = 0;
    const std::uint8_t* ptr = data.empty() ? &empty : data.data();
    EVP_Digest(ptr, data.size(), out.data(), &len, EVP_sha1(), nullptr);
    return out;
}

bool bytes_equal(const Oid& a, Bytes b) {
    return b.size() == a.size() && std::memcmp(a.data(), b.data(), a.size()) == 0;
}

std::string kind_name(std::uint8_t kind) {
    switch (kind) {
    case KIND_COMMIT:
        return "commit";
    case KIND_TREE:
        return "tree";
    case KIND_BLOB:
        return "blob";
    case KIND_TAG:
        return "tag";
    default:
        return "unknown";
    }
}

std::uint8_t kind_from_name(std::string_view name) {
    if (name == "commit")
        return KIND_COMMIT;
    if (name == "tree")
        return KIND_TREE;
    if (name == "blob")
        return KIND_BLOB;
    if (name == "tag")
        return KIND_TAG;
    return 0;
}

std::optional<std::vector<std::uint8_t>> inflate_unknown(Bytes input);

std::optional<std::vector<std::uint8_t>> inflate_exact(Bytes input, std::size_t expected) {
    if (expected == 0) {
        auto result = inflate_unknown(input);
        if (!result || !result->empty())
            return std::nullopt;
        return result;
    }
    std::vector<std::uint8_t> out(expected);
    uLongf dest_len = static_cast<uLongf>(expected);
    const int rc =
        uncompress(out.data(), &dest_len, input.data(), static_cast<uLong>(input.size()));
    if (rc != Z_OK || dest_len != expected)
        return std::nullopt;
    out.resize(expected);
    return out;
}

std::optional<std::vector<std::uint8_t>> inflate_unknown(Bytes input) {
    z_stream zs{};
    if (inflateInit(&zs) != Z_OK)
        return std::nullopt;
    std::vector<std::uint8_t> out(4096);
    zs.next_in = const_cast<Bytef*>(input.data());
    zs.avail_in = static_cast<uInt>(input.size());
    int rc = Z_OK;
    for (;;) {
        if (zs.total_out == out.size())
            out.resize(out.size() * 2);
        zs.next_out = out.data() + zs.total_out;
        zs.avail_out = static_cast<uInt>(out.size() - zs.total_out);
        rc = inflate(&zs, Z_NO_FLUSH);
        if (rc == Z_STREAM_END)
            break;
        if (rc != Z_OK) {
            inflateEnd(&zs);
            return std::nullopt;
        }
    }
    const std::size_t written = zs.total_out;
    inflateEnd(&zs);
    out.resize(written);
    return out;
}

struct Varint {
    std::uint64_t value = 0;
    std::size_t next = 0;
};

std::optional<Varint> read_be_varint(Bytes data, std::size_t start) {
    if (start >= data.size())
        return std::nullopt;
    const std::uint8_t c0 = data[start];
    std::uint64_t value = c0 & 0x0f;
    std::uint64_t shift = 4;
    std::size_t pos = start + 1;
    bool more = (c0 & 0x80) != 0;
    while (more) {
        if (pos >= data.size())
            return std::nullopt;
        const std::uint8_t c = data[pos++];
        value |= (static_cast<std::uint64_t>(c & 0x7f) << shift);
        shift += 7;
        more = (c & 0x80) != 0;
    }
    return Varint{value, pos};
}

std::optional<Varint> read_delta_varint(Bytes data, std::size_t start) {
    std::uint64_t value = 0;
    std::uint64_t shift = 0;
    std::size_t pos = start;
    for (;;) {
        if (pos >= data.size() || shift > 63)
            return std::nullopt;
        const std::uint8_t c = data[pos++];
        value |= (static_cast<std::uint64_t>(c & 0x7f) << shift);
        shift += 7;
        if ((c & 0x80) == 0)
            return Varint{value, pos};
    }
}

std::optional<std::vector<std::uint8_t>> apply_delta(Bytes base, Bytes delta) {
    const auto src_size = read_delta_varint(delta, 0);
    if (!src_size || src_size->value != base.size())
        return std::nullopt;
    const auto dst_size = read_delta_varint(delta, src_size->next);
    if (!dst_size || dst_size->value > 2147483648ull)
        return std::nullopt;
    const std::size_t cap = static_cast<std::size_t>(dst_size->value);
    std::vector<std::uint8_t> out(cap);
    std::size_t written = 0;
    std::size_t pos = dst_size->next;
    while (pos < delta.size()) {
        const std::uint8_t op = delta[pos++];
        if ((op & 0x80) != 0) {
            std::uint64_t off = 0;
            std::uint64_t size = 0;
            for (int bit = 0; bit < 4; ++bit) {
                if ((op & (1u << bit)) != 0) {
                    if (pos >= delta.size())
                        return std::nullopt;
                    off |= static_cast<std::uint64_t>(delta[pos++]) << (8 * bit);
                }
            }
            for (int bit = 0; bit < 3; ++bit) {
                if ((op & (1u << (4 + bit))) != 0) {
                    if (pos >= delta.size())
                        return std::nullopt;
                    size |= static_cast<std::uint64_t>(delta[pos++]) << (8 * bit);
                }
            }
            if (size == 0)
                size = 65536;
            if (off > base.size() || size > base.size() - off)
                return std::nullopt;
            if (size > cap - written)
                return std::nullopt;
            if (size > 0)
                std::memcpy(out.data() + written, base.data() + off,
                            static_cast<std::size_t>(size));
            written += static_cast<std::size_t>(size);
        } else {
            if (op == 0)
                return std::nullopt;
            const std::size_t n = op;
            if (pos + n > delta.size() || n > cap - written)
                return std::nullopt;
            std::memcpy(out.data() + written, delta.data() + pos, n);
            pos += n;
            written += n;
        }
    }
    if (written != cap)
        return std::nullopt;
    return out;
}

std::optional<std::size_t> find_oid(const Pack& pack, const Oid& oid) {
    auto it = std::lower_bound(pack.oids.begin(), pack.oids.end(), oid, OidLess{});
    if (it == pack.oids.end() || std::memcmp(it->data(), oid.data(), oid.size()) != 0)
        return std::nullopt;
    return static_cast<std::size_t>(it - pack.oids.begin());
}

std::optional<Object> read_at(Repo& repo, Pack& pack, std::uint64_t start, bool verify,
                              std::size_t depth) {
    if (depth > 4096 || start >= pack.data.size())
        return std::nullopt;
    Bytes data(pack.data.data(), pack.data.size());
    const std::size_t begin = static_cast<std::size_t>(start);
    const std::uint8_t c0 = data[begin];
    const std::uint8_t kind = static_cast<std::uint8_t>((c0 >> 4) & 7);
    const auto header = read_be_varint(data, begin);
    if (!header || header->value > 2147483648ull)
        return std::nullopt;
    const std::size_t size = static_cast<std::size_t>(header->value);
    std::size_t pos = header->next;

    Oid base_oid{};
    bool has_base_oid = false;
    std::uint64_t base_off = 0;
    bool has_base_off = false;
    if (kind == KIND_OFS_DELTA) {
        if (pos >= data.size())
            return std::nullopt;
        std::uint8_t c = data[pos++];
        std::uint64_t acc = c & 0x7f;
        bool more = (c & 0x80) != 0;
        while (more) {
            if (pos >= data.size())
                return std::nullopt;
            c = data[pos++];
            acc = ((acc + 1) << 7) | (c & 0x7f);
            more = (c & 0x80) != 0;
        }
        has_base_off = true;
        base_off = start - acc;
    } else if (kind == KIND_REF_DELTA) {
        if (pos + 20 > data.size())
            return std::nullopt;
        std::memcpy(base_oid.data(), data.data() + pos, 20);
        has_base_oid = true;
        pos += 20;
    }

    if (pos > data.size())
        return std::nullopt;
    auto inflated = inflate_exact(data.subspan(pos), size);
    if (!inflated)
        return std::nullopt;
    if (kind >= KIND_COMMIT && kind <= KIND_TAG)
        return Object{kind, std::move(*inflated)};
    if (kind != KIND_OFS_DELTA && kind != KIND_REF_DELTA)
        return std::nullopt;

    std::optional<Object> base;
    if (has_base_off) {
        if (base_off >= start)
            return std::nullopt;
        base = read_at(repo, pack, base_off, verify, depth + 1);
    } else if (has_base_oid) {
        base = read_object(repo, base_oid, verify);
    }
    if (!base)
        return std::nullopt;
    auto merged = apply_delta(Bytes(base->body.data(), base->body.size()),
                              Bytes(inflated->data(), inflated->size()));
    if (!merged)
        return std::nullopt;
    return Object{base->kind, std::move(*merged)};
}

std::optional<Pack> parse_idx(Bytes data, std::size_t pack_count, Bytes pack_trailer) {
    if (data.size() < 40)
        return std::nullopt;
    const std::size_t trailer_off = data.size() - 20;
    const Oid check = sha1(data.first(trailer_off));
    if (!bytes_equal(check, data.subspan(trailer_off, 20)))
        return std::nullopt;
    if (pack_trailer.size() != 20 ||
        std::memcmp(data.data() + data.size() - 40, pack_trailer.data(), 20) != 0)
        return std::nullopt;

    const bool is_v2 = data.size() >= 4 && data[0] == 0xff && data[1] == 0x74 && data[2] == 0x4f &&
                       data[3] == 0x63;
    const std::size_t fanout_off = is_v2 ? 8 : 0;
    if (is_v2 && be32(data, 4) != 2)
        return std::nullopt;
    if (data.size() < fanout_off + 1024 + 40)
        return std::nullopt;
    const std::size_t n = be32(data, fanout_off + 255 * 4);
    if (n != pack_count)
        return std::nullopt;

    Pack pack;
    pack.oids.resize(n);
    pack.offsets.resize(n);
    if (is_v2) {
        const std::size_t names_off = fanout_off + 1024;
        const std::size_t crcs_off = names_off + n * 20;
        const std::size_t offs_off = crcs_off + n * 4;
        const std::size_t large_off = offs_off + n * 4;
        if (large_off + 40 > data.size())
            return std::nullopt;
        const std::size_t large_bytes = data.size() - 40 - large_off;
        if (large_bytes % 8 != 0)
            return std::nullopt;
        for (std::size_t i = 0; i < n; ++i) {
            std::memcpy(pack.oids[i].data(), data.data() + names_off + i * 20, 20);
            const std::uint32_t raw_off = be32(data, offs_off + i * 4);
            std::uint64_t resolved = raw_off;
            if ((raw_off & 0x80000000u) != 0) {
                const std::size_t idx = raw_off & 0x7fffffffu;
                if (idx * 8 + 8 > large_bytes)
                    return std::nullopt;
                resolved = be64(data, large_off + idx * 8);
            }
            pack.offsets[i] = resolved;
        }
    } else {
        const std::size_t records_off = 1024;
        if (records_off + n * 24 + 40 > data.size())
            return std::nullopt;
        for (std::size_t i = 0; i < n; ++i) {
            const std::size_t rec = records_off + i * 24;
            pack.offsets[i] = be32(data, rec);
            std::memcpy(pack.oids[i].data(), data.data() + rec + 4, 20);
        }
    }
    return pack;
}

std::optional<Pack> open_pack(const fs::path& pack_path, const fs::path& idx_path) {
    auto pdata = read_file_opt(pack_path);
    if (!pdata || pdata->size() < 32)
        return std::nullopt;
    if (std::memcmp(pdata->data(), "PACK", 4) != 0)
        return std::nullopt;
    const std::uint32_t version = be32(bytes_of(*pdata), 4);
    if (version != 2 && version != 3)
        return std::nullopt;
    const std::size_t count = be32(bytes_of(*pdata), 8);
    const std::size_t trailer_off = pdata->size() - 20;
    const Oid pack_trailer = sha1(Bytes(pdata->data(), trailer_off));
    if (std::memcmp(pack_trailer.data(), pdata->data() + trailer_off, 20) != 0)
        return std::nullopt;

    auto idata = read_file_opt(idx_path);
    if (!idata)
        return std::nullopt;
    auto parsed = parse_idx(bytes_of(*idata), count, Bytes(pdata->data() + trailer_off, 20));
    if (!parsed)
        return std::nullopt;
    parsed->path = pack_path;
    parsed->data = std::move(*pdata);
    return parsed;
}

std::optional<Object> read_loose(const Repo& repo, const Oid& oid, bool verify) {
    const std::string hex = oid_hex(oid);
    const fs::path path = repo.git_dir / "objects" / path_from_bytes(hex.substr(0, 2)) /
                          path_from_bytes(hex.substr(2));
    auto compressed = read_file_opt(path);
    if (!compressed)
        return std::nullopt;
    auto inflated = inflate_unknown(bytes_of(*compressed));
    if (!inflated)
        return std::nullopt;
    Bytes data(inflated->data(), inflated->size());
    const std::size_t space =
        static_cast<std::size_t>(std::find(data.begin(), data.end(), ' ') - data.begin());
    std::size_t nul = space;
    while (nul < data.size() && data[nul] != 0)
        ++nul;
    if (space == 0 || nul >= data.size())
        return std::nullopt;
    const std::uint8_t kind = kind_from_name(str_of(data.first(space)));
    if (kind == 0)
        return std::nullopt;
    std::uint64_t declared = 0;
    for (std::size_t i = space + 1; i < nul; ++i) {
        const std::uint8_t c = data[i];
        if (c < '0' || c > '9')
            return std::nullopt;
        declared = declared * 10 + (c - '0');
    }
    Bytes body = data.subspan(nul + 1);
    if (body.size() != declared)
        return std::nullopt;
    Object object{kind, std::vector<std::uint8_t>(body.begin(), body.end())};
    if (verify) {
        auto hash = object_hash(kind, body);
        if (!hash || std::memcmp(hash->data(), oid.data(), oid.size()) != 0)
            return std::nullopt;
    }
    return object;
}

std::string trim_line(std::string_view text) {
    while (!text.empty() && (text.back() == '\n' || text.back() == '\r'))
        text.remove_suffix(1);
    return std::string(text);
}

void replace_ref(std::vector<Ref>& refs, std::string name, const Oid& oid) {
    for (auto& ref : refs) {
        if (ref.name == name) {
            ref.oid = oid;
            return;
        }
    }
    refs.push_back(Ref{std::move(name), oid});
}

std::optional<Oid> find_ref(const std::vector<Ref>& refs, std::string_view name) {
    for (const auto& ref : refs) {
        if (ref.name == name)
            return ref.oid;
    }
    return std::nullopt;
}

void read_packed_refs(const fs::path& git_dir, std::vector<Ref>& branches, std::vector<Ref>& tags) {
    auto data = read_file_opt(git_dir / "packed-refs");
    if (!data)
        return;
    std::string_view text(reinterpret_cast<const char*>(data->data()), data->size());
    std::size_t start = 0;
    while (start <= text.size()) {
        std::size_t end = text.find('\n', start);
        if (end == std::string_view::npos)
            end = text.size();
        std::string_view line = text.substr(start, end - start);
        if (!line.empty() && line.front() != '#' && line.front() != '^') {
            const std::size_t space = line.find(' ');
            if (space != std::string_view::npos && space != 0) {
                auto oid = oid_from_hex(line.substr(0, space));
                std::string_view name = line.substr(space + 1);
                if (oid) {
                    if (name.starts_with("refs/heads/"))
                        replace_ref(branches, std::string(name.substr(11)), *oid);
                    else if (name.starts_with("refs/tags/"))
                        replace_ref(tags, std::string(name.substr(10)), *oid);
                }
            }
        }
        if (end == text.size())
            break;
        start = end + 1;
    }
}

void read_ref_dir(const fs::path& base, std::string_view rel, std::vector<Ref>& refs) {
    const fs::path dir = rel.empty() ? base : base / path_from_bytes(rel);
    for (const auto& name : list_directory(dir)) {
        std::string child_rel(rel);
        if (!child_rel.empty())
            child_rel.push_back('/');
        child_rel += name;
        const fs::path child = base / path_from_bytes(child_rel);
        std::error_code ec;
        if (fs::is_directory(child, ec)) {
            read_ref_dir(base, child_rel, refs);
        } else {
            auto content = read_file_opt(child);
            if (!content)
                continue;
            const std::string line = trim_line(
                std::string_view(reinterpret_cast<const char*>(content->data()), content->size()));
            if (auto oid = oid_from_hex(line))
                replace_ref(refs, child_rel, *oid);
        }
    }
}

std::optional<Oid> resolve_head(const fs::path& git_dir, const std::vector<Ref>& branches,
                                const std::vector<Ref>& tags) {
    auto data = read_file_opt(git_dir / "HEAD");
    if (!data)
        return std::nullopt;
    const std::string line =
        trim_line(std::string_view(reinterpret_cast<const char*>(data->data()), data->size()));
    if (line.starts_with("ref: ")) {
        std::string_view name(line.data() + 5, line.size() - 5);
        if (name.starts_with("refs/heads/"))
            return find_ref(branches, name.substr(11));
        if (name.starts_with("refs/tags/"))
            return find_ref(tags, name.substr(10));
        return std::nullopt;
    }
    return oid_from_hex(line);
}

std::optional<fs::path> resolve_source(const fs::path& source) {
    std::error_code ec;
    const fs::path dotgit = source / ".git";
    if (fs::is_directory(dotgit, ec))
        return dotgit;
    if (fs::is_regular_file(source / "HEAD", ec) && fs::is_directory(source / "objects", ec))
        return source;
    return std::nullopt;
}

bool copy_tree(const fs::path& src, const fs::path& dst) {
    std::error_code ec;
    fs::create_directories(dst, ec);
    if (ec)
        return false;
    for (const auto& name : list_directory(src)) {
        const fs::path s = src / path_from_bytes(name);
        const fs::path d = dst / path_from_bytes(name);
        if (fs::is_directory(s, ec)) {
            if (!copy_tree(s, d))
                return false;
        } else if (fs::is_regular_file(s, ec)) {
            fs::create_hard_link(s, d, ec);
            if (ec) {
                ec.clear();
                fs::copy_file(s, d, fs::copy_options::overwrite_existing, ec);
                if (ec)
                    return false;
            }
        }
    }
    return true;
}

} // namespace

std::string oid_hex(const Oid& oid) {
    return hex_encode(Bytes(oid.data(), oid.size()));
}

std::optional<Oid> oid_from_hex(std::string_view hex) {
    Oid out{};
    if (!hex_decode(hex, MutBytes(out.data(), out.size())))
        return std::nullopt;
    return out;
}

std::optional<Oid> object_hash(std::uint8_t kind, Bytes body) {
    const std::string name = kind_name(kind);
    if (name == "unknown")
        return std::nullopt;
    std::string header = name;
    header.push_back(' ');
    header += std::to_string(body.size());
    header.push_back('\0');
    std::vector<std::uint8_t> data;
    data.reserve(header.size() + body.size());
    data.insert(data.end(), header.begin(), header.end());
    data.insert(data.end(), body.begin(), body.end());
    return sha1(Bytes(data.data(), data.size()));
}

std::optional<Repo> open_repo(const fs::path& git_dir) {
    Repo repo;
    repo.git_dir = git_dir;
    const fs::path pack_dir = git_dir / "objects" / "pack";
    std::error_code ec;
    if (fs::is_directory(pack_dir, ec)) {
        std::vector<std::string> names = list_directory(pack_dir);
        std::sort(names.begin(), names.end());
        for (const auto& name : names) {
            if (name.size() <= 4 || name.compare(name.size() - 4, 4, ".idx") != 0)
                continue;
            const std::string base = name.substr(0, name.size() - 4);
            const fs::path pack_path = pack_dir / path_from_bytes(base + ".pack");
            const fs::path idx_path = pack_dir / path_from_bytes(name);
            if (!path_is_file(pack_path))
                continue;
            auto pack = open_pack(pack_path, idx_path);
            if (!pack)
                return std::nullopt;
            repo.packs.push_back(std::move(*pack));
        }
    }
    return repo;
}

std::optional<Object> read_object(Repo& repo, const Oid& oid, bool verify) {
    for (auto& pack : repo.packs) {
        auto idx = find_oid(pack, oid);
        if (!idx)
            continue;
        auto object = read_at(repo, pack, pack.offsets[*idx], verify, 0);
        if (!object)
            return std::nullopt;
        if (verify) {
            auto hash = object_hash(object->kind, Bytes(object->body.data(), object->body.size()));
            if (!hash || std::memcmp(hash->data(), oid.data(), oid.size()) != 0)
                return std::nullopt;
        }
        return object;
    }
    return read_loose(repo, oid, verify);
}

std::shared_ptr<Repo> cached_repo(const fs::path& git_dir) {
    static std::mutex mutex;
    static std::map<std::string, std::pair<fs::file_time_type, std::shared_ptr<Repo>>> cache;
    std::error_code ec;
    const fs::path pack_dir = git_dir / "objects" / "pack";
    const fs::file_time_type stamp = fs::last_write_time(pack_dir, ec);
    const std::string key = path_to_bytes(git_dir);
    std::lock_guard<std::mutex> lock(mutex);
    auto it = cache.find(key);
    if (it != cache.end() && !ec && it->second.first == stamp)
        return it->second.second;
    auto repo = open_repo(git_dir);
    if (!repo)
        return nullptr;
    auto shared = std::make_shared<Repo>(std::move(*repo));
    cache[key] = {stamp, shared};
    return shared;
}

std::optional<Sig> parse_sig(std::string_view value) {
    const std::size_t tz_space = value.rfind(' ');
    if (tz_space == std::string_view::npos || tz_space == 0)
        return std::nullopt;
    const std::size_t sec_space = value.rfind(' ', tz_space - 1);
    if (sec_space == std::string_view::npos)
        return std::nullopt;
    const std::string_view sec_text = value.substr(sec_space + 1, tz_space - sec_space - 1);
    const std::string_view tz_text = value.substr(tz_space + 1);
    if (sec_text.empty() || tz_text.size() != 5 || (tz_text[0] != '+' && tz_text[0] != '-'))
        return std::nullopt;
    std::int64_t seconds = 0;
    bool negative = false;
    std::size_t i = 0;
    if (sec_text[0] == '-') {
        negative = true;
        i = 1;
    }
    if (i >= sec_text.size())
        return std::nullopt;
    for (; i < sec_text.size(); ++i) {
        if (sec_text[i] < '0' || sec_text[i] > '9')
            return std::nullopt;
        seconds = seconds * 10 + (sec_text[i] - '0');
    }
    if (negative)
        seconds = -seconds;
    std::int64_t hh = 0;
    std::int64_t mm = 0;
    for (std::size_t j = 1; j < 3; ++j) {
        if (tz_text[j] < '0' || tz_text[j] > '9')
            return std::nullopt;
        hh = hh * 10 + (tz_text[j] - '0');
    }
    for (std::size_t j = 3; j < 5; ++j) {
        if (tz_text[j] < '0' || tz_text[j] > '9')
            return std::nullopt;
        mm = mm * 10 + (tz_text[j] - '0');
    }
    std::int64_t tz = hh * 60 + mm;
    if (tz_text[0] == '-')
        tz = -tz;
    if (tz > 32767 || tz < -32768)
        return std::nullopt;

    const std::string_view ident = value.substr(0, sec_space);
    const std::size_t lt = ident.rfind('<');
    const std::size_t gt = ident.rfind('>');
    if (lt == std::string_view::npos || gt == std::string_view::npos || gt <= lt)
        return std::nullopt;
    std::string_view name = ident.substr(0, lt);
    if (!name.empty() && name.back() == ' ')
        name.remove_suffix(1);
    Sig sig;
    sig.name = std::string(name);
    sig.email = std::string(ident.substr(lt + 1, gt - lt - 1));
    sig.seconds = seconds;
    sig.tz_min = static_cast<std::int16_t>(tz);
    return sig;
}

namespace {

void append_sig(std::vector<std::uint8_t>& out, const Sig& sig) {
    auto append = [&](std::string_view text) { out.insert(out.end(), text.begin(), text.end()); };
    append(sig.name);
    append(" <");
    append(sig.email);
    append("> ");
    append(std::to_string(sig.seconds));
    out.push_back(' ');
    const std::int64_t minutes = sig.tz_min;
    const std::int64_t abs_min = minutes < 0 ? -minutes : minutes;
    out.push_back(minutes < 0 ? '-' : '+');
    const std::int64_t hh = abs_min / 60;
    const std::int64_t mm = abs_min % 60;
    out.push_back(static_cast<std::uint8_t>('0' + hh / 10));
    out.push_back(static_cast<std::uint8_t>('0' + hh % 10));
    out.push_back(static_cast<std::uint8_t>('0' + mm / 10));
    out.push_back(static_cast<std::uint8_t>('0' + mm % 10));
}

std::optional<ChangeId> parse_change_id(std::string_view text) {
    if (text.size() != 32)
        return std::nullopt;
    ChangeId id{};
    if (!hex_decode(text, MutBytes(id.data(), id.size())))
        return std::nullopt;
    return id;
}

bool canonical_mode(std::string_view mode) {
    return mode == "100644" || mode == "100755" || mode == "120000" || mode == "40000" ||
           mode == "160000";
}

} // namespace

std::optional<ParsedCommit> parse_commit(Bytes body) {
    const std::string_view text(reinterpret_cast<const char*>(body.data()), body.size());
    const std::size_t blank = text.find("\n\n");
    if (blank == std::string_view::npos)
        return std::nullopt;
    ParsedCommit out;
    out.message = std::string(text.substr(blank + 2));
    const std::size_t header_end = blank;
    std::size_t pos = 0;
    int last_extra = -1;
    std::size_t last_extra_start = 0;
    while (pos < header_end) {
        std::size_t line_end = text.find('\n', pos);
        if (line_end == std::string_view::npos || line_end > header_end)
            line_end = header_end;
        const std::string_view line = text.substr(pos, line_end - pos);
        if (!line.empty() && line.front() == ' ') {
            if (last_extra < 0) {
                out.canonical = false;
            } else {
                out.extras[static_cast<std::size_t>(last_extra)].value =
                    std::string(text.substr(last_extra_start, line_end - last_extra_start));
            }
        } else {
            last_extra = -1;
            const std::size_t space = line.find(' ');
            if (space == std::string_view::npos || space == 0) {
                out.canonical = false;
            } else {
                const std::string_view key = line.substr(0, space);
                const std::string_view value = line.substr(space + 1);
                if (key == "tree") {
                    if (auto oid = oid_from_hex(value))
                        out.tree = *oid;
                    else
                        out.canonical = false;
                } else if (key == "parent") {
                    if (auto oid = oid_from_hex(value))
                        out.parents.push_back(*oid);
                    else
                        out.canonical = false;
                } else if (key == "author") {
                    if (auto sig = parse_sig(value))
                        out.author = *sig;
                    else
                        out.canonical = false;
                } else if (key == "committer") {
                    if (auto sig = parse_sig(value))
                        out.committer = *sig;
                    else
                        out.canonical = false;
                } else if (key == "veins-change-id") {
                    if (auto change = parse_change_id(value))
                        out.change_id = *change;
                    else
                        out.canonical = false;
                } else {
                    out.extras.push_back(KeyValue{std::string(key), std::string(value)});
                    last_extra = static_cast<int>(out.extras.size() - 1);
                    last_extra_start = pos + key.size() + 1;
                }
            }
        }
        pos = line_end + 1;
    }
    return out;
}

std::vector<std::uint8_t> serialize_commit(const ParsedCommit& commit) {
    std::vector<std::uint8_t> out;
    auto append = [&](std::string_view text) { out.insert(out.end(), text.begin(), text.end()); };
    append("tree ");
    append(oid_hex(commit.tree));
    out.push_back('\n');
    for (const auto& parent : commit.parents) {
        append("parent ");
        append(oid_hex(parent));
        out.push_back('\n');
    }
    append("author ");
    append_sig(out, commit.author);
    out.push_back('\n');
    append("committer ");
    append_sig(out, commit.committer);
    out.push_back('\n');
    for (const auto& kv : commit.extras) {
        append(kv.key);
        out.push_back(' ');
        append(kv.value);
        out.push_back('\n');
    }
    out.push_back('\n');
    append(commit.message);
    return out;
}

std::optional<ParsedTree> parse_tree(Bytes body) {
    ParsedTree out;
    std::size_t pos = 0;
    while (pos < body.size()) {
        const std::size_t mode_start = pos;
        while (pos < body.size() && body[pos] != ' ')
            ++pos;
        if (pos >= body.size()) {
            out.canonical = false;
            break;
        }
        const std::string mode(reinterpret_cast<const char*>(body.data() + mode_start),
                               pos - mode_start);
        ++pos;
        const std::size_t name_start = pos;
        while (pos < body.size() && body[pos] != 0)
            ++pos;
        if (pos >= body.size()) {
            out.canonical = false;
            break;
        }
        const std::string name(reinterpret_cast<const char*>(body.data() + name_start),
                               pos - name_start);
        ++pos;
        if (pos + 20 > body.size()) {
            out.canonical = false;
            break;
        }
        RawTreeEntry entry;
        entry.mode = mode;
        entry.name = name;
        std::memcpy(entry.oid.data(), body.data() + pos, 20);
        pos += 20;
        if (!canonical_mode(mode))
            out.canonical = false;
        out.entries.push_back(std::move(entry));
    }
    if (pos != body.size())
        out.canonical = false;
    return out;
}

std::string mode_for_kind(std::uint8_t kind) {
    if (kind == KIND_EXECUTABLE)
        return "100755";
    if (kind == KIND_SYMLINK)
        return "120000";
    if (kind == KIND_SUBTREE)
        return "40000";
    if (kind == KIND_SUBMODULE)
        return "160000";
    return "100644";
}

std::uint8_t mode_kind(std::string_view mode) {
    if (mode == "40000" || mode == "040000")
        return KIND_SUBTREE;
    if (mode == "120000")
        return KIND_SYMLINK;
    if (mode == "160000")
        return KIND_SUBMODULE;
    if (mode == "100755")
        return KIND_EXECUTABLE;
    return KIND_FILE;
}

std::optional<ParsedTag> parse_tag(Bytes body) {
    ParsedTag out;
    const std::string_view text(reinterpret_cast<const char*>(body.data()), body.size());
    std::size_t pos = 0;
    while (pos < text.size()) {
        std::size_t end = text.find('\n', pos);
        if (end == std::string_view::npos)
            end = text.size();
        const std::string_view line = text.substr(pos, end - pos);
        if (line.empty())
            break;
        const std::size_t space = line.find(' ');
        if (space != std::string_view::npos && space != 0) {
            const std::string_view key = line.substr(0, space);
            const std::string_view value = line.substr(space + 1);
            if (key == "object") {
                if (auto oid = oid_from_hex(value))
                    out.target = *oid;
            } else if (key == "type") {
                out.target_kind = kind_from_name(value);
            }
        }
        pos = end + 1;
    }
    return out;
}

std::optional<Id> IdMap::get(const Oid& oid) const {
    auto it = items.find(oid);
    if (it == items.end())
        return std::nullopt;
    return it->second;
}

void IdMap::put(const Oid& oid, const Id& id) {
    items[oid] = id;
}

std::optional<Oid> IdMap::reverse(const Id& id) const {
    for (const auto& item : items) {
        if (item.second == id)
            return item.first;
    }
    return std::nullopt;
}

namespace {

fs::path map_path(const fs::path& root, std::string_view name) {
    return git_map_dir(root) / path_from_bytes(std::string(name) + ".map");
}

} // namespace

bool load_map(const fs::path& root, std::string_view name, IdMap& out) {
    out.items.clear();
    auto data = read_file_opt(map_path(root, name));
    if (!data)
        return true;
    if (data->size() < 9 || std::memcmp(data->data(), "VMAP1", 5) != 0)
        return false;
    const std::uint32_t count = static_cast<std::uint32_t>((*data)[5]) |
                                (static_cast<std::uint32_t>((*data)[6]) << 8) |
                                (static_cast<std::uint32_t>((*data)[7]) << 16) |
                                (static_cast<std::uint32_t>((*data)[8]) << 24);
    if (data->size() != 9 + static_cast<std::size_t>(count) * 52)
        return false;
    for (std::size_t i = 0; i < count; ++i) {
        const std::size_t off = 9 + i * 52;
        Oid oid{};
        std::memcpy(oid.data(), data->data() + off, 20);
        Id id{};
        std::memcpy(id.data(), data->data() + off + 20, 32);
        out.put(oid, id);
    }
    return true;
}

bool save_map(const fs::path& root, std::string_view name, const IdMap& map) {
    std::vector<std::uint8_t> data;
    data.insert(data.end(), {'V', 'M', 'A', 'P', '1'});
    const std::uint32_t count = static_cast<std::uint32_t>(map.items.size());
    data.push_back(static_cast<std::uint8_t>(count & 0xff));
    data.push_back(static_cast<std::uint8_t>((count >> 8) & 0xff));
    data.push_back(static_cast<std::uint8_t>((count >> 16) & 0xff));
    data.push_back(static_cast<std::uint8_t>((count >> 24) & 0xff));
    for (const auto& item : map.items) {
        data.insert(data.end(), item.first.begin(), item.first.end());
        data.insert(data.end(), item.second.begin(), item.second.end());
    }
    return write_atomic(map_path(root, name), Bytes(data.data(), data.size()));
}

bool save_raw(const fs::path& root, const Id& id, Bytes body) {
    const fs::path path = git_map_dir(root) / "raw" / path_from_bytes(hex_encode(id));
    return write_atomic(path, body);
}

std::optional<std::vector<std::uint8_t>> load_raw(const fs::path& root, const Id& id) {
    return read_file_opt(git_map_dir(root) / "raw" / path_from_bytes(hex_encode(id)));
}

RefSet read_refs(const fs::path& git_dir) {
    RefSet out;
    read_packed_refs(git_dir, out.branches, out.tags);
    read_ref_dir(git_dir / "refs" / "heads", "", out.branches);
    read_ref_dir(git_dir / "refs" / "tags", "", out.tags);
    read_ref_dir(git_dir / "refs" / "remotes", "", out.remotes);
    out.head = resolve_head(git_dir, out.branches, out.tags);
    return out;
}

Id lazy_blob_id(const Oid& oid) {
    Id id{};
    std::memcpy(id.data(), "veins-gitoid", 12);
    std::memcpy(id.data() + 12, oid.data(), 20);
    return id;
}

std::optional<Oid> lazy_blob_oid(const Id& id) {
    if (!is_lazy_blob(id))
        return std::nullopt;
    Oid out{};
    std::memcpy(out.data(), id.data() + 12, 20);
    return out;
}

bool ensure_mirror(const fs::path& root) {
    const fs::path dir = git_dir(root);
    if (!ensure_directory(dir) || !ensure_directory(dir / "objects") ||
        !ensure_directory(dir / "refs" / "heads") || !ensure_directory(dir / "refs" / "tags"))
        return false;
    if (!path_is_file(dir / "HEAD")) {
        const std::string body = "ref: refs/heads/main\n";
        if (!write_file(dir / "HEAD", bytes_of(body)))
            return false;
    }
    if (!path_is_file(dir / "config")) {
        const std::string body = "[core]\n\trepositoryformatversion = "
                                 "0\n\tfilemode = true\n\tbare = true\n";
        if (!write_file(dir / "config", bytes_of(body)))
            return false;
    }
    return true;
}

int prepare_mirror(const fs::path& root, const fs::path& source) {
    const fs::path target = git_dir(root);
    if (path_is_file(target / "HEAD"))
        return 0;
    const auto resolved = resolve_source(source);
    if (!resolved)
        return 2;
    if (!copy_tree(*resolved, target))
        return 3;
    return 0;
}

bool write_loose(const fs::path& git_dir, std::uint8_t kind, const Oid& oid, Bytes body) {
    const std::string hex = oid_hex(oid);
    const fs::path final_path =
        git_dir / "objects" / path_from_bytes(hex.substr(0, 2)) / path_from_bytes(hex.substr(2));
    if (path_is_file(final_path))
        return true;
    std::string header = kind_name(kind);
    header.push_back(' ');
    header += std::to_string(body.size());
    header.push_back('\0');
    uLongf bound = compressBound(static_cast<uLong>(header.size() + body.size()));
    std::vector<std::uint8_t> compressed(bound);
    uLongf dest_len = bound;
    std::vector<std::uint8_t> raw;
    raw.reserve(header.size() + body.size());
    raw.insert(raw.end(), header.begin(), header.end());
    raw.insert(raw.end(), body.begin(), body.end());
    const int rc =
        compress2(compressed.data(), &dest_len, raw.data(), static_cast<uLong>(raw.size()), 6);
    if (rc != Z_OK)
        return false;
    compressed.resize(dest_len);
    return write_atomic(final_path, Bytes(compressed.data(), compressed.size()));
}

bool write_ref(const fs::path& git_dir, std::string_view name, const Oid& oid) {
    const std::string line = oid_hex(oid) + "\n";
    return write_atomic(git_dir / path_from_bytes(name), bytes_of(line));
}

std::string remote_key(std::string_view remote, std::string_view field) {
    std::string out = "remote.";
    out += remote;
    out.push_back('.');
    out += field;
    return out;
}

std::vector<std::string> list_remotes(const fs::path& root) {
    std::vector<std::string> out;
    auto data = read_file_opt(root / ".veins" / "config");
    if (!data)
        return out;
    std::string_view text(reinterpret_cast<const char*>(data->data()), data->size());
    std::size_t start = 0;
    while (start <= text.size()) {
        std::size_t end = text.find('\n', start);
        if (end == std::string_view::npos)
            end = text.size();
        const std::string_view line = text.substr(start, end - start);
        if (line.starts_with("remote.")) {
            const std::size_t dot = line.find(".url", 7);
            if (dot != std::string_view::npos && dot > 7)
                out.emplace_back(line.substr(7, dot - 7));
        }
        if (end == text.size())
            break;
        start = end + 1;
    }
    return out;
}

} // namespace vn::git