Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

cli-belt

Package Overview
Dependencies
Maintainers
0
Versions
11
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

cli-belt

An utility belt to complement your arguments parser of choice

  • 2.0.2
  • latest
  • Source
  • npm
  • Socket score

Version published
Weekly downloads
2.6K
increased by39.73%
Maintainers
0
Weekly downloads
 
Created
Source

cli-belt

Version Types License

A lossless slug that preserves uniqueness.

Install

npm install cli-belt

Motivation

Most solutions for creating command line interfaces have a too high degree of magic going on that prevents proper control over how arguments are parsed, which arguments are parsed, and so on. On the other hand, using barebones argument parsers can require much boilerplate. cli-belt intends to complement the later, reducing the amount of boilerplate needed. I've found arg to be a blissful middle ground for argument parsing, but which parser you use is entirely up to you.

Documentation

These are all of cli-belt's helper functions -see docs:

  • loadPackage finds and returns the contents of the first package.json found, recursing up from a dir.
  • flags parses a help string and returns an object with options, aliases, arguments, and descriptions.
  • safePairs ensures all properties of an object exist in another.
  • splitBy splits an arguments array into two arrays by the first separator.
  • error formats and prints an error message, optionally exiting the process.

Usage example

import { error, flags, loadPackage, safePairs, splitBy } from 'cli-belt';
import { stripIndent as indent } from 'common-tags';
import arg from 'arg';
import logger from 'loglevel';
import spawn from 'await-spawn';

main().catch((err) => error(err, { exit: 1, debug: true, logger }));

export default async function main() {
  // Get description and version from `package.json`
  const pkg = await loadPackage(__dirname, { title: true });

  const help = indent`
    ${pkg.description || ''}

    Usage: example [options] -- [echoArgs]

    Options:
      -e, --env <environment>    Node environment
      -h, --help                 Show help
      -v, --version              Show version number

    Examples:
      $ example -v
      $ example --help
      $ example -- "this will get printed because we're spawning echo"
  `;

  // Get flags and aliases from help
  const { options, aliases } = flags(help);

  // Define option types
  const types = {
    '--env': String,
    '--help': Boolean,
    '--version': Boolean
  };

  // Ensure all parsed flags have a defined type,
  // and that they have all been successfully parsed and exist on help
  safePairs(types, options, { fail: true, bidirectional: true });

  // Add aliases to the ones explicitly typed
  Object.assign(types, aliases);

  // Only pass to `arg` arguments before '--'
  // arguments after '--' will be passed to spawn
  const [argv, args] = splitBy(process.argv.slice(2), '--');
  const cmd = arg(types, {
    argv,
    permissive: false,
    stopAtPositional: true
  });

  // Handle options
  if (cmd._.length) throw new Error(`Unknown command ${cmd._[0]}`);
  if (cmd['--help']) return console.log(help);
  if (cmd['--version']) return console.log(pkg.version);

  const env = cmd['--env'] ? { NODE_ENV: cmd['--env'] } : {};
  await spawn('echo', args, { env, stdio: 'inherit' });
}

Keywords

FAQs

Package last updated on 29 Jul 2024

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc