Skip to content

allow customising program#74

Merged
mmkal merged 1 commit intomainfrom
customise-program
May 1, 2025
Merged

allow customising program#74
mmkal merged 1 commit intomainfrom
customise-program

Conversation

@mmkal
Copy link
Copy Markdown
Owner

@mmkal mmkal commented Apr 24, 2025

fixes #73

@Blackskyliner cli.run(...) now accepts a Command as a second argument. This lets you modify the commander program directly:

import {Command} from 'commander'

const cli = createCli(...)
const program = cli.buildProgram() as Command
program.usage('Here is how to use: `calculator add 1 1`')
program.addHelpText('afterAll', `Good luck have fun`)
await cli.run({}, program)

Test:

test('modify commander program manually', async () => {
  const cli = createCli({router: calculatorRouter})
  const program = cli.buildProgram() as Command
  program.usage('Here is how to use: `calculator add 1 1`')
  program.addHelpText('afterAll', `Good luck have fun`)
  const mockLog = vi.fn()
  const result = await cli
    .run(
      {
        argv: ['--help'],
        process: {exit: () => void 0 as never},
        logger: {...console, error: mockLog, info: mockLog},
      },
      program,
    )
    .catch(err => err?.cause)

  expect(result).toMatchInlineSnapshot(`[CommanderError: (outputHelp)]`)
  expect(mockLog.mock.calls.join('\n')).toMatchInlineSnapshot(`
    "Usage: program Here is how to use: \`calculator add 1 1\`

    Options:
      -h, --help                       display help for command

    Commands:
      add <parameter_1> <parameter_2>
      square-root <number>
      help [command]                   display help for command

    Good luck have fun
    "
  `)
})

Notes:

  1. I want to avoid any "type could not be named" errors downstream so buildProgram returns a CommandProgramLike and it needs to be cast into an actual import {Command} from 'commander' type
  2. This isn't documented for now - I haven't fully thought through the use case here but thought it was worth making it possible to do since it's almost possible already. There are some methods on the Program called in run, not just in buildProgram - in theory you could use this to pass in a subclass of Command that alters what they do

@mmkal mmkal merged commit b6b9280 into main May 1, 2025
5 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Feature Request: Return command to integrate in existing CLIs

1 participant