GithubHelp home page GithubHelp logo

drew-y / cliffy Goto Github PK

View Code? Open in Web Editor NEW
350.0 3.0 46.0 288 KB

NodeJS Framework for Interactive CLIs

License: ISC License

TypeScript 100.00%
cli command vorpal node typescript repl nodejs command-line

cliffy's Introduction

Cliffy - A Framework For Interactive CLIs

Cliffy is a simple, powerful utility for making interactive command line interfaces.

Cliffy is run as a REPL. This allows you to accept multiple commands with one running node process. Cliffy is NOT an argv parser.

Features:

  • REPL Style interface
  • Simple API
  • Can parse negative numbers
  • Typed parameters
  • Git Style Sub-Commands
  • Optional parameters (New in v2)
  • Rest parameters (New in v2)
  • Options
  • Auto generated help
  • Typescript Support

Gotchas:

  • Options are specified with an @ symbol. Not - or --. This is what allows Cliffy to parse negatives.
  • Requires node v6+

Quickstart

Installation:

npm i cliffy # --save if using npm < v5

Usage

import { CLI } from "cliffy";

const cli = new CLI()
    .setDelimiter("-->")
    .addCommand("run", {
        description: "Run somewhere",
        options: [{ label: "quickly", description: "Run quickly" }],
        parameters: ["destination"],
        action: (params, options) => {
            if (options.quickly) {
                console.log(`I ran to ${params.destination} quickly`)
                return;
            }

            console.log(`I ran to ${params.destination}`)
        },
        subcommands: {
            to: {
                description: "Run to a destination",
                parameters: ["destination"],
                action: params => console.log(`I ran to ${params.destination}`)
            },
            from: {
                description: "Run from a destination",
                parameters: ["location"],
                action: params => console.log(`I ran from ${params.location}`)
            }
        }
    })
    .show();

Result:

--> run to nevada
I ran to nevada
--> help

Available commands:

    run [options]  <destination>    Run somewhere

--> help run

Run somewhere

Usage:

    run [options] <destination>

Options:

   @quickly                          Run quickly

Sub-Commands:

    to [options] <destination>       Run to a destination
    from [options] <destination>     Run from a destination

Quoted parameters

Parameters may be quoted using either ' (single) or " (double) quotes. For example the command could be

say "Hello World" 'Lovely Weather'

This would give two parameters of Hello World and Lovely Weather. When inside the quoted parameter, the other type of quotes can be used. This lets JSON be entered for example.

say '{"text": "This is the weather"}'

Will give a parameter of the string, {"text": "This is the weather"} that can then be parsed as JSON.

Autogenerated Help Menu

Cliffy automatically generates a help menu for each command.

To get an overview of all the commands simply type:

help

To get help with a specific command, type help followed by the command.

help ls

This works with subcommands as well

help git pull

Build instructions

  1. Clone this repo
  2. CD into the repo
  3. npm install
  4. npm run build

API

new CLI()

Interface:

class CLI {
    constructor(opts: {
        input?: NodeJS.ReadableStream,
        output?: NodeJS.WritableStream,
         /** Set to true to prevent cliffy from displaying help text after entering a blank line. Defaults to false */
        quietBlank?: boolean
    } = {})
}

Usage:

const cli = new CLI(opts)

cli.addCommand(name: string, command: Command): this

Register a command

Takes a name and a command object.

The command name is what the user will enter to execute the command.

The command interface is defined as follows:

interface Command {
    /**
     * The action to perform when its command is called.
     *
     * parameters is a key value store. Where the key is the parameter label,
     * and its value is the value entered by the user.
     *
     * options is a key value store. Key being the option, value being true if the user
     * specified the option, false otherwise.
     */
    action(parameters: any, options: { [key: string]: boolean }): void | Promise<void>;

    /** Optional description for documentation */
    description?: string;

    /** Aliases the command can be accessed from */
    aliases?: string[];

    /**
     * An array of options available to the user.
     * The user specifies an option with an @ symbol i.e. @force
     */
    options?: (Option | string)[];

    /**
     * All the parameters available to the user.
     * See the parameters interface.
     *
     * If a string is passed it is assumed to be string parameter
     */
    parameters?: (Parameter | string)[];

    /** Sub commands of the command. Follows the same interface as Command */
    subcommands?: Commands;
}

export interface Parameter {
    label: string;

    /** The type to convert the provided value to. Can be a custom converter. */
    type?: "boolean" | "number" | "string" | ((val: string) => any);

    /** The parameter is optional */
    optional?: boolean;

    /**
     * The parameter is a rest parameter.
     *
     * If true, the user can pass an indefinite amount of arguments
     * that are put in an array set in this parameter.
     **/
    rest?: boolean;

    /** Optional description for the help menu */
    description?: string;
}

export interface Option {
    label: string;
    description?: string;
}

Example Usage:

cli.addCommand("run", {
    description: "Run somewhere",
    options: [{ option: "fast", description: "Run fast" }],
    parameters: [{ label: "destination" }],
    action: (params, options) => {
        if (options.fast) return console.log(`I ran to ${params.destination} quickly`);
        console.log(`I ran to ${params.destination}`);
    },
    subcommands: {
        to: {
            parameters: [{ label: "destination" }],
            action: params => console.log(`I ran to ${params.destination}`),
        }
        from: {
            parameters: [{ label: "destination" }],
            action: params => console.log(`I ran to ${params.destination}),
        }
    }
});

cli.addCommand(name: string, opts: Action): this

Register a basic command.

This overload allows you to pass the action function directy. Useful for quick commands where parameters, options, and a description may not be needed.

Example usage:

cli.addCommand("speak", () => sayHello("World"));

cli.addCommands(commands: { [name: string]: Command | Action }): this

Register multiple commands at once.

Example usage:

cli.addCommands({
    run: {
        action(params, options) {
            console.log("Running");
        }
    },

    jog: {
        action(params, options) {
            console.log("Jogging");
        }
    },

    walk: {
        action(params, options) {
            console.log("Walking");
        }
    }
});

cli.setDelimiter(delimiter: string): this

Set the CLI delimiter

Defaults to: "$>"

cli.setInfo(info: string): this

Set the CLI info.

Info is meant to give an overview of what the CLI does and how to use it. If it is set it is shown directly under the CLI name.

Defaults to: none

cli.setName(name: string): this

Set the name of the CLI (Shown at the top of the help menu)

Defaults to: none

cli.setVersion(version: string): this

Set the CLI version. Shown beside the CLI name if set.

Defaults to: none

cli.show(): this

Show the CLI.

cli.hide(): this

Hide the cli.

cli.showHelp(): this

Show the main help menu.

cliffy's People

Contributors

ar065 avatar dependabot[bot] avatar drew-y avatar imagdy avatar localjo avatar mbwhite avatar paralax avatar sergeshkurko avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

cliffy's Issues

Unable to print color in the console

I am using chalk to print color, but it doesn't work with cliffy...

import { CLI } from "cliffy"
import chalk from "chalk"

const cli = new CLI()
  .setDelimiter(chalk.bold.blue("󰥭 "))
  .addCommand("run", {
    description: "Run somewhere",
    options: [{ label: "quickly", description: "Run quickly" }],
    parameters: ["destination"],
    action: (params, options) => {
      if (options.quickly) {
        console.log(chalk.yellow(`I ran to ${params.destination} quickly`))
        return
      }

      console.log(`I ran to ${params.destination}`)
    },
    subcommands: {
      to: {
        description: "Run to a destination",
        parameters: ["destination"],
        action: (params) => console.log(`I ran to ${params.destination}`),
      },
      from: {
        description: "Run from a destination",
        parameters: ["location"],
        action: (params) => console.log(`I ran from ${params.location}`),
      },
    },
  })
  .show()

Feature suggestions

Been playing around with this for a CLI client before building a full on GUI. Had some ideas:

  1. Tab support - command name or if sub command is next suggest that instead
  2. Support single quotes for parameters - compute networkID 'a b c' currently gives a
    while compute networkID "a b c" gives an a b c
  3. Function to display help for a certain command. For example if I use compute for as a namespace, if I type compute without a sub command following it, then I could show a list of sub commands help as if I typed help compute

Also curious, is it's possible to type while writing out text? I was playing with a CLI a few years ago and ran into that problem, but thinking it's probably some limitation in general. https://youtu.be/Q_E7ZFtoKY4 - I guess if that's the case then you wouldn't want to write anything to the console unless responding to a command.

[Request] Command Aliases

I may do a PR for this if I have time - I imagine this should be relatively simple?
Basically, my feature request just an array of aliases - set as a property on addCommand. Then, you can use these to execute the command as well as the normal trigger.

(The aliases wouldn't have to show up in help)

Custom Error Messages and Header

I would like to start off that the tool is exactly what I needed only I miss out on the following:

  • Customize Error (Command not Found)
  • Maybe set a header as ASCII Art that will come back

Commands take more arguments than supported

I just ran the example snippet and was surprised that this is accepted as input:

-->run foo bar

The command supports only one argument; if more are provided, I would expect that the CLI yields an error message that reminds the user of the correct syntax, but the CLI seems to ignore the superflous input silently and outputs this:

I ran to foo
-->

TS Error with option "noUnusedLocals"

With these tsc option "noUnusedLocals": true,
TSC give console errors:

node_modules/cliffy/src/index.ts(4,19): error TS6133: 'Parameter' is declared but its value is never read.
node_modules/cliffy/src/index.ts(10,7): error TS6133: 'columnify' is declared but its value is never read.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.