This repository has been archived by the owner on Jul 18, 2023. It is now read-only.
/
argument.go
71 lines (55 loc) · 1.57 KB
/
argument.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
package commander
import (
"log"
"os"
"strconv"
"strings"
"github.com/mitchellh/go-homedir"
)
type argumentTypeFunction func(string) (interface{}, error)
var argumentTypeList map[string]argumentTypeFunction
// RegisterArgumentType registers a new argument type
func RegisterArgumentType(name string, f argumentTypeFunction) {
argumentTypeList[name] = f
}
// Argument represents a single argument
type Argument struct {
Name string
Type string
OriginalValue string
Value interface{}
Error error
FailOnError bool
}
// SetValue saves the original value to the argument.
// Returns with an error if conversion failed
func (a *Argument) SetValue(original string) error {
a.OriginalValue = original
a.Value, a.Error = argumentTypeList[a.Type](a.OriginalValue)
return a.Error
}
func init() {
argumentTypeList = map[string]argumentTypeFunction{}
RegisterArgumentType("String", func(value string) (interface{}, error) {
return value, nil
})
RegisterArgumentType("Int64", func(value string) (interface{}, error) {
return strconv.ParseInt(value, 10, 64)
})
RegisterArgumentType("Uint64", func(value string) (interface{}, error) {
return strconv.ParseUint(value, 10, 64)
})
RegisterArgumentType("StringArray[]", func(value string) (interface{}, error) {
arr := strings.Split(value, ",")
return arr, nil
})
RegisterArgumentType("FilePath", func(value string) (interface{}, error) {
value, _ = homedir.Expand(value)
_, err := os.Stat(value)
if os.IsNotExist(err) {
log.Println(err)
value = ""
}
return value, err
})
}