Generated SDK

This example demonstrates the basic usage of cli-forge to create a simple CLI with two commands and various options, and how that CLI can be used programmatically.

All Example Files

FILE EXPLORER
sdk.ts
1import cliForge from 'cli-forge';
2
3const cli = cliForge('basic-cli')
4  .demandCommand()
5  .command('hello', {
6    builder: (args) =>
7      args.option('name', {
8        type: 'string',
9        description: 'The name to say hello to',
10        default: 'World',
11      }),
12    handler: (args) => {
13      console.log(`Hello, ${args.name}!`);
14    },
15  })
16  .command('goodbye', {
17    builder: (args) =>
18      args
19        .option('name', {
20          type: 'string',
21          description: 'The name to say goodbye to',
22          default: 'World',
23        })
24        .option('excited', {
25          type: 'boolean',
26          description: 'Whether to say goodbye excitedly',
27        }),
28    handler: (args) => {
29      console.log(`Goodbye, ${args.name}${args.excited ? '!' : '.'}`);
30    },
31  })
32  .command('nested', {
33    builder: (args) =>
34      args.command('config', {
35        builder: (args) =>
36          args.option('set', {
37            type: 'object',
38            properties: {
39              key: { type: 'string', required: true },
40              value: { type: 'string', required: true },
41            },
42          }),
43        handler: (args) => {
44          console.log(`Setting config ${args.set?.key} to ${args.set?.value}`);
45        },
46      }),
47    handler: (_args) => {
48      console.log('Use a subcommand of nested');
49    },
50  });
51
52const sdk = cli.sdk();
53
54sdk.hello({
55  name: 'sir',
56});
57
58sdk.nested.config({
59  set: {
60    key: 'theme',
61    value: 'dark',
62  },
63});
64
65// Calling `.forge()` executes the CLI. It's single parameter is the CLI args
66// and they default to `process.argv.slice(2)`.
67if (require.main === module) {
68  (async () => {
69    await cli.forge();
70  })();
71}
72