A Go library for building command line applications

Overview

gocmd

Release Build Status Coverage Report GoDoc

A Go library for building command line applications.

Features

  • Advanced command line arguments handling
    • Subcommand handling
    • Short and long command line arguments
    • Multiple arguments (repeated or delimited)
    • Support for environment variables
    • Well formatted usage printing
    • Auto usage and version printing
    • Unknown argument handling
  • Output tables in the terminal
  • Template support for config files
  • No external dependency

Installation

go get github.com/devfacet/gocmd

Usage

A basic app

See basic for full code.

func main() {
	flags := struct {
		Help      bool `short:"h" long:"help" description:"Display usage" global:"true"`
		Version   bool `short:"v" long:"version" description:"Display version"`
		VersionEx bool `long:"vv" description:"Display version (extended)"`
		Echo      struct {
			Settings bool `settings:"true" allow-unknown-arg:"true"`
		} `command:"echo" description:"Print arguments"`
		Math struct {
			Sqrt struct {
				Number float64 `short:"n" long:"number" required:"true" description:"Number"`
			} `command:"sqrt" description:"Calculate square root"`
			Pow struct {
				Base     float64 `short:"b" long:"base" required:"true" description:"Base"`
				Exponent float64 `short:"e" long:"exponent" required:"true" description:"Exponent"`
			} `command:"pow" description:"Calculate base exponential"`
		} `command:"math" description:"Math functions" nonempty:"true"`
	}{}

	// Echo command
	gocmd.HandleFlag("Echo", func(cmd *gocmd.Cmd, args []string) error {
		fmt.Printf("%s\n", strings.Join(cmd.FlagArgs("Echo")[1:], " "))
		return nil
	})

	// Math commands
	gocmd.HandleFlag("Math.Sqrt", func(cmd *gocmd.Cmd, args []string) error {
		fmt.Println(math.Sqrt(flags.Math.Sqrt.Number))
		return nil
	})
	gocmd.HandleFlag("Math.Pow", func(cmd *gocmd.Cmd, args []string) error {
		fmt.Println(math.Pow(flags.Math.Pow.Base, flags.Math.Pow.Exponent))
		return nil
	})

	// Init the app
	gocmd.New(gocmd.Options{
		Name:        "basic",
		Version:     "1.0.0",
		Description: "A basic app",
		Flags:       &flags,
		ConfigType:  gocmd.ConfigTypeAuto,
	})
}
cd examples/basic/
go build .
$ ./basic
Usage: basic [options...] COMMAND [options...]

A basic app

Options:
  -h, --help         	Display usage
  -v, --version      	Display version
      --vv           	Display version (extended)

Commands:
  echo               	Print arguments
  math               	Math functions
    sqrt             	Calculate square root
      -n, --number   	Number
    pow              	Calculate base exponential
      -b, --base     	Base
      -e, --exponent 	Exponent

Build

go build .

Test

./test.sh

Release

git add CHANGELOG.md # update CHANGELOG.md
./release.sh v1.0.0  # replace "v1.0.0" with new version

git ls-remote --tags # check the new tag

Contributing

  • Code contributions must be through pull requests
  • Run tests, linting and formatting before a pull request
  • Pull requests can not be merged without being reviewed
  • Use "Issues" for bug reports, feature requests and discussions
  • Do not refactor existing code without a discussion
  • Do not add a new third party dependency without a discussion
  • Use semantic versioning and git tags for versioning

License

Licensed under The MIT License (MIT)
For the full copyright and license information, please view the LICENSE.txt file.

You might also like...
MyApps is a universal command line tool for managing manually installed applications.
MyApps is a universal command line tool for managing manually installed applications.

MyApps MyApps is a universal command line tool for managing manually installed applications. Disclaimer I wrote this tool over two long nights while p

Go package to make lightweight ASCII line graph ╭┈╯ in command line apps with no other dependencies.
Go package to make lightweight ASCII line graph ╭┈╯ in command line apps with no other dependencies.

asciigraph Go package to make lightweight ASCII line graphs ╭┈╯. Installation go get github.com/guptarohit/asciigraph Usage Basic graph package main

git-xargs is a command-line tool (CLI) for making updates across multiple Github repositories with a single command.
git-xargs is a command-line tool (CLI) for making updates across multiple Github repositories with a single command.

Table of contents Introduction Reference Contributing Introduction Overview git-xargs is a command-line tool (CLI) for making updates across multiple

git-xargs is a command-line tool (CLI) for making updates across multiple GitHub repositories with a single command
git-xargs is a command-line tool (CLI) for making updates across multiple GitHub repositories with a single command

git-xargs is a command-line tool (CLI) for making updates across multiple GitHub repositories with a single command. You give git-xargs:

Package command provide simple API to create modern command-line interface

Package command Package command provide simple API to create modern command-line interface, mainly for lightweight usage, inspired by cobra Usage pack

A command line tool for simplified docker volume command built with go

dockervol A command line tool for simplified docker volume command built with go. Features: Remove anonymous volume (beta) Remove volume by matching n

Watcher - A simple command line app to watch files in a directory for changes and run a command when files change!

Watcher - Develop your programs easily Watcher watches all the files present in the directory it is run from of the directory that is specified while

A golang library for building interactive prompts with full support for windows and posix terminals.
A golang library for building interactive prompts with full support for windows and posix terminals.

Survey A library for building interactive prompts on terminals supporting ANSI escape sequences. package main import ( "fmt" "github.com/Alec

argv - Go library to split command line string as arguments array using the bash syntax.

Argv Argv is a library for Go to split command line string into arguments array. Documentation Documentation can be found at Godoc Example func TestAr

Comments
  • Error when running same flag in different sub-commands

    Error when running same flag in different sub-commands

    When running same flag short/long name in different sub-commands I get the following error:

    short argument n in Name field is already defined in Name field

    This is some code triggering the error.

    Create struct {
    	Python struct {
    		Name string `short:"n"`
    	} `command:"python"`
    	Golang struct {
    		Name string `short:"n"`
    	} `command:"golang"`
    } `command:"create"`
    

    Also when giving them different short flag (like m and n) the auto help puts then in the same context:

    create
        python         
        golang         
          -m, --mame   
          -n, --name   
    

    I would expect it to be possible to use the same flags within different sub-commands. Bug or by design?

    Edit: Added auto-help output.

    mystery 
    opened by sirmar 5
  • Flag value same as subcommand name result in error

    Flag value same as subcommand name result in error

    Here is another bug I found

    Minimal example:

    package main
    
    import (
    	"log"
    	"github.com/devfacet/gocmd"
    )
    
    func main() {
    	flags := struct {
    		Command struct {} `command:"command"`
    		Flag string `short:"f" long:"flag" required:"true"`
    	}{}
    
    	_, err := gocmd.New(gocmd.Options{
    		Flags:       &flags,
    		AnyError:    true,
    	})
    
    	if err != nil {
    		log.Fatal(err)
    	}
    }
    

    When running:

    # bug -f command
    argument -f needs a nonempty value
    
    # bug -f "command"
    argument -f needs a nonempty value
    
    # bug -f other
    
    investigating 
    opened by sirmar 4
Owner
Fatih Cetinkaya
Software Developer
Fatih Cetinkaya
A versatile library for building CLI applications in Go

mow.cli Package cli provides a framework to build command line applications in Go with most of the burden of arguments parsing and validation placed o

Jawher Moussa 830 Sep 26, 2022
CLI - A package for building command line app with go

Command line interface Screenshot Key features Lightweight and easy to use. Defines flag by tag, e.g. flag name(short or/and long), description, defau

王仕晋 668 Sep 18, 2022
A simple, fast, and fun package for building command line apps in Go

cli cli is a simple, fast, and fun package for building command line apps in Go. The goal is to enable developers to write fast and distributable comm

null 19k Sep 23, 2022
cli is a simple, fast, and fun package for building command line apps in Go.

cli cli is a simple, fast, and fun package for building command line apps in Go. The goal is to enable developers to write fast and distributable comm

凹语言 2 Jul 10, 2022
An open-source GitLab command line tool bringing GitLab's cool features to your command line

GLab is an open source GitLab CLI tool bringing GitLab to your terminal next to where you are already working with git and your code without switching

Clement Sam 2.1k Sep 22, 2022
A command line tool that builds and (re)starts your web application everytime you save a Go or template fileA command line tool that builds and (re)starts your web application everytime you save a Go or template file

# Fresh Fresh is a command line tool that builds and (re)starts your web application everytime you save a Go or template file. If the web framework yo

null 0 Nov 22, 2021
A command line tool to prompt for a value to be included in another command line.

readval is a command line tool which is designed for one specific purpose—to prompt for a value to be included in another command line. readval prints

Venky 0 Dec 22, 2021
Several Examples for building docker containers for your Go applications

go-docker Several Examples for building docker containers for your Go applicatio

Eric Calabretta 0 Dec 27, 2021
Interactive prompt for command-line applications

promptui Interactive prompt for command-line applications. We built Promptui because we wanted to make it easy and fun to explore cloud services with

Manifold 5.1k Sep 20, 2022
Soren L. Hansen 1.6k Sep 27, 2022