Add a command
A luna command is a generic, reusable piece of tooling — parameterised and re-runnable, modelled on the AWS CLI's noun verb --flags shape (aws lambda create --…), not a one-off script. If what you actually need is a single-use task, use luna script run instead — see Patterns & conventions for where the line is.
This guide walks through adding a new top-level command end to end. cli/STRUCTURE.md is the authoritative reference for the folder layout; this page grounds it in a worked example.
Where commands live
Every command follows a three-tier structure under cli/src/commands/<command>/:
src/commands/<command>/
├── index.ts # registers the command's subcommands
├── lib/ # shared code across this command's subcommands
└── commands/
└── <subcommand>/
├── index.ts # Commander config only — args, options, .action()
├── <subcommand>.service.ts # all business logic for the subcommand
└── __test__/ # tests mirroring the subcommandsrc/utils/— generic, cross-command utilities (AWS config, database helpers, prompts, error handling). If a helper is used by more than one command, it belongs here, re-exported fromsrc/utils/index.ts.commands/<command>/lib/— code shared across a command's own subcommands, but not generic enough forsrc/utils/.commands/<command>/<subcommand>/<subcommand>.service.ts— everything specific to one subcommand. Keep the subcommand folder flat — don't add autils/subdirectory here; consolidate into the service file instead.
The real datacopyback command (cli/src/commands/datacopyback/) is a good reference — it has three subcommands (copy, upload, wipe), each with its own index.ts + *.service.ts + __test__/.
1. Scaffold the command
Create src/commands/<command>/index.ts. This is where you register the command's subcommands with Commander:
// src/commands/<command>/index.ts
import { Command } from 'commander'
import myAction from './commands/my-subcommand'
export default () => {
const myCommand = new Command('<command>')
.description('What this command does')
myCommand
.command('my-subcommand')
.description('what this subcommand does')
.argument('<input>', 'a required positional argument')
.option('-o, --output-dir [output-directory]', 'output directory', '.')
.action(async (input, options) => {
await myAction(input, options)
})
return myCommand
}Each subcommand gets its own folder with a Commander-only index.ts and the real logic in a .service.ts:
// commands/<command>/commands/my-subcommand/index.ts
import { CLILogger } from '@bhag-business-platform/luna-logger'
import { doTheWork } from './my-subcommand.service'
export default async (input: string, options: { outputDir: string }) => {
CLILogger.Info(`Running my-subcommand for ${input}`)
await doTheWork(input, options)
}// commands/<command>/commands/my-subcommand/my-subcommand.service.ts
export const doTheWork = async (input: string, options: { outputDir: string }) => {
// business logic lives here, not in index.ts
}2. Register it in src/index.ts
src/index.ts builds the root Commander program and registers every top-level command with program.addCommand(...). Add yours alongside the existing ones:
import makeMyCommand from './commands/<command>';
// ...
program.addCommand(makeMyCommand())The command won't appear in luna --help or be runnable until this line is added.
3. Let the lifecycle hooks do their job
You don't need to handle AWS credentials, role assumption, or auditing yourself — Commander lifecycle hooks (preAction/postAction/errorHook, wired up in src/index.ts) do this for every command automatically before and after your .action() runs. See Patterns & conventions for how that lifecycle works.
The one thing this means for your code: throw an Error on failure, don't call process.exit() — exiting directly bypasses the error hook, so the audit record never gets marked FAILED. Use the shared prompt helpers (confirm, confirmWithItems, confirmProductionEnvironment, terminateIfProduction — all exported from src/utils/index.ts) rather than hand-rolling confirmation prompts; they throw the errors the hooks expect. datacopyback copy uses confirmProductionEnvironment() this way when ENVIRONMENT === 'production'.
4. Test it
Mirror the subcommand in a __test__/ folder next to it. Mock the service and shared utils, and test the index.ts action function directly — see cli/src/commands/datacopyback/commands/copy/__test__/index.test.ts for the pattern:
jest.mock('../../../../../utils')
jest.mock('../copy.service')
describe('datacopyback copy command', () => {
it('confirms production before running', async () => {
process.env.ENVIRONMENT = 'production'
await datacopybackCopyCommand(['some-table'], { outputDir: '.', exclude: [] })
expect(confirmProductionEnvironment).toHaveBeenCalledTimes(1)
})
})Run the CLI's tests with yarn run test (Jest) from cli/.
5. Build and run it locally
The CLI runs its compiled dist/, not src/ — you must rebuild for the command to register:
cd cli
yarn run build # one-off rebuild
# or
yarn run dev # watch mode, rebuilds on saveThen try it out:
luna <command> --help
luna <command> <subcommand> --help
luna -e local <command> <subcommand> ... # local env skips AWS entirely6. Bump the version
cli/package.json's version field is the single source of truth for luna --version. Bump it (semver) as part of your change.
Naming conventions
| What | Convention | Example |
|---|---|---|
| Command/subcommand source files | camelCase | getAllTables.ts |
| Business logic files | <subcommand>.service.ts | copy.service.ts |
| Type files | *.types.ts | datacopyback.types.ts |
| Config files | *.config.ts | aws.config.ts |
| Test files | *.test.ts, in __test__/ | index.test.ts |
See Patterns & conventions for the CLI's broader conventions — environment handling, auditing, and why cli-scripts-legacy/ isn't where new work goes.
