arg

package module
v1.2.1 Latest Latest
Warning

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

Go to latest
Published: Jan 31, 2021 License: MIT Imports: 4 Imported by: 0

README

Arg

A command-line arguments parser

Installation

Use the alias "arg". To use Arg in your Go code:

import "github.com/AkvicorEdwards/arg"

To install Arg in your $GOPATH:

go get "github.com/AkvicorEdwards/arg"

Usage

Template Code

package main

import (
	"errors"
	"fmt"
	"github.com/AkvicorEdwards/arg"
)

var Err1 = errors.New("err1")
var Err2 = errors.New("err2")

func main() {
	// Set Root Command
	arg.RootCommand.Name = "Arg"
	arg.RootCommand.Size = -1
	arg.RootCommand.Describe = `Arg is a project for go,
to parse arguments and execute command
This project is free`
	arg.RootCommand.DescribeBrief = "Arg is a arguments parser"
	arg.RootCommand.Usage = "[arguments...]"
	arg.RootCommand.Executor = func(str []string) error {
		fmt.Println("RootCommand.Executor is run", str)
		return nil
	}
	arg.RootCommand.ErrorHandler = func(err error) error {
		fmt.Println("RootCommand.Handler Error:", err)
		return nil
	}

	// Add a Command
	vBuildType := ""
	vBuildDel := false
	err := arg.AddCommand([]string{"build"}, 1, 2, "build to fi",
		"build a file to fi", "", "[ori filename] [target filename]",
		func(str []string) error {
			fmt.Println("build", vBuildType, str[1:])
			if vBuildDel {
				fmt.Println("build delete file", str[1:])
			}
			return nil
		}, func(err error) error {
			fmt.Println("Handled build err:", err)
			return err
		})

	// Add a Option
	err = arg.AddOption([]string{"build", "-type"}, 1, 1, 10,
		"This is a type for test", "test type", "", "[type]",
		func(str []string) error {
			fmt.Println("build type", str[1])
			vBuildType = str[1]
			if str[1] == "err1" {
				return Err1
			}
			if str[1] == "err2" {
				return Err2
			}
			return nil
		}, func(err error) error {
			fmt.Println("Handle build.type err", err)
			if err == Err1 {
				return nil
			}
			if err == Err2 {
				return err
			}
			return nil
		})
	if err != nil {
		fmt.Println("1:", err)
	}

	// Add a Option
	err = arg.AddOption([]string{"build", "-del"}, 1, 0, 10,
		"delete origin file after build", "del origin file", "User design help", "",
		func(str []string) error {
			vBuildDel = true
			return nil
		}, nil)
	if err != nil {
		fmt.Println("2:", err)
	}

	arg.RootCommand.GenerateHelp()
	arg.AddHelpCommandArg("help")
	err = arg.Parse()
	if err != nil {
		fmt.Println("Parse Error:", err)
	}
	fmt.Println("Finished")
}

Test

go build
RootCommand
$ ./aflag Akvicor
RootCommand.Executor is run [./aflag Akvicor]
Finished
build
$ ./aflag build            
Handled build err: wrong number of arg
Parse Error: wrong number of arg
Finished
build with args
$ ./aflag build file1 file2               
build  [file1 file2]
Finished
build with -type
$ ./aflag build file1 file2 -type tgz     
build type tgz
build tgz [file1 file2]
Finished
build with -type and -del
$ ./aflag build file1 file2 -type tgz -del
build type tgz
build tgz [file1 file2]
build delete file [file1 file2]
Finished
build with err1
$ ./aflag build -type err1 file1 file2
build type err1
Handle build.type err err1
build fixed [file1 file2]
Finished
build with err2
$ ./aflag build -type err2 file1 file2
build type err2
Handle build.type err err2
Parse Error: err2
Finished
help
$ ./aflag help

Arg

    Arg is a project for go,
to parse arguments and execute command
This project is free

Usage:
        Arg [arguments...]        Arg <command> [arguments]

The commands are:

        build build a file to fi

Use "Arg help <command>" for more information about a command.

Parse Error: help
Finished

OptionCombination

if an arguments is not

  • Command
  • Option
  • "Help"
  1. Each letter of this parameter will be prefixed and then checked whether it is a parameter.
  2. Option.Size must be equal to 0
  3. if all the newly formed parameters are legal, execute them

EnableOptionCombination() equal OptionCombination='-'

if OptionCombination = ' ', set prefix = ''

Example:

OptionCombination=' ' arguments = "abcd" = a b c d

OptionCombination='-' arguments = "-abcd" = -a -b -c -d

API

Package

AddCommand(arg []string, order, size int, describe, describeBrief, help, 
	usage string, executor FuncExecutor, errExecutor FuncErrorHandler)
AddOption(arg []string, order, size, priority int, describe, describeBrief, help,
	usage string, executor FuncExecutor, errExecutor FuncErrorHandler) 
Add(isCmd bool, arg []string, order, size, priority int, describe, 
	describeBrief, help, usage string, executor FuncExecutor, 
	errExecutor FuncErrorHandler) 
Parse()
AddHelpCommandArg("help")

Command

PrintHelp()
GenerateHelp()

Documentation

Overview

Example
var err error
var Err1 = errors.New("error 1") // handled
var Err2 = errors.New("error 2") // unhandled
os.Args = []string{"Arg", "Akvicer", "-type", "err2"}

AddHelpCommandArg("help")

// Set Root Command
RootCommand.Name = "Arg"
RootCommand.Size = -1
RootCommand.Describe = `Arg is a project for go,
to parse arguments and execute command
This project is free`
RootCommand.DescribeBrief = "Arg is a arguments parser"
RootCommand.Usage = "[arguments...]"
RootCommand.Executor = func(str []string) error {
	fmt.Println("RootCommand.Executor is run", str)
	return nil
}
RootCommand.ErrorHandler = func(err error) error {
	fmt.Println("Handle Error:", err)
	return nil
}

err = AddOption([]string{"-type"}, 1, 1, 10, "This is a type for test",
	"test type", "", "", func(str []string) error {
		fmt.Println("Enter type", str[1])
		if str[1] == "err1" {
			return Err1
		}
		if str[1] == "err2" {
			return Err2
		}
		return nil
	}, func(err error) error {
		fmt.Println("Handle err", err)
		if err == Err1 {
			return nil
		}
		if err == Err2 {
			return err
		}
		return nil
	})
if err != nil {
	fmt.Println("1:", err)
}

RootCommand.GenerateHelp()

err = Parse()
if err != nil {
	log.Println("2:", err)
}

fmt.Println("Finished")
Output:

Enter type err2
Handle err error 2
Finished

Index

Examples

Constants

This section is empty.

Variables

View Source
var ErrHelp = errors.New("help")
View Source
var ErrNeedMoreArguments = errors.New("wrong number of arg")
View Source
var ErrWrongArgPath = errors.New("wrong arg path")
View Source
var HTplCommandList = `
The commands are:

%s
Use "%s %s <command>" for more information about a command.
`

HTplCommandList ======================================================

The commands are:

build      build a programme
encrypt    encrypt a file

Use "%s help <command>" for more information about a command.

View Source
var HTplLineCommand = `        %%-%ds  %%s
`

HTplLineCommand ======================================================

%%-%ds  %%s
%-8s    %s
build   build to tgz

name describeBrief

View Source
var HTplLineOption = `        %%-%ds  %%s
        %%%ds    %%s
`

HTplLineOption ======================================================

%%-%ds  %%s
	%%s

-------------------

%-8s    %s
	%s

-------------------

-o      [filename]
	Specify out file

--------------------

name    usage
    describeBrief
View Source
var HTplOptionList = `
The options are:

%s
Use "%s %s <option>" for more information about a option.
`

HTplOptionList ======================================================

The options are:

-o [filename]
        Specify out file
-e [password]
        Encrypt File

Use "%s help <option>" for more information about a command.

View Source
var HTplOptionUsage = `
Usage: %s

%s
`

HTplOptionUsage ======================================================

Usage: Arg -build [-o file.tgz] #Usage: father name usage

build file to file.tgz #describe

View Source
var HelpCommandArgs = make(map[string]bool)

The specified "help" parameters

View Source
var OptionCombination int32 = 0
View Source
var RootCommand = NewCommand(os.Args[0], "")

Default Root Command, init by os.Args[0]

View Source
var TplCommandUsageCommand = "        %s <command> [arguments]\n"
View Source
var TplCommandUsageOption = "        %s <option>  [arguments]\n"
View Source
var TplCommandUsageSelf = "        %s %s"
View Source
var TplDescribeDown = "\n\n    %s"
View Source
var TplDescribeUp = "%s"

TplDescribe =====================================================

Arg

Arg is a arguments parser

var TplDescribe = "%s\n\n %s"

View Source
var TplHelp = `
%s

%s%s%s
`

TplHelp =====================================================

Arg

Arg is a flag parser

Usage:

arg [filename]
arg <command> [arguments]
arg <option>  [arguments]

The commands are

build    build a programme
encrypt  encrypt a file

Usage "arg help <command>" for more information about a command

The options are

-o  [filename]
	  Specify out file
-e  [password]
	  The password for file

Usage "arg help <option>" for more information about a option

===========================================================================

TplDescribe Begin ---

TplDescribe End ---

TplUsage Begin ---

# TplCommandUsageSelf Begin ---
# TplCommandUsageSelf End ---
# TplCommandUsageCommand Begin ---
# TplCommandUsageCommand End ---
# TplCommandUsageOption Begin ---
# TplCommandUsageOption End ---

TplUsage End ---

HTplCommandList Begin ---

# HTplLineCommand Begin ---
# HTplLineCommand End ---
# HTplLineCommand Begin ---
# HTplLineCommand End ---

HTplCommandList End ---

HTplOptionList Begin ---

# HTplLineOption Begin ---
# HTplLineOption End ---
# HTplLineOption Begin ---
# HTplLineOption End ---

HTplOptionList End ---

View Source
var TplNeedMoreArguments = "The %s [%s] requires %d arguments to execute\n"
View Source
var TplUsage = `Usage:

%s`

TplUsage =====================================================

Usage:

arg <command> [arguments]
View Source
var Version = "Arg 1.0.0"

Functions

func Add

func Add(isCmd bool, arg []string, order, size, priority int, describe, describeBrief, help, usage string,
	executor FuncExecutor, errExecutor FuncErrorHandler) error

Add

add a Command or Option to RootCommand

You can use this function through AddCommand and AddOption

Example
// Add command
_ = Add(true, []string{"phone"}, 1, -1, 0 /* invalid parameter */, "specify phone number",
	"specify user phone number", "", "[phone number]", func(str []string) error {
		for k, v := range str {
			if len(v) != 11 {
				return errors.New(fmt.Sprintf("check phone number on [%d]: [%s]", k, v))
			}
		}
		return nil
	}, func(err error) error {
		log.Println("Handled Option Err:", err)
		return err
	})
// Add option
_ = Add(false, []string{"-phone"}, 1, -1, 100, "specify phone number",
	"specify user phone number", "", "[phone number]", func(str []string) error {
		for k, v := range str {
			if len(v) != 11 {
				return errors.New(fmt.Sprintf("check phone number on [%d]: [%s]", k, v))
			}
		}
		return nil
	}, func(err error) error {
		log.Println("Handled Option Err:", err)
		return err
	})
Output:

func AddCommand

func AddCommand(arg []string, order, size int, describe, describeBrief, help, usage string,
	executor FuncExecutor, errExecutor FuncErrorHandler) error

AddCommand

add a command to RootCommand

arg is the path for command, like "go mod download" is []string{"mod", "download"}

size  is the number of arguments
order  little first
Example
err := AddCommand([]string{"version"}, 1, 1, "check version", "check programme version",
	"", "[version]", func(str []string) error {
		if Version == str[1] {
			return nil
		}
		return errors.New("check version failure")
	}, func(err error) error {
		log.Println("Handled Command Err:", err)
		return nil
	})
if err != nil {
	panic(err)
}
Output:

func AddHelpCommandArg

func AddHelpCommandArg(h string)
Example
os.Args = []string{"fi", "help"}
queue = make(workQueue, 0)
RootCommand = NewCommand("fi", "")
commandArgs = []string{"fi"}
command = RootCommand
RootCommand.Name = "fi"
RootCommand.Describe = "this is describe"

RootCommand.Executor = func(str []string) error {
	fmt.Println("Root Command", str)
	return nil
}

err := AddCommand([]string{"version"}, 1, 1, "check version", "check programme version",
	"", "[version]", func(str []string) error {
		fmt.Println("version", str)
		return nil
	}, nil)
if err != nil {
	panic(err)
}
err = AddOption([]string{"-phone"}, 1, -1, 100, "specify phone number",
	"specify user phone number", "", "[phone number]", func(str []string) error {
		fmt.Println("Phone number:", str)
		return nil
	}, nil)
if err != nil {
	panic(err)
}
err = AddCommand([]string{"version", "v1"}, 1, 0, "display version 1", "dis v1", "",
	"u1", func(str []string) error {
		fmt.Println("version 1")
		return nil
	}, nil)
err = AddCommand([]string{"version", "v2"}, 1, 0, "display version 2", "dis v2", "",
	"", func(str []string) error {
		fmt.Println("version 2")
		return nil
	}, nil)
AddHelpCommandArg("help")
RootCommand.GenerateHelp()

err = Parse()
if err != nil {
	if err != ErrHelp {
		fmt.Println(err)
	}
}

fmt.Println("======================================")

os.Args = []string{"fi", "help", "version"}
err = Parse()
if err != nil {
	if err != ErrHelp {
		fmt.Println(err)
	}
}

fmt.Println("======================================")

os.Args = []string{"fi", "version", "help", "v1"}
err = Parse()
if err != nil {
	if err != ErrHelp {
		fmt.Println(err)
	}
}

//fi
//
//    this is describe
//
//Usage:
//
//        fi <command> [arguments]
//        fi <option>  [arguments]
//
//The commands are:
//
//        version  check programme version
//
//Use "fi help <command>" for more information about a command.
//
//The options are:
//
//        -phone  [phone number]
//                  specify user phone number
//
//Use "fi help <option>" for more information about a option.
//
//======================================
//
//fi version
//
//    check version
//
//Usage:
//
//        fi version [version]        fi version <command> [arguments]
//
//The commands are:
//
//        v1  dis v1
//        v2  dis v2
//
//Use "fi version help <command>" for more information about a command.
//
//======================================
//
//fi version v1
//
//    display version 1
//
//Usage:
//
//        fi version v1 u1
Output:

func AddOption

func AddOption(arg []string, order, size, priority int, describe, describeBrief, help, usage string,
	executor FuncExecutor, errExecutor FuncErrorHandler) error

AddOption

add a option to RootCommand

arg  is the path for option, like "go mod -version" is []string{"mod", "-version"}
size  is the number of arguments
priority  is the execution priority
order  little first
Example
err := AddCommand([]string{"-phone"}, 1, -1, "specify phone number",
	"specify user phone number", "", "[phone number]", func(str []string) error {
		for k, v := range str {
			if len(v) != 11 {
				return errors.New(fmt.Sprintf("check phone number on [%d]: [%s]", k, v))
			}
		}
		return nil
	}, func(err error) error {
		log.Println("Handled Option Err:", err)
		return err
	})
if err != nil {
	panic(err)
}
Output:

func EnableOptionCombination added in v1.1.0

func EnableOptionCombination()
Example
// Example '-'
os.Args = []string{"fi", "-pdwa", "Akvicor"}
queue = make(workQueue, 0)
RootCommand = NewCommand("fi", "")
commandArgs = []string{"fi"}
command = RootCommand
RootCommand.Name = "fi"
RootCommand.Size = -1
RootCommand.Executor = func(str []string) error {
	fmt.Println("Root Command", str)
	return nil
}
_ = Add(false, []string{"-p"}, 1, 0, 100, "",
	"", "", "", func(str []string) error {
		fmt.Println("Enter -p:", str[0])
		return nil
	}, nil)
_ = Add(false, []string{"-d"}, 2, 0, 100, "",
	"", "", "", func(str []string) error {
		fmt.Println("Enter -d:", str[0])
		return nil
	}, nil)
_ = Add(false, []string{"-w"}, 3, 0, 100, "",
	"", "", "", func(str []string) error {
		fmt.Println("Enter -w:", str[0])
		return nil
	}, nil)
_ = Add(false, []string{"-a"}, 4, 0, 100, "",
	"", "", "", func(str []string) error {
		fmt.Println("Enter -a:", str[0])
		return nil
	}, nil)
EnableOptionCombination()
err := Parse()
if err != nil {
	fmt.Println(err)
}

// Example ' '
queue = make(workQueue, 0)
commandArgs = []string{"fi"}
os.Args = []string{"fi", "pdwa", "Akvicor"}
_ = Add(false, []string{"p"}, 1, 0, 100, "",
	"", "", "", func(str []string) error {
		fmt.Println("Enter p:", str[0])
		return nil
	}, nil)
_ = Add(false, []string{"d"}, 1, 0, 100, "",
	"", "", "", func(str []string) error {
		fmt.Println("Enter d:", str[0])
		return nil
	}, nil)
_ = Add(false, []string{"w"}, 1, 0, 100, "",
	"", "", "", func(str []string) error {
		fmt.Println("Enter w:", str[0])
		return nil
	}, nil)
_ = Add(false, []string{"a"}, 1, 0, 100, "",
	"", "", "", func(str []string) error {
		fmt.Println("Enter a:", str[0])
		return nil
	}, nil)
OptionCombination = ' '
err = Parse()
if err != nil {
	fmt.Println(err)
}
Output:

Enter -p: -p
Enter -d: -d
Enter -w: -w
Enter -a: -a
Root Command [fi Akvicor]
Enter p: p
Enter d: d
Enter w: w
Enter a: a
Root Command [fi Akvicor]

func NewCommands

func NewCommands() map[string]*Command

Create a new Command map

func NewOptions

func NewOptions() map[string]*Option

Create a new Option map

func Parse

func Parse() (err error)

Parse

Parse os.Args use RootCommand

Example
var err error
var Err1 = errors.New("error 1") // handled
var Err2 = errors.New("error 2") // unhandled
os.Args = []string{"Arg", "build", "-type", "tgz", "fileA", "fileB"}

AddHelpCommandArg("help")

// Set Root Command
RootCommand.Name = "Arg"
RootCommand.Size = -1
RootCommand.Describe = `Arg is a project for go,
to parse arguments and execute command
This project is free`
RootCommand.DescribeBrief = "Arg is a arguments parser"
RootCommand.Usage = "[arguments...]"
RootCommand.Executor = func(str []string) error {
	fmt.Println("RootCommand.Executor is run", str)
	return nil
}
RootCommand.ErrorHandler = func(err error) error {
	fmt.Println("Handle Error:", err)
	return nil
}

err = AddCommand([]string{"build"}, 1, 2, "build to fi", "build a file to fi", "",
	"[ori filename] [target filename]", func(str []string) error {
		fmt.Println("build", str[1:])
		return nil
	}, func(err error) error {
		fmt.Println("Handled build err:", err)
		return err
	})

err = AddOption([]string{"build", "-type"}, 1, 1, 10, "This is a type for test",
	"test type", "", "", func(str []string) error {
		fmt.Println("build type", str[1])
		if str[1] == "err1" {
			return Err1
		}
		if str[1] == "err2" {
			return Err2
		}
		return nil
	}, func(err error) error {
		fmt.Println("Handle build.type err", err)
		if err == Err1 {
			return nil
		}
		if err == Err2 {
			return err
		}
		return nil
	})
if err != nil {
	fmt.Println("1:", err)
}

RootCommand.GenerateHelp()

err = Parse()
if err != nil {
	log.Println("2:", err)
}

fmt.Println("Finished")
Output:

build type tgz
build [fileA fileB]
Finished

Types

type Command

type Command struct {
	Order         int
	Name          string
	Father        string
	Describe      string
	DescribeBrief string
	Help          string
	Usage         string

	Options map[string]*Option

	Commands map[string]*Command

	// Number of parameters required
	// if Size=-1 All parameters that follow belong to this command
	Size         int
	Executor     FuncExecutor
	ErrorHandler FuncErrorHandler
}

Command

func NewCommand

func NewCommand(name, father string) *Command

Create a new Command

func NewCommandFull

func NewCommandFull(order int, name, father, describe, describeBrief, help, usage string, size int,
	executor FuncExecutor, errExecutor FuncErrorHandler) *Command

Create a new Command

func (*Command) GenerateHelp

func (c *Command) GenerateHelp()

Generate Help

func (*Command) PrintHelp

func (c *Command) PrintHelp()

Print Help

type FuncErrorHandler

type FuncErrorHandler func(error) error

type FuncExecutor

type FuncExecutor func([]string) error

type Line added in v1.2.0

type Line struct {
	Order int
	Line  string
}

type Lines added in v1.2.0

type Lines []Line

func (*Lines) Sort added in v1.2.0

func (l *Lines) Sort()

Little first

type Option

type Option struct {
	Order         int
	Name          string
	Father        string
	Size          int
	Priority      int
	Describe      string
	DescribeBrief string
	Help          string
	Usage         string
	Executor      FuncExecutor
	ErrorExecutor FuncErrorHandler
}

Option

func NewOption

func NewOption(name, father string) *Option

Create a new Option

func NewOptionFull

func NewOptionFull(order int, name, father string, size, priority int, describe, describeBrief, help, usage string,
	executor FuncExecutor, errExecutor FuncErrorHandler) *Option

Create a new Option

func (*Option) GenerateHelp

func (o *Option) GenerateHelp()

Generate Help

func (*Option) PrintHelp

func (o *Option) PrintHelp()

Print Help

Jump to

Keyboard shortcuts

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