Caporal CLI Framework

1.4.0 · active · verified Tue Apr 21

Caporal is a comprehensive framework for building command-line interface (CLI) applications with Node.js. It offers robust features for defining commands, parsing arguments, and handling options, along with automated help generation, colorful output, adjustable verbosity, and custom logging. Distinguishing features include built-in type coercion (e.g., `prog.INT`), intelligent typo suggestions for commands, and shell auto-completion capabilities for Bash, Zsh, and Fish. The current stable version is 3.1.5, released in August 2023, succeeding the major 3.0.0 release which introduced updated Node.js compatibility requirements. The project maintains an active development pace, with regular patch and minor updates focused on bug fixes and feature enhancements.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates a simple 'deploy' command with required and optional arguments, along with boolean and integer options. It showcases Caporal's argument validation, type coercion, and integrated logger for informative output.

#!/usr/bin/env node
import * as prog from 'caporal';

prog
  .version('1.0.0')
  .description('A simple deployment CLI application')
  .command('deploy', 'Deploy an application to a specified environment')
  .argument('<appName>', 'The name of the application to deploy', /^myapp|their-app$/)
  .argument('[environment]', 'The target environment (dev, staging, production)', /^dev|staging|production$/, 'local')
  .option('--tail <lines>', 'Tail log lines after deployment', prog.INT, 10)
  .option('--force', 'Force deployment even if warnings exist', prog.BOOL, false)
  .action(async (args, options, logger) => {
    const { appName, environment } = args;
    const { tail, force } = options;

    logger.info(`Deploying application: ${appName}`);
    logger.info(`Target environment: ${environment}`);
    logger.info(`Tail ${tail} log lines: ${tail > 0}`);
    logger.info(`Force deploy: ${force}`);

    if (force) {
      logger.warn('Forcing deployment, ignoring warnings...');
    }

    // Simulate deployment process
    await new Promise(resolve => setTimeout(resolve, 1500));

    logger.info(`Application '${appName}' deployed to '${environment}' successfully.`);
    if (tail > 0) {
      logger.info(`Tailing last ${tail} log lines...`);
      // Simulate log tailing
      for (let i = 1; i <= tail; i++) {
        logger.info(`[${new Date().toISOString()}] Log line ${i}`);
      }
    }
  });

prog.parse(process.argv);

view raw JSON →