xonecas.io
6533
Yo

yoctomarkdown / files

yoctomarkdown / src / cli.ts

2.0 KB
1#!/usr/bin/env bun
2import { readFileSync } from "node:fs";
3import { parseArgs } from "node:util";
4import { createHighlighter, type Options } from "./index";
5
6const { values, positionals } = parseArgs({
7  args: Bun.argv.slice(2),
8  options: {
9    theme: { type: "string", short: "t" },
10    wrap: { type: "string", short: "w" },
11    help: { type: "boolean", short: "h" },
12  },
13  allowPositionals: true,
14});
15
16if (values.help) {
17  console.log(`
18Usage: yoctomarkdown [options] [file]
19
20Options:
21  -t, --theme <name>    Theme to use: 16, 256, truecolor, minimal, none (default: 16)
22  -w, --wrap <n|auto|0> Word wrap setting (default: auto)
23  -h, --help            Show this help message
24`);
25  process.exit(0);
26}
27
28const themeName = values.theme || "16";
29const validThemes = ["16", "256", "truecolor", "minimal", "none"];
30if (!validThemes.includes(themeName)) {
31  console.error(`Invalid theme: ${themeName}`);
32  process.exit(1);
33}
34
35const wrapVal = values.wrap || "auto";
36let wordWrap: number | "auto" | 0 = "auto";
37if (wrapVal === "auto" || wrapVal === "0") {
38  wordWrap = wrapVal === "auto" ? "auto" : 0;
39} else {
40  const n = parseInt(wrapVal, 10);
41  if (Number.isNaN(n) || n < 0) {
42    console.error(`Invalid wrap value: ${wrapVal}`);
43    process.exit(1);
44  }
45  wordWrap = n;
46}
47
48const options: Options = {
49  theme: themeName as Options["theme"],
50  wordWrap,
51};
52
53const highlighter = createHighlighter(options);
54
55async function run() {
56  if (positionals.length > 0) {
57    const file = positionals[0] as string;
58    try {
59      const content = readFileSync(file, "utf8");
60      process.stdout.write(highlighter.write(content));
61      process.stdout.write(highlighter.end());
62    } catch (err: unknown) {
63      console.error(
64        `Error reading file: ${err instanceof Error ? err.message : String(err)}`,
65      );
66      process.exit(1);
67    }
68  } else {
69    for await (const chunk of process.stdin) {
70      process.stdout.write(highlighter.write(chunk));
71    }
72    process.stdout.write(highlighter.end());
73  }
74}
75
76run();