import type { Database } from "bun:sqlite"; import type { DescribeEntry } from "../cli"; import { DocumentMetadataError, validateDescription } from "./validation"; export type DocumentedCommand = { name: string; description: string; pathOrder: number; }; export function documentCommands( database: Database, entries: DescribeEntry[], source: string, ): void { const upsert = database.query( `INSERT INTO command_metadata (command_name, description, source, updated_at) VALUES (?1, ?2, ?3, ?4) ON CONFLICT(command_name) DO UPDATE SET description = excluded.description, source = excluded.source, updated_at = excluded.updated_at`, ); const exists = database.query("SELECT EXISTS(SELECT 1 FROM commands WHERE name = ?1) AS present"); database.transaction((items: DescribeEntry[]) => { for (const entry of items) { const row = exists.get(entry.name) as { present: number }; if (row.present === 0) { throw new DocumentMetadataError( "unknown_command", `cannot document \`${entry.name}\` because it is not in the current index`, ); } upsert.run(entry.name, validateDescription(entry.description), source, now()); } })(entries); } export function undocumentedCommandNames(database: Database): string[] { const rows = database .query( `SELECT commands.name FROM commands LEFT JOIN command_metadata ON command_metadata.command_name = commands.name WHERE command_metadata.command_name IS NULL ORDER BY commands.path_order ASC`, ) .all() as { name: string }[]; return rows.map((row) => row.name); } export function documentedCommands(database: Database): DocumentedCommand[] { const rows = database .query( `SELECT commands.name, command_metadata.description, commands.path_order AS pathOrder FROM commands INNER JOIN command_metadata ON command_metadata.command_name = commands.name ORDER BY commands.path_order ASC`, ) .all() as DocumentedCommand[]; return rows; } function now(): number { return Math.floor(Date.now() / 1000); }