Code: config.go
package projector
import (
"fmt"
"os"
"path"
)
type Operation = int
const (
Print Operation = iota
Add
Remove
)
type Config struct {
Args []string
Operation Operation
Config string
Pwd string
}
func getPwd(opts *Opts) (string, error) {
if opts.Pwd != "" {
return opts.Pwd, nil
}
return os.Getwd()
}
func getConfig(opts *Opts) (string, error) {
if opts.Config != "" {
return opts.Config, nil
}
config, err := os.UserConfigDir()
if err != nil {
return "", nil
}
return path.Join(config, "projector", "projector.json"), nil
}
func getOperation(opts *Opts) Operation {
if len(opts.Args) == 0 {
return Print
}
if opts.Args[0] == "add" {
return Add
}
if opts.Args[0] == "rm" {
return Remove
}
return Print
}
func getArgs(opts *Opts) ([]string, error) {
if len(opts.Args) == 0 {
return []string{}, nil
}
operation := getOperation(opts)
if operation == Add {
if len(opts.Args) != 3 {
return nil, fmt.Errorf("add requries 2 arguments, but received %v", len(opts.Args) - 1)
}
return opts.Args[1:], nil
}
if operation == Remove {
if len(opts.Args) != 2 {
return nil, fmt.Errorf("remove requries 1 arguments, but received %v", len(opts.Args) -1)
}
return opts.Args[1:], nil
}
if len(opts.Args) > 1 {
return nil, fmt.Errorf("print requries 0 or 1 arguments, but received %v", len(opts.Args))
}
return opts.Args, nil
}
func NewConfig(opts *Opts) (*Config, error) {
pwd, err := getPwd(opts)
if err != nil {
return nil, err
}
config, err := getConfig(opts)
if err != nil {
return nil, err
}
args, err := getArgs(opts)
if err != nil {
return nil, err
}
return &Config{
Pwd: pwd,
Config: config,
Args: args,
Operation: getOperation(opts),
}, nil
}
Testing code: config_test.go
package projector_test
import (
"reflect"
"testing"
"github.com/zhen/projector/pkg/projector"
)
func testConfig(t *testing.T, args []string, expectedArgs []string, operation projector.Operation) {
opts := getOpts(args)
config, err := projector.NewConfig(opts)
if err != nil {
t.Errorf("expected to get no error %v", err)
}
if !reflect.DeepEqual(expectedArgs, config.Args) {
t.Errorf("expected args to be %+v array but got %+v", expectedArgs, config.Args)
}
if config.Operation != operation {
t.Errorf("operation expect was %v but got %v", operation, config.Operation)
}
}
func getOpts(args []string) *projector.Opts {
opts := &projector.Opts{
Args: args,
Config: "",
Pwd: "",
}
return opts
}
func TestConfigPrint(t *testing.T) {
testConfig(t, []string{}, []string{}, projector.Print)
}
func TestConfigPrintKey(t *testing.T) {
testConfig(t, []string{"foo"}, []string{"foo"}, projector.Print)
}
func TestConfigAddKeyValue(t *testing.T) {
testConfig(t, []string{"add", "foo", "bar"}, []string{"foo", "bar"}, projector.Add)
}
func TestConfigRmKey(t *testing.T) {
testConfig(t, []string{"rm", "foo"}, []string{"foo"}, projector.Remove)
}
标签:Args,return,string,nil,testing,Unit,Go,opts,projector From: https://www.cnblogs.com/Answer1215/p/18034499