cli-builder

26
3
Source

Guide for building TypeScript CLIs with Bun. Use when creating command-line tools, adding subcommands to existing CLIs, or building developer tooling. Covers argument parsing, subcommand patterns, output formatting, and distribution.

Install

mkdir -p .claude/skills/cli-builder && curl -L -o skill.zip "https://mcp.directory/api/skills/download/2917" && unzip -o skill.zip -d .claude/skills/cli-builder && rm skill.zip

Installs to .claude/skills/cli-builder

About this skill

CLI Builder

Build TypeScript command-line tools with Bun.

When to Build a CLI

CLIs are ideal for:

  • Developer tools and automation
  • Project-specific commands (swarm, bd, etc.)
  • Scripts that need arguments/flags
  • Tools that compose with shell pipelines

Quick Start

Minimal CLI

#!/usr/bin/env bun
// scripts/my-tool.ts

const args = process.argv.slice(2);
const command = args[0];

if (!command || command === "help") {
  console.log(`
Usage: my-tool <command>

Commands:
  hello    Say hello
  help     Show this message
`);
  process.exit(0);
}

if (command === "hello") {
  console.log("Hello, world!");
}

Run with: bun scripts/my-tool.ts hello

With Argument Parsing

Use parseArgs from Node's util module (works in Bun):

#!/usr/bin/env bun
import { parseArgs } from "util";

const { values, positionals } = parseArgs({
  args: process.argv.slice(2),
  options: {
    name: { type: "string", short: "n" },
    verbose: { type: "boolean", short: "v", default: false },
    help: { type: "boolean", short: "h", default: false },
  },
  allowPositionals: true,
});

if (values.help) {
  console.log(`
Usage: greet [options] <message>

Options:
  -n, --name <name>   Name to greet
  -v, --verbose       Verbose output
  -h, --help          Show help
`);
  process.exit(0);
}

const message = positionals[0] || "Hello";
const name = values.name || "World";

console.log(`${message}, ${name}!`);
if (values.verbose) {
  console.log(`  (greeted at ${new Date().toISOString()})`);
}

Subcommand Pattern

For CLIs with multiple commands, use a command registry:

#!/usr/bin/env bun
import { parseArgs } from "util";

type Command = {
  description: string;
  run: (args: string[]) => Promise<void>;
};

const commands: Record<string, Command> = {
  init: {
    description: "Initialize a new project",
    run: async (args) => {
      const { values } = parseArgs({
        args,
        options: {
          template: { type: "string", short: "t", default: "default" },
        },
      });
      console.log(`Initializing with template: ${values.template}`);
    },
  },

  build: {
    description: "Build the project",
    run: async (args) => {
      const { values } = parseArgs({
        args,
        options: {
          watch: { type: "boolean", short: "w", default: false },
        },
      });
      console.log(`Building...${values.watch ? " (watch mode)" : ""}`);
    },
  },
};

function showHelp() {
  console.log(`
Usage: mytool <command> [options]

Commands:`);
  for (const [name, cmd] of Object.entries(commands)) {
    console.log(`  ${name.padEnd(12)} ${cmd.description}`);
  }
  console.log(`
Run 'mytool <command> --help' for command-specific help.
`);
}

// Main
const [command, ...args] = process.argv.slice(2);

if (!command || command === "help" || command === "--help") {
  showHelp();
  process.exit(0);
}

const cmd = commands[command];
if (!cmd) {
  console.error(`Unknown command: ${command}`);
  showHelp();
  process.exit(1);
}

await cmd.run(args);

Output Formatting

Colors (without dependencies)

const colors = {
  reset: "\x1b[0m",
  red: "\x1b[31m",
  green: "\x1b[32m",
  yellow: "\x1b[33m",
  blue: "\x1b[34m",
  dim: "\x1b[2m",
  bold: "\x1b[1m",
};

function success(msg: string) {
  console.log(`${colors.green}✓${colors.reset} ${msg}`);
}

function error(msg: string) {
  console.error(`${colors.red}✗${colors.reset} ${msg}`);
}

function warn(msg: string) {
  console.log(`${colors.yellow}⚠${colors.reset} ${msg}`);
}

function info(msg: string) {
  console.log(`${colors.blue}ℹ${colors.reset} ${msg}`);
}

JSON Output Mode

Support --json for scriptable output:

const { values } = parseArgs({
  args: process.argv.slice(2),
  options: {
    json: { type: "boolean", default: false },
  },
  allowPositionals: true,
});

const result = { status: "ok", items: ["a", "b", "c"] };

if (values.json) {
  console.log(JSON.stringify(result, null, 2));
} else {
  console.log("Status:", result.status);
  console.log("Items:", result.items.join(", "));
}

Progress Indicators

function spinner(message: string) {
  const frames = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"];
  let i = 0;

  const id = setInterval(() => {
    process.stdout.write(`\r${frames[i++ % frames.length]} ${message}`);
  }, 80);

  return {
    stop: (finalMessage?: string) => {
      clearInterval(id);
      process.stdout.write(`\r${finalMessage || message}\n`);
    },
  };
}

// Usage
const spin = spinner("Loading...");
await someAsyncWork();
spin.stop("✓ Done!");

File System Operations

import { readFile, writeFile, mkdir, readdir } from "fs/promises";
import { existsSync } from "fs";
import { join, dirname } from "path";

// Ensure directory exists before writing
async function writeFileWithDir(path: string, content: string) {
  await mkdir(dirname(path), { recursive: true });
  await writeFile(path, content);
}

// Read JSON with defaults
async function readJsonFile<T>(path: string, defaults: T): Promise<T> {
  if (!existsSync(path)) return defaults;
  const content = await readFile(path, "utf-8");
  return { ...defaults, ...JSON.parse(content) };
}

Shell Execution

import { $ } from "bun";

// Simple command
const result = await $`git status`.text();

// With error handling
try {
  await $`npm test`.quiet();
  console.log("Tests passed!");
} catch (error) {
  console.error("Tests failed");
  process.exit(1);
}

// Capture output
const branch = await $`git branch --show-current`.text();
console.log(`Current branch: ${branch.trim()}`);

Error Handling

class CLIError extends Error {
  constructor(message: string, public exitCode = 1) {
    super(message);
    this.name = "CLIError";
  }
}

async function main() {
  try {
    await runCommand();
  } catch (error) {
    if (error instanceof CLIError) {
      console.error(`Error: ${error.message}`);
      process.exit(error.exitCode);
    }
    throw error; // Re-throw unexpected errors
  }
}

main();

Distribution

package.json bin field

{
  "name": "my-cli",
  "bin": {
    "mycli": "./dist/cli.js"
  },
  "scripts": {
    "build": "bun build ./src/cli.ts --outfile ./dist/cli.js --target node"
  }
}

Shebang for direct execution

#!/usr/bin/env bun
// First line of your CLI script

Make executable: chmod +x scripts/my-cli.ts

Best Practices

  1. Always provide --help - Users expect it
  2. Exit codes matter - 0 for success, non-zero for errors
  3. Support --json - For scriptability and piping
  4. Fail fast - Validate inputs early
  5. Be quiet by default - Use --verbose for noise
  6. Respect NO_COLOR - Check process.env.NO_COLOR
  7. Stream large output - Don't buffer everything in memory

publish-package-cicd

joelhooks

CI/CD publishing workflow for npm packages using Changesets + npm Trusted Publishers (OIDC). Use when setting up automated npm publishing for monorepos, configuring GitHub Actions for releases, troubleshooting workspace:* protocol resolution issues, fixing "Cannot find module" errors in published packages, or debugging npm OIDC authentication. Covers Bun + Turborepo + Changesets + npm Trusted Publishers with workspace protocol resolution.

41

gh-issue-triage

joelhooks

GitHub issue triage workflow with contributor profile extraction. Analyze → clarify → file cells → tag → implement → credit. Captures Twitter handles for changeset acknowledgments.

21

hive-workflow

joelhooks

Issue tracking and task management using the hive system. Use when creating, updating, or managing work items. Use when you need to track bugs, features, tasks, or epics. Do NOT use for simple one-off questions or explorations.

21

learning-systems

joelhooks

Implicit feedback scoring, confidence decay, and anti-pattern detection. Use when understanding how the swarm plugin learns from outcomes, implementing learning loops, or debugging why patterns are being promoted or deprecated. Unique to opencode-swarm-plugin.

31

swarm-coordination

joelhooks

Multi-agent coordination patterns for OpenCode swarm workflows. Use when work benefits from parallelization or coordination.

30

pr-triage

joelhooks

Context-efficient PR comment triage. Evaluate, decide, act. Fix important issues, resolve the rest silently.

00

You might also like

flutter-development

aj-geddes

Build beautiful cross-platform mobile apps with Flutter and Dart. Covers widgets, state management with Provider/BLoC, navigation, API integration, and material design.

1,6881,430

ui-ux-pro-max

nextlevelbuilder

"UI/UX design intelligence. 50 styles, 21 palettes, 50 font pairings, 20 charts, 8 stacks (React, Next.js, Vue, Svelte, SwiftUI, React Native, Flutter, Tailwind). Actions: plan, build, create, design, implement, review, fix, improve, optimize, enhance, refactor, check UI/UX code. Projects: website, landing page, dashboard, admin panel, e-commerce, SaaS, portfolio, blog, mobile app, .html, .tsx, .vue, .svelte. Elements: button, modal, navbar, sidebar, card, table, form, chart. Styles: glassmorphism, claymorphism, minimalism, brutalism, neumorphism, bento grid, dark mode, responsive, skeuomorphism, flat design. Topics: color palette, accessibility, animation, layout, typography, font pairing, spacing, hover, shadow, gradient."

1,2711,337

drawio-diagrams-enhanced

jgtolentino

Create professional draw.io (diagrams.net) diagrams in XML format (.drawio files) with integrated PMP/PMBOK methodologies, extensive visual asset libraries, and industry-standard professional templates. Use this skill when users ask to create flowcharts, swimlane diagrams, cross-functional flowcharts, org charts, network diagrams, UML diagrams, BPMN, project management diagrams (WBS, Gantt, PERT, RACI), risk matrices, stakeholder maps, or any other visual diagram in draw.io format. This skill includes access to custom shape libraries for icons, clipart, and professional symbols.

1,5451,153

godot

bfollington

This skill should be used when working on Godot Engine projects. It provides specialized knowledge of Godot's file formats (.gd, .tscn, .tres), architecture patterns (component-based, signal-driven, resource-based), common pitfalls, validation tools, code templates, and CLI workflows. The `godot` command is available for running the game, validating scripts, importing resources, and exporting builds. Use this skill for tasks involving Godot game development, debugging scene/resource files, implementing game systems, or creating new Godot components.

1,359809

nano-banana-pro

garg-aayush

Generate and edit images using Google's Nano Banana Pro (Gemini 3 Pro Image) API. Use when the user asks to generate, create, edit, modify, change, alter, or update images. Also use when user references an existing image file and asks to modify it in any way (e.g., "modify this image", "change the background", "replace X with Y"). Supports both text-to-image generation and image-to-image editing with configurable resolution (1K default, 2K, or 4K for high resolution). DO NOT read the image file first - use this skill directly with the --input-image parameter.

1,268732

pdf-to-markdown

aliceisjustplaying

Convert entire PDF documents to clean, structured Markdown for full context loading. Use this skill when the user wants to extract ALL text from a PDF into context (not grep/search), when discussing or analyzing PDF content in full, when the user mentions "load the whole PDF", "bring the PDF into context", "read the entire PDF", or when partial extraction/grepping would miss important context. This is the preferred method for PDF text extraction over page-by-page or grep approaches.

1,496685