gcmd

package
v1.1.2 Latest Latest
Warning

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

Go to latest
Published: Mar 20, 2024 License: MIT Imports: 35 Imported by: 0

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'.

Example
package main

import (
	"fmt"

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

func main() {
	fmt.Println(gcmd.Scan("gf scan"))

}
Output:

gf scan

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'.

Example
package main

import (
	"fmt"

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

func main() {
	fmt.Println(gcmd.Scanf("gf %s", "scanf"))

}
Output:

gf scanf

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.
	CaseSensitive bool          // CaseSensitive parsing options, which means it parses input options in case-sensitive way.
	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.

Example
package main

import (
	"context"
	"fmt"

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

func main() {
	var (
		command = gcmd.Command{
			Name: "start",
		}
	)

	ctx := context.WithValue(gctx.New(), gcmd.CtxKeyCommand, &command)
	unAddCtx := context.WithValue(gctx.New(), gcmd.CtxKeyCommand, &gcmd.Command{})
	nonKeyCtx := context.WithValue(gctx.New(), "Testkey", &gcmd.Command{})

	fmt.Println(gcmd.CommandFromCtx(ctx).Name)
	fmt.Println(gcmd.CommandFromCtx(unAddCtx).Name)
	fmt.Println(gcmd.CommandFromCtx(nonKeyCtx) == nil)

}
Output:

start

true

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.

Example
package main

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

func main() {
	commandRoot := &gcmd.Command{
		Name: "gf",
	}
	commandRoot.AddCommand(&gcmd.Command{
		Name: "start",
	}, &gcmd.Command{})

	commandRoot.Print()

}
Output:

USAGE
    gf COMMAND [OPTION]

COMMAND
    start

func (*Command) AddObject

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

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

Example
var (
	command = gcmd.Command{
		Name: "start",
	}
)

command.AddObject(&TestCmdObject{})

command.Print()
Output:

USAGE
    start COMMAND [OPTION]

COMMAND
    root    root env command

func (*Command) Print

func (c *Command) Print()

Print prints help info to stdout for current command.

Example
package main

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

func main() {
	commandRoot := &gcmd.Command{
		Name: "gf",
	}
	commandRoot.AddCommand(&gcmd.Command{
		Name: "start",
	}, &gcmd.Command{})

	commandRoot.Print()

}
Output:

USAGE
    gf COMMAND [OPTION]

COMMAND
    start

func (*Command) PrintTo

func (c *Command) PrintTo(writer io.Writer)

PrintTo prints help info to custom io.Writer.

func (*Command) Run

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

Run calls custom function in os.Args 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 in os.Args that bound to this command with error output.

func (*Command) RunWithSpecificArgs

func (c *Command) RunWithSpecificArgs(ctx context.Context, args []string) (value interface{}, err error)

RunWithSpecificArgs calls custom function in specific args that bound to this command with value and error output.

func (*Command) RunWithValue

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

RunWithValue calls custom function in os.Args 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 in os.Args 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, option ...ParserOption) (*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)
	fmt.Println(p.GetOpt("none", "Def"))

}
Output:

gf.exe
gf.exe
true
true
false
Def

func ParseArgs

func ParseArgs(args []string, supportedOptions map[string]bool, option ...ParserOption) (*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.

Example
package main

import (
	"fmt"

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

func main() {
	p, _ := gcmd.ParseArgs([]string{
		"gf", "--force", "remove", "-fq", "-p=www", "path", "-n", "root",
	}, nil)

	fmt.Println(p.GetArgAll())
	fmt.Println(p.GetOptAll())

}
Output:

[gf path]
map[force:remove fq: n:root p:www]

func ParserFromCtx

func ParserFromCtx(ctx context.Context) *Parser

ParserFromCtx retrieves and returns Parser from context.

Example
package main

import (
	"context"
	"fmt"

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

func main() {
	parser, _ := gcmd.Parse(nil)

	ctx := context.WithValue(gctx.New(), gcmd.CtxKeyParser, parser)
	nilCtx := context.WithValue(gctx.New(), "NilCtxKeyParser", parser)

	fmt.Println(gcmd.ParserFromCtx(ctx).GetArgAll())
	fmt.Println(gcmd.ParserFromCtx(nilCtx) == nil)

}
Output:

[gf build main.go]
true

func (*Parser) GetArg

func (p *Parser) 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() {
	p, _ := gcmd.ParseArgs([]string{
		"gf", "--force", "remove", "-fq", "-p=www", "path", "-n", "root",
	}, nil)

	fmt.Println(p.GetArg(-1, "Def").String())
	fmt.Println(p.GetArg(-1) == nil)

}
Output:

Def
true

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.

type ParserOption

type ParserOption struct {
	CaseSensitive bool // Marks options parsing in case-sensitive way.
	Strict        bool // Whether stops parsing and returns error if invalid option passed.
}

ParserOption manages the parsing options.

Jump to

Keyboard shortcuts

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