-
Notifications
You must be signed in to change notification settings - Fork 0
/
parser.go
97 lines (83 loc) · 2.46 KB
/
parser.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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
package flagforge
import (
"fmt"
"io"
"github.com/spf13/viper"
)
// GoConfig represents the configuration for the generated Go code.
type GoConfig struct {
Package string `mapstructure:"package"`
ConfigTypeName string `mapstructure:"config_type_name"`
FlagSetUsage string `mapstructure:"flag_set_usage"`
FlagSetName string `mapstructure:"flag_set_name"`
FlagErrorHandling string `mapstructure:"flag_error_handling"`
}
// Argument represents a single argument configuration.
type Argument struct {
Name string `mapstructure:"name"`
Type string `mapstructure:"type"`
Required bool `mapstructure:"required"`
ShortHelp string `mapstructure:"short_help"`
LongHelp string `mapstructure:"long_help"`
}
// Flag represents a single flag configuration.
type Flag struct {
Name string `mapstructure:"name"`
CLI string `mapstructure:"cli"`
Type string `mapstructure:"type"`
Default interface{} `mapstructure:"default"`
ShortHelp string `mapstructure:"short_help"`
LongHelp string `mapstructure:"long_help"`
}
type ParsedConfig struct {
GoConfig GoConfig
Arguments []Argument
Flags []Flag
}
type Parser struct {
}
func NewParser() *Parser {
return &Parser{}
}
func (p *Parser) ParsePath(path string) (*ParsedConfig, error) {
v := getViper()
v.SetConfigFile(path)
if err := v.ReadInConfig(); err != nil {
return nil, fmt.Errorf("failed to read TOML file at %s: %w", path, err)
}
return parseConfig(v)
}
func (p *Parser) ParseReader(r io.Reader) (*ParsedConfig, error) {
v := getViper()
if err := viper.ReadConfig(r); err != nil {
return nil, fmt.Errorf("failed to read TOML from reader: %w", err)
}
return parseConfig(v)
}
func parseConfig(v *viper.Viper) (*ParsedConfig, error) {
goConfig := GoConfig{
Package: "pkg",
ConfigTypeName: "Config",
FlagSetName: "name",
FlagErrorHandling: "ExitOnError",
}
if err := v.UnmarshalKey("go", &goConfig); err != nil {
return nil, fmt.Errorf("failed to unmarshal go config: %w", err)
}
var args []Argument
if err := v.UnmarshalKey("arguments", &args); err != nil {
return nil, fmt.Errorf("failed to unmarshal arguments: %w", err)
}
var flags []Flag
if err := v.UnmarshalKey("flags", &flags); err != nil {
return nil, fmt.Errorf("failed to unmarshal flags: %w", err)
}
return &ParsedConfig{
GoConfig: goConfig,
Arguments: args,
Flags: flags,
}, nil
}
func getViper() *viper.Viper {
return viper.New()
}