/** * TOML parser for configuration files. * Parse TOML files (Cargo.toml, pyproject.toml, etc.). * Extract sections, list dependencies, compare versions. * * This is a self-contained TOML parser — no external dependency needed. */ type TomlValue = string | number | boolean | Date | TomlValue[] | TomlTable; interface TomlTable { [key: string]: TomlValue; } /** Trim inline comments from a line (respecting quoted strings). */ function trimComment(line: string): string { let inStr = false; let quote = ""; for (let i = 0; i < line.length; i++) { const ch = line[i]; if (inStr) { if (ch === quote) inStr = false; continue; } if (ch === '"' || ch === "'") { inStr = true; quote = ch; continue; } if (ch === "#") return line.slice(0, i).trimEnd(); } return line; } /** Parse a TOML value token. */ function parseValue(raw: string): TomlValue { raw = raw.trim(); // Boolean if (raw === "true") return true; if (raw === "false") return false; // String (basic) if (raw.startsWith('"') && raw.endsWith('"')) { return raw .slice(1, -1) .replace(/\\n/g, "\n") .replace(/\\t/g, "\t") .replace(/\\\\/g, "\\") .replace(/\\"/g, '"'); } // String (literal) if (raw.startsWith("'") && raw.endsWith("'")) { return raw.slice(1, -1); } // Inline array if (raw.startsWith("[") && raw.endsWith("]")) { const inner = raw.slice(1, -1).trim(); if (inner === "") return []; return splitArrayElements(inner).map((el) => parseValue(el.trim())); } // Inline table if (raw.startsWith("{") && raw.endsWith("}")) { const inner = raw.slice(1, -1).trim(); const table: TomlTable = {}; if (inner === "") return table; for (const part of splitArrayElements(inner)) { const eqIdx = part.indexOf("="); if (eqIdx === -1) continue; const k = part.slice(0, eqIdx).trim(); const v = part.slice(eqIdx + 1).trim(); table[k] = parseValue(v); } return table; } // Integer or Float if (/^[+-]?\d[\d_]*$/.test(raw)) return parseInt(raw.replace(/_/g, ""), 10); if (/^[+-]?\d[\d_]*\.\d[\d_]*$/.test(raw)) return parseFloat(raw.replace(/_/g, "")); // Date (basic check) if (/^\d{4}-\d{2}-\d{2}/.test(raw)) { const d = new Date(raw); if (!isNaN(d.getTime())) return d; } return raw; } /** Split top-level comma-separated elements, respecting brackets/braces/quotes. */ function splitArrayElements(s: string): string[] { const parts: string[] = []; let depth = 0; let inStr = false; let quote = ""; let current = ""; for (const ch of s) { if (inStr) { current += ch; if (ch === quote) inStr = false; continue; } if (ch === '"' || ch === "'") { inStr = true; quote = ch; current += ch; continue; } if (ch === "[" || ch === "{") { depth++; current += ch; continue; } if (ch === "]" || ch === "}") { depth--; current += ch; continue; } if (ch === "," && depth === 0) { parts.push(current); current = ""; continue; } current += ch; } if (current.trim()) parts.push(current); return parts; } /** Set a nested key on a table. */ function setNested(root: TomlTable, keyPath: string[], value: TomlValue): void { let current = root; for (let i = 0; i < keyPath.length - 1; i++) { const k = keyPath[i]; if (!(k in current) || typeof current[k] !== "object" || Array.isArray(current[k])) { current[k] = {}; } current = current[k] as TomlTable; } current[keyPath[keyPath.length - 1]] = value; } /** Parse a key that may be dotted or quoted. */ function parseKey(raw: string): string[] { const parts: string[] = []; let current = ""; let inQuote = false; let quoteChar = ""; for (const ch of raw) { if (inQuote) { if (ch === quoteChar) { inQuote = false; } else { current += ch; } continue; } if (ch === '"' || ch === "'") { inQuote = true; quoteChar = ch; continue; } if (ch === ".") { parts.push(current.trim()); current = ""; continue; } current += ch; } parts.push(current.trim()); return parts; } /** Parse a TOML document string into a nested object. */ export function parseToml(text: string): TomlTable { const root: TomlTable = {}; let currentTable = root; let currentPath: string[] = []; const lines = text.split(/\r?\n/); for (let i = 0; i < lines.length; i++) { let line = lines[i].trim(); // Skip empty lines and comments if (line === "" || line.startsWith("#")) continue; // Array of tables: [[section]] const arrayMatch = line.match(/^\[\[(.+)\]\]\s*$/); if (arrayMatch) { const path = parseKey(arrayMatch[1].trim()); currentPath = path; // Navigate to parent, create array entry let target = root; for (let p = 0; p < path.length - 1; p++) { if (!(path[p] in target)) target[path[p]] = {}; target = target[path[p]] as TomlTable; } const lastKey = path[path.length - 1]; if (!(lastKey in target)) target[lastKey] = []; const arr = target[lastKey]; if (Array.isArray(arr)) { const newEntry: TomlTable = {}; arr.push(newEntry); currentTable = newEntry; } continue; } // Table header: [section] const tableMatch = line.match(/^\[(.+)\]\s*$/); if (tableMatch) { const path = parseKey(tableMatch[1].trim()); currentPath = path; // Ensure path exists let target = root; for (const key of path) { if (!(key in target)) target[key] = {}; const val = target[key]; if (Array.isArray(val)) { target = val[val.length - 1] as TomlTable; } else { target = val as TomlTable; } } currentTable = target; continue; } // Key-value pair line = trimComment(line); const eqIdx = line.indexOf("="); if (eqIdx === -1) continue; const rawKey = line.slice(0, eqIdx).trim(); const rawVal = line.slice(eqIdx + 1).trim(); // Handle multi-line basic strings let value: string = rawVal; if (rawVal === '"""' || (rawVal.startsWith('"""') && !rawVal.endsWith('"""'))) { const parts = [rawVal.slice(3)]; while (i + 1 < lines.length) { i++; if (lines[i].includes('"""')) { parts.push(lines[i].slice(0, lines[i].indexOf('"""'))); break; } parts.push(lines[i]); } const keyParts = parseKey(rawKey); setNested(currentTable, keyParts, parts.join("\n")); continue; } // Handle multi-line arrays if (rawVal.startsWith("[") && !rawVal.endsWith("]")) { const parts = [rawVal]; while (i + 1 < lines.length) { i++; parts.push(lines[i].trim()); if (lines[i].trim().endsWith("]")) break; } value = parts.join(" "); } const keyParts = parseKey(rawKey); setNested(currentTable, keyParts, parseValue(value)); } return root; } /** Extract a specific section from a TOML table. */ export function extractSection(table: TomlTable, sectionPath: string): TomlValue | undefined { const keys = sectionPath.split("."); let current: TomlValue = table; for (const key of keys) { if (typeof current !== "object" || current === null || Array.isArray(current)) return undefined; current = (current as TomlTable)[key]; if (current === undefined) return undefined; } return current; } export interface DependencyInfo { name: string; version: string; source: string; } /** List dependencies from a Cargo.toml or pyproject.toml structure. */ export function listDependencies(table: TomlTable): DependencyInfo[] { const deps: DependencyInfo[] = []; // Cargo.toml style const cargoDeps = table.dependencies as TomlTable | undefined; if (cargoDeps && typeof cargoDeps === "object" && !Array.isArray(cargoDeps)) { for (const [name, val] of Object.entries(cargoDeps)) { if (typeof val === "string") { deps.push({ name, version: val, source: "dependencies" }); } else if (typeof val === "object" && val !== null && !Array.isArray(val)) { const t = val as TomlTable; deps.push({ name, version: String(t.version ?? "*"), source: "dependencies" }); } } } const cargoDevDeps = table["dev-dependencies"] as TomlTable | undefined; if (cargoDevDeps && typeof cargoDevDeps === "object" && !Array.isArray(cargoDevDeps)) { for (const [name, val] of Object.entries(cargoDevDeps)) { if (typeof val === "string") { deps.push({ name, version: val, source: "dev-dependencies" }); } else if (typeof val === "object" && val !== null && !Array.isArray(val)) { const t = val as TomlTable; deps.push({ name, version: String(t.version ?? "*"), source: "dev-dependencies" }); } } } // pyproject.toml style (PEP 621) const project = table.project as TomlTable | undefined; if (project && typeof project === "object" && !Array.isArray(project)) { const projDeps = project.dependencies; if (Array.isArray(projDeps)) { for (const d of projDeps) { if (typeof d === "string") { const match = d.match(/^([a-zA-Z0-9_-]+)\s*(.*)/); if (match) { deps.push({ name: match[1], version: match[2] || "*", source: "project.dependencies" }); } } } } } return deps; } /** Compare version strings. Returns -1, 0, or 1. */ export function compareVersions(a: string, b: string): number { const normalize = (v: string) => v.replace(/^[~^>= parseInt(n, 10) || 0); const pa = normalize(a); const pb = normalize(b); const len = Math.max(pa.length, pb.length); for (let i = 0; i < len; i++) { const na = pa[i] || 0; const nb = pb[i] || 0; if (na < nb) return -1; if (na > nb) return 1; } return 0; }