also looking at this
Add BunPress guide and pre-E2E quality gates
#4
246 files
+1744
-64381
| @@ -1,585 +0,0 @@ | ||
| 1 | --- | |
| 2 | title: Commands | |
| 3 | description: Learn how to create and use CLI commands in Stacks applications | |
| 4 | --- | |
| 5 | ||
| 6 | ### Variadic Arguments | |
| 7 | ||
| 8 | Use `...` for variadic arguments: | |
| 9 | ||
| 10 | ```typescript | |
| 11 | ||
| 12 | cli.command('install <packages...>', 'Install packages') | |
| 13 | .action((packages: string[]) => { | |
| 14 | console.log(`Installing: ${packages.join(', ')}`) | |
| 15 | }) | |
| 16 | ||
| 17 | ``` | |
| 18 | ||
| 19 | ### Multiple Arguments | |
| 20 | ||
| 21 | Combine multiple arguments: | |
| 22 | ||
| 23 | ```typescript | |
| 24 | ||
| 25 | cli.command('move <source> <destination> [options...]', 'Move files') | |
| 26 | .action((source: string, destination: string, options: string[]) => { | |
| 27 | console.log(`Moving ${source} to ${destination}`) | |
| 28 | if (options.length > 0) { | |
| 29 | console.log(`Options: ${options.join(', ')}`) | |
| 30 | } | |
| 31 | }) | |
| 32 | ||
| 33 | ``` | |
| 34 | ||
| 35 | ## Options | |
| 36 | ||
| 37 | ### Boolean Options | |
| 38 | ||
| 39 | ```typescript | |
| 40 | ||
| 41 | cli.command('build', 'Build the project') | |
| 42 | .option('--verbose, -v', 'Enable verbose output') | |
| 43 | .option('--watch, -w', 'Watch for changes') | |
| 44 | .option('--minify, -m', 'Minify output') | |
| 45 | .action((options) => { | |
| 46 | if (options.verbose) { | |
| 47 | console.log('Verbose mode enabled') | |
| 48 | } | |
| 49 | // Build logic | |
| 50 | }) | |
| 51 | ||
| 52 | ``` | |
| 53 | ||
| 54 | ### Options with Values | |
| 55 | ||
| 56 | ```typescript | |
| 57 | ||
| 58 | cli.command('serve', 'Start the server') | |
| 59 | .option('--port, -p <port>', 'Port to listen on', { default: 3000 }) | |
| 60 | .option('--host, -h <host>', 'Host to bind to', { default: 'localhost' }) | |
| 61 | .action((options) => { | |
| 62 | console.log(`Starting server on ${options.host}:${options.port}`) | |
| 63 | }) | |
| 64 | ||
| 65 | ``` | |
| 66 | ||
| 67 | ### Required Options | |
| 68 | ||
| 69 | ```typescript | |
| 70 | ||
| 71 | cli.command('deploy', 'Deploy the application') | |
| 72 | .option('--environment, -e <env>', 'Deployment environment', { required: true }) | |
| 73 | .action((options) => { | |
| 74 | console.log(`Deploying to ${options.environment}`) | |
| 75 | }) | |
| 76 | ||
| 77 | ``` | |
| 78 | ||
| 79 | ### Option Types | |
| 80 | ||
| 81 | ```typescript | |
| 82 | ||
| 83 | cli.command('process', 'Process data') | |
| 84 | // String option | |
| 85 | .option('--format, -f <format>', 'Output format', { default: 'json' }) | |
| 86 | ||
| 87 | // Number option (parsed automatically) | |
| 88 | .option('--count, -c <count>', 'Number of items', { default: 10 }) | |
| 89 | ||
| 90 | // Boolean option (flag) | |
| 91 | .option('--dry-run, -d', 'Perform dry run') | |
| 92 | ||
| 93 | // Array option | |
| 94 | .option('--include, -i <patterns...>', 'Patterns to include') | |
| 95 | ||
| 96 | .action((options) => { | |
| 97 | console.log('Format:', options.format) // string | |
| 98 | console.log('Count:', options.count) // number | |
| 99 | console.log('Dry run:', options.dryRun) // boolean | |
| 100 | console.log('Include:', options.include) // string[] | |
| 101 | }) | |
| 102 | ||
| 103 | ``` | |
| 104 | ||
| 105 | ### Option Validation | |
| 106 | ||
| 107 | ```typescript | |
| 108 | ||
| 109 | cli.command('resize', 'Resize an image') | |
| 110 | .option('--width, -w <width>', 'Image width', { | |
| 111 | default: 100, | |
| 112 | validate: (value) => { | |
| 113 | const num = parseInt(value, 10) | |
| 114 | if (isNaN(num) || num < 1) { | |
| 115 | return 'Width must be a positive number' | |
| 116 | } | |
| 117 | return true | |
| 118 | }, | |
| 119 | }) | |
| 120 | .action((options) => { | |
| 121 | console.log(`Resizing to width: ${options.width}`) | |
| 122 | }) | |
| 123 | ||
| 124 | ``` | |
| 125 | ||
| 126 | ## Input/Output | |
| 127 | ||
| 128 | ### Console Output | |
| 129 | ||
| 130 | ```typescript | |
| 131 | ||
| 132 | import { log } from '@stacksjs/cli' | |
| 133 | ||
| 134 | export default function (cli: CLI) { | |
| 135 | cli.command('status', 'Check status') | |
| 136 | .action(() => { | |
| 137 | // Standard log levels | |
| 138 | log.info('Information message') | |
| 139 | log.success('Success message') | |
| 140 | log.warn('Warning message') | |
| 141 | log.error('Error message') | |
| 142 | log.debug('Debug message') | |
| 143 | ||
| 144 | // Formatted output | |
| 145 | console.log('') // Empty line | |
| 146 | console.log('Plain output') | |
| 147 | }) | |
| 148 | } | |
| 149 | ||
| 150 | ``` | |
| 151 | ||
| 152 | ### Styled Output | |
| 153 | ||
| 154 | ```typescript | |
| 155 | ||
| 156 | import { bold, green, red, yellow, italic, dim } from '@stacksjs/cli' | |
| 157 | ||
| 158 | export default function (cli: CLI) { | |
| 159 | cli.command('styled', 'Show styled output') | |
| 160 | .action(() => { | |
| 161 | console.log(bold('Bold text')) | |
| 162 | console.log(green('Green text')) | |
| 163 | console.log(red('Red text')) | |
| 164 | console.log(yellow('Yellow text')) | |
| 165 | console.log(italic('Italic text')) | |
| 166 | console.log(dim('Dimmed text')) | |
| 167 | ||
| 168 | // Combine styles | |
| 169 | console.log(bold(green('Bold and green'))) | |
| 170 | }) | |
| 171 | } | |
| 172 | ||
| 173 | ``` | |
| 174 | ||
| 175 | ### Progress Indicators | |
| 176 | ||
| 177 | ```typescript | |
| 178 | ||
| 179 | import { spinner } from '@stacksjs/cli' | |
| 180 | ||
| 181 | export default function (cli: CLI) { | |
| 182 | cli.command('download', 'Download files') | |
| 183 | .action(async () => { | |
| 184 | const spin = spinner('Downloading...') | |
| 185 | spin.start() | |
| 186 | ||
| 187 | try { | |
| 188 | await downloadFiles() | |
| 189 | spin.succeed('Download complete') | |
| 190 | } catch (error) { | |
| 191 | spin.fail('Download failed') | |
| 192 | } | |
| 193 | }) | |
| 194 | } | |
| 195 | ||
| 196 | ``` | |
| 197 | ||
| 198 | ### Interactive Prompts | |
| 199 | ||
| 200 | ```typescript | |
| 201 | ||
| 202 | import { prompt, confirm, select, multiselect } from '@stacksjs/cli' | |
| 203 | ||
| 204 | export default function (cli: CLI) { | |
| 205 | cli.command('setup', 'Interactive setup') | |
| 206 | .action(async () => { | |
| 207 | // Text input | |
| 208 | const name = await prompt('What is your name?') | |
| 209 | ||
| 210 | // Confirmation | |
| 211 | const proceed = await confirm('Do you want to continue?') | |
| 212 | ||
| 213 | // Single selection | |
| 214 | const framework = await select('Choose a framework:', [ | |
| 215 | 'Vue', | |
| 216 | 'React', | |
| 217 | 'Svelte', | |
| 218 | ]) | |
| 219 | ||
| 220 | // Multiple selection | |
| 221 | const features = await multiselect('Select features:', [ | |
| 222 | { name: 'TypeScript', value: 'ts', checked: true }, | |
| 223 | { name: 'ESLint', value: 'eslint', checked: true }, | |
| 224 | { name: 'Prettier', value: 'prettier' }, | |
| 225 | ]) | |
| 226 | ||
| 227 | console.log({ name, proceed, framework, features }) | |
| 228 | }) | |
| 229 | } | |
| 230 | ||
| 231 | ``` | |
| 232 | ||
| 233 | ## Command Aliases | |
| 234 | ||
| 235 | ### Single Alias | |
| 236 | ||
| 237 | ```typescript | |
| 238 | ||
| 239 | cli.command('inspire', 'Inspire yourself') | |
| 240 | .alias('insp') | |
| 241 | .action(() => { | |
| 242 | // Can be run as `buddy inspire` or `buddy insp` | |
| 243 | }) | |
| 244 | ||
| 245 | ``` | |
| 246 | ||
| 247 | ### Multiple Aliases | |
| 248 | ||
| 249 | ```typescript | |
| 250 | ||
| 251 | cli.command('generate:component', 'Generate a component') | |
| 252 | .alias('g:c') | |
| 253 | .alias('gc') | |
| 254 | .action(() => { | |
| 255 | // Can be run as any of the aliases | |
| 256 | }) | |
| 257 | ||
| 258 | ``` | |
| 259 | ||
| 260 | ## Subcommands | |
| 261 | ||
| 262 | ### Creating Subcommands | |
| 263 | ||
| 264 | ```typescript | |
| 265 | ||
| 266 | // app/Commands/User.ts | |
| 267 | export default function (cli: CLI) { | |
| 268 | // Main command group | |
| 269 | cli.command('user', 'User management commands') | |
| 270 | ||
| 271 | // Subcommands | |
| 272 | cli.command('user:create <email>', 'Create a new user') | |
| 273 | .option('--admin', 'Create as admin') | |
| 274 | .action(async (email, options) => { | |
| 275 | await createUser(email, options.admin) | |
| 276 | }) | |
| 277 | ||
| 278 | cli.command('user:delete <id>', 'Delete a user') | |
| 279 | .option('--force', 'Skip confirmation') | |
| 280 | .action(async (id, options) => { | |
| 281 | if (!options.force) { | |
| 282 | const confirmed = await confirm('Are you sure?') | |
| 283 | if (!confirmed) return | |
| 284 | } | |
| 285 | await deleteUser(id) | |
| 286 | }) | |
| 287 | ||
| 288 | cli.command('user:list', 'List all users') | |
| 289 | .option('--format, -f <format>', 'Output format', { default: 'table' }) | |
| 290 | .action(async (options) => { | |
| 291 | const users = await getUsers() | |
| 292 | displayUsers(users, options.format) | |
| 293 | }) | |
| 294 | ||
| 295 | // Catch unknown subcommands | |
| 296 | cli.on('user:*', () => { | |
| 297 | log.error('Invalid command. See --help for available commands.') | |
| 298 | process.exit(1) | |
| 299 | }) | |
| 300 | ||
| 301 | return cli | |
| 302 | } | |
| 303 | ||
| 304 | ``` | |
| 305 | ||
| 306 | ## Calling Commands Programmatically | |
| 307 | ||
| 308 | ### From Actions | |
| 309 | ||
| 310 | ```typescript | |
| 311 | ||
| 312 | // app/Actions/MaintenanceAction.ts | |
| 313 | import { runCommand } from '@stacksjs/cli' | |
| 314 | ||
| 315 | export default new Action({ | |
| 316 | async handle() { | |
| 317 | // Run a CLI command | |
| 318 | await runCommand('buddy cache:clear') | |
| 319 | await runCommand('buddy queue:restart') | |
| 320 | ||
| 321 | return response.json({ message: 'Maintenance complete' }) | |
| 322 | }, | |
| 323 | }) | |
| 324 | ||
| 325 | ``` | |
| 326 | ||
| 327 | ### From Other Commands | |
| 328 | ||
| 329 | ```typescript | |
| 330 | ||
| 331 | export default function (cli: CLI) { | |
| 332 | cli.command('reset', 'Reset the application') | |
| 333 | .action(async () => { | |
| 334 | const { runCommand } = await import('@stacksjs/cli') | |
| 335 | ||
| 336 | log.info('Clearing cache...') | |
| 337 | await runCommand('buddy cache:clear') | |
| 338 | ||
| 339 | log.info('Running migrations...') | |
| 340 | await runCommand('buddy migrate:fresh') | |
| 341 | ||
| 342 | log.info('Seeding database...') | |
| 343 | await runCommand('buddy db:seed') | |
| 344 | ||
| 345 | log.success('Application reset complete!') | |
| 346 | }) | |
| 347 | } | |
| 348 | ||
| 349 | ``` | |
| 350 | ||
| 351 | ### Using exec | |
| 352 | ||
| 353 | ```typescript | |
| 354 | ||
| 355 | import { exec } from '@stacksjs/cli' | |
| 356 | ||
| 357 | export default function (cli: CLI) { | |
| 358 | cli.command('deploy', 'Deploy application') | |
| 359 | .action(async () => { | |
| 360 | // Run shell commands | |
| 361 | const result = await exec('git status') | |
| 362 | ||
| 363 | if (result.isOk()) { | |
| 364 | console.log(result.value.stdout) | |
| 365 | } else { | |
| 366 | console.error(result.error) | |
| 367 | } | |
| 368 | }) | |
| 369 | } | |
| 370 | ||
| 371 | ``` | |
| 372 | ||
| 373 | ## Error Handling | |
| 374 | ||
| 375 | ### Exit Codes | |
| 376 | ||
| 377 | ```typescript | |
| 378 | ||
| 379 | import { ExitCode } from '@stacksjs/types' | |
| 380 | ||
| 381 | export default function (cli: CLI) { | |
| 382 | cli.command('check', 'Check something') | |
| 383 | .action(() => { | |
| 384 | try { | |
| 385 | // Check logic | |
| 386 | process.exit(ExitCode.Success) // 0 | |
| 387 | } catch (error) { | |
| 388 | process.exit(ExitCode.FatalError) // 1 | |
| 389 | } | |
| 390 | }) | |
| 391 | } | |
| 392 | ||
| 393 | ``` | |
| 394 | ||
| 395 | ### Graceful Error Handling | |
| 396 | ||
| 397 | ```typescript | |
| 398 | ||
| 399 | import { handleError } from '@stacksjs/error-handling' | |
| 400 | ||
| 401 | export default function (cli: CLI) { | |
| 402 | cli.command('risky', 'Risky operation') | |
| 403 | .action(async () => { | |
| 404 | try { | |
| 405 | await riskyOperation() | |
| 406 | log.success('Operation completed') | |
| 407 | } catch (error) { | |
| 408 | handleError(error) | |
| 409 | log.error('Operation failed') | |
| 410 | process.exit(1) | |
| 411 | } | |
| 412 | }) | |
| 413 | } | |
| 414 | ||
| 415 | ``` | |
| 416 | ||
| 417 | ### Validation Errors | |
| 418 | ||
| 419 | ```typescript | |
| 420 | ||
| 421 | export default function (cli: CLI) { | |
| 422 | cli.command('process <file>', 'Process a file') | |
| 423 | .action(async (file) => { | |
| 424 | // Validate input | |
| 425 | if (!file.endsWith('.json')) { | |
| 426 | log.error('File must be a JSON file') | |
| 427 | process.exit(1) | |
| 428 | } | |
| 429 | ||
| 430 | // Check file exists | |
| 431 | if (!await exists(file)) { | |
| 432 | log.error(`File not found: ${file}`) | |
| 433 | process.exit(1) | |
| 434 | } | |
| 435 | ||
| 436 | // Process file | |
| 437 | await processFile(file) | |
| 438 | }) | |
| 439 | } | |
| 440 | ||
| 441 | ``` | |
| 442 | ||
| 443 | ## Best Practices | |
| 444 | ||
| 445 | ### Command Structure | |
| 446 | ||
| 447 | ```typescript | |
| 448 | ||
| 449 | // Recommended command structure | |
| 450 | export default function (cli: CLI) { | |
| 451 | cli | |
| 452 | .command('namespace:action', 'Description of what this command does') | |
| 453 | .option('--option, -o <value>', 'Option description', { default: 'default' }) | |
| 454 | .alias('n:a') | |
| 455 | .action(async (options) => { | |
| 456 | try { | |
| 457 | // 1. Validate inputs | |
| 458 | validateInputs(options) | |
| 459 | ||
| 460 | // 2. Show progress | |
| 461 | const spin = spinner('Processing...') | |
| 462 | spin.start() | |
| 463 | ||
| 464 | // 3. Perform action | |
| 465 | const result = await performAction(options) | |
| 466 | ||
| 467 | // 4. Show success | |
| 468 | spin.succeed('Complete!') | |
| 469 | displayResult(result) | |
| 470 | ||
| 471 | // 5. Exit cleanly | |
| 472 | process.exit(ExitCode.Success) | |
| 473 | } catch (error) { | |
| 474 | // 6. Handle errors gracefully | |
| 475 | handleError(error) | |
| 476 | process.exit(ExitCode.FatalError) | |
| 477 | } | |
| 478 | }) | |
| 479 | ||
| 480 | return cli | |
| 481 | } | |
| 482 | ||
| 483 | ``` | |
| 484 | ||
| 485 | ### Help Text | |
| 486 | ||
| 487 | ```typescript | |
| 488 | ||
| 489 | cli.command('complex', 'A complex command') | |
| 490 | .option('--input, -i <file>', 'Input file path') | |
| 491 | .option('--output, -o <file>', 'Output file path') | |
| 492 | .example('buddy complex -i data.json -o result.json') | |
| 493 | .example('buddy complex --input=data.json --output=result.json') | |
| 494 | ||
| 495 | ``` | |
| 496 | ||
| 497 | ## Edge Cases and Gotchas | |
| 498 | ||
| 499 | ### Option Name Conflicts | |
| 500 | ||
| 501 | Avoid using reserved option names: | |
| 502 | ||
| 503 | ```typescript | |
| 504 | ||
| 505 | // Avoid these (used by CLI framework) | |
| 506 | // --help, -h | |
| 507 | // --version, -v (if version is enabled) | |
| 508 | ||
| 509 | ``` | |
| 510 | ||
| 511 | ### Async Actions | |
| 512 | ||
| 513 | Always handle async operations properly: | |
| 514 | ||
| 515 | ```typescript | |
| 516 | ||
| 517 | // Correct: await async operations | |
| 518 | cli.command('async', 'Async command') | |
| 519 | .action(async () => { | |
| 520 | await someAsyncOperation() | |
| 521 | process.exit(0) | |
| 522 | }) | |
| 523 | ||
| 524 | // Incorrect: missing await causes early exit | |
| 525 | cli.command('async', 'Async command') | |
| 526 | .action(() => { | |
| 527 | someAsyncOperation() // Command exits before this completes | |
| 528 | process.exit(0) | |
| 529 | }) | |
| 530 | ||
| 531 | ``` | |
| 532 | ||
| 533 | ### Environment Variables | |
| 534 | ||
| 535 | Access environment variables in commands: | |
| 536 | ||
| 537 | ```typescript | |
| 538 | ||
| 539 | cli.command('config', 'Show configuration') | |
| 540 | .action(() => { | |
| 541 | const env = process.env.NODE_ENV || 'development' | |
| 542 | const debug = process.env.DEBUG === 'true' | |
| 543 | ||
| 544 | console.log(`Environment: ${env}`) | |
| 545 | console.log(`Debug: ${debug}`) | |
| 546 | }) | |
| 547 | ||
| 548 | ``` | |
| 549 | ||
| 550 | ## API Reference | |
| 551 | ||
| 552 | ### CLI Methods | |
| 553 | ||
| 554 | | Method | Description | | |
| 555 | |--------|-------------| | |
| 556 | | `command(name, description)` | Define a command | | |
| 557 | | `option(flags, description, config?)` | Add an option | | |
| 558 | | `alias(name)` | Add a command alias | | |
| 559 | | `action(handler)` | Set the action handler | | |
| 560 | | `example(text)` | Add an example | | |
| 561 | | `on(event, handler)` | Listen for events | | |
| 562 | ||
| 563 | ### Exit Codes | |
| 564 | ||
| 565 | | Code | Constant | Description | | |
| 566 | |------|----------|-------------| | |
| 567 | | 0 | `ExitCode.Success` | Successful execution | | |
| 568 | | 1 | `ExitCode.FatalError` | General error | | |
| 569 | ||
| 570 | ### Log Methods | |
| 571 | ||
| 572 | | Method | Description | | |
| 573 | |--------|-------------| | |
| 574 | | `log.info(message)` | Information message | | |
| 575 | | `log.success(message)` | Success message | | |
| 576 | | `log.warn(message)` | Warning message | | |
| 577 | | `log.error(message)` | Error message | | |
| 578 | | `log.debug(message)` | Debug message | | |
| 579 | ||
| 580 | ## Related Documentation | |
| 581 | ||
| 582 | - [Actions](/basics/actions) - HTTP request handlers | |
| 583 | - [Jobs](/basics/jobs) - Background job processing | |
| 584 | - [Logging](/basics/logging) - Application logging | |
| 585 | - [Error Handling](/basics/error-handling) - Error management | |