All Projects → posener → Cmd

posener / Cmd

Licence: apache-2.0
The standard library flag package with its missing features

Programming Languages

go
31211 projects - #10 most used programming language
golang
3204 projects

Projects that are alternatives of or similar to Cmd

Homebridge Cmd4
CMD4 Plugin for Homebridge - Supports ~All Accessory Types & now all Characteristics too
Stars: ✭ 92 (+187.5%)
Mutual labels:  cmd, command
Cmd Command Cheat Sheet
CMD - Command Cheat Sheat ✅
Stars: ✭ 50 (+56.25%)
Mutual labels:  cmd, command
Slacker
Slack Bot Framework
Stars: ✭ 495 (+1446.88%)
Mutual labels:  command
Executor
Watch for file changes and then execute command. Very nice for test driven development.
Stars: ✭ 14 (-56.25%)
Mutual labels:  command
Aruba
Test command-line applications with Cucumber-Ruby, RSpec or Minitest. The most up to date documentation can be found on Cucumber.Pro (https://app.cucumber.pro/projects/aruba)
Stars: ✭ 900 (+2712.5%)
Mutual labels:  command
Laravel Initializer
A convenient way to initialize your application
Stars: ✭ 597 (+1765.63%)
Mutual labels:  command
Python
Python cheatsheet
Stars: ✭ 25 (-21.87%)
Mutual labels:  command
Cmd
Non-blocking external commands in Go with and streaming output and concurrent-safe access
Stars: ✭ 477 (+1390.63%)
Mutual labels:  command
Libcmdf
Single-header library for writing CLI applications in C/C++
Stars: ✭ 30 (-6.25%)
Mutual labels:  cmd
Arg
Simple argument parsing
Stars: ✭ 897 (+2703.13%)
Mutual labels:  command
Vercel
Develop. Preview. Ship.
Stars: ✭ 8,015 (+24946.88%)
Mutual labels:  command
Initior
A command line application that let's you initialize your new projects the right way, replaces npm and yarn's init 🎆
Stars: ✭ 17 (-46.87%)
Mutual labels:  cmd
Readline Sync
Synchronous Readline for interactively running to have a conversation with the user via a console(TTY).
Stars: ✭ 601 (+1778.13%)
Mutual labels:  command
Serve
Static file serving and directory listing
Stars: ✭ 7,444 (+23162.5%)
Mutual labels:  command
Phper Linux Gitbook
💡PHPer 必知必会的 Linux 命令
Stars: ✭ 540 (+1587.5%)
Mutual labels:  command
Vsphere Connect
A modern vSphere Client
Stars: ✭ 14 (-56.25%)
Mutual labels:  command
Powershell
🧛🏻‍♂️ Dark theme for PowerShell and cmd.exe
Stars: ✭ 477 (+1390.63%)
Mutual labels:  cmd
Node Cross Spawn
A cross platform solution to node's spawn and spawnSync
Stars: ✭ 831 (+2496.88%)
Mutual labels:  cmd
Ps Webapi
(Migrated from CodePlex) Let PowerShell Script serve or command-line process as WebAPI. PSWebApi is a simple library for building ASP.NET Web APIs (RESTful Services) by PowerShell Scripts or batch/executable files out of the box.
Stars: ✭ 24 (-25%)
Mutual labels:  cmd
Ssh Agent Helper
Use SSH keys from CMD, PowerShell, etc. on Windows
Stars: ✭ 31 (-3.12%)
Mutual labels:  cmd

cmd

codecov GoDoc

Package cmd is a minimalistic library that enables easy sub commands with the standard flag library.

This library extends the standard library flag package to support sub commands and more features in a minimalistic and idiomatic API.

Features:

  • [x] Sub commands.

  • [x] Automatic bash completion.

  • [x] Flag values definition and check.

  • [x] Explicit positional arguments definition.

  • [x] Automatic usage text.

Usage

Define a root command object using the New function. This object exposes the standard library's flag.FlagSet API, which enables adding flags in the standard way. Additionally, this object exposes the SubCommand method, which returns another command object. This objects also exposing the same API, enabling definition of flags and nested sub commands. The root object then have to be called with the Parse method, similarly to the flag.Parse call.

Principles

  • Minimalistic and flag-like.

  • Any flag that is defined in the base command will be reflected in all of its sub commands.

  • When user types the command, it starts from the command and sub commands, only then types the flags and then the positional arguments:

[command] [sub commands...] [flags...] [positional args...]
  • When a command defines positional arguments, all its sub commands has these positional arguments and thus can't define their own positional arguments.

  • When flag configuration is wrong, the program will panic.

Examples

Definition and usage of sub commands and sub commands flags.

package main

import (
	"fmt"

	"github.com/posener/cmd"
)

var (
	// Define root command with a single string flag. This object the familiar standard library
	// `*flag.FlagSet` API, so it can be used similarly.
	root  = cmd.New()
	flag0 = root.String("flag0", "", "root string flag")

	// Define a sub command from the root command with a single string flag. The sub command object
	// also have the same API as the root command object.
	sub1  = root.SubCommand("sub1", "first sub command")
	flag1 = sub1.String("flag1", "", "sub1 string flag")

	// Define a second sub command from the root command with an int flag.
	sub2  = root.SubCommand("sub2", "second sub command")
	flag2 = sub1.Int("flag2", 0, "sub2 int flag")
)

// Definition and usage of sub commands and sub commands flags.
func main() {
	// Parse command line arguments.
	root.ParseArgs("cmd", "sub1", "-flag1", "value")

	// Check which sub command was choses by the user.
	switch {
	case sub1.Parsed():
		fmt.Printf("Called sub1 with flag: %s", *flag1)
	case sub2.Parsed():
		fmt.Printf("Called sub2 with flag: %d", *flag2)
	}
}

Values

An example that shows how to use advanced configuration of flags and positional arguments using the predict package.

package main

import (
	"fmt"
	"github.com/posener/cmd"
	"github.com/posener/complete/v2/predict"
)

func main() {
	// Should be defined in global `var`.
	var (
		root = cmd.New()
		// Define a flag with valid values 'foo' and 'bar', and enforce the values by `OptCheck()`.
		// The defined values will be used for bash completion, and since the OptCheck was set, the
		// flag value will be checked during the parse call.
		flag1 = root.String("flag1", "", "first flag", predict.OptValues("foo", "bar"), predict.OptCheck())
		// Define a flag to accept a valid Go file path. Choose to enforce the valid path using the
		// `OptCheck` function. The file name will also be completed in the bash completion
		// processes.
		file = root.String("file", "", "file path", predict.OptPredictor(predict.Files("*.go")), predict.OptCheck())
		// Positional arguments should be explicitly defined. Define positional arguments with valid
		// values of 'baz' and 'buzz', and choose not to enforce these values by not calling
		// `OptCheck`. These values will also be completed in the bash completion process.
		args = root.Args("[args...]", "positional arguments", predict.OptValues("baz", "buzz"))
	)

	// Parse fake command line arguments.
	root.ParseArgs("cmd", "-flag1", "foo", "-file", "cmd.go", "buz", "bazz")

	// Test:

	fmt.Println(*flag1, *file, *args)
}

Output:

foo cmd.go [buz bazz]

Args

In the cmd package, positional arguments should be explicitly defined. They are defined using the Args or ArgsVar methods.

package main

import (
	"fmt"
	"github.com/posener/cmd"
)

func main() {
	// Should be defined in global `var`.
	var (
		root = cmd.New()
		// Positional arguments should be defined as any other flag.
		args = root.Args("[args...]", "positional arguments for command line")
	)

	// Parse fake command line arguments.
	root.ParseArgs("cmd", "v1", "v2", "v3")

	// Test:

	fmt.Println(*args)
}

Output:

[v1 v2 v3]

ArgsFn

An example of how to parse positional arguments using a custom function. It enables the advantage of using named variables such as src and dst as opposed to args[0] and args[1].

package main

import (
	"fmt"
	"github.com/posener/cmd"
)

func main() {
	// Should be defined in global `var`.
	var (
		root = cmd.New()
		// Define variables that will hold the command line positional arguments.
		src, dst string
	)

	// Define an `ArgsFn` that converts a list of positional arguments to the named variables. It
	// should return an error when the arguments are invalid.
	argsFn := cmd.ArgsFn(func(args []string) error {
		if len(args) != 2 {
			return fmt.Errorf("expected src and dst, got %d arguments", len(args))
		}
		src, dst = args[0], args[1]
		return nil
	})

	// Should be in `init()`.
	// Register the function in the root command using the `ArgsVar` method.
	root.ArgsVar(argsFn, "[src] [dst]", "positional arguments for command line")

	// Should be in `main()`.
	root.ParseArgs("cmd", "from.txt", "to.txt")

	// Test:

	fmt.Println(src, dst)
}

Output:

from.txt to.txt

ArgsInt

An example of defining int positional arguments.

package main

import (
	"fmt"
	"github.com/posener/cmd"
)

func main() {
	// Should be defined in global `var`.
	var (
		root = cmd.New()
		// Define a variable that will hold the positional arguments values. Use the `ArgsInt` type
		// to parse them as int.
		args cmd.ArgsInt
	)

	// Should be in `init()`.
	// Register the positional argument variable in the root command using the `ArgsVar` method.
	root.ArgsVar(&args, "[int...]", "numbers to sum")

	// Should be in `main()`.
	// Parse fake command line arguments.
	root.ParseArgs("cmd", "10", "20", "30")

	// Test:

	sum := 0
	for _, n := range args {
		sum += n
	}
	fmt.Println(sum)
}

Output:

60

ArgsN

An example of defining an exact number of positional arguments.

package main

import (
	"fmt"
	"github.com/posener/cmd"
)

func main() {
	// Should be defined in global `var`.
	var (
		root = cmd.New()
		// Define a variable that will hold positional arguments. Create the `ArgsStr` object with
		// cap=2 to ensure that the number of arguments is exactly 2.
		args = make(cmd.ArgsStr, 2)
	)

	// Should be in `init()`.
	// Register the positional argument variable in the root command using the `ArgsVar` method
	// (similar to the Var methods of the standard library).
	root.ArgsVar(&args, "[src] [dst]", "positional arguments for command line")

	// Should be in `main()`.
	// Parse fake command line arguments.
	root.ParseArgs("cmd", "from.txt", "to.txt")

	// Test:

	fmt.Println(args)
}

Output:

[from.txt to.txt]

Readme created from Go doc with goreadme

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].