config.go 5.95 KB
Newer Older
songlinfeng's avatar
songlinfeng committed
1
2
3
4
5
6
7
/**
# Copyright (c) 2024, HCUOpt CORPORATION.  All rights reserved.
**/

package config

import (
8
9
10
11
	createdefault "dcu-container-toolkit/cmd/dcu-ctk/config/create-default"
	"dcu-container-toolkit/cmd/dcu-ctk/config/flags"
	"dcu-container-toolkit/internal/config"
	"dcu-container-toolkit/internal/logger"
songlinfeng's avatar
songlinfeng committed
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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
	"errors"
	"fmt"
	"reflect"
	"strconv"
	"strings"

	"github.com/urfave/cli/v2"
)

type command struct {
	logger logger.Interface
}

// options stores the subcommand options
type options struct {
	flags.Options
	setListSeparator string
	sets             cli.StringSlice
}

// NewCommand constructs an config command with the specified logger
func NewCommand(logger logger.Interface) *cli.Command {
	c := command{
		logger: logger,
	}
	return c.build()
}

// build
func (m command) build() *cli.Command {
	opts := options{}

	// Create the 'config' command
	c := cli.Command{
		Name:  "config",
		Usage: "Interact with the C-3000 DTK Container Toolkit configuration",
		Before: func(ctx *cli.Context) error {
			return validateFlags(ctx, &opts)
		},
		Action: func(ctx *cli.Context) error {
			return run(ctx, &opts)
		},
	}

	c.Flags = []cli.Flag{
		&cli.StringFlag{
			Name:        "config-file",
			Aliases:     []string{"config", "c"},
			Usage:       "Specify the config file to modify.",
			Value:       config.GetConfigFilePath(),
			Destination: &opts.Config,
		},
		&cli.StringSliceFlag{
			Name: "set",
			Usage: "Set a config value using the pattern 'key[=value]'. " +
				"Specifying only 'key' is equivalent to 'key=true' for boolean settings. " +
				"This flag can be specified multiple times, but only the last value for a specific " +
				"config option is applied. " +
				"If the setting represents a list, the elements are colon-separated.",
			Destination: &opts.sets,
		},
		&cli.StringFlag{
			Name:        "set-list-separator",
			Usage:       "Specify a separator for lists applied using the set command.",
			Hidden:      true,
			Value:       ":",
			Destination: &opts.setListSeparator,
		},
		&cli.BoolFlag{
			Name:        "in-place",
			Aliases:     []string{"i"},
			Usage:       "Modify the config file in-place",
			Destination: &opts.InPlace,
		},
		&cli.StringFlag{
			Name:        "output",
			Aliases:     []string{"o"},
			Usage:       "Specify the output file to write to; If not specified, the output is written to stdout",
			Destination: &opts.Output,
		},
	}

	c.Subcommands = []*cli.Command{
		createdefault.NewCommand(m.logger),
	}

	return &c
}

func validateFlags(c *cli.Context, opts *options) error {
	if opts.setListSeparator == "" {
		return fmt.Errorf("set-list-separator must be set")
	}
	return nil
}

func run(c *cli.Context, opts *options) error {
	cfgToml, err := config.New(
		config.WithConfigFile(opts.Config),
	)
	if err != nil {
		return fmt.Errorf("unable to create config: %v", err)
	}

	for _, set := range opts.sets.Value() {
		key, value, err := setFlagToKeyValue(set, opts.setListSeparator)
		if err != nil {
			return fmt.Errorf("invalid --set option %v: %w", set, err)
		}
		if value == nil {
			_ = cfgToml.Delete(key)
		} else {
			cfgToml.Set(key, value)
		}
	}

	if err := opts.EnsureOutputFolder(); err != nil {
		return fmt.Errorf("failed to create output directory: %v", err)
	}
	output, err := opts.CreateOutput()
	if err != nil {
		return fmt.Errorf("failed to open output file: %v", err)
	}
	defer output.Close()

	if _, err := cfgToml.Save(output); err != nil {
		return fmt.Errorf("failed to save config: %v", err)
	}

	return nil
}

var errInvalidConfigOption = errors.New("invalid config option")
var errUndefinedField = errors.New("undefined field")
var errInvalidFormat = errors.New("invalid format")

// setFlagToKeyValue converts a --set flag to a key-value pair.
// The set flag is of the form key[=value], with the value being optional if key refers to a
// boolean config option.
func setFlagToKeyValue(setFlag string, setListSeparator string) (string, interface{}, error) {
	setParts := strings.SplitN(setFlag, "=", 2)
	key := setParts[0]

	field, err := getField(key)
	if err != nil {
		return key, nil, fmt.Errorf("%w: %w", errInvalidConfigOption, err)
	}

	kind := field.Kind()
	if len(setParts) != 2 {
		if kind == reflect.Bool || (kind == reflect.Pointer && field.Elem().Kind() == reflect.Bool) {
			return key, true, nil
		}
		return key, nil, fmt.Errorf("%w: expected key=value; got %v", errInvalidFormat, setFlag)
	}

	value := setParts[1]
	if kind == reflect.Pointer && value != "nil" {
		kind = field.Elem().Kind()
	}
	switch kind {
	case reflect.Pointer:
		return key, nil, nil
	case reflect.Bool:
		b, err := strconv.ParseBool(value)
		if err != nil {
			return key, value, fmt.Errorf("%w: %w", errInvalidFormat, err)
		}
		return key, b, nil
	case reflect.String:
		return key, value, nil
	case reflect.Slice:
		valueParts := strings.Split(value, setListSeparator)
		switch field.Elem().Kind() {
		case reflect.String:
			return key, valueParts, nil
		case reflect.Int:
			var output []int64
			for _, v := range valueParts {
				vi, err := strconv.ParseInt(v, 10, 0)
				if err != nil {
					return key, nil, fmt.Errorf("%w: %w", errInvalidFormat, err)
				}
				output = append(output, vi)
			}
			return key, output, nil
		}
	}
	return key, nil, fmt.Errorf("unsupported type for %v (%v)", setParts, kind)
}

func getField(key string) (reflect.Type, error) {
	s, err := getStruct(reflect.TypeOf(config.Config{}), strings.Split(key, ".")...)
	if err != nil {
		return nil, err
	}
	return s.Type, err
}

func getStruct(current reflect.Type, paths ...string) (reflect.StructField, error) {
	if len(paths) < 1 {
		return reflect.StructField{}, fmt.Errorf("%w: no fields selected", errUndefinedField)
	}
	tomlField := paths[0]
	for i := 0; i < current.NumField(); i++ {
		f := current.Field(i)
		v, ok := f.Tag.Lookup("toml")
		if !ok {
			continue
		}
		if strings.SplitN(v, ",", 2)[0] != tomlField {
			continue
		}
		if len(paths) == 1 {
			return f, nil
		}
		return getStruct(f.Type, paths[1:]...)
	}
	return reflect.StructField{}, fmt.Errorf("%w: %q", errUndefinedField, tomlField)
}