Luigit
repositories / dotfiles

dotfiles

bugabingas dorkfiles

owned by admin

niri/.pi/skills/modernize/scripts/inspect.mjs

Raw
import { execFileSync } from "node:child_process";
import { readFileSync } from "node:fs";
import { fileURLToPath } from "node:url";

const repository = "https://github.com/niri-wm/niri";
const api = "https://api.github.com/repos/niri-wm/niri";
const config = new URL("../../../../config.kdl", import.meta.url);

export function parseVersion(value) {
    const match = /^(\d{2}\.\d{2}(?:\.\d+)?) \(([0-9a-f]{7,40})\)$/.exec(value);
    if (!match) throw new Error(`Unrecognized Niri version: ${value}`);
    return { version: match[1], hash: match[2] };
}

export function readBaseline(source) {
    const lines = source.split(/\r?\n/).filter(line => /^\s*\/\/\s*reviewed-with:/.test(line));
    if (!lines.length) return null;
    if (lines.length !== 1) throw new Error("Expected one reviewed-with comment");
    const value = lines[0].replace(/^\s*\/\/\s*reviewed-with:\s*/, "").trim();
    return value === "unknown" ? null : parseVersion(value);
}

async function request(path) {
    const url = `${api}/${path}`;
    const response = await fetch(url, {
        headers: { Accept: "application/vnd.github+json", "User-Agent": "niri-modernize" },
        signal: AbortSignal.timeout(30_000),
    });
    if (!response.ok) throw new Error(`GitHub HTTP ${response.status}: ${url}`);
    return response.json();
}

function checkSha(sha) {
    if (!/^[0-9a-f]{40}$/.test(sha ?? "")) throw new Error("GitHub returned an invalid commit SHA");
    return sha;
}

async function resolve(ref) {
    const sha = checkSha((await request(`commits/${ref}`)).sha);
    const raw = `https://raw.githubusercontent.com/niri-wm/niri/${sha}`;
    return {
        sha,
        url: `${repository}/commit/${sha}`,
        docs: `${raw}/docs/wiki/`,
        docs_tree: `${repository}/tree/${sha}/docs/wiki`,
        default_config: `${raw}/resources/default-config.kdl`,
        config_source: `${repository}/tree/${sha}/niri-config/src`,
    };
}

// Same complete-range checks as the WezTerm inspector; this skill is standalone.
export async function compare(base, head) {
    checkSha(base);
    checkSha(head);
    const commits = [];
    const seen = new Set();
    let total;
    let status;
    for (let page = 1; ; page++) {
        const data = await request(`compare/${base}...${head}?per_page=100&page=${page}`);
        if (!["ahead", "identical"].includes(data.status))
            throw new Error(`Cannot review ${base}...${head}: history is ${data.status}`);
        total ??= data.total_commits;
        status ??= data.status;
        if (!Number.isSafeInteger(total) || total < 0 || data.total_commits !== total || data.status !== status || !Array.isArray(data.commits))
            throw new Error("Invalid or inconsistent GitHub comparison");
        for (const commit of data.commits) {
            const sha = checkSha(commit.sha);
            if (seen.has(sha) || typeof commit.commit?.message !== "string")
                throw new Error("Invalid or repeated GitHub commit");
            seen.add(sha);
            commits.push({ sha, title: commit.commit.message.split("\n")[0], url: `${repository}/commit/${sha}` });
        }
        if (commits.length === total) break;
        if (!data.commits.length || commits.length > total) throw new Error("Incomplete GitHub comparison");
    }
    return { url: `${repository}/compare/${base}...${head}`, status, total_commits: total, commits };
}

export async function inspect(source, installedVersion) {
    const baseline = readBaseline(source);
    if (!installedVersion.startsWith("niri ")) throw new Error("Unexpected niri --version output");
    const installed = parseVersion(installedVersion.slice(5));
    const release = await request("releases/latest");
    if (!/^v\d{2}\.\d{2}(?:\.\d+)?$/.test(release.tag_name ?? "")) throw new Error("Invalid latest release metadata");
    const upstream = await resolve("main");
    const installedCommit = await resolve(installed.hash);
    const baselineCommit = baseline ? await resolve(baseline.hash) : null;
    return {
        config: fileURLToPath(config),
        baseline: baseline ? { ...baseline, ...baselineCommit } : null,
        installed: { ...installed, ...installedCommit },
        latest_release: { tag: release.tag_name, url: `${repository}/releases/tag/${release.tag_name}` },
        upstream: { ref: "main", ...upstream },
        review: baseline ? await compare(baselineCommit.sha, installedCommit.sha) : null,
        requires_upgrade: await compare(installedCommit.sha, upstream.sha),
    };
}

if (import.meta.main) {
    try {
        const source = readFileSync(config, "utf8");
        const installed = execFileSync("niri", ["--version"], { encoding: "utf8", timeout: 10_000 }).trim();
        console.log(JSON.stringify(await inspect(source, installed), null, 2));
    } catch (error) {
        console.error(error.message);
        process.exitCode = 1;
    }
}