ProductPromotion
Logo

Go.Lang

made by https://0x3d.site

GitHub - yitsushi/go-commander: Go library to simplify CLI workflow
Go library to simplify CLI workflow. Contribute to yitsushi/go-commander development by creating an account on GitHub.
Visit Site

GitHub - yitsushi/go-commander: Go library to simplify CLI workflow

GitHub - yitsushi/go-commander: Go library to simplify CLI workflow

Documentation Go Report Card Coverage Status Build Status

This is a simple Go library to manage commands for your CLI tool. Easy to use and now you can focus on Business Logic instead of building the command routing.

What this library does for you?

Manage your separated commands. How? Generates a general help and command specific helps for your commands. If your command fails somewhere (panic for example), commander will display the error message and the command specific help to guide your user.

Install

$ go get github.com/yitsushi/go-commander

Sample output (from totp-cli)

$ totp-cli help

change-password                   Change password
update                            Check and update totp-cli itself
version                           Print current version of this application
generate <namespace>.<account>    Generate a specific OTP
add-token [namespace] [account]   Add new token
list [namespace]                  List all available namespaces or accounts under a namespace
delete <namespace>[.account]      Delete an account or a whole namespace
help [command]                    Display this help or a command specific help

Usage

Every single command has to implement CommandHandler. Check this project for examples.

package main

// Import the package
import "github.com/yitsushi/go-commander"

// Your Command
type YourCommand struct {
}

// Executed only on command call
func (c *YourCommand) Execute(opts *commander.CommandHelper) {
  // Command Action
}

func NewYourCommand(appName string) *commander.CommandWrapper {
  return &commander.CommandWrapper{
    Handler: &YourCommand{},
    Help: &commander.CommandDescriptor{
      Name:             "your-command",
      ShortDescription: "This is my own command",
      LongDescription:  `This is a very long
description about this command.`,
      Arguments:        "<filename> [optional-argument]",
      Examples:         []string {
        "test.txt",
        "test.txt copy",
        "test.txt move",
      },
    },
  }
}

// Main Section
func main() {
	registry := commander.NewCommandRegistry()

	registry.Register(NewYourCommand)

	registry.Execute()
}

Now you have a CLI tool with two commands: help and your-command.

❯ go build mytool.go

❯ ./mytool
your-command <filename> [optional-argument]   This is my own command
help [command]                                Display this help or a command specific help

❯ ./mytool help your-command
Usage: mytool your-command <filename> [optional-argument]

This is a very long
description about this command.

Examples:
  mytool your-command test.txt
  mytool your-command test.txt copy
  mytool your-command test.txt move

How to use subcommand pattern?

When you create your main command, just create a new CommandRegistry inside the Execute function like you did in your main() and change Depth.

import subcommand "github.com/yitsushi/mypackage/command/something"

func (c *Something) Execute(opts *commander.CommandHelper) {
	registry := commander.NewCommandRegistry()
	registry.Depth = 1
	registry.Register(subcommand.NewSomethingMySubCommand)
	registry.Execute()
}

PreValidation

If you want to write a general pre-validation for your command or just simply keep your validation logic separated:

// Or you can define inline if you want
func MyValidator(c *commander.CommandHelper) {
  if c.Arg(0) == "" {
    panic("File?")
  }

  info, err := os.Stat(c.Arg(0))
  if err != nil {
    panic("File not found")
  }

  if !info.Mode().IsRegular() {
    panic("It's not a regular file")
  }

  if c.Arg(1) != "" {
    if c.Arg(1) != "copy" && c.Arg(1) != "move" {
      panic("Invalid operation")
    }
  }
}

func NewYourCommand(appName string) *commander.CommandWrapper {
  return &commander.CommandWrapper{
    Handler: &YourCommand{},
    Validator: MyValidator
    Help: &commander.CommandDescriptor{
      Name:             "your-command",
      ShortDescription: "This is my own command",
      LongDescription:  `This is a very long
description about this command.`,
      Arguments:        "<filename> [optional-argument]",
      Examples:         []string {
        "test.txt",
        "test.txt copy",
        "test.txt move",
      },
    },
  }
}

Define arguments with type

&commander.CommandWrapper{
  Handler: &MyCommand{},
  Arguments: []*commander.Argument{
    &commander.Argument{
      Name: "list",
      Type: "StringArray[]",
    },
  },
  Help: &commander.CommandDescriptor{
    Name: "my-command",
  },
}

In your command:

if opts.HasValidTypedOpt("list") == nil {
  myList := opts.TypedOpt("list").([]string)
  if len(myList) > 0 {
    mockPrintf("My list: %v\n", myList)
  }
}

Define own type

Yes you can ;)

// Define your struct (optional)
type MyCustomType struct {
	ID   uint64
	Name string
}

// register your own type with parsing/validation
commander.RegisterArgumentType("MyType", func(value string) (interface{}, error) {
  values := strings.Split(value, ":")

  if len(values) < 2 {
    return &MyCustomType{}, errors.New("Invalid format! MyType => 'ID:Name'")
  }

  id, err := strconv.ParseUint(values[0], 10, 64)
  if err != nil {
    return &MyCustomType{}, errors.New("Invalid format! MyType => 'ID:Name'")
  }

  return &MyCustomType{
      ID:   id,
      Name: values[1],
    },
    nil
})

// Define your command
&commander.CommandWrapper{
  Handler: &MyCommand{},
  Arguments: []*commander.Argument{
    &commander.Argument{
      Name:        "owner",
      Type:        "MyType",
      FailOnError: true,          // Optional boolean
    },
  },
  Help: &commander.CommandDescriptor{
    Name: "my-command",
  },
}

In your command:

if opts.HasValidTypedOpt("owner") == nil {
  owner := opts.TypedOpt("owner").(*MyCustomType)
  mockPrintf("OwnerID: %d, Name: %s\n", owner.ID, owner.Name)
}

Articles
to learn more about the golang concepts.

Resources
which are currently available to browse on.

mail [email protected] to add your project or resources here 🔥.

FAQ's
to know more about the topic.

mail [email protected] to add your project or resources here 🔥.

Queries
or most google FAQ's about GoLang.

mail [email protected] to add more queries here 🔍.

More Sites
to check out once you're finished browsing here.

0x3d
https://www.0x3d.site/
0x3d is designed for aggregating information.
NodeJS
https://nodejs.0x3d.site/
NodeJS Online Directory
Cross Platform
https://cross-platform.0x3d.site/
Cross Platform Online Directory
Open Source
https://open-source.0x3d.site/
Open Source Online Directory
Analytics
https://analytics.0x3d.site/
Analytics Online Directory
JavaScript
https://javascript.0x3d.site/
JavaScript Online Directory
GoLang
https://golang.0x3d.site/
GoLang Online Directory
Python
https://python.0x3d.site/
Python Online Directory
Swift
https://swift.0x3d.site/
Swift Online Directory
Rust
https://rust.0x3d.site/
Rust Online Directory
Scala
https://scala.0x3d.site/
Scala Online Directory
Ruby
https://ruby.0x3d.site/
Ruby Online Directory
Clojure
https://clojure.0x3d.site/
Clojure Online Directory
Elixir
https://elixir.0x3d.site/
Elixir Online Directory
Elm
https://elm.0x3d.site/
Elm Online Directory
Lua
https://lua.0x3d.site/
Lua Online Directory
C Programming
https://c-programming.0x3d.site/
C Programming Online Directory
C++ Programming
https://cpp-programming.0x3d.site/
C++ Programming Online Directory
R Programming
https://r-programming.0x3d.site/
R Programming Online Directory
Perl
https://perl.0x3d.site/
Perl Online Directory
Java
https://java.0x3d.site/
Java Online Directory
Kotlin
https://kotlin.0x3d.site/
Kotlin Online Directory
PHP
https://php.0x3d.site/
PHP Online Directory
React JS
https://react.0x3d.site/
React JS Online Directory
Angular
https://angular.0x3d.site/
Angular JS Online Directory