#include "cli/cli.h"
#include "cli/local_commands.h"
#include "cli/net_commands.h"
#include "git/git.h"
#include "merge/merge.h"
#include "protocol/promisor.h"
#include "store/store.h"
#include "worktree/attributes.h"
#include "worktree/pathspec.h"
#include "worktree/worktree.h"

#include <algorithm>
#include <atomic>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <map>
#include <set>
#include <sstream>
#include <thread>
#include <unordered_map>

namespace vn {

namespace {

bool is_flag(std::string_view arg) {
    return !arg.empty() && arg.front() == '-';
}

std::optional<fs::path> open_repo() {
    const auto root = discover_repo(".");
    if (!root) {
        error_prefix();
        std::cout << "not a veins repository\n";
        return std::nullopt;
    }
    return root;
}

std::string join_args(const std::vector<std::string>& parts) {
    std::string out;
    for (std::size_t i = 0; i < parts.size(); ++i) {
        if (i != 0)
            out.push_back(' ');
        out += parts[i];
    }
    return out;
}

bool message_is_blank(const std::vector<std::string>& parts) {
    for (const auto& part : parts) {
        for (char c : part) {
            if (c != ' ' && c != '\t' && c != '\n' && c != '\r')
                return false;
        }
    }
    return true;
}

Result<std::vector<std::string>> parse_message(const std::vector<std::string>& args,
                                               std::size_t start) {
    std::vector<std::string> parts;
    bool end_flags = false;
    for (std::size_t i = start; i < args.size(); ++i) {
        const std::string& arg = args[i];
        if (!end_flags && arg == "--") {
            end_flags = true;
        } else if (!end_flags && (arg == "-m" || arg == "-message")) {
            if (i + 1 < args.size()) {
                parts.push_back(args[++i]);
            } else {
                error_prefix();
                std::cout << arg << " requires a message\n";
                return fail_usage("missing message");
            }
        } else if (!end_flags && is_flag(arg)) {
            error_prefix();
            std::cout << "unknown flag: " << arg << "\n";
            return fail_usage("unknown flag");
        } else {
            parts.push_back(arg);
        }
    }
    return parts;
}

std::optional<std::string> edit_commit_message(const fs::path& root, std::string_view initial) {
    const fs::path file = tmp_dir(root) / "commit-message.txt";
    std::string body(initial);
    if (!body.empty() && body.back() != '\n')
        body.push_back('\n');
    body += "\n# Enter a commit message. Lines starting with '#' are ignored.\n";
    if (!write_file(file, bytes_of(body))) {
        error_prefix();
        std::cout << "cannot write message file\n";
        return std::nullopt;
    }
    if (!run_editor(root, {}, file)) {
        (void)remove_file(file);
        error_prefix();
        std::cout << "editor exited with an error\n";
        return std::nullopt;
    }
    auto data = read_file_opt(file);
    (void)remove_file(file);
    if (!data)
        return std::nullopt;
    std::string_view text(reinterpret_cast<const char*>(data->data()), data->size());
    std::vector<std::string> lines;
    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 line(text.substr(start, end - start));
        const auto first = line.find_first_not_of(" \t\r");
        if (first != std::string::npos && line[first] == '#')
            line.clear();
        else if (first == std::string::npos)
            line.clear();
        else
            line.erase(0, first);
        lines.push_back(std::move(line));
        if (end == text.size())
            break;
        start = end + 1;
    }
    while (!lines.empty() && lines.back().empty())
        lines.pop_back();
    while (!lines.empty() && lines.front().empty())
        lines.erase(lines.begin());
    std::string out;
    for (std::size_t i = 0; i < lines.size(); ++i) {
        if (i != 0)
            out.push_back('\n');
        out += lines[i];
    }
    return out;
}

void print_cell(std::string_view text, std::size_t width, Color color, bool dim) {
    if (dim) {
        print_styled(text, color, true, false);
    } else if (color == Color::Default) {
        std::cout << text;
    } else {
        print_colored(text, color, false, false);
    }
    for (std::size_t i = text.size(); i < width; ++i)
        std::cout << ' ';
}

void print_gap() {
    std::cout << "  ";
}

std::string first_line(const std::string& message) {
    const std::size_t newline = message.find('\n');
    return newline == std::string::npos ? message : message.substr(0, newline);
}

std::string short_hex(const Id& id) {
    return hex_encode(id).substr(0, 12);
}

std::string short_change_id(const std::vector<std::string>& ids, std::size_t index) {
    const std::string& target = ids[index];
    std::size_t len = std::min<std::size_t>(4, target.size());
    while (len < target.size()) {
        const std::string_view prefix(target.data(), len);
        bool unique = true;
        for (std::size_t j = 0; j < ids.size(); ++j) {
            if (j == index)
                continue;
            if (ids[j] == target)
                continue;
            if (ids[j].starts_with(prefix)) {
                unique = false;
                break;
            }
        }
        if (unique)
            break;
        ++len;
    }
    return target.substr(0, len);
}

struct DiffOp {
    char tag = ' ';
    std::size_t ai = 0;
    std::size_t bi = 0;
};

std::vector<std::string> split_lines(Bytes data) {
    std::vector<std::string> out;
    std::size_t start = 0;
    for (std::size_t i = 0; i < data.size(); ++i) {
        if (data[i] == '\n') {
            out.emplace_back(reinterpret_cast<const char*>(data.data() + start), i - start);
            start = i + 1;
        }
    }
    if (start < data.size()) {
        out.emplace_back(reinterpret_cast<const char*>(data.data() + start), data.size() - start);
    } else if (!data.empty() && data.back() == '\n') {
        // A trailing newline does not introduce an extra empty line.
    } else if (data.empty()) {
        // No lines.
    }
    return out;
}

std::vector<DiffOp> build_ops_lcs(const std::vector<std::string>& a,
                                  const std::vector<std::string>& b) {
    const std::size_t n = a.size();
    const std::size_t m = b.size();
    const std::size_t cols = m + 1;
    std::vector<std::uint32_t> dp((n + 1) * cols, 0);
    for (std::size_t i = 1; i <= n; ++i) {
        for (std::size_t j = 1; j <= m; ++j) {
            if (a[i - 1] == b[j - 1])
                dp[i * cols + j] = dp[(i - 1) * cols + (j - 1)] + 1;
            else
                dp[i * cols + j] = std::max(dp[(i - 1) * cols + j], dp[i * cols + (j - 1)]);
        }
    }
    std::vector<DiffOp> ops;
    std::size_t i = n;
    std::size_t j = m;
    while (i > 0 || j > 0) {
        if (i > 0 && j > 0 && a[i - 1] == b[j - 1]) {
            ops.push_back(DiffOp{' ', i - 1, j - 1});
            --i;
            --j;
        } else if (j > 0 && (i == 0 || dp[i * cols + (j - 1)] >= dp[(i - 1) * cols + j])) {
            ops.push_back(DiffOp{'+', 0, j - 1});
            --j;
        } else {
            ops.push_back(DiffOp{'-', i - 1, 0});
            --i;
        }
    }
    std::reverse(ops.begin(), ops.end());
    return ops;
}

std::vector<DiffOp> build_ops_myers(const std::vector<std::string>& a,
                                    const std::vector<std::string>& b) {
    const int n = static_cast<int>(a.size());
    const int m = static_cast<int>(b.size());
    const int max_d = n + m;
    const int offset = max_d;
    std::vector<int> v(static_cast<std::size_t>(2 * max_d + 1), 0);
    std::vector<std::vector<int>> trace;
    constexpr std::size_t trace_cap = 64u * 1024u * 1024u;
    int found_d = -1;
    for (int d = 0; d <= max_d; ++d) {
        if (static_cast<std::size_t>(trace.size() + 1) * v.size() * sizeof(int) > trace_cap)
            return {};
        trace.push_back(v);
        for (int k = -d; k <= d; k += 2) {
            int x = 0;
            if (k == -d || (k != d && v[static_cast<std::size_t>(offset + k - 1)] <
                                          v[static_cast<std::size_t>(offset + k + 1)]))
                x = v[static_cast<std::size_t>(offset + k + 1)];
            else
                x = v[static_cast<std::size_t>(offset + k - 1)] + 1;
            int y = x - k;
            while (x < n && y < m &&
                   a[static_cast<std::size_t>(x)] == b[static_cast<std::size_t>(y)]) {
                ++x;
                ++y;
            }
            v[static_cast<std::size_t>(offset + k)] = x;
            if (x >= n && y >= m) {
                found_d = d;
                break;
            }
        }
        if (found_d >= 0)
            break;
    }
    if (found_d < 0)
        return {};
    std::vector<DiffOp> ops;
    int x = n;
    int y = m;
    for (int d = found_d; d >= 0; --d) {
        const auto& prev = trace[static_cast<std::size_t>(d)];
        const int k = x - y;
        int prev_k = 0;
        if (k == -d || (k != d && prev[static_cast<std::size_t>(offset + k - 1)] <
                                      prev[static_cast<std::size_t>(offset + k + 1)]))
            prev_k = k + 1;
        else
            prev_k = k - 1;
        const int prev_x = prev[static_cast<std::size_t>(offset + prev_k)];
        const int prev_y = prev_x - prev_k;
        while (x > prev_x && y > prev_y) {
            ops.push_back(
                DiffOp{' ', static_cast<std::size_t>(x - 1), static_cast<std::size_t>(y - 1)});
            --x;
            --y;
        }
        if (d > 0) {
            if (x == prev_x) {
                ops.push_back(DiffOp{'+', 0, static_cast<std::size_t>(y - 1)});
                --y;
            } else {
                ops.push_back(DiffOp{'-', static_cast<std::size_t>(x - 1), 0});
                --x;
            }
        }
    }
    std::reverse(ops.begin(), ops.end());
    return ops;
}

std::vector<DiffOp> build_ops_fallback(const std::vector<std::string>& a,
                                       const std::vector<std::string>& b) {
    std::size_t prefix = 0;
    while (prefix < a.size() && prefix < b.size() && a[prefix] == b[prefix])
        ++prefix;
    std::size_t suffix = 0;
    while (suffix < a.size() - prefix && suffix < b.size() - prefix &&
           a[a.size() - 1 - suffix] == b[b.size() - 1 - suffix])
        ++suffix;
    std::vector<DiffOp> ops;
    for (std::size_t i = 0; i < prefix; ++i)
        ops.push_back(DiffOp{' ', i, i});
    for (std::size_t i = prefix; i < a.size() - suffix; ++i)
        ops.push_back(DiffOp{'-', i, 0});
    for (std::size_t j = prefix; j < b.size() - suffix; ++j)
        ops.push_back(DiffOp{'+', 0, j});
    for (std::size_t k = 0; k < suffix; ++k) {
        const std::size_t i = a.size() - suffix + k;
        const std::size_t j = b.size() - suffix + k;
        ops.push_back(DiffOp{' ', i, j});
    }
    return ops;
}

std::vector<DiffOp> build_ops(const std::vector<std::string>& a,
                              const std::vector<std::string>& b) {
    const std::size_t n = a.size();
    const std::size_t m = b.size();
    if (n == 0 && m == 0)
        return {};
    if (n != 0 && m != 0 && n <= 2048 && m <= 2048)
        return build_ops_lcs(a, b);
    if (n != 0 && m != 0 && n * m <= 4'000'000)
        return build_ops_lcs(a, b);
    auto myers = build_ops_myers(a, b);
    if (!myers.empty())
        return myers;
    return build_ops_fallback(a, b);
}

void render_unified(const std::vector<std::string>& a, const std::vector<std::string>& b) {
    const auto ops = build_ops(a, b);
    std::vector<std::size_t> changes;
    for (std::size_t i = 0; i < ops.size(); ++i) {
        if (ops[i].tag != ' ')
            changes.push_back(i);
    }
    constexpr std::size_t context = 3;
    std::size_t pos = 0;
    std::size_t old_seen = 0;
    std::size_t new_seen = 0;
    std::size_t ci = 0;
    while (ci < changes.size()) {
        const std::size_t first = changes[ci];
        std::size_t start = first > context ? first - context : 0;
        std::size_t last = first;
        ++ci;
        while (ci < changes.size() && changes[ci] <= last + context * 2) {
            last = changes[ci];
            ++ci;
        }
        std::size_t end = std::min(last + context + 1, ops.size());
        while (pos < start) {
            const auto& op = ops[pos];
            if (op.tag == ' ') {
                ++old_seen;
                ++new_seen;
            } else if (op.tag == '-') {
                ++old_seen;
            } else {
                ++new_seen;
            }
            ++pos;
        }
        std::size_t old_count = 0;
        std::size_t new_count = 0;
        for (std::size_t e = start; e < end; ++e) {
            if (ops[e].tag == ' ') {
                ++old_count;
                ++new_count;
            } else if (ops[e].tag == '-') {
                ++old_count;
            } else {
                ++new_count;
            }
        }
        const std::size_t old_start = old_seen + (old_count > 0 ? 1 : 0);
        const std::size_t new_start = new_seen + (new_count > 0 ? 1 : 0);
        std::cout << "@@ -" << old_start << "," << old_count << " +" << new_start << ","
                  << new_count << " @@\n";
        while (pos < end) {
            const auto& op = ops[pos];
            if (op.tag == ' ') {
                std::cout << " " << a[op.ai] << "\n";
                ++old_seen;
                ++new_seen;
            } else if (op.tag == '-') {
                print_colored("-", Color::Red, false, false);
                print_colored(a[op.ai], Color::Red, false, false);
                std::cout << "\n";
                ++old_seen;
            } else {
                print_colored("+", Color::Green, false, false);
                print_colored(b[op.bi], Color::Green, false, false);
                std::cout << "\n";
                ++new_seen;
            }
            ++pos;
        }
    }
}

bool contains_nul(Bytes data) {
    const std::size_t limit = std::min<std::size_t>(data.size(), 8192);
    for (std::size_t i = 0; i < limit; ++i) {
        if (data[i] == 0)
            return true;
    }
    return false;
}

std::size_t render_diff(Store& store, std::optional<Id> old_tree, std::optional<Id> new_tree,
                        bool announce_no_diff, std::string_view path_filter = {}) {
    auto changes = compare_trees(store, old_tree, new_tree);
    if (!path_filter.empty()) {
        changes.erase(std::remove_if(changes.begin(), changes.end(),
                                     [&](const TreeChange& change) {
                                         return change.path != path_filter &&
                                                !(change.path.size() > path_filter.size() &&
                                                  change.path.compare(0, path_filter.size(),
                                                                      path_filter) == 0 &&
                                                  change.path[path_filter.size()] == '/');
                                     }),
                      changes.end());
    }
    for (const auto& change : changes) {
        if (change.new_kind == KIND_CONFLICT) {
            std::cout << "Conflict: " << change.path << "\n";
            continue;
        }
        std::vector<std::uint8_t> old_data;
        std::vector<std::uint8_t> new_data;
        if (change.old_kind != KIND_MISSING && change.old_id) {
            if (auto data = read_blob(store, *change.old_id))
                old_data = std::move(*data);
        }
        if (change.new_kind != KIND_MISSING && change.new_id) {
            if (auto data = read_blob(store, *change.new_id))
                new_data = std::move(*data);
        }
        if (contains_nul(bytes_of(old_data)) || contains_nul(bytes_of(new_data))) {
            std::cout << "Binary files a/" << change.path << " and b/" << change.path
                      << " differ\n";
            continue;
        }
        print_colored("--- ", Color::Red, false, false);
        if (change.old_kind == KIND_MISSING) {
            print_colored("/dev/null", Color::Red, false, false);
        } else {
            print_colored("a/", Color::Red, false, false);
            print_colored(change.path, Color::Red, false, false);
        }
        std::cout << "\n";
        print_colored("+++ ", Color::Green, false, false);
        if (change.new_kind == KIND_MISSING) {
            print_colored("/dev/null", Color::Green, false, false);
        } else {
            print_colored("b/", Color::Green, false, false);
            print_colored(change.path, Color::Green, false, false);
        }
        std::cout << "\n";
        const auto a = split_lines(bytes_of(old_data));
        const auto b = split_lines(bytes_of(new_data));
        render_unified(a, b);
    }
    if (announce_no_diff && changes.empty()) {
        info_prefix();
        std::cout << "no diff to show\n";
    }
    return changes.size();
}

int run_init(const std::vector<std::string>& args) {
    std::string path = ".";
    std::optional<std::string> source;
    bool end_flags = false;
    for (std::size_t i = 2; i < args.size(); ++i) {
        const std::string& arg = args[i];
        if (!end_flags && arg == "--") {
            end_flags = true;
        } else if (!end_flags && arg.rfind("-git-import:", 0) == 0) {
            source = arg.substr(12);
            if (source->empty()) {
                error_prefix();
                std::cout << "-git-import: requires a path\n";
                return 1;
            }
        } else if (!end_flags && is_flag(arg)) {
            error_prefix();
            std::cout << "unknown flag: " << arg << "\n";
            return 1;
        } else {
            path = arg;
        }
    }
    const auto initialized = init_repo(path_from_bytes(path));
    if (!initialized) {
        error_prefix();
        std::cout << "init failed with code " << initialized.error().offset << "\n";
        return 1;
    }
    info_prefix();
    std::cout << "initialized veins repository at " << path_display(*initialized) << "\n";
    if (source) {
        const int prepared = git_prepare_mirror(*initialized, *source);
        if (prepared != 0) {
            error_prefix();
            if (prepared == 2) {
                std::cout << "-git-import: " << *source
                          << " is not a git repository root (expected the directory "
                             "containing .git)\n";
            } else {
                std::cout << "cannot prepare git mirror from " << *source << " (code " << prepared
                          << ")\n";
            }
            return 1;
        }
        return git_import(*initialized);
    }
    return 0;
}

int run_status() {
    const auto root = open_repo();
    if (!root)
        return 1;
    Store store = Store::open_all(*root);
    const int snap = snapshot_run(*root, store);
    if (snap != 0)
        return snap;
    auto view = current_view(*root, store);
    if (!view) {
        error_prefix();
        std::cout << "no operation state\n";
        return 1;
    }
    const auto wc = working_copy_id(*view);
    if (!wc) {
        info_prefix();
        std::cout << "working copy clean\n";
        return 0;
    }
    std::optional<Id> old_tree;
    std::optional<Id> new_tree;
    auto wc_body = store.read_body(*wc, TYPE_COMMIT);
    if (!wc_body) {
        error_prefix();
        std::cout << "no operation state\n";
        return 1;
    }
    auto wc_commit = decode_commit(bytes_of(*wc_body));
    if (!wc_commit) {
        error_prefix();
        std::cout << "no operation state\n";
        return 1;
    }
    new_tree = wc_commit->root_tree;
    if (!wc_commit->parents.empty()) {
        auto parent_body = store.read_body(wc_commit->parents.front(), TYPE_COMMIT);
        if (parent_body) {
            auto parent_commit = decode_commit(bytes_of(*parent_body));
            if (parent_commit)
                old_tree = parent_commit->root_tree;
        }
    }
    const bool trees_equal =
        old_tree && new_tree && std::memcmp(old_tree->data(), new_tree->data(), ID_LEN) == 0;
    const auto changes =
        trees_equal ? std::vector<TreeChange>{} : compare_trees(store, old_tree, new_tree);
    std::size_t conflicts = 0;
    for (const auto& change : changes) {
        if (change.old_kind == KIND_MISSING) {
            print_colored("A", Color::BrightGreen, false, false);
            std::cout << " " << change.path << "\n";
        } else if (change.new_kind == KIND_MISSING) {
            print_colored("D", Color::Red, false, false);
            std::cout << " " << change.path << "\n";
        } else if (change.new_kind == KIND_CONFLICT) {
            print_colored("C", Color::BrightRed, false, false);
            std::cout << " " << change.path << "\n";
            ++conflicts;
        } else {
            print_colored("M", Color::Cyan, false, false);
            std::cout << " " << change.path << "\n";
        }
    }
    if (changes.empty()) {
        info_prefix();
        std::cout << "working copy clean\n";
    }
    if (conflicts > 0)
        std::cout << conflicts << " conflict(s)\n";

    std::vector<Id> stack{*wc};
    std::set<Id> seen;
    std::size_t conflicted_commits = 0;
    while (!stack.empty()) {
        const Id id = stack.back();
        stack.pop_back();
        if (!seen.insert(id).second)
            continue;
        auto loaded = load_commit(store, id);
        if (!loaded)
            continue;
        if (tree_conflicted(store, loaded->commit.root_tree))
            ++conflicted_commits;
        for (const auto& parent : loaded->commit.parents)
            stack.push_back(parent);
    }
    if (conflicted_commits > 0)
        std::cout << conflicted_commits << " conflicted commit(s) in ancestry\n";
    return 0;
}

int run_log(const std::vector<std::string>& args) {
    std::string rev;
    bool col_titles = true;
    bool end_flags = false;
    std::optional<std::size_t> limit;
    bool first = false;
    auto parse_count = [](std::string_view text, std::size_t& out) -> bool {
        if (text.empty())
            return false;
        std::size_t value = 0;
        for (char c : text) {
            if (c < '0' || c > '9')
                return false;
            value = value * 10 + static_cast<std::size_t>(c - '0');
        }
        if (value == 0)
            return false;
        out = value;
        return true;
    };
    for (std::size_t i = 2; i < args.size(); ++i) {
        const std::string& arg = args[i];
        if (!end_flags && arg == "--") {
            end_flags = true;
        } else if (!end_flags && (arg == "-r" || arg == "-rev")) {
            if (i + 1 >= args.size()) {
                error_prefix();
                std::cout << arg << " requires a revision\n";
                return 1;
            }
            rev = args[++i];
        } else if (!end_flags && arg == "-no-col-titles") {
            col_titles = false;
        } else if (!end_flags && (arg == "-l" || arg == "-f")) {
            if (i + 1 >= args.size()) {
                error_prefix();
                std::cout << arg << " requires a count\n";
                return 1;
            }
            std::size_t count = 0;
            if (!parse_count(args[++i], count)) {
                error_prefix();
                std::cout << arg << " requires a positive count\n";
                return 1;
            }
            limit = count;
            first = arg == "-f";
        } else if (!end_flags && arg.size() > 2 &&
                   (arg[0] == '-' && (arg[1] == 'l' || arg[1] == 'f'))) {
            std::size_t count = 0;
            if (!parse_count(std::string_view(arg).substr(2), count)) {
                error_prefix();
                std::cout << "invalid log count: " << arg << "\n";
                return 1;
            }
            limit = count;
            first = arg[1] == 'f';
        } else if (!end_flags && arg.size() > 1 && (arg[0] == 'l' || arg[0] == 'f')) {
            std::size_t count = 0;
            if (parse_count(std::string_view(arg).substr(1), count)) {
                limit = count;
                first = arg[0] == 'f';
            } else {
                rev = arg;
            }
        } else if (!end_flags && is_flag(arg)) {
            error_prefix();
            std::cout << "unknown flag: " << arg << "\n";
            return 1;
        } else {
            rev = arg;
        }
    }
    if (!limit) {
        std::size_t amount = 20;
        if (auto configured = user_config_value("log.default_amount")) {
            if (!parse_count(*configured, amount))
                amount = 20;
        }
        limit = amount;
    }
    const auto root = open_repo();
    if (!root)
        return 1;
    Store store = Store::open_all(*root);
    const int snap = snapshot_run(*root, store);
    if (snap != 0)
        return snap;
    auto view = current_view(*root, store);
    if (!view) {
        error_prefix();
        std::cout << "no operation state\n";
        return 1;
    }
    const auto wc = working_copy_id(*view);
    std::vector<Id> stack;
    if (rev.empty() || rev == "all()") {
        stack = view_roots(*view);
    } else if (auto one = resolve_revision(store, *view, rev)) {
        stack.push_back(*one);
    }
    std::set<Id> seen(stack.begin(), stack.end());

    struct Rec {
        Id id{};
        Id root_tree{};
        std::vector<Id> parents;
        std::string change;
        std::int64_t seconds = 0;
        std::string message;
        std::string author;
        bool conflicted = false;
        bool has_changes = false;
    };
    std::vector<Rec> recs;
    while (!stack.empty()) {
        const Id id = stack.back();
        stack.pop_back();
        auto loaded = load_commit(store, id);
        if (!loaded)
            continue;
        Rec rec;
        rec.id = id;
        rec.root_tree = loaded->commit.root_tree;
        rec.parents = loaded->commit.parents;
        rec.change = base32_encode(loaded->commit.change_id);
        rec.seconds = loaded->commit.committer.seconds;
        rec.message = first_line(loaded->commit.message);
        rec.author = loaded->commit.author.name;
        if (wc && std::memcmp(wc->data(), id.data(), ID_LEN) == 0)
            rec.has_changes = has_changes(store, *loaded);
        recs.push_back(std::move(rec));
        for (const auto& parent : loaded->commit.parents) {
            if (seen.insert(parent).second)
                stack.push_back(parent);
        }
    }
    std::vector<LogOrderNode> nodes;
    nodes.reserve(recs.size());
    for (const auto& rec : recs)
        nodes.push_back(LogOrderNode{rec.id, rec.seconds, rec.parents});
    const auto order = order_log_nodes(nodes);
    std::vector<Rec> ordered;
    ordered.reserve(recs.size());
    for (std::size_t index : order)
        ordered.push_back(std::move(recs[index]));
    recs = std::move(ordered);

    if (limit) {
        if (first) {
            if (recs.size() > *limit)
                recs.erase(recs.begin(), recs.end() - static_cast<std::ptrdiff_t>(*limit));
            std::reverse(recs.begin(), recs.end());
        } else if (recs.size() > *limit) {
            recs.resize(*limit);
        }
    }

    for (auto& rec : recs)
        rec.conflicted = tree_conflicted(store, rec.root_tree);

    std::vector<std::string> change_ids;
    for (const auto& rec : recs)
        change_ids.push_back(rec.change);
    std::size_t w_commit = 12;
    std::size_t w_change = 6;
    std::size_t w_date = 19;
    std::size_t w_author = 6;
    std::unordered_map<std::string, std::size_t> change_counts;
    for (std::size_t i = 0; i < recs.size(); ++i) {
        const auto cid = short_change_id(change_ids, i);
        w_change = std::max(w_change, cid.size());
        w_author = std::max(w_author, recs[i].author.size());
        ++change_counts[recs[i].change];
    }
    if (col_titles) {
        print_cell("", 1, Color::Default, false);
        std::cout << " ";
        print_cell("Commit", w_commit, Color::Default, false);
        print_gap();
        print_cell("Change", w_change, Color::Default, false);
        print_gap();
        print_cell("Date", w_date, Color::Default, false);
        print_gap();
        print_cell("Author", w_author, Color::Default, false);
        print_gap();
        std::cout << "Message\n";
    }
    for (std::size_t i = 0; i < recs.size(); ++i) {
        const auto& rec = recs[i];
        const bool is_wc = wc && std::memcmp(wc->data(), rec.id.data(), ID_LEN) == 0;
        std::string marker = is_wc ? "@" : " ";
        Color marker_color = Color::Default;
        if (is_wc)
            marker_color = rec.has_changes ? Color::BrightCyan : Color::Red;
        const auto cid = short_change_id(change_ids, i);
        const auto stamp = format_utc(rec.seconds);
        print_cell(marker, 1, marker_color, false);
        std::cout << " ";
        print_cell(short_hex(rec.id), w_commit, Color::Red, false);
        print_gap();
        print_cell(cid, w_change, Color::Red, false);
        print_gap();
        print_cell(stamp, w_date, Color::Cyan, true);
        print_gap();
        print_cell(rec.author, w_author, Color::Cyan, false);
        print_gap();
        if (!rec.message.empty())
            print_colored(rec.message, Color::Green, false, false);
        else
            print_colored("<unset>", Color::BrightBlack, false, false);
        for (const auto& name : bookmark_names(*view, rec.id))
            std::cout << " [" << name << "]";
        for (const auto& name : tag_names(*view, rec.id))
            std::cout << " <" << name << ">";
        if (rec.conflicted)
            std::cout << " (conflicted)";
        bool divergent = change_counts[rec.change] > 1;
        if (divergent)
            std::cout << " (divergent)";
        std::cout << "\n";
    }
    return 0;
}

int run_show(const std::vector<std::string>& args) {
    std::string rev;
    bool col_titles = true;
    bool all = false;
    bool end_flags = false;
    for (std::size_t i = 2; i < args.size(); ++i) {
        const std::string& arg = args[i];
        if (!end_flags && arg == "--") {
            end_flags = true;
        } else if (!end_flags && (arg == "-r" || arg == "-rev")) {
            if (i + 1 >= args.size()) {
                error_prefix();
                std::cout << arg << " requires a revision\n";
                return 1;
            }
            rev = args[++i];
        } else if (!end_flags && (arg == "-a" || arg == "-all")) {
            all = true;
        } else if (!end_flags && arg == "-no-col-titles") {
            col_titles = false;
        } else if (!end_flags && is_flag(arg)) {
            error_prefix();
            std::cout << "unknown flag: " << arg << "\n";
            return 1;
        } else {
            rev = arg;
        }
    }
    const auto root = open_repo();
    if (!root)
        return 1;
    const int snap = snapshot_run(*root);
    if (snap != 0)
        return snap;
    Store store = Store::open_all(*root);
    auto view = current_view(*root, store);
    if (!view) {
        error_prefix();
        std::cout << "no operation state\n";
        return 1;
    }
    auto target = resolve_revision(store, *view, rev);
    if (!target) {
        error_prefix();
        if (rev.empty())
            std::cout << "no working-copy commit\n";
        else
            std::cout << "unknown revision: " << rev << "\n";
        return 1;
    }
    auto loaded = load_commit(store, *target);
    if (!loaded) {
        error_prefix();
        std::cout << "cannot read commit\n";
        return 1;
    }
    std::ostringstream rendered;
    auto* old_out = std::cout.rdbuf(rendered.rdbuf());
    if (col_titles) {
        std::cout << "commit   " << hex_encode(*target) << "\n";
        std::cout << "change   " << base32_encode(loaded->commit.change_id) << "\n";
        std::cout << "author   " << loaded->commit.author.name << " <"
                  << loaded->commit.author.email << ">\n";
        std::cout << "date     " << format_utc(loaded->commit.committer.seconds) << "\n";
        std::cout << "parents  ";
        if (loaded->commit.parents.empty()) {
            std::cout << "<none>";
        } else {
            for (std::size_t i = 0; i < loaded->commit.parents.size(); ++i) {
                if (i != 0)
                    std::cout << " ";
                std::cout << short_hex(loaded->commit.parents[i]);
            }
        }
        std::cout << "\n";
        const auto names = bookmark_names(*view, *target);
        if (!names.empty()) {
            std::cout << "bookmarks";
            for (const auto& name : names)
                std::cout << " [" << name << "]";
            std::cout << "\n";
        }
        std::cout << "\n";
        if (!loaded->commit.message.empty())
            std::cout << loaded->commit.message << "\n";
        else
            std::cout << "<unset>\n";
        std::cout << "\n";
    }
    std::optional<Id> old_tree;
    if (!loaded->commit.parents.empty()) {
        auto parent = load_commit(store, loaded->commit.parents.front());
        if (parent)
            old_tree = parent->commit.root_tree;
    }
    const std::size_t diff_count = render_diff(store, old_tree, loaded->commit.root_tree, false);
    std::cout.rdbuf(old_out);
    if (diff_count > 0 && !all && stdout_is_terminal())
        (void)run_pager(*root, rendered.str());
    else
        std::cout << rendered.str();
    return 0;
}

int run_hash(const std::vector<std::string>& args) {
    std::string rev;
    bool short_hash = false;
    bool end_flags = false;
    for (std::size_t i = 2; i < args.size(); ++i) {
        const std::string& arg = args[i];
        if (!end_flags && arg == "--") {
            end_flags = true;
        } else if (!end_flags && arg == "-short") {
            short_hash = true;
        } else if (!end_flags && arg == "-long") {
            short_hash = false;
        } else if (!end_flags && (arg == "-r" || arg == "-rev")) {
            if (i + 1 >= args.size()) {
                error_prefix();
                std::cout << arg << " requires a revision\n";
                return 1;
            }
            rev = args[++i];
        } else if (!end_flags && is_flag(arg)) {
            error_prefix();
            std::cout << "unknown flag: " << arg << "\n";
            return 1;
        } else {
            rev = arg;
        }
    }
    const auto root = open_repo();
    if (!root)
        return 1;
    const int snap = snapshot_run(*root);
    if (snap != 0)
        return snap;
    Store store = Store::open_all(*root);
    auto view = current_view(*root, store);
    if (!view) {
        error_prefix();
        std::cout << "no operation state\n";
        return 1;
    }
    auto target = resolve_revision(store, *view, rev);
    if (!target) {
        error_prefix();
        if (rev.empty())
            std::cout << "no working-copy commit\n";
        else
            std::cout << "unknown revision: " << rev << "\n";
        return 1;
    }
    const auto hex = hex_encode(*target);
    std::cout << hex.substr(0, short_hash ? 12 : 64) << "\n";
    return 0;
}

bool print_tree(const fs::path& root, Store& store, const Id& tree_id, const std::string& prefix,
                std::size_t depth) {
    if (depth > 4096)
        return false;
    auto body = store.read_body(tree_id, TYPE_TREE);
    if (!body)
        return false;
    auto tree = decode_tree(bytes_of(*body));
    if (!tree)
        return false;
    for (std::size_t i = 0; i < tree->entries.size(); ++i) {
        const auto& entry = tree->entries[i];
        const bool last = i + 1 == tree->entries.size();
        std::cout << prefix << (last ? "`-- " : "|-- ") << entry.name << "\n";
        if (entry.kind == KIND_SUBTREE) {
            if (!print_tree(root, store, entry.target, prefix + (last ? "    " : "|   "),
                            depth + 1))
                return false;
        }
    }
    return true;
}

int run_ls(const std::vector<std::string>& args) {
    std::string rev;
    bool plain = false;
    bool end_flags = false;
    for (std::size_t i = 2; i < args.size(); ++i) {
        const std::string& arg = args[i];
        if (!end_flags && arg == "--") {
            end_flags = true;
        } else if (!end_flags && (arg == "-plain" || arg == "-p")) {
            plain = true;
        } else if (!end_flags && (arg == "-r" || arg == "-rev")) {
            if (i + 1 >= args.size()) {
                error_prefix();
                std::cout << arg << " requires a revision\n";
                return 1;
            }
            rev = args[++i];
        } else if (!end_flags && is_flag(arg)) {
            error_prefix();
            std::cout << "unknown flag: " << arg << "\n";
            return 1;
        } else {
            rev = arg;
        }
    }
    const auto root = open_repo();
    if (!root)
        return 1;
    const int snap = snapshot_run(*root);
    if (snap != 0)
        return snap;
    Store store = Store::open_all(*root);
    auto view = current_view(*root, store);
    if (!view) {
        error_prefix();
        std::cout << "no operation state\n";
        return 1;
    }
    auto target = resolve_revision(store, *view, rev);
    if (!target) {
        error_prefix();
        if (rev.empty())
            std::cout << "no working-copy commit\n";
        else
            std::cout << "unknown revision: " << rev << "\n";
        return 1;
    }
    auto loaded = load_commit(store, *target);
    if (!loaded) {
        error_prefix();
        std::cout << "cannot read commit\n";
        return 1;
    }
    bool good = true;
    if (plain) {
        auto entries = flatten_tree_checked(store, loaded->commit.root_tree);
        if (!entries) {
            good = false;
        } else {
            for (const auto& entry : *entries)
                std::cout << entry.path << "\n";
        }
    } else {
        std::cout << ".\n";
        good = print_tree(*root, store, loaded->commit.root_tree, "", 0);
    }
    if (!good) {
        error_prefix();
        std::cout << "cannot read tree\n";
        return 1;
    }
    return 0;
}

int run_diff(const std::vector<std::string>& args) {
    std::vector<std::string> flag_revs;
    std::vector<std::string> operands;
    bool all = false;
    bool end_flags = false;
    for (std::size_t i = 2; i < args.size(); ++i) {
        const std::string& arg = args[i];
        if (!end_flags && arg == "--") {
            end_flags = true;
        } else if (!end_flags && (arg == "-a" || arg == "-all")) {
            all = true;
        } else if (!end_flags && (arg == "-r" || arg == "-rev")) {
            if (i + 1 >= args.size()) {
                error_prefix();
                std::cout << arg << " requires a revision\n";
                return 1;
            }
            flag_revs.push_back(args[++i]);
        } else if (!end_flags && is_flag(arg)) {
            error_prefix();
            std::cout << "unknown flag: " << arg << "\n";
            return 1;
        } else {
            operands.push_back(arg);
        }
    }
    const auto root = open_repo();
    if (!root)
        return 1;
    const int snap = snapshot_run(*root);
    if (snap != 0)
        return snap;
    Store store = Store::open_all(*root);
    auto view = current_view(*root, store);
    if (!view) {
        error_prefix();
        std::cout << "no operation state\n";
        return 1;
    }

    std::vector<std::string> revs = flag_revs;
    std::optional<std::string> path_filter;
    if (!operands.empty()) {
        if (!revs.empty()) {
            if (operands.size() > 1) {
                error_prefix();
                std::cout << "too many arguments\n";
                return 1;
            }
            path_filter = operands.front();
        } else if (operands.size() >= 2) {
            if (operands.size() > 2) {
                error_prefix();
                std::cout << "too many revisions\n";
                return 1;
            }
            revs.push_back(operands[0]);
            revs.push_back(operands[1]);
        } else if (resolve_revision(store, *view, operands.front())) {
            revs.push_back(operands.front());
        } else {
            path_filter = operands.front();
        }
    }
    if (revs.size() > 2) {
        error_prefix();
        std::cout << "too many revisions\n";
        return 1;
    }
    if (path_filter) {
        const auto cwd_rel = cwd_relative(*root);
        if (!cwd_rel) {
            error_prefix();
            std::cout << "cannot determine current directory\n";
            return 1;
        }
        auto normalized = pathspec_normalize(*root, *cwd_rel, *path_filter);
        if (!normalized || normalized->empty()) {
            error_prefix();
            std::cout << "path is outside the repository: " << *path_filter << "\n";
            return 1;
        }
        path_filter = std::move(*normalized);
    }

    std::optional<Id> old_tree;
    std::optional<Id> new_tree;
    bool failed = false;
    auto tree_of = [&](const Id& id) -> std::optional<Id> {
        auto loaded = load_commit(store, id);
        if (!loaded)
            return std::nullopt;
        return loaded->commit.root_tree;
    };
    auto parent_tree_of = [&](const Id& id) -> std::optional<Id> {
        auto loaded = load_commit(store, id);
        if (!loaded || loaded->commit.parents.empty())
            return std::nullopt;
        auto parent = load_commit(store, loaded->commit.parents.front());
        if (!parent)
            return std::nullopt;
        return parent->commit.root_tree;
    };
    if (revs.size() == 2) {
        auto a = resolve_revision(store, *view, revs[0]);
        auto b = resolve_revision(store, *view, revs[1]);
        if (!a || !b)
            failed = true;
        else {
            old_tree = tree_of(*a);
            new_tree = tree_of(*b);
        }
    } else if (revs.size() == 1) {
        auto a = resolve_revision(store, *view, revs[0]);
        if (!a)
            failed = true;
        else {
            old_tree = parent_tree_of(*a);
            new_tree = tree_of(*a);
        }
    } else {
        const auto wc = working_copy_id(*view);
        if (wc) {
            old_tree = parent_tree_of(*wc);
            new_tree = tree_of(*wc);
        }
    }
    if (failed) {
        error_prefix();
        std::cout << "unknown revision\n";
        return 1;
    }

    const std::string_view filter =
        path_filter ? std::string_view(*path_filter) : std::string_view{};
    std::ostringstream rendered;
    auto* old_out = std::cout.rdbuf(rendered.rdbuf());
    const std::size_t diff_count = render_diff(store, old_tree, new_tree, true, filter);
    std::cout.rdbuf(old_out);
    if (diff_count > 0 && !all && stdout_is_terminal())
        (void)run_pager(*root, rendered.str());
    else
        std::cout << rendered.str();
    return 0;
}

int run_new(const std::vector<std::string>& args) {
    std::vector<std::string> revs;
    bool end_flags = false;
    for (std::size_t i = 2; i < args.size(); ++i) {
        const std::string& arg = args[i];
        if (!end_flags && arg == "--") {
            end_flags = true;
        } else if (!end_flags && is_flag(arg)) {
            error_prefix();
            std::cout << "unknown flag: " << arg << "\n";
            return 1;
        } else {
            revs.push_back(arg);
        }
    }
    const auto root = open_repo();
    if (!root)
        return 1;
    const int snap = snapshot_run(*root);
    if (snap != 0)
        return snap;
    Store store = Store::open_all(*root);
    auto tx = Txn::begin(*root, store);
    if (!tx) {
        error_prefix();
        std::cout << "cannot load repository state\n";
        return 1;
    }
    const auto wc = working_copy_id(tx->view());
    std::optional<Id> old_root;
    std::vector<Id> parents;
    std::optional<Id> root_tree;
    if (revs.empty()) {
        if (!wc) {
            error_prefix();
            std::cout << "no working-copy commit\n";
            return 1;
        }
        auto loaded = load_commit(store, *wc);
        if (!loaded) {
            error_prefix();
            std::cout << "cannot read working-copy commit\n";
            return 1;
        }
        parents.push_back(*wc);
        root_tree = loaded->commit.root_tree;
        old_root = root_tree;
    } else {
        for (std::size_t i = 0; i < revs.size(); ++i) {
            auto resolved = resolve_revision(store, tx->view(), revs[i]);
            if (!resolved) {
                error_prefix();
                std::cout << "unknown revision\n";
                return 1;
            }
            parents.push_back(*resolved);
            if (i == 0) {
                auto loaded = load_commit(store, *resolved);
                if (!loaded) {
                    error_prefix();
                    std::cout << "unknown revision\n";
                    return 1;
                }
                root_tree = loaded->commit.root_tree;
            }
        }
        if (wc) {
            auto old_loaded = load_commit(store, *wc);
            if (old_loaded)
                old_root = old_loaded->commit.root_tree;
        }
    }
    const Sig sig = identity_signature(*root);
    Commit commit;
    commit.version = 1;
    commit.parents = parents;
    commit.root_tree = *root_tree;
    commit.change_id = random_change_id();
    commit.author = sig;
    commit.committer = sig;
    commit.message = "";
    commit.renames_state = RENAMES_RECORDED;
    const auto encoded = encode_commit(commit);
    const Id new_id = tx->add_object(TYPE_COMMIT, encoded);
    if (wc)
        remove_head(tx->view(), *wc);
    set_workspace(tx->view(), new_id);
    rebuild_heads(tx->view());
    const auto status = tx->finish("new");
    if (!status)
        return 1;
    store.refresh(*root);
    (void)mark_native(*root, new_id);
    if (!revs.empty()) {
        const int materialized = checkout_materialize_commit(*root, store, old_root, *root_tree);
        if (materialized != 0)
            return materialized;
    }
    return 0;
}

int describe_impl(const fs::path& root, Store& store, const std::vector<std::string>& parts,
                  bool require_changes, bool start_new = false) {
    const int snap = snapshot_run(root, store);
    if (snap != 0)
        return snap;
    auto tx = Txn::begin(root, store);
    if (!tx) {
        error_prefix();
        std::cout << "cannot load repository state\n";
        return 1;
    }
    const auto wc = working_copy_id(tx->view());
    if (!wc) {
        error_prefix();
        std::cout << "no working-copy commit\n";
        return 1;
    }
    auto loaded = load_commit(store, *wc);
    if (!loaded) {
        error_prefix();
        std::cout << "cannot read working-copy commit\n";
        return 1;
    }
    const std::string message = join_args(parts);
    const bool changed = has_changes(store, *loaded);
    const bool same_message = message == loaded->commit.message;
    if (!changed && (require_changes || same_message)) {
        if (require_changes) {
            info_prefix();
            std::cout << "nothing to commit, working copy clean\n";
            return 2;
        }
        return 0;
    }
    const Sig sig = identity_signature(root);
    Commit commit = loaded->commit;
    commit.committer = sig;
    if (!changed)
        commit.author = sig;
    commit.message = message;
    const auto encoded = encode_commit(commit);
    const Id new_id = tx->add_object(TYPE_COMMIT, encoded);
    remove_head(tx->view(), *wc);
    move_bookmarks(tx->view(), *wc, new_id);
    if (auto current = current_bookmark_name(root)) {
        if (find_bookmark(tx->view(), *current))
            set_bookmark_target(tx->view(), *current, new_id);
    }
    set_workspace(tx->view(), new_id);
    rebuild_heads(tx->view());
    if (start_new) {
        std::vector<ChainedOperation> operations;
        operations.push_back(ChainedOperation{tx->view(), "describe"});
        Commit next;
        next.version = 1;
        next.parents = {new_id};
        next.root_tree = commit.root_tree;
        next.change_id = random_change_id();
        next.author = sig;
        next.committer = sig;
        next.message = "";
        next.renames_state = RENAMES_RECORDED;
        const auto next_encoded = encode_commit(next);
        const Id next_id = tx->add_object(TYPE_COMMIT, next_encoded);
        remove_head(tx->view(), new_id);
        set_workspace(tx->view(), next_id);
        rebuild_heads(tx->view());
        operations.push_back(ChainedOperation{tx->view(), "new"});
        const auto status = tx->finish_chain(std::move(operations));
        if (!status)
            return 1;
        store.refresh(root);
        (void)mark_native(root, new_id);
        (void)mark_native(root, next_id);
        return 0;
    }
    const auto status = tx->finish("describe");
    if (!status)
        return 1;
    store.refresh(root);
    (void)mark_native(root, new_id);
    return 0;
}

int run_describe(const std::vector<std::string>& args) {
    auto parsed = parse_message(args, 2);
    if (!parsed)
        return 1;
    const auto root = open_repo();
    if (!root)
        return 1;
    Store store = Store::open_all(*root);
    return describe_impl(*root, store, *parsed, false);
}

int run_commit(const std::vector<std::string>& args) {
    auto parsed = parse_message(args, 2);
    if (!parsed)
        return 1;
    const auto root = open_repo();
    if (!root)
        return 1;
    if (message_is_blank(*parsed) && stdin_is_terminal()) {
        auto edited = edit_commit_message(*root, join_args(*parsed));
        if (!edited || edited->empty()) {
            error_prefix();
            std::cout << "commit requires a non-empty message (-message)\n";
            return 1;
        }
        *parsed = {*edited};
    }
    if (message_is_blank(*parsed)) {
        error_prefix();
        std::cout << "commit requires a non-empty message (-message)\n";
        return 1;
    }
    Store store = Store::open_all(*root);
    const int described = describe_impl(*root, store, *parsed, true, true);
    if (described == 2)
        return 0;
    return described;
}

std::optional<Id> mapped_id(const std::vector<Id>& old_ids, const std::vector<Id>& new_ids,
                            const Id& id) {
    for (std::size_t i = 0; i < old_ids.size(); ++i) {
        if (std::memcmp(old_ids[i].data(), id.data(), ID_LEN) == 0)
            return new_ids[i];
    }
    return std::nullopt;
}

void remap_ids(const std::vector<Id>& old_ids, const std::vector<Id>& new_ids,
               std::vector<std::optional<Id>>& ids) {
    for (auto& id : ids) {
        if (!id)
            continue;
        if (auto mapped = mapped_id(old_ids, new_ids, *id))
            id = *mapped;
    }
}

int run_amend(const std::vector<std::string>& args) {
    std::string rev;
    std::vector<std::string> parts;
    bool end_flags = false;
    for (std::size_t i = 2; i < args.size(); ++i) {
        const std::string& arg = args[i];
        if (!end_flags && arg == "--") {
            end_flags = true;
        } else if (!end_flags && (arg == "-m" || arg == "-message")) {
            if (i + 1 >= args.size()) {
                error_prefix();
                std::cout << arg << " requires a message\n";
                return 1;
            }
            parts.push_back(args[++i]);
        } else if (!end_flags && is_flag(arg)) {
            error_prefix();
            std::cout << "unknown flag: " << arg << "\n";
            return 1;
        } else if (rev.empty()) {
            rev = arg;
        } else {
            parts.push_back(arg);
        }
    }
    if (rev.empty()) {
        error_prefix();
        std::cout << "amend requires a revision\n";
        return 1;
    }
    if (message_is_blank(parts)) {
        error_prefix();
        std::cout << "amend requires a non-empty message (-message)\n";
        return 1;
    }
    const auto root = open_repo();
    if (!root)
        return 1;
    const int snap = snapshot_run(*root);
    if (snap != 0)
        return snap;
    Store store = Store::open_all(*root);
    auto tx = Txn::begin(*root, store);
    if (!tx) {
        error_prefix();
        std::cout << "cannot load repository state\n";
        return 1;
    }
    auto target = resolve_revision(store, tx->view(), rev);
    if (!target) {
        error_prefix();
        std::cout << "unknown revision\n";
        return 1;
    }
    std::vector<Id> pushed_roots;
    for (const auto& ref : tx->view().remote_refs)
        pushed_roots.push_back(ref.target);
    if (!pushed_roots.empty() && contains_id(collect_commits(store, pushed_roots), *target)) {
        error_prefix();
        std::cout << "cannot amend a revision that has been pushed\n";
        return 1;
    }
    auto target_loaded = load_commit(store, *target);
    if (!target_loaded) {
        error_prefix();
        std::cout << "cannot read revision\n";
        return 1;
    }
    const std::string message = join_args(parts);
    if (target_loaded->commit.message == message) {
        info_prefix();
        std::cout << "message unchanged\n";
        return 0;
    }
    auto remaining = all_commits(store, tx->view());
    std::vector<Id> old_ids;
    std::vector<Id> new_ids;
    const Sig sig = identity_signature(*root);
    bool target_rewritten = false;
    bool failed = false;
    while (!remaining.empty() && !failed) {
        std::optional<std::size_t> ready;
        for (std::size_t i = 0; i < remaining.size(); ++i) {
            bool is_ready = std::memcmp(remaining[i].data(), target->data(), ID_LEN) == 0;
            if (!is_ready) {
                auto loaded = load_commit(store, remaining[i]);
                if (loaded) {
                    for (const auto& parent : loaded->commit.parents) {
                        if (contains_id(old_ids, parent)) {
                            is_ready = true;
                            break;
                        }
                    }
                }
            }
            if (is_ready) {
                ready = i;
                break;
            }
        }
        if (!ready)
            break;
        const Id chosen = remaining[*ready];
        auto loaded = load_commit(store, chosen);
        if (!loaded) {
            failed = true;
            break;
        }
        std::vector<Id> new_parents;
        for (const auto& parent : loaded->commit.parents) {
            if (auto mapped = mapped_id(old_ids, new_ids, parent))
                new_parents.push_back(*mapped);
            else
                new_parents.push_back(parent);
        }
        Commit commit = loaded->commit;
        commit.parents = new_parents;
        commit.committer = sig;
        if (std::memcmp(chosen.data(), target->data(), ID_LEN) == 0)
            commit.message = message;
        const auto encoded = encode_commit(commit);
        const Id new_id = tx->add_object(TYPE_COMMIT, encoded);
        old_ids.push_back(chosen);
        new_ids.push_back(new_id);
        if (std::memcmp(chosen.data(), target->data(), ID_LEN) == 0)
            target_rewritten = true;
        remaining.erase(remaining.begin() + static_cast<std::ptrdiff_t>(*ready));
    }
    if (failed || !target_rewritten) {
        error_prefix();
        std::cout << "cannot amend revision\n";
        return 1;
    }
    for (auto& bookmark : tx->view().bookmarks) {
        remap_ids(old_ids, new_ids, bookmark.targets.adds);
        remap_ids(old_ids, new_ids, bookmark.targets.removes);
    }
    for (auto& tag : tx->view().tags) {
        if (auto mapped = mapped_id(old_ids, new_ids, tag.target))
            tag.target = *mapped;
    }
    for (auto& workspace : tx->view().working_copies) {
        if (auto mapped = mapped_id(old_ids, new_ids, workspace.target))
            workspace.target = *mapped;
    }
    for (auto& ref : tx->view().remote_refs) {
        if (auto mapped = mapped_id(old_ids, new_ids, ref.target))
            ref.target = *mapped;
    }
    rebuild_heads(tx->view());
    const auto status = tx->finish("amend " + rev);
    if (!status)
        return 1;
    for (const auto& id : new_ids)
        (void)mark_native(*root, id);
    return 0;
}

int run_checkout(const std::vector<std::string>& args) {
    std::string rev;
    bool end_flags = false;
    for (std::size_t i = 2; i < args.size(); ++i) {
        const std::string& arg = args[i];
        if (!end_flags && arg == "--") {
            end_flags = true;
        } else if (!end_flags && is_flag(arg)) {
            error_prefix();
            std::cout << "unknown flag: " << arg << "\n";
            return 1;
        } else if (rev.empty()) {
            rev = arg;
        }
    }
    const auto root = open_repo();
    if (!root)
        return 1;
    return checkout_run(*root, rev);
}

int run_edit(const std::vector<std::string>& args) {
    std::vector<std::string> paths;
    bool end_flags = false;
    for (std::size_t i = 2; i < args.size(); ++i) {
        const std::string& arg = args[i];
        if (!end_flags && arg == "--") {
            end_flags = true;
        } else if (!end_flags && is_flag(arg)) {
            error_prefix();
            std::cout << "unknown flag: " << arg << "\n";
            return 1;
        } else {
            paths.push_back(arg);
        }
    }
    if (paths.empty())
        paths.push_back(".");
    std::optional<fs::path> root = discover_repo(".");
    fs::path config_root = root ? *root : fs::current_path();
    if (!run_editor(config_root, paths))
        return 1;
    return 0;
}

int run_fsck(const std::vector<std::string>& args) {
    std::string path = ".";
    bool verbose = false;
    bool end_flags = false;
    for (std::size_t i = 2; i < args.size(); ++i) {
        const std::string& arg = args[i];
        if (!end_flags && arg == "--") {
            end_flags = true;
        } else if (!end_flags && (arg == "-v" || arg == "-verbose")) {
            verbose = true;
        } else if (!end_flags && is_flag(arg)) {
            error_prefix();
            std::cout << "unknown flag: " << arg << "\n";
            return 1;
        } else {
            path = arg;
        }
    }
    const auto root = discover_repo(path_from_bytes(path));
    if (!root) {
        error_prefix();
        std::cout << "not a veins repository: " << path << "\n";
        return 1;
    }
    return fsck_repository(*root, verbose);
}

int run_repack(const std::vector<std::string>& args) {
    std::string path = ".";
    bool verbose = false;
    int level = 6;
    bool end_flags = false;
    for (std::size_t i = 2; i < args.size(); ++i) {
        const std::string& arg = args[i];
        if (!end_flags && arg == "--") {
            end_flags = true;
        } else if (!end_flags && (arg == "-v" || arg == "-verbose")) {
            verbose = true;
        } else if (!end_flags && arg.starts_with("-level:")) {
            const std::string value = arg.substr(7);
            if (value.empty()) {
                error_prefix();
                std::cout << "-level: requires a value (1-19)\n";
                return 1;
            }
            level = std::atoi(value.c_str());
            if (level < 1 || level > 19) {
                error_prefix();
                std::cout << "compression level must be between 1 and 19\n";
                return 1;
            }
        } else if (!end_flags && is_flag(arg)) {
            error_prefix();
            std::cout << "unknown flag: " << arg << "\n";
            return 1;
        } else {
            path = arg;
        }
    }
    const auto root = discover_repo(path_from_bytes(path));
    if (!root) {
        error_prefix();
        std::cout << "not a veins repository: " << path << "\n";
        return 1;
    }
    return repack_repository(*root, level, verbose);
}

int run_self_test() {
    auto fail = [](std::string_view why) {
        error_prefix();
        std::cout << "self-test: failed: " << why << "\n";
        return 1;
    };
    const auto empty_hash = blake3_hash(Bytes{});
    const std::string expected_empty =
        "af1349b9f5f9a1a6a0404dea36dcc9499bcb25c9adc112b7cc9a93cae41f3262";
    if (hex_encode(Bytes(empty_hash.data(), empty_hash.size())) != expected_empty)
        return fail("blake3 vector");
    const auto& gear = fastcdc_gear();
    if (gear[0] != 0xf8447b379cdadcd5ull || gear[1] != 0xbe63d125aec8ca6dull)
        return fail("fastcdc gear table");

    BlobBuild build = build_blob(bytes_of(std::string("hello world")));
    if (!build.objects.empty()) {
        auto body = build.objects.back().body;
        auto decoded = decode_blob(bytes_of(body));
        if (!decoded || decoded->form != BlobForm::Inline)
            return fail("blob round trip");
    }
    Tree tree;
    tree.entries.push_back(TreeEntry{"a.txt", KIND_FILE, build.root});
    auto tree_body = encode_tree(tree.entries);
    if (!tree_body)
        return fail("tree encode");
    auto decoded_tree = decode_tree(bytes_of(*tree_body));
    if (!decoded_tree || decoded_tree->entries.size() != 1)
        return fail("tree round trip");

    std::vector<RawObject> objects;
    objects.push_back(RawObject{TYPE_TREE, *tree_body, object_id(TYPE_TREE, bytes_of(*tree_body))});
    PackOutput pack = encode_pack(objects);
    auto decoded_pack = decode_pack(pack.pack);
    if (!decoded_pack)
        return fail("pack decode");
    auto decoded_index = decode_index(pack.index, decoded_pack->trailer);
    if (!decoded_index)
        return fail("index decode");
    if (decoded_index->ids.size() != 1)
        return fail("index count");

    std::vector<std::uint8_t> left(96 * 1024);
    for (std::size_t i = 0; i < left.size(); ++i)
        left[i] = static_cast<std::uint8_t>((i * 31 + (i / 97) * 7) % 251);
    std::vector<std::uint8_t> right = left;
    for (std::size_t i = 48 * 1024; i < 48 * 1024 + 64; ++i)
        right[i] = static_cast<std::uint8_t>((right[i] + 19) % 251);
    std::vector<RawObject> delta_objects;
    auto append_version = [&](const std::vector<std::uint8_t>& data) {
        BlobBuild version = build_blob(bytes_of(data));
        for (auto& object : version.objects) {
            const Id id = object.id ? *object.id : object_id(object.type, bytes_of(object.body));
            delta_objects.push_back(RawObject{object.type, std::move(object.body), id});
        }
    };
    append_version(left);
    append_version(right);
    PackOutput delta_pack = encode_pack(delta_objects);
    auto delta_decoded = decode_pack(delta_pack.pack);
    if (!delta_decoded)
        return fail("delta pack decode");
    bool saw_delta = false;
    for (std::size_t i = 0; i < delta_decoded->records.size(); ++i) {
        const auto& record = delta_decoded->records[i];
        if (record.compression == 2)
            saw_delta = true;
        auto body = delta_decoded->get(i);
        if (!body)
            return fail("delta pack body");
        const Id computed = object_id(record.type, bytes_of(*body));
        if (std::memcmp(computed.data(), record.id.data(), ID_LEN) != 0)
            return fail("delta pack hash");
    }
    if (!saw_delta)
        return fail("delta pack compression");
    auto delta_index = decode_index(delta_pack.index, delta_decoded->trailer);
    if (!delta_index || delta_index->ids.size() != delta_decoded->records.size())
        return fail("delta index");

    info_prefix();
    std::cout << "self-test: ok\n";
    return 0;
}

struct ExtStat {
    std::string ext;
    std::uint64_t files = 0;
    std::uint64_t lines = 0;
    std::uint64_t bytes = 0;
};

struct AuthorStat {
    std::string name;
    std::uint64_t commits = 0;
};

std::uint64_t percent(std::uint64_t num, std::uint64_t total) {
    if (total == 0)
        return 0;
    return (num * 100 + total / 2) / total;
}

void print_percent(std::uint64_t pct) {
    if (pct < 10)
        std::cout << "  " << pct;
    else if (pct < 100)
        std::cout << " " << pct;
    else
        std::cout << pct;
}

Color color_for(std::size_t i) {
    static const Color colors[] = {Color::BrightCyan,    Color::BrightGreen, Color::BrightYellow,
                                   Color::BrightMagenta, Color::BrightBlue,  Color::BrightRed,
                                   Color::Cyan,          Color::Green};
    return colors[i % 8];
}

void print_bar(std::uint64_t num, std::uint64_t total, Color color) {
    std::uint64_t filled = 0;
    if (total > 0 && num > 0) {
        filled = (num * 24 + total / 2) / total;
        if (filled == 0)
            filled = 1;
        if (filled > 24)
            filled = 24;
    }
    for (std::uint64_t i = 0; i < filled; ++i)
        print_colored("\xe2\x96\x88", color, false, false);
    for (std::uint64_t i = filled; i < 24; ++i)
        print_colored("\xe2\x96\x91", Color::BrightBlack, false, false);
}

void print_left(std::string_view text, std::size_t width, Color color, bool dim) {
    if (dim)
        print_styled(text, color, true, false);
    else if (color == Color::Default)
        std::cout << text;
    else
        print_colored(text, color, false, false);
    for (std::size_t i = text.size(); i < width; ++i)
        std::cout << ' ';
}

void row_value(std::string_view label, std::string_view value) {
    print_left(label, 14, Color::Default, true);
    std::cout << value << "\n";
}

void row_number(std::string_view label, std::uint64_t value) {
    print_left(label, 14, Color::Default, true);
    std::cout << value << "\n";
}

std::string ext_of(std::string_view path) {
    std::size_t base_start = 0;
    for (std::size_t i = 0; i < path.size(); ++i) {
        if (path[i] == '/')
            base_start = i + 1;
    }
    std::optional<std::size_t> dot;
    for (std::size_t i = base_start; i < path.size(); ++i) {
        if (path[i] == '.')
            dot = i;
    }
    if (!dot || *dot <= base_start || *dot + 1 >= path.size())
        return "(none)";
    std::string out(path.substr(*dot));
    for (char& c : out) {
        if (c >= 'A' && c <= 'Z')
            c = static_cast<char>(c + 32);
    }
    return out;
}

bool looks_binary(Bytes data) {
    const std::size_t limit = std::min<std::size_t>(data.size(), 8192);
    for (std::size_t i = 0; i < limit; ++i)
        if (data[i] == 0)
            return true;
    return false;
}

std::uint64_t count_nonblank(Bytes data) {
    std::uint64_t count = 0;
    std::size_t i = 0;
    while (i < data.size()) {
        std::size_t end = i;
        while (end < data.size() && data[end] != '\n')
            ++end;
        bool blank = true;
        for (std::size_t j = i; j < end; ++j) {
            if (data[j] != ' ' && data[j] != '\t' && data[j] != '\r') {
                blank = false;
                break;
            }
        }
        if (!blank)
            ++count;
        i = end >= data.size() ? data.size() : end + 1;
    }
    return count;
}

std::uint64_t dir_size(const fs::path& path, std::size_t depth) {
    if (depth > 64)
        return 0;
    std::uint64_t total = 0;
    std::error_code ec;
    fs::recursive_directory_iterator it(path, ec);
    if (ec)
        return 0;
    for (const auto& entry : it) {
        if (entry.is_regular_file(ec)) {
            const auto size = entry.file_size(ec);
            if (!ec)
                total += size;
        }
    }
    return total;
}

std::string size_text(std::uint64_t n) {
    if (n >= 1073741824)
        return std::to_string(n / 1073741824) + "." +
               std::to_string(((n % 1073741824) * 10) / 1073741824) + " GiB";
    if (n >= 1048576)
        return std::to_string(n / 1048576) + "." + std::to_string(((n % 1048576) * 10) / 1048576) +
               " MiB";
    if (n >= 1024)
        return std::to_string(n / 1024) + "." + std::to_string(((n % 1024) * 10) / 1024) + " KiB";
    return std::to_string(n) + " B";
}

void print_size(std::uint64_t n) {
    std::cout << size_text(n) << "\n";
}

void show_date(std::string_view label, std::int64_t seconds) {
    const std::string stamp = format_utc(seconds);
    print_left(label, 14, Color::Default, true);
    std::cout << stamp.substr(0, 10) << "\n";
}

int run_inf(const std::vector<std::string>& args) {
    bool include_generated = false;
    bool end_flags = false;
    for (std::size_t i = 2; i < args.size(); ++i) {
        const std::string& arg = args[i];
        if (!end_flags && arg == "--")
            end_flags = true;
        else if (!end_flags &&
                 (arg == "-inc-gen" || arg == "-include-generated" || arg == "--include-generated"))
            include_generated = true;
        else if (!end_flags && is_flag(arg)) {
            error_prefix();
            std::cout << "unknown flag: " << arg << "\n";
            return 1;
        }
    }

    const auto root = open_repo();
    if (!root)
        return 1;
    Store store = Store::open_all(*root);
    auto view_opt = current_view(*root, store);
    View view = view_opt ? *view_opt : empty_view();
    const auto wc = working_copy_id(view);
    std::optional<Id> wc_tree;
    if (wc) {
        auto loaded = load_commit(store, *wc);
        if (loaded)
            wc_tree = loaded->commit.root_tree;
    }

    struct FileJob {
        const FlatEntry* entry = nullptr;
        PathAttributes attributes;
    };
    struct FileResult {
        std::string ext;
        std::uint64_t lines = 0;
        std::uint64_t bytes = 0;
    };

    std::vector<ExtStat> exts;
    std::vector<AuthorStat> authors;
    std::uint64_t total_files = 0;
    std::uint64_t total_lines = 0;
    std::uint64_t generated_files = 0;
    std::uint64_t generated_lines = 0;
    std::uint64_t generated_bytes = 0;
    if (wc_tree) {
        const AttributeRules attributes = AttributeRules::load(*root);
        const auto entries = flatten_tree(store, *wc_tree);
        std::vector<FileJob> jobs;
        jobs.reserve(entries.size());
        for (const auto& entry : entries) {
            if (entry.kind != KIND_FILE && entry.kind != KIND_EXECUTABLE)
                continue;
            jobs.push_back(FileJob{&entry, attributes.lookup(entry.path)});
        }

        std::vector<FileResult> results(jobs.size());
        std::atomic<std::size_t> next{0};
        const auto worker = [&]() {
            for (;;) {
                const std::size_t index = next.fetch_add(1);
                if (index >= jobs.size())
                    return;
                const auto& job = jobs[index];
                FileResult result;
                result.ext = ext_of(job.entry->path);
                if (auto data = read_blob(store, job.entry->target)) {
                    result.bytes = data->size();
                    const bool binary = job.attributes.text == AttributeText::Binary ||
                                        (job.attributes.text == AttributeText::Auto &&
                                         looks_binary(bytes_of(*data)));
                    if (!binary)
                        result.lines = count_nonblank(bytes_of(*data));
                }
                results[index] = std::move(result);
            }
        };

        std::size_t workers = std::min<std::size_t>(available_cpu_count(), jobs.size());
        workers = std::min<std::size_t>(workers, 16);
        if (workers <= 1) {
            worker();
        } else {
            store.preload();
            std::vector<std::thread> threads;
            threads.reserve(workers);
            for (std::size_t w = 0; w < workers; ++w)
                threads.emplace_back(worker);
            for (auto& thread : threads)
                thread.join();
        }

        std::map<std::string, ExtStat> by_ext;
        for (std::size_t i = 0; i < jobs.size(); ++i) {
            const auto& job = jobs[i];
            const auto& result = results[i];
            if (job.attributes.generated) {
                ++generated_files;
                generated_lines += result.lines;
                generated_bytes += result.bytes;
                if (!include_generated)
                    continue;
            }
            ++total_files;
            total_lines += result.lines;
            auto& stat = by_ext[result.ext];
            stat.ext = result.ext;
            ++stat.files;
            stat.lines += result.lines;
            stat.bytes += result.bytes;
        }
        for (auto& [ext, stat] : by_ext) {
            (void)ext;
            exts.push_back(std::move(stat));
        }
    }

    std::uint64_t commits = 0;
    bool has_time = false;
    std::int64_t created = 0;
    std::int64_t last = 0;
    const auto roots = view_roots(view);
    for (const auto& id : collect_commits(store, roots)) {
        auto loaded = load_commit(store, id);
        if (!loaded)
            continue;
        ++commits;
        const auto secs = loaded->commit.committer.seconds;
        if (!has_time) {
            created = secs;
            last = secs;
            has_time = true;
        } else {
            created = std::min(created, secs);
            last = std::max(last, secs);
        }
        std::string name = loaded->commit.author.name;
        if (name.empty())
            name = "(unknown)";
        bool found = false;
        for (auto& author : authors) {
            if (author.name == name) {
                ++author.commits;
                found = true;
                break;
            }
        }
        if (!found)
            authors.push_back(AuthorStat{name, 1});
    }

    std::cout << "\n";
    print_bold("Repository overview", Color::BrightCyan, false);
    std::cout << "\n\n";
    row_value("Project", basename_string(*root));
    print_left("HEAD", 14, Color::Default, true);
    if (wc)
        std::cout << short_hex(*wc) << "\n";
    else
        std::cout << "<none>\n";
    row_number("Changes", commits);
    row_number("Bookmarks", view.bookmarks.size());
    row_number("Tags", view.tags.size());
    row_number("Files", total_files);
    row_number("Lines", total_lines);
    row_number("Authors", authors.size());
    if (has_time) {
        show_date("Created", created);
        show_date("Last change", last);
    }
    print_left("Size", 14, Color::Default, true);
    print_size(dir_size(veins_dir(*root), 0));
    if (generated_files > 0) {
        print_left("Generated", 14, Color::Default, true);
        std::cout << generated_files << " files  " << generated_lines << " lines  "
                  << size_text(generated_bytes);
        if (!include_generated)
            std::cout << "  (excluded; use -inc-gen)";
        std::cout << "\n";
    }
    std::cout << "\n";

    print_bold("Languages", Color::BrightCyan, false);
    std::cout << "\n\n";
    if (exts.empty()) {
        std::cout << "  no tracked files\n";
    } else {
        std::stable_sort(exts.begin(), exts.end(), [](const ExtStat& a, const ExtStat& b) {
            if (a.lines != b.lines)
                return a.lines > b.lines;
            return compare(bytes_of(a.ext), bytes_of(b.ext)) < 0;
        });
        std::size_t w_ext = 6;
        for (const auto& ext : exts)
            w_ext = std::max(w_ext, ext.ext.size());
        for (std::size_t i = 0; i < exts.size(); ++i) {
            const auto& ext = exts[i];
            print_left(ext.ext, w_ext, Color::Default, false);
            std::cout << "  ";
            print_bar(ext.lines, total_lines, color_for(i));
            std::cout << "  ";
            print_percent(percent(ext.lines, total_lines));
            std::cout << "%  " << ext.lines << " lines  " << ext.files << " files\n";
        }
    }
    std::cout << "\n";

    print_bold("Authors", Color::BrightCyan, false);
    std::cout << "\n\n";
    if (authors.empty()) {
        std::cout << "  no commits\n";
    } else {
        std::stable_sort(authors.begin(), authors.end(),
                         [](const AuthorStat& a, const AuthorStat& b) {
                             if (a.commits != b.commits)
                                 return a.commits > b.commits;
                             return compare(bytes_of(a.name), bytes_of(b.name)) < 0;
                         });
        std::size_t w_name = 6;
        for (const auto& author : authors)
            w_name = std::max(w_name, author.name.size());
        for (std::size_t i = 0; i < authors.size(); ++i) {
            const auto& author = authors[i];
            print_left(author.name, w_name, Color::Cyan, false);
            std::cout << "  ";
            print_bar(author.commits, commits, color_for(i));
            std::cout << "  ";
            print_percent(percent(author.commits, commits));
            std::cout << "%  " << author.commits << " commits\n";
        }
    }
    std::cout << "\n";
    return 0;
}

// ---------------------------------------------------------------------------
// Help
// ---------------------------------------------------------------------------

void usage() {
    std::cout << "veins is a tool for managing source code\n";
    std::cout << "\n";
    std::cout << "subcommands:\n";
    std::cout << "  init         create a repository\n";
    std::cout << "  git          import from or export to git\n";
    std::cout << "  remote       manage native remotes\n";
    std::cout << "  clone        clone a repository over the native protocol\n";
    std::cout << "  fetch        fetch from a native remote\n";
    std::cout << "  gg           fetch the active remote, or clone a URL\n";
    std::cout << "  push         push a bookmark to a native remote\n";
    std::cout << "  serve        run the native server over stdio or TLS\n";
    std::cout << "  key          manage local Ed25519 keys\n";
    std::cout << "  auth         remember keys for hosts and set a default\n";
    std::cout << "  access       manage a served repository's access file\n";
    std::cout << "  whoami       report the role granted by a server\n";
    std::cout << "  co           write a revision into the working directory; "
                 "alias: checkout\n";
    std::cout << "  stat         show working-copy changes; alias: status\n";
    std::cout << "  ls           list tracked files\n";
    std::cout << "  inf          show a repository breakdown\n";
    std::cout << "  log          show commit history\n";
    std::cout << "  show         show a commit and its diff\n";
    std::cout << "  hash         print the commit hash for a revision\n";
    std::cout << "  diff         show a unified diff, paged on a terminal\n";
    std::cout << "  merge        create a merge commit; never fails\n";
    std::cout << "  rebase       rewrite changes onto a new parent\n";
    std::cout << "  xs           list conflicted paths\n";
    std::cout << "  resolve      resolve a conflicted path\n";
    std::cout << "  new          start a new change\n";
    std::cout << "  bmk          manage named branch pointers\n";
    std::cout << "  tag          manage named tags\n";
    std::cout << "  cfg          read and write configuration\n";
    std::cout << "  edit         open paths in the configured text editor\n";
    std::cout << "  rm           untrack paths, keeping files on disk by default\n";
    std::cout << "  mv           move a tracked file and record the rename\n";
    std::cout << "  ex           add paths or globs to .vnexclude\n";
    std::cout << "  desc         set the working-copy commit message; alias: "
                 "describe\n";
    std::cout << "  go           describe and start a new change; alias: commit\n";
    std::cout << "  amend        rewrite a revision's message and its descendants\n";
    std::cout << "  undo         restore the previous operation view\n";
    std::cout << "  op           operation log commands\n";
    std::cout << "  fsck         verify repository integrity\n";
    std::cout << "  repack       rewrite packs into one delta-compressed pack; "
                 "alias: gc\n";
    std::cout << "  self-test    run the format self-tests\n";
    std::cout << "  version      print version information\n";
    std::cout << "  bench-import compare lazy import metadata; requires git\n";
    std::cout << "  help         show help for a command\n";
    std::cout << "\n";
    std::cout << "run 'vn help <command>' for details\n";
}

void show_init() {
    std::cout << "usage: vn init [path] [-git-import:<gitdir>]\n\n";
    std::cout << "create a veins repository, optionally importing an existing "
                 "git repository\n\n";
    std::cout << "arguments:\n";
    std::cout << "  [path]                    directory to create (default: .)\n\n";
    std::cout << "options:\n";
    std::cout << "  -git-import:<gitdir>      import from <gitdir> (a directory "
                 "containing .git)\n";
}

void show_status() {
    std::cout << "usage: vn stat\n\n";
    std::cout << "show working-copy changes relative to the parent commit\n\n";
    std::cout << "aliases: status\n";
}

void show_ls() {
    std::cout << "usage: vn ls [rev] [-plain]\n\n";
    std::cout << "list tracked files as an ASCII tree\n\n";
    std::cout << "arguments:\n";
    std::cout << "  [rev]                     revision to list (default: @)\n\n";
    std::cout << "options:\n";
    std::cout << "  -rev <rev>                revision to list\n";
    std::cout << "  -plain, -p                print one tracked path per line\n";
}

void show_inf() {
    std::cout << "usage: vn inf [-inc-gen]\n\n";
    std::cout << "show a repository overview with a language breakdown by file "
                 "extension,\n";
    std::cout << "line-of-code shares, author commit shares, and repository metadata\n\n";
    std::cout << "options:\n";
    std::cout << "  -inc-gen                  include files marked generated in .vnattribs\n";
}

void show_log() {
    std::cout << "usage: vn log [-rev <revset>] [-lN | -fN] [-no-col-titles]\n\n";
    std::cout << "show commit history, newest first\n\n";
    std::cout << "options:\n";
    std::cout << "  -rev <revset>             show only the given revision set\n";
    std::cout << "  -lN, -l <N>               show the last N commits (newest N)\n";
    std::cout << "  -fN, -f <N>               show the first N commits (oldest N)\n";
    std::cout << "  -no-col-titles            omit column titles\n\n";
    std::cout << "without -l or -f, the last log.default_amount commits are shown\n";
    std::cout << "(global config, default 20)\n";
}

void show_show() {
    std::cout << "usage: vn show [-a] [rev] [-no-col-titles]\n\n";
    std::cout << "show a commit's metadata and its diff against its first parent,\n";
    std::cout << "paged when stdout is a terminal\n\n";
    std::cout << "arguments:\n";
    std::cout << "  [rev]                     revision to show (default: @)\n\n";
    std::cout << "options:\n";
    std::cout << "  -a, -all                  print the whole output at once\n";
    std::cout << "  -no-col-titles            omit the metadata labels\n";
}

void show_hash() {
    std::cout << "usage: vn hash [rev] [-short|-long]\n\n";
    std::cout << "print the commit hash for a revision\n\n";
    std::cout << "arguments:\n";
    std::cout << "  [rev]                     revision to hash (default: @)\n\n";
    std::cout << "options:\n";
    std::cout << "  -rev <rev>                revision to hash\n";
    std::cout << "  -short                    print the 12-character abbreviated "
                 "hash\n";
    std::cout << "  -long                     print the full 64-character hash "
                 "(default)\n";
}

void show_diff() {
    std::cout << "usage: vn diff [-a] [-rev <rev>] [<rev> <rev>] [<path>]\n\n";
    std::cout << "show a unified diff, paged when stdout is a terminal\n\n";
    std::cout << "options:\n";
    std::cout << "  -a, -all                  print the whole diff at once\n";
    std::cout << "  -rev <rev>                compare a revision with its parent\n";
}

void show_new() {
    std::cout << "usage: vn new [<rev>...]\n\n";
    std::cout << "start a new empty change on top of the working copy or a revision\n";
}

void show_describe() {
    std::cout << "usage: vn desc [-message <message>] [<message>]\n\n";
    std::cout << "set the working-copy commit message\n\n";
    std::cout << "aliases: describe\n";
}

void show_commit() {
    std::cout << "usage: vn go -message <message>\n\n";
    std::cout << "set the message and start a new change\n\n";
    std::cout << "a non-empty commit message is required\n\n";
    std::cout << "aliases: commit\n";
}

void show_amend() {
    std::cout << "usage: vn amend <rev> -m <message>\n\n";
    std::cout << "rewrite a revision's message and update its descendants\n\n";
    std::cout << "options:\n";
    std::cout << "  -m, -message <message>    new commit message\n\n";
    std::cout << "revisions reachable from a remote ref cannot be amended\n";
}

void show_checkout() {
    std::cout << "usage: vn co [rev]\n\n";
    std::cout << "write a revision into the working directory\n\n";
    std::cout << "aliases: checkout\n\n";
    std::cout << "arguments:\n";
    std::cout << "  [rev]                     revision to check out\n";
}

void show_fsck() {
    std::cout << "usage: vn fsck [path] [-verbose]\n\n";
    std::cout << "verify pack, index, object, and operation-log integrity\n\n";
    std::cout << "arguments:\n";
    std::cout << "  [path]                    repository to check (default: .)\n\n";
    std::cout << "options:\n";
    std::cout << "  -v, -verbose              print verbose output\n";
}

void show_repack() {
    std::cout << "usage: vn repack [path] [-level:<n>] [-verbose]\n\n";
    std::cout << "rewrite all packs into one delta-compressed pack\n\n";
    std::cout << "arguments:\n";
    std::cout << "  [path]                    repository to rewrite (default: .)\n\n";
    std::cout << "options:\n";
    std::cout << "  -level:<n>                zstd level, 1-19 (default: 6)\n";
    std::cout << "  -v, -verbose              print the size change\n";
}

void show_selftest() {
    std::cout << "usage: vn self-test\n\n";
    std::cout << "run the format self-tests\n";
}

void show_version() {
    std::cout << "usage: vn version\n\n";
    std::cout << "print version information\n";
}

void show_help() {
    std::cout << "usage: vn help [command]\n\n";
    std::cout << "show help for the program or a command\n\n";
    std::cout << "arguments:\n";
    std::cout << "  [command]                 command to describe\n";
}

void show_bmk() {
    std::cout << "usage: vn bmk <set|mv|ls|rm> ...\n\n";
    std::cout << "manage named, movable pointers to commits (branches)\n\n";
    std::cout << "subcommands:\n";
    std::cout << "  set <name> [-rev <rev>]   create or move a bookmark (default: @)\n";
    std::cout << "  mv <name> [-rev <rev>]    alias of set\n";
    std::cout << "  ls [-no-col-titles]       list bookmarks\n";
    std::cout << "  rm <name>                 delete a bookmark\n\n";
    std::cout << "examples:\n";
    std::cout << "  vn bmk set main\n";
    std::cout << "  vn new main\n";
    std::cout << "  vn co main\n";
}

void show_tag() {
    std::cout << "usage: vn tag <set|ls|rm|latest> ...\n\n";
    std::cout << "manage named pointers to commits (tags)\n\n";
    std::cout << "subcommands:\n";
    std::cout << "  set <name> [-rev <rev>]   create or move a tag (default: @)\n";
    std::cout << "  ls [-no-col-titles]       list tags\n";
    std::cout << "  rm <name>                 delete a tag\n";
    std::cout << "  latest                    print the latest tag name\n\n";
    std::cout << "the latest tag is the one whose target commit has the newest\n";
    std::cout << "committer timestamp; equal timestamps use natural name order\n";
}

void show_cfg() {
    std::cout << "usage: vn cfg [<key>] [<value>]\n";
    std::cout << "       vn cfg [<get|set|unset|list>] [<key>] [<value>]\n";
    std::cout << "       vn cfg -list\n";
    std::cout << "       vn cfg -unset <key>\n\n";
    std::cout << "read and write local repository configuration\n\n";
    std::cout << "  vn cfg                      list all keys\n";
    std::cout << "  vn cfg <key>                print a value\n";
    std::cout << "  vn cfg <key> <value>        set a value\n";
    std::cout << "  vn cfg -unset <key>         remove a key\n";
    std::cout << "  vn cfg -global ...          use the user config instead\n\n";
    std::cout << "the global editor command is read from 'editor' or 'core.editor'\n";
    std::cout << "  vn cfg -global editor \"code --wait\"\n";
}

void show_edit() {
    std::cout << "usage: vn edit [<path>...]\n\n";
    std::cout << "open paths in the configured text editor\n\n";
    std::cout << "the editor is read from the global 'editor' or 'core.editor' key,\n";
    std::cout << "then $VN_EDITOR, $VISUAL, and $EDITOR. With no paths, opens '.'.\n";
}

void show_rm() {
    std::cout << "usage: vn rm [-delete] <path>...\n\n";
    std::cout << "remove paths from the working-copy tree\n\n";
    std::cout << "files stay on disk by default. Arguments may be paths or globs "
                 "and are\n";
    std::cout << "resolved relative to the current directory. Supported "
                 "wildcards are\n";
    std::cout << "'*', '?', and '**'; '*' and '?' do not cross directory "
                 "separators.\n\n";
    std::cout << "options:\n";
    std::cout << "  -delete                   delete matching files from disk "
                 "after untracking\n";
}

void show_mv() {
    std::cout << "usage: vn mv <from> <to>\n\n";
    std::cout << "move a tracked file; the following snapshot records the rename\n";
}

void show_ex() {
    std::cout << "usage: vn ex <pattern>...\n\n";
    std::cout << "append ignore patterns to the repository root .vnexclude\n\n";
    std::cout << "patterns use gitignore syntax and are resolved relative to the "
                 "current\n";
    std::cout << "directory. Quote wildcard patterns so the shell does not "
                 "expand them:\n";
    std::cout << "  vn ex '*.dSYM'\n";
}

void show_undo() {
    std::cout << "usage: vn undo\n\n";
    std::cout << "record an operation that restores the previous operation view\n";
}

void show_op() {
    std::cout << "usage: vn op <log|restore|revert> [<op>]\n\n";
    std::cout << "inspect and restore operations\n";
}

void show_merge() {
    std::cout << "usage: vn merge <rev>...\n\n";
    std::cout << "create a merge commit from the working-copy commit and the "
                 "revisions\n";
    std::cout << "the merge never fails; conflicts are stored as conflict values\n";
}

void show_rebase() {
    std::cout << "usage: vn rebase -s <rev> -d <rev>\n\n";
    std::cout << "rewrite the source change and its descendants onto the "
                 "destination\n\n";
    std::cout << "options:\n";
    std::cout << "  -s, -source <rev>         first change to rewrite\n";
    std::cout << "  -d, -destination <rev>    new parent\n";
}

void show_xs() {
    std::cout << "usage: vn xs [-porcelain]\n\n";
    std::cout << "list conflicted paths and, for text conflicts, conflicting "
                 "line ranges\n\n";
    std::cout << "porcelain columns (tab-separated):\n";
    std::cout << "  path, kind, base-ranges, ours-ranges, theirs-ranges\n";
}

void show_resolve() {
    std::cout << "usage: vn resolve [-take ours|theirs|base] [-tool <cmd>] <path>...\n";
    std::cout << "       vn resolve -list\n\n";
    std::cout << "resolve conflicted paths. Without -take, the current file "
                 "content is\n";
    std::cout << "recorded as the resolution. -tool substitutes $BASE, $OURS, "
                 "$THEIRS,\n";
    std::cout << "and $OUTPUT in the command.\n";
}

void show_git() {
    std::cout << "usage: vn git <subcommand> [arguments]\n\n";
    std::cout << "git bridge commands:\n";
    std::cout << "  import [-source:<gitdir>] [path]\n";
    std::cout << "                            import reachable git commits and refs\n";
    std::cout << "  export [path]             export commits into the git mirror\n";
    std::cout << "  materialize [path]        replace lazy git blobs with stored "
                 "blobs\n";
    std::cout << "  fetch [<remote>] [path]   git fetch into the mirror, then import\n";
    std::cout << "  push [<remote>] <bookmark> [path]\n";
    std::cout << "                            export and git push a bookmark\n";
    std::cout << "  remote <add|list|remove>  manage git remotes\n\n";
    std::cout << "run 'vn help git <subcommand>' for details\n";
}

void show_git_import() {
    std::cout << "usage: vn git import [-source:<gitdir>] [path]\n\n";
    std::cout << "import commits and refs reachable from a git repository\n\n";
    std::cout << "an empty working tree is checked out to the imported head\n\n";
    std::cout << "arguments:\n";
    std::cout << "  [path]                    veins repository (default: .)\n\n";
    std::cout << "options:\n";
    std::cout << "  -source:<gitdir>          source git root to mirror (a directory "
                 "containing .git)\n";
}

void show_git_export() {
    std::cout << "usage: vn git export [path]\n\n";
    std::cout << "export commits reachable from bookmarks and tags into .veins/git\n";
}

void show_git_materialize() {
    std::cout << "usage: vn git materialize [path]\n\n";
    std::cout << "replace lazy git-backed blobs with canonical stored blobs.\n";
    std::cout << "rewrites affected trees, commits, and refs and records one "
                 "operation\n";
}

void show_unimplemented(std::string_view command) {
    std::cout << "usage: vn " << command << "\n\n";
    std::cout << "this command is planned for a later stage of the C++ rewrite\n";
    std::cout << "and is not available in the current local-core build\n";
}

int run_help(const std::vector<std::string>& args) {
    if (args.size() <= 2) {
        usage();
        return 0;
    }
    const std::string& cmd = args[2];
    if (cmd == "init")
        show_init();
    else if (cmd == "stat" || cmd == "status")
        show_status();
    else if (cmd == "ls")
        show_ls();
    else if (cmd == "inf")
        show_inf();
    else if (cmd == "log")
        show_log();
    else if (cmd == "show")
        show_show();
    else if (cmd == "hash")
        show_hash();
    else if (cmd == "diff" || cmd == "d")
        show_diff();
    else if (cmd == "new")
        show_new();
    else if (cmd == "desc" || cmd == "describe")
        show_describe();
    else if (cmd == "go" || cmd == "commit")
        show_commit();
    else if (cmd == "amend")
        show_amend();
    else if (cmd == "co" || cmd == "checkout")
        show_checkout();
    else if (cmd == "fsck")
        show_fsck();
    else if (cmd == "repack" || cmd == "gc")
        show_repack();
    else if (cmd == "bmk")
        show_bmk();
    else if (cmd == "tag")
        show_tag();
    else if (cmd == "cfg")
        show_cfg();
    else if (cmd == "edit")
        show_edit();
    else if (cmd == "rm")
        show_rm();
    else if (cmd == "mv")
        show_mv();
    else if (cmd == "ex")
        show_ex();
    else if (cmd == "undo")
        show_undo();
    else if (cmd == "op")
        show_op();
    else if (cmd == "merge")
        show_merge();
    else if (cmd == "rebase")
        show_rebase();
    else if (cmd == "xs")
        show_xs();
    else if (cmd == "resolve")
        show_resolve();
    else if (cmd == "self-test")
        show_selftest();
    else if (cmd == "version")
        show_version();
    else if (cmd == "help")
        show_help();
    else if (net_help(cmd)) {
    } else if (cmd == "git") {
        if (args.size() > 3) {
            const std::string& sub = args[3];
            if (sub == "import")
                show_git_import();
            else if (sub == "export")
                show_git_export();
            else if (sub == "materialize")
                show_git_materialize();
            else if (sub == "fetch")
                std::cout << "usage: vn git fetch [<remote>] [path]\n";
            else if (sub == "push")
                std::cout << "usage: vn git push [<remote>] <bookmark> [path]\n";
            else if (sub == "remote")
                std::cout << "usage: vn git remote <add|list|remove> ...\n";
            else {
                error_prefix();
                std::cout << "unknown git subcommand: " << sub << "\n";
                return 1;
            }
        } else {
            show_git();
        }
    } else if (cmd == "bench-import")
        show_unimplemented(cmd);
    else {
        usage();
        error_prefix();
        std::cout << "unknown command: " << cmd << "\n";
        return 1;
    }
    return 0;
}

} // namespace

int cli_run(const std::vector<std::string>& args) {
    install_promisor_fetcher();
    if (args.size() < 2) {
        usage();
        return 1;
    }
    const std::string& cmd = args[1];
    if (cmd == "init")
        return run_init(args);
    if (cmd == "stat" || cmd == "status" || cmd == "s")
        return run_status();
    if (cmd == "ls")
        return run_ls(args);
    if (cmd == "inf")
        return run_inf(args);
    if (cmd == "log")
        return run_log(args);
    if (cmd == "show")
        return run_show(args);
    if (cmd == "hash")
        return run_hash(args);
    if (cmd == "diff" || cmd == "d")
        return run_diff(args);
    if (cmd == "new")
        return run_new(args);
    if (cmd == "desc" || cmd == "describe")
        return run_describe(args);
    if (cmd == "go" || cmd == "commit")
        return run_commit(args);
    if (cmd == "amend")
        return run_amend(args);
    if (cmd == "co" || cmd == "checkout")
        return run_checkout(args);
    if (cmd == "bmk")
        return bmk_run(args);
    if (cmd == "tag")
        return tag_run(args);
    if (cmd == "cfg" || cmd == "config")
        return cfg_run(args);
    if (cmd == "edit")
        return run_edit(args);
    if (cmd == "rm")
        return rm_run(args);
    if (cmd == "mv")
        return mv_run(args);
    if (cmd == "ex")
        return ex_run(args);
    if (cmd == "op")
        return op_run(args);
    if (cmd == "undo")
        return undo_run(args);
    if (cmd == "merge")
        return merge_run(args);
    if (cmd == "rebase")
        return rebase_run(args);
    if (cmd == "xs")
        return xs_run(args);
    if (cmd == "resolve")
        return resolve_run(args);
    if (cmd == "fsck")
        return run_fsck(args);
    if (cmd == "repack" || cmd == "gc")
        return run_repack(args);
    if (cmd == "self-test")
        return run_self_test();
    if (cmd == "version" || cmd == "-version") {
        std::cout << "veins v" << VN_VERSION << " (veins-store 1)\n";
        return 0;
    }
    if (cmd == "help" || cmd == "-help" || cmd == "-h")
        return run_help(args);

    if (cmd == "remote")
        return remote_run(args);
    if (cmd == "clone")
        return clone_run(args);
    if (cmd == "fetch")
        return fetch_run(args);
    if (cmd == "gg")
        return gg_run(args);
    if (cmd == "push")
        return push_run(args);
    if (cmd == "serve")
        return serve_run(args);
    if (cmd == "key")
        return key_run(args);
    if (cmd == "auth")
        return auth_run(args);
    if (cmd == "access")
        return access_run(args);
    if (cmd == "whoami")
        return whoami_run(args);

    if (cmd == "git")
        return git_cli_run(args);
    if (cmd == "bench-import") {
        error_prefix();
        std::cout << "command '" << cmd << "' is not available in this stage\n";
        return 1;
    }
    usage();
    error_prefix();
    std::cout << "unknown command: " << cmd << "\n";
    return 1;
}

} // namespace vn
