Convert Figma logo to code with AI

mitchellh logocli

A Go library for implementing command-line interfaces.

1,730
122
1,730
7

Top Related Projects

37,918

A Commander for modern Go CLI interactions

22,275

A simple, fast, and fun package for building command line apps in Go

3,493

CONTRIBUTIONS ONLY: A Go (golang) command line and flag parser

go command line option parser

7,943

Create *beautiful* command-line interfaces with Python

1,369

Flags-first package for configuration

Quick Overview

mitchellh/cli is a Go package for building command-line interfaces (CLIs) with subcommands, help documentation, and more. It provides a simple and flexible way to create powerful CLI applications in Go, offering features like command parsing, help generation, and autocomplete support.

Pros

  • Easy to use and integrate into existing Go projects
  • Supports nested subcommands and command grouping
  • Automatically generates help documentation and usage information
  • Provides built-in support for command autocompletion

Cons

  • Limited customization options for help output formatting
  • Lacks built-in support for advanced features like flags and arguments parsing
  • May require additional libraries for more complex CLI applications
  • Documentation could be more comprehensive and include more examples

Code Examples

  1. Creating a basic CLI with a single command:
package main

import (
    "github.com/mitchellh/cli"
    "os"
)

func main() {
    c := cli.NewCLI("app", "1.0.0")
    c.Args = os.Args[1:]
    c.Commands = map[string]cli.CommandFactory{
        "greet": func() (cli.Command, error) {
            return &GreetCommand{}, nil
        },
    }

    exitStatus, err := c.Run()
    if err != nil {
        log.Println(err)
    }

    os.Exit(exitStatus)
}

type GreetCommand struct{}

func (g *GreetCommand) Run(args []string) int {
    fmt.Println("Hello, World!")
    return 0
}

func (g *GreetCommand) Synopsis() string {
    return "Greet the user"
}

func (g *GreetCommand) Help() string {
    return "Usage: app greet"
}
  1. Adding subcommands:
c.Commands = map[string]cli.CommandFactory{
    "greet": func() (cli.Command, error) {
        return &GreetCommand{}, nil
    },
    "version": func() (cli.Command, error) {
        return &cli.VersionCommand{
            Version: "1.0.0",
            Revision: "abcdef123",
        }, nil
    },
}
  1. Using command groups:
c.Commands = map[string]cli.CommandFactory{
    "user list": func() (cli.Command, error) {
        return &UserListCommand{}, nil
    },
    "user create": func() (cli.Command, error) {
        return &UserCreateCommand{}, nil
    },
}

Getting Started

To use mitchellh/cli in your Go project:

  1. Install the package:

    go get github.com/mitchellh/cli
    
  2. Import the package in your Go code:

    import "github.com/mitchellh/cli"
    
  3. Create a new CLI instance and define your commands:

    c := cli.NewCLI("app", "1.0.0")
    c.Args = os.Args[1:]
    c.Commands = map[string]cli.CommandFactory{
        "command": func() (cli.Command, error) {
            return &YourCommand{}, nil
        },
    }
    
  4. Implement the cli.Command interface for your commands and run the CLI.

Competitor Comparisons

37,918

A Commander for modern Go CLI interactions

Pros of Cobra

  • More feature-rich with built-in support for flags, nested subcommands, and auto-generated documentation
  • Larger community and ecosystem, with more third-party extensions and integrations
  • Better suited for complex CLI applications with multiple levels of commands

Cons of Cobra

  • Steeper learning curve due to more extensive API and features
  • Can be overkill for simple CLI applications, potentially leading to unnecessary complexity
  • Slightly more verbose syntax for basic command definitions

Code Comparison

Cobra:

var rootCmd = &cobra.Command{
  Use:   "app",
  Short: "A brief description of your application",
  Run: func(cmd *cobra.Command, args []string) {
    // Your code here
  },
}

CLI:

cli := cli.NewCLI("app", "1.0.0")
cli.Args = os.Args[1:]
cli.Commands = map[string]cli.CommandFactory{
  "command": commandFactory,
}

Both libraries provide ways to create command-line interfaces in Go, but Cobra offers a more comprehensive set of features and is better suited for complex applications. CLI, on the other hand, has a simpler API and may be preferable for smaller projects or developers who prefer a more minimalist approach. The choice between the two depends on the specific requirements of your project and personal preferences.

22,275

A simple, fast, and fun package for building command line apps in Go

Pros of cli

  • More feature-rich with built-in support for subcommands, flags, and arguments
  • Extensive documentation and examples
  • Active community and regular updates

Cons of cli

  • Steeper learning curve due to more complex API
  • Potentially overkill for simple CLI applications
  • Slightly larger binary size due to additional features

Code Comparison

cli:

app := &cli.App{
  Name: "greet",
  Usage: "fight the loneliness!",
  Action: func(c *cli.Context) error {
    fmt.Println("Hello friend!")
    return nil
  },
}

cli:

cli := cli.NewCLI("app", "1.0.0")
cli.Args = os.Args[1:]
cli.Commands = map[string]cli.CommandFactory{
  "greet": func() (cli.Command, error) {
    return &greetCommand{}, nil
  },
}

Both libraries provide ways to create CLI applications in Go, but cli offers a more comprehensive set of features and a higher level of abstraction. cli is better suited for complex CLI applications with multiple subcommands and options, while cli is simpler and more lightweight, making it ideal for smaller projects or when you need more control over the CLI structure.

The choice between the two depends on the specific requirements of your project, the desired level of control, and the complexity of the CLI application you're building.

3,493

CONTRIBUTIONS ONLY: A Go (golang) command line and flag parser

Pros of Kingpin

  • More feature-rich with built-in support for flags, arguments, and subcommands
  • Offers a fluent API for easier and more intuitive command-line app creation
  • Provides automatic help generation and version flags

Cons of Kingpin

  • Less flexibility in customizing the help output
  • May have a steeper learning curve for simpler CLI applications
  • Not as actively maintained as CLI (last commit was in 2022)

Code Comparison

Kingpin:

app := kingpin.New("chat", "A chat application.")
send := app.Command("send", "Send a message.")
message := send.Arg("message", "The message to send.").Required().String()

CLI:

c := cli.NewCLI("app", "1.0.0")
c.Args = os.Args[1:]
c.Commands = map[string]cli.CommandFactory{
    "send": func() (cli.Command, error) {
        return &SendCommand{}, nil
    },
}

Summary

Kingpin offers a more feature-rich and intuitive API for creating CLI applications, with built-in support for various command-line elements. However, CLI provides greater flexibility and customization options, making it potentially better suited for complex applications or those requiring fine-grained control over the CLI structure and help output.

go command line option parser

Pros of go-flags

  • More comprehensive flag parsing with support for advanced features like short and long options, default values, and environment variables
  • Automatic generation of help text and usage information
  • Supports parsing flags into struct fields, making it easier to organize and access configuration

Cons of go-flags

  • Steeper learning curve due to more complex API and features
  • May be overkill for simpler command-line applications
  • Less focus on subcommand functionality compared to cli

Code Comparison

go-flags example:

type Options struct {
    Verbose []bool `short:"v" long:"verbose" description:"Show verbose debug information"`
    Name    string `short:"n" long:"name" description:"A name" required:"true"`
}

var opts Options
_, err := flags.Parse(&opts)

cli example:

c := cli.NewCLI("app", "1.0.0")
c.Args = os.Args[1:]
c.Commands = map[string]cli.CommandFactory{
    "foo": fooCommandFactory,
}
c.Run()

Summary

go-flags offers more advanced flag parsing features and automatic help generation, while cli focuses on simplicity and subcommand support. go-flags may be better suited for complex command-line applications with many options, while cli excels in creating intuitive multi-command tools with simpler flag requirements.

7,943

Create *beautiful* command-line interfaces with Python

Pros of docopt

  • Declarative approach: Define CLI interface using a simple and intuitive syntax
  • Language-agnostic: Implementations available in multiple programming languages
  • Automatic help message generation based on the interface definition

Cons of docopt

  • Less flexibility for complex command structures or nested subcommands
  • Limited built-in validation and type conversion features
  • Steeper learning curve for the specific docopt syntax

Code Comparison

docopt example:

"""Naval Fate.

Usage:
  naval_fate ship new <name>...
  naval_fate ship <name> move <x> <y> [--speed=<kn>]
  naval_fate ship shoot <x> <y>
  naval_fate mine (set|remove) <x> <y> [--moored|--drifting]
  naval_fate -h | --help
  naval_fate --version

Options:
  -h --help     Show this screen.
  --version     Show version.
  --speed=<kn>  Speed in knots [default: 10].
  --moored      Moored (anchored) mine.
  --drifting    Drifting mine.
"""

cli example:

cli.NewApp().Commands = []cli.Command{
  {
    Name:    "ship",
    Aliases: []string{"s"},
    Subcommands: []cli.Command{
      {
        Name:  "new",
        Usage: "Create a new ship",
        Action: func(c *cli.Context) error {
          // Implementation
        },
      },
    },
  },
}
1,369

Flags-first package for configuration

Pros of ff

  • Focused on configuration management with support for multiple sources (flags, environment variables, config files)
  • Lightweight and minimal dependencies
  • Designed for use with Go's standard flag package

Cons of ff

  • Less comprehensive CLI toolkit compared to cli
  • Fewer built-in features for creating complex command structures
  • Limited documentation and examples compared to cli

Code Comparison

ff:

fs := flag.NewFlagSet("example", flag.ExitOnError)
var (
    listenAddr = fs.String("listen-addr", "localhost:8080", "listen address")
    refresh    = fs.Duration("refresh", 15*time.Second, "refresh interval")
)
ff.Parse(fs, os.Args[1:])

cli:

c := cli.NewCLI("app", "1.0.0")
c.Args = os.Args[1:]
c.Commands = map[string]cli.CommandFactory{
    "foo": fooCommandFactory,
    "bar": barCommandFactory,
}
exitStatus, err := c.Run()

Summary

ff is a lightweight configuration management library that works well with Go's standard flag package, while cli provides a more comprehensive toolkit for building complex command-line applications. ff excels in simplicity and flexibility for configuration, while cli offers more structure and features for creating multi-command CLIs.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

🚨 This project is archived. 🚨 Learn More

Go CLI Library GoDoc

cli is a library for implementing command-line interfaces in Go. cli is the library that powers the CLI for Packer, Consul, Vault, Terraform, Nomad, and more.

Features

  • Easy sub-command based CLIs: cli foo, cli bar, etc.

  • Support for nested subcommands such as cli foo bar.

  • Optional support for default subcommands so cli does something other than error.

  • Support for shell autocompletion of subcommands, flags, and arguments with callbacks in Go. You don't need to write any shell code.

  • Automatic help generation for listing subcommands.

  • Automatic help flag recognition of -h, --help, etc.

  • Automatic version flag recognition of -v, --version.

  • Helpers for interacting with the terminal, such as outputting information, asking for input, etc. These are optional, you can always interact with the terminal however you choose.

  • Use of Go interfaces/types makes augmenting various parts of the library a piece of cake.

Example

Below is a simple example of creating and running a CLI

package main

import (
	"log"
	"os"

	"github.com/mitchellh/cli"
)

func main() {
	c := cli.NewCLI("app", "1.0.0")
	c.Args = os.Args[1:]
	c.Commands = map[string]cli.CommandFactory{
		"foo": fooCommandFactory,
		"bar": barCommandFactory,
	}

	exitStatus, err := c.Run()
	if err != nil {
		log.Println(err)
	}

	os.Exit(exitStatus)
}