gcmd

package
v2.0.0-rc3 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Feb 23, 2022 License: MIT Imports: 23 Imported by: 59

Documentation

Overview

Package gcmd provides console operations, like options/arguments reading and command running.

Index

Examples

Constants

View Source
const (
	CtxKeyParser    gctx.StrKey = `CtxKeyParser`
	CtxKeyCommand   gctx.StrKey = `CtxKeyCommand`
	CtxKeyArguments gctx.StrKey = `CtxKeyArguments`
)

Variables

This section is empty.

Functions

func BuildOptions

func BuildOptions(m map[string]string, prefix ...string) string

BuildOptions builds the options as string.

func GetArg

func GetArg(index int, def ...string) *gvar.Var

GetArg returns the argument at `index` as gvar.Var.

Example
package main

import (
	"fmt"

	"github.com/gogf/gf/v2/os/gcmd"
)

func main() {
	gcmd.Init("gf", "build", "main.go", "-o=gf.exe", "-y")
	fmt.Printf(
		`Arg[0]: "%v", Arg[1]: "%v", Arg[2]: "%v", Arg[3]: "%v"`,
		gcmd.GetArg(0), gcmd.GetArg(1), gcmd.GetArg(2), gcmd.GetArg(3),
	)

}
Output:

Arg[0]: "gf", Arg[1]: "build", Arg[2]: "main.go", Arg[3]: ""

func GetArgAll

func GetArgAll() []string

GetArgAll returns all parsed arguments.

Example
package main

import (
	"fmt"

	"github.com/gogf/gf/v2/os/gcmd"
)

func main() {
	gcmd.Init("gf", "build", "main.go", "-o=gf.exe", "-y")
	fmt.Printf(`%#v`, gcmd.GetArgAll())

}
Output:

[]string{"gf", "build", "main.go"}

func GetOpt

func GetOpt(name string, def ...string) *gvar.Var

GetOpt returns the option value named `name` as gvar.Var.

Example
package main

import (
	"fmt"

	"github.com/gogf/gf/v2/os/gcmd"
)

func main() {
	gcmd.Init("gf", "build", "main.go", "-o=gf.exe", "-y")
	fmt.Printf(
		`Opt["o"]: "%v", Opt["y"]: "%v", Opt["d"]: "%v"`,
		gcmd.GetOpt("o"), gcmd.GetOpt("y"), gcmd.GetOpt("d", "default value"),
	)

}
Output:

Opt["o"]: "gf.exe", Opt["y"]: "", Opt["d"]: "default value"

func GetOptAll

func GetOptAll() map[string]string

GetOptAll returns all parsed options.

Example
package main

import (
	"fmt"

	"github.com/gogf/gf/v2/os/gcmd"
)

func main() {
	gcmd.Init("gf", "build", "main.go", "-o=gf.exe", "-y")
	fmt.Printf(`%#v`, gcmd.GetOptAll())

	// May Output:
	// map[string]string{"o":"gf.exe", "y":""}
}
Output:

func GetOptWithEnv

func GetOptWithEnv(key string, def ...interface{}) *gvar.Var

GetOptWithEnv returns the command line argument of the specified `key`. If the argument does not exist, then it returns the environment variable with specified `key`. It returns the default value `def` if none of them exists.

Fetching Rules: 1. Command line arguments are in lowercase format, eg: gf.`package name`.<variable name>; 2. Environment arguments are in uppercase format, eg: GF_`package name`_<variable name>;

Example
package main

import (
	"fmt"

	"github.com/gogf/gf/v2/os/gcmd"
	"github.com/gogf/gf/v2/os/genv"
)

func main() {
	fmt.Printf("Opt[gf.test]:%s\n", gcmd.GetOptWithEnv("gf.test"))
	_ = genv.Set("GF_TEST", "YES")
	fmt.Printf("Opt[gf.test]:%s\n", gcmd.GetOptWithEnv("gf.test"))

}
Output:

Opt[gf.test]:
Opt[gf.test]:YES

func Init

func Init(args ...string)

Init does custom initialization.

Example
package main

import (
	"fmt"

	"github.com/gogf/gf/v2/os/gcmd"
)

func main() {
	gcmd.Init("gf", "build", "main.go", "-o=gf.exe", "-y")
	fmt.Printf(`%#v`, gcmd.GetArgAll())

}
Output:

[]string{"gf", "build", "main.go"}

func Scan

func Scan(info ...interface{}) string

Scan prints `info` to stdout, reads and returns user input, which stops by '\n'.

func Scanf

func Scanf(format string, info ...interface{}) string

Scanf prints `info` to stdout with `format`, reads and returns user input, which stops by '\n'.

Types

type Argument

type Argument struct {
	Name   string // Option name.
	Short  string // Option short.
	Brief  string // Brief info about this Option, which is used in help info.
	IsArg  bool   // IsArg marks this argument taking value from command line argument instead of option.
	Orphan bool   // Whether this Option having or having no value bound to it.
}

Argument is the command value that are used by certain command.

type Command

type Command struct {
	Name          string        // Command name(case-sensitive).
	Usage         string        // A brief line description about its usage, eg: gf build main.go [OPTION]
	Brief         string        // A brief info that describes what this command will do.
	Description   string        // A detailed description.
	Arguments     []Argument    // Argument array, configuring how this command act.
	Func          Function      // Custom function.
	FuncWithValue FuncWithValue // Custom function with output parameters that can interact with command caller.
	HelpFunc      Function      // Custom help function
	Examples      string        // Usage examples.
	Additional    string        // Additional info about this command, which will be appended to the end of help info.
	Strict        bool          // Strict parsing options, which means it returns error if invalid option given.
	Config        string        // Config node name, which also retrieves the values from config component along with command line.
	// contains filtered or unexported fields
}

Command holds the info about an argument that can handle custom logic.

func CommandFromCtx

func CommandFromCtx(ctx context.Context) *Command

CommandFromCtx retrieves and returns Command from context.

func NewFromObject

func NewFromObject(object interface{}) (rootCmd *Command, err error)

NewFromObject creates and returns a root command object using given object.

func (*Command) AddCommand

func (c *Command) AddCommand(commands ...*Command) error

AddCommand adds one or more sub-commands to current command.

func (*Command) AddObject

func (c *Command) AddObject(objects ...interface{}) error

AddObject adds one or more sub-commands to current command using struct object.

func (*Command) Print

func (c *Command) Print()

Print prints help info to stdout for current command.

func (*Command) Run

func (c *Command) Run(ctx context.Context)

Run calls custom function that bound to this command. It exits this process with exit code 1 if any error occurs.

func (*Command) RunWithError

func (c *Command) RunWithError(ctx context.Context) (err error)

RunWithError calls custom function that bound to this command with error output.

func (*Command) RunWithValue

func (c *Command) RunWithValue(ctx context.Context) (value interface{})

RunWithValue calls custom function that bound to this command with value output. It exits this process with exit code 1 if any error occurs.

func (*Command) RunWithValueError

func (c *Command) RunWithValueError(ctx context.Context) (value interface{}, err error)

RunWithValueError calls custom function that bound to this command with value and error output.

type FuncWithValue

type FuncWithValue func(ctx context.Context, parser *Parser) (out interface{}, err error)

FuncWithValue is similar like Func but with output parameters that can interact with command caller.

type Function

type Function func(ctx context.Context, parser *Parser) (err error)

Function is a custom command callback function that is bound to a certain argument.

type Parser

type Parser struct {
	// contains filtered or unexported fields
}

Parser for arguments.

func Parse

func Parse(supportedOptions map[string]bool, strict ...bool) (*Parser, error)

Parse creates and returns a new Parser with os.Args and supported options.

Note that the parameter `supportedOptions` is as [option name: need argument], which means the value item of `supportedOptions` indicates whether corresponding option name needs argument or not.

The optional parameter `strict` specifies whether stops parsing and returns error if invalid option passed.

Example
package main

import (
	"fmt"
	"os"

	"github.com/gogf/gf/v2/frame/g"
	"github.com/gogf/gf/v2/os/gcmd"
)

func main() {
	os.Args = []string{"gf", "build", "main.go", "-o=gf.exe", "-y"}
	p, err := gcmd.Parse(g.MapStrBool{
		"o,output": true,
		"y,yes":    false,
	})
	if err != nil {
		panic(err)
	}
	fmt.Println(p.GetOpt("o"))
	fmt.Println(p.GetOpt("output"))
	fmt.Println(p.GetOpt("y") != nil)
	fmt.Println(p.GetOpt("yes") != nil)
	fmt.Println(p.GetOpt("none") != nil)

}
Output:

gf.exe
gf.exe
true
true
false

func ParseArgs

func ParseArgs(args []string, supportedOptions map[string]bool, strict ...bool) (*Parser, error)

ParseArgs creates and returns a new Parser with given arguments and supported options.

Note that the parameter `supportedOptions` is as [option name: need argument], which means the value item of `supportedOptions` indicates whether corresponding option name needs argument or not.

The optional parameter `strict` specifies whether stops parsing and returns error if invalid option passed.

func ParserFromCtx

func ParserFromCtx(ctx context.Context) *Parser

ParserFromCtx retrieves and returns Parser from context.

func (*Parser) GetArg

func (p *Parser) GetArg(index int, def ...string) *gvar.Var

GetArg returns the argument at `index` as gvar.Var.

func (*Parser) GetArgAll

func (p *Parser) GetArgAll() []string

GetArgAll returns all parsed arguments.

func (*Parser) GetOpt

func (p *Parser) GetOpt(name string, def ...interface{}) *gvar.Var

GetOpt returns the option value named `name` as gvar.Var.

func (*Parser) GetOptAll

func (p *Parser) GetOptAll() map[string]string

GetOptAll returns all parsed options.

func (Parser) MarshalJSON

func (p Parser) MarshalJSON() ([]byte, error)

MarshalJSON implements the interface MarshalJSON for json.Marshal.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL