Build a shelf-label CLI
The command library label "The Odyssey" --shelf classics will print a label. It will also tell a shell script when the title is missing. Start with project setup and install @chojs/command.
1. Declare the command
Save as app.ts. The action name selects the method, args._ contains the positional title, and args.shelf contains the named option. CHO also uses the flag declaration to generate help.
import {
Action, ChoCommand, type ChoCommandContext, Controller, Help, Module,
} from "@chojs/command";
@Help("Library catalog")
@Controller()
class Catalog {
@Help("Print a label for a book")
@Action("label", {
string: ["shelf"],
alias: { s: "shelf" },
default: { shelf: "general" },
describe: { shelf: "Shelf printed on the label" },
})
label({ args }: ChoCommandContext) {
const [title] = args._;
if (title === undefined) {
console.error("Supply a book title.");
return 2;
}
console.log("[" + args.shelf + "] " + title);
}
}
@Module({ controllers: [Catalog] })
class Library {}
export const createApp = () =>
ChoCommand.create(Library, { name: "library", version: "1.0.0" });2. Connect the process
Create cli.ts alongside app.ts. Only this entry point needs to know where the runtime keeps its arguments or how it reports an exit code.
import { createApp } from "./app.ts";
const app = createApp();
let code: number;
try {
code = await app.run(Deno.args);
} finally {
await app.close();
}
Deno.exit(code);import { createApp } from "./app.ts";
const app = createApp();
try {
process.exitCode = await app.run(process.argv.slice(2));
} finally {
await app.close();
}3. Try success, help and failure
deno run cli.ts label "The Odyssey" -s classics
deno run cli.ts label --help
deno run cli.ts labelnpx tsx cli.ts label "The Odyssey" -s classics
npx tsx cli.ts label --help
npx tsx cli.ts labelbun run cli.ts label "The Odyssey" -s classics
bun run cli.ts label --help
bun run cli.ts labelThe first invocation prints [classics] The Odyssey. The second lists the shelf option, its alias and its default. The last prints Supply a book title. to stderr. In a POSIX shell, run echo $? immediately afterwards to see status 2.
Use @Main for a tool with one implicit command. For a complete single-command project with an injected file reader, build a catalog audit. For additional named actions, see flag parsing and help output.