UNPKG

mdclint

Version:

Markdown Linting

100 lines (95 loc) 2.78 kB
import { defineCommand } from 'citty'; import fs from 'node:fs/promises'; import { g as getMarkdownlintOptions, a as applyFixes } from './shared/mdclint.C8nPUujy.mjs'; import { glob } from 'glob'; import { resolve } from 'node:path'; import 'c12'; import 'node:fs'; import 'node:module'; import 'node:os'; import 'remark-mdc'; function printResult(result) { let totalErrors = 0; const gray = (text) => `\x1B[90m${text}\x1B[0m`; const underline = (text) => `\x1B[4m${text}\x1B[0m`; for (const [file, errors] of Object.entries(result)) { if (errors.length === 0) { continue; } totalErrors += errors.length; console.log("\n" + underline(file)); errors.forEach((error) => { const { lineNumber, ruleNames, ruleDescription, errorDetail } = error; console.log(` ${gray(`${lineNumber}:`)} ${ruleDescription}${errorDetail ? `(${errorDetail})` : ""} ${gray(ruleNames.join(", "))}`); }); } if (totalErrors > 0) { console.log(` ${totalErrors} problems `); process.exit(1); } } async function getFiles(files) { const resolvedFiles = files.map((file) => resolve(process.cwd(), file)); const matchedFiles = []; for (const file of resolvedFiles) { const stat = await fs.stat(file).catch(() => null); if (stat?.isFile()) { matchedFiles.push(file); } else { const path = stat?.isDirectory() ? `${file}/**` : file; const files2 = await glob(path, { nodir: true, absolute: true }); matchedFiles.push(...files2); } } return matchedFiles; } const index = defineCommand({ meta: { name: "mdclint", description: "Markdownlint CLI" }, args: { fix: { type: "boolean", description: "Automatically fix problems", default: false }, preset: { type: "string", description: "Preset to use, (markdown, mdc)", default: "mdc", values: ["markdown", "mdc"] } }, run: async ({ args }) => { const options = await getMarkdownlintOptions(process.cwd(), { preset: args.preset }); const files = await getFiles(args._); if (!files?.length) { return; } const lint = await import('./chunks/exports-sync.mjs').then((m) => m.lint); if (args.fix) { for (const file of files) { const lintTask = { files: [file], ...options }; const result2 = lint(lintTask)[file].filter((error) => error.fixInfo); if (result2.length === 0) { continue; } const content = await fs.readFile(file, "utf-8"); const fixed = applyFixes(content, result2); await fs.writeFile(file, fixed); } } const result = lint({ ...options, files }); printResult(result); } }); export { index as default };