Convert Figma logo to code with AI

urfave logocli

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

22,275
1,702
22,275
43

Top Related Projects

37,918

A Commander for modern Go CLI interactions

3,493

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

1,730

A Go library for implementing command-line interfaces.

7,943

Create *beautiful* command-line interfaces with Python

go command line option parser

1,981

Struct-based argument parsing in Go

Quick Overview

urfave/cli is a popular Go package for building command-line applications. It provides a simple, fast, and fun way to create CLI apps in Go, offering a rich set of features for parsing command-line arguments, handling flags, and organizing commands.

Pros

  • Easy to use and intuitive API
  • Extensive documentation and examples
  • Supports nested commands and subcommands
  • Automatic help generation and customization options

Cons

  • Can be overkill for very simple CLI applications
  • Some advanced features may require a steeper learning curve
  • Limited built-in support for interactive prompts (though can be integrated with other libraries)

Code Examples

Basic CLI app with a single command:

package main

import (
    "fmt"
    "log"
    "os"

    "github.com/urfave/cli/v2"
)

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

    if err := app.Run(os.Args); err != nil {
        log.Fatal(err)
    }
}

CLI app with flags:

app := &cli.App{
    Flags: []cli.Flag{
        &cli.StringFlag{
            Name:    "lang",
            Aliases: []string{"l"},
            Value:   "english",
            Usage:   "language for the greeting",
        },
    },
    Action: func(c *cli.Context) error {
        name := "someone"
        if c.NArg() > 0 {
            name = c.Args().Get(0)
        }
        if c.String("lang") == "spanish" {
            fmt.Println("Hola", name)
        } else {
            fmt.Println("Hello", name)
        }
        return nil
    },
}

CLI app with subcommands:

app := &cli.App{
    Commands: []*cli.Command{
        {
            Name:    "add",
            Aliases: []string{"a"},
            Usage:   "add a task to the list",
            Action: func(c *cli.Context) error {
                fmt.Println("Added task:", c.Args().First())
                return nil
            },
        },
        {
            Name:    "complete",
            Aliases: []string{"c"},
            Usage:   "complete a task on the list",
            Action: func(c *cli.Context) error {
                fmt.Println("Completed task:", c.Args().First())
                return nil
            },
        },
    },
}

Getting Started

To use urfave/cli in your Go project:

  1. Install the package:

    go get github.com/urfave/cli/v2
    
  2. Import it in your Go file:

    import "github.com/urfave/cli/v2"
    
  3. Create a basic CLI app structure:

    func main() {
        app := &cli.App{
            Name:  "myapp",
            Usage: "fight the loneliness!",
            Action: func(c *cli.Context) error {
                fmt.Println("Hello friend!")
                return nil
            },
        }
    
        if err := app.Run(os.Args); err != nil {
            log.Fatal(err)
        }
    }
    
  4. Build and run your app:

    go build
    ./myapp
    

Competitor Comparisons

37,918

A Commander for modern Go CLI interactions

Pros of Cobra

  • More comprehensive feature set, including built-in support for subcommands and persistent flags
  • Extensive documentation and a larger community, leading to better support and resources
  • Generates boilerplate code and CLI documentation automatically

Cons of Cobra

  • Steeper learning curve due to its more complex structure and additional features
  • Slightly more verbose syntax for basic command-line applications
  • Larger dependency footprint compared to CLI

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:

app := &cli.App{
  Name:  "app",
  Usage: "A brief description of your application",
  Action: func(c *cli.Context) error {
    // Your code here
    return nil
  },
}

Both Cobra and CLI are popular Go libraries for building command-line interfaces. Cobra offers a more feature-rich experience with built-in support for complex command structures, while CLI provides a simpler and more lightweight approach. The choice between the two depends on the complexity of your application and your specific requirements.

3,493

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

Pros of kingpin

  • More concise and expressive API for defining commands and flags
  • Built-in support for environment variables and default values
  • Better handling of enum-like flag values

Cons of kingpin

  • Less actively maintained compared to cli
  • Smaller community and ecosystem
  • Limited support for custom help text formatting

Code Comparison

kingpin:

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

cli:

app := &cli.App{
    Name:  "chat",
    Usage: "A command-line chat application",
    Commands: []*cli.Command{
        {
            Name:  "send",
            Usage: "Send a message",
            Action: func(c *cli.Context) error {
                message := c.Args().First()
                // Send message logic
                return nil
            },
        },
    },
}

Both libraries offer similar functionality for creating command-line interfaces, but kingpin provides a more fluent and declarative API. cli, on the other hand, uses a more traditional struct-based approach with explicit command definitions. The choice between the two often comes down to personal preference and specific project requirements.

1,730

A Go library for implementing command-line interfaces.

Pros of cli (mitchellh)

  • Simpler API with fewer concepts to learn
  • Built-in support for subcommands and nested command structures
  • Includes a basic testing framework for CLI applications

Cons of cli (mitchellh)

  • Less feature-rich compared to urfave/cli
  • Fewer built-in flag types and parsing options
  • Less active development and smaller community

Code Comparison

cli (mitchellh):

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

cli (urfave):

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

Both libraries provide ways to create CLI applications in Go, but they differ in their approach and feature set. cli (mitchellh) offers a more straightforward API with built-in support for subcommands, while cli (urfave) provides a richer set of features and more active development. The choice between the two depends on the specific needs of your project and your preference for simplicity versus feature completeness.

7,943

Create *beautiful* command-line interfaces with Python

Pros of docopt

  • Declarative approach using POSIX-style usage patterns
  • Language-agnostic design, available in multiple programming languages
  • Minimal code required to define complex CLI structures

Cons of docopt

  • Less flexibility for custom validation and complex argument handling
  • Limited built-in support for subcommands compared to urfave/cli
  • Steeper learning curve for developers unfamiliar with 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.
"""

urfave/cli example:

app := &cli.App{
  Name: "naval-fate",
  Commands: []*cli.Command{
    {
      Name:    "ship",
      Subcommands: []*cli.Command{
        {
          Name:  "new",
          Usage: "Create a new ship",
          Action: func(c *cli.Context) error {
            // Implementation
          },
        },
        // Other subcommands...
      },
    },
    // Other commands...
  },
}

go command line option parser

Pros of go-flags

  • More flexible tag-based approach for defining flags
  • Supports automatic generation of man pages
  • Allows for more complex command-line structures with nested commands

Cons of go-flags

  • Less intuitive API for simple use cases
  • Documentation is not as comprehensive as cli
  • Fewer built-in features for common CLI patterns

Code Comparison

go-flags:

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

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

cli:

app := &cli.App{
    Flags: []cli.Flag{
        &cli.StringFlag{Name: "name", Aliases: []string{"n"}, Usage: "A name"},
        &cli.BoolFlag{Name: "verbose", Aliases: []string{"v"}, Usage: "Show verbose debug information"},
    },
}

Both libraries offer robust solutions for building command-line interfaces in Go. cli provides a more straightforward approach for simple applications, while go-flags offers greater flexibility for complex command structures. The choice between them depends on the specific requirements of your project and personal preference for API design.

1,981

Struct-based argument parsing in Go

Pros of go-arg

  • Simpler and more intuitive API, requiring less boilerplate code
  • Automatic generation of help text based on struct tags
  • Built-in support for environment variables

Cons of go-arg

  • Less flexibility for complex command-line structures
  • Fewer built-in features compared to cli's extensive functionality
  • Smaller community and ecosystem

Code Comparison

go-arg:

type Args struct {
    Foo string `arg:"required,-f" help:"foo is a required flag"`
    Bar int
}

func main() {
    var args Args
    arg.MustParse(&args)
}

cli:

app := &cli.App{
    Flags: []cli.Flag{
        &cli.StringFlag{
            Name:     "foo",
            Aliases:  []string{"f"},
            Usage:    "foo is a required flag",
            Required: true,
        },
        &cli.IntFlag{
            Name:  "bar",
            Usage: "bar flag",
        },
    },
    Action: func(c *cli.Context) error {
        // Handle command logic
        return nil
    },
}

Both go-arg and cli are popular command-line argument parsing libraries for Go. go-arg focuses on simplicity and ease of use, leveraging struct tags for configuration. It automatically generates help text and supports environment variables out of the box. However, it may be less suitable for complex command structures.

cli offers more flexibility and features, making it better suited for larger applications with intricate command-line interfaces. It provides a wider range of options for customization but requires more code to set up. cli also has a larger community and ecosystem, which can be beneficial for long-term support and additional tools.

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

Welcome to urfave/cli

Go Reference Go Report Card codecov Tests status

urfave/cli is a declarative, simple, fast, and fun package for building command line tools in Go featuring:

  • commands and subcommands with alias and prefix match support
  • flexible and permissive help system
  • dynamic shell completion for bash, zsh, fish, and powershell
  • no dependencies except Go standard library
  • input flags for simple types, slices of simple types, time, duration, and others
  • compound short flag support (-a -b -c can be shortened to -abc)
  • documentation generation in man and Markdown (supported via the urfave/cli-docs module)
  • input lookup from:
    • environment variables
    • plain text files
    • structured file formats (supported via the urfave/cli-altsrc module)

Documentation

See the hosted documentation website at https://cli.urfave.org. Contents of this website are built from the ./docs directory.

Support

Check the Q&A discussions. If you don't find answer to your question, create a new discussion.

If you found a bug or have a feature request, create a new issue.

Please keep in mind that this project is run by unpaid volunteers.

License

See LICENSE.