markdown-code
Version:
Keep code examples in Markdown synchronized with actual source files
82 lines (80 loc) • 2.55 kB
JavaScript
import {
extractSnippets
} from "./chunk-LFQPKNTT.js";
import "./chunk-7RDMPJH4.js";
import {
DEFAULT_CONFIG,
fileExists,
getValidatedConfig,
handleError,
logWarningsAndErrors
} from "./chunk-LNSAPIWZ.js";
// src/commands/init.ts
import { writeFile, mkdir } from "fs/promises";
import { resolve } from "path";
var command = "init";
var describe = "Create a default configuration file";
var builder = (yargs) => {
return yargs.option("extract", {
type: "boolean",
describe: "Extract snippets from existing code blocks after creating config",
default: false
});
};
async function createDefaultConfig() {
const configPath = resolve(".markdown-coderc.json");
const snippetsDir = resolve("snippets");
if (await fileExists(configPath)) {
console.log("Configuration file already exists at .markdown-coderc.json");
return;
}
const defaultConfig = { ...DEFAULT_CONFIG, snippetRoot: "./snippets" };
try {
await writeFile(configPath, JSON.stringify(defaultConfig, null, 2));
console.log("Created .markdown-coderc.json with default configuration");
if (!await fileExists(snippetsDir)) {
await mkdir(snippetsDir, { recursive: true });
console.log("Created snippets/ directory for your source files");
}
console.log("\nNext steps:");
console.log("1. Place your source files in the snippets/ directory");
console.log(
"2. Add snippet directives to your markdown files: ```js snippet=example.js"
);
console.log("3. Run `md-code` to sync your code examples");
} catch (error) {
const errorMessage = error instanceof Error ? error.message : String(error);
throw new Error(`Failed to create configuration: ${errorMessage}`);
}
}
function logExtractionResults(result) {
if (result.extracted.length > 0) {
console.log(`Extracted ${result.snippetsCreated} snippets from:`);
result.extracted.forEach((file) => console.log(` ${file}`));
} else {
console.log("No code blocks found to extract.");
}
}
async function handleExtraction(argv) {
console.log("Extracting snippets from existing code blocks...");
const config = await getValidatedConfig(argv);
const result = await extractSnippets(config);
logWarningsAndErrors(result.warnings, result.errors);
logExtractionResults(result);
}
var handler = async (argv) => {
try {
await createDefaultConfig();
if (argv.extract) {
await handleExtraction(argv);
}
} catch (error) {
handleError(error);
}
};
export {
builder,
command,
describe,
handler
};