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 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 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335
|
package konghcl
import (
"bytes"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"os"
"strings"
"github.com/alecthomas/kong"
"github.com/hashicorp/hcl/v2"
"github.com/hashicorp/hcl/v2/gohcl"
"github.com/hashicorp/hcl/v2/hclparse"
"github.com/hashicorp/hcl/v2/hclsyntax"
"github.com/pkg/errors"
"github.com/zclconf/go-cty/cty"
)
// Resolver resolves kong Flags from configuration in HCL.
type Resolver struct {
config map[string]interface{}
}
var _ kong.ConfigurationLoader = Loader
// DecodeValue decodes Kong values into a Go structure.
func DecodeValue(ctx *kong.DecodeContext, dest interface{}) error {
v := ctx.Scan.Pop().Value
var (
data []byte
err error
)
filename := "config.hcl"
switch v := v.(type) {
case string:
// Value is a string; it can either be a filename or a HCL fragment.
filename = kong.ExpandPath(v)
data, err = ioutil.ReadFile(filename) // nolint: gosec
if os.IsNotExist(err) {
data = []byte(v)
} else if err != nil {
return errors.Wrapf(err, "invalid HCL in %q", filename)
}
case []map[string]interface{}:
merged := map[string]interface{}{}
for _, m := range v {
for k, v := range m {
merged[k] = v
}
}
data, err = json.Marshal(merged)
if err != nil {
return err
}
default:
data, err = json.Marshal(v)
if err != nil {
return err
}
}
parser := hclparse.NewParser()
var (
ast *hcl.File
diag hcl.Diagnostics
)
if bytes.HasPrefix(data, []byte("{")) {
ast, diag = parser.ParseJSON(data, filename)
} else {
ast, diag = parser.ParseHCL(data, filename)
}
if diag.HasErrors() {
return errors.Errorf("invalid HCL %s: %s", data, diag[0].Summary)
}
diag = gohcl.DecodeBody(ast.Body, nil, dest)
if diag.HasErrors() {
return errors.Errorf("invalid HCL %s: %s", data, diag[0].Summary)
}
return nil
}
// Loader is a Kong configuration loader for HCL.
func Loader(r io.Reader) (kong.Resolver, error) {
filename := "config.hcl"
if named, ok := r.(interface{ Name() string }); ok {
filename = named.Name()
}
parser := hclparse.NewParser()
source, err := ioutil.ReadAll(r)
if err != nil {
return nil, errors.WithStack(err)
}
ast, diag := parser.ParseHCL(source, filename)
if diag.HasErrors() {
return nil, errors.Wrap(diag, filename)
}
config := map[string]interface{}{}
err = flattenHCL(nil, ast.Body.(*hclsyntax.Body), config)
if err != nil {
return nil, err
}
return &Resolver{config: config}, nil
}
func flattenHCL(key []string, node hclsyntax.Node, dest map[string]interface{}) (err error) {
defer func() {
if err != nil && len(key) > 0 {
err = errors.Wrap(err, key[len(key)-1])
}
}()
switch node := node.(type) {
case hclsyntax.Attributes:
for attr, value := range node {
if err := flattenHCL(append(key, attr), value, dest); err != nil {
return err
}
}
case *hclsyntax.Attribute:
value, err := decodeHCLExpr(node.Expr)
if err != nil {
return err
}
dest[strings.Join(key, "-")] = value
case hclsyntax.Blocks:
for _, block := range node {
if err := flattenHCL(key, block, dest); err != nil {
return err
}
}
case *hclsyntax.Block:
sub := map[string]interface{}{}
key = append(key, node.Type)
for _, label := range node.Labels {
next := map[string]interface{}{}
sub[label] = []map[string]interface{}{next}
sub = next
}
if err := flattenHCL(nil, node.Body, sub); err != nil {
return err
}
dkey := strings.Join(key, "-")
switch value := dest[dkey].(type) {
case nil:
dest[dkey] = []map[string]interface{}{sub}
case []map[string]interface{}:
value = append(value, sub)
dest[dkey] = value
}
case *hclsyntax.Body:
if err := flattenHCL(key, node.Attributes, dest); err != nil {
return err
}
if err := flattenHCL(key, node.Blocks, dest); err != nil {
return err
}
default:
panic(fmt.Sprintf("%T", node))
}
return nil
}
func decodeHCLExpr(expr hclsyntax.Expression) (interface{}, error) {
value, diag := expr.Value(nil)
if diag.HasErrors() {
return nil, errors.WithStack(diag)
}
return decodeCTYValue(value), nil
}
func decodeCTYValue(value cty.Value) interface{} {
switch value.Type() {
case cty.String:
return value.AsString()
case cty.Bool:
return value.True()
case cty.Number:
f, _ := value.AsBigFloat().Float64()
return f
default:
if value.Type().IsListType() || value.Type().IsTupleType() {
out := []interface{}{}
value.ForEachElement(func(key cty.Value, val cty.Value) (stop bool) {
out = append(out, decodeCTYValue(val))
return false
})
return out
} else if value.Type().IsMapType() || value.Type().IsObjectType() {
out := map[string]interface{}{}
value.ForEachElement(func(key cty.Value, val cty.Value) (stop bool) {
out[key.AsString()] = decodeCTYValue(val)
return false
})
return out
}
}
panic(value.Type().GoString())
}
func (r *Resolver) Validate(app *kong.Application) error { // nolint: golint
// Find all valid configuration keys from the Application.
valid := map[string]bool{}
rawPrefixes := []string{}
path := []string{}
_ = kong.Visit(app, func(node kong.Visitable, next kong.Next) error {
switch node := node.(type) {
case *kong.Node:
path = append(path, node.Name)
_ = next(nil)
path = path[:len(path)-1]
return nil
case *kong.Flag:
flagPath := append([]string{}, path...)
if node.Group != "" {
flagPath = append(flagPath, node.Group)
}
key := strings.Join(append(flagPath, node.Name), "-")
if _, ok := node.Target.Interface().(kong.MapperValue); ok {
rawPrefixes = append(rawPrefixes, key)
} else {
valid[key] = true
}
default:
return next(nil)
}
return nil
})
// Then check all configuration keys against the Application keys.
next:
for key := range flattenConfig(valid, r.config) {
if !valid[key] {
for _, prefix := range rawPrefixes {
if strings.HasPrefix(key, prefix) {
continue next
}
}
return errors.Errorf("unknown configuration key %q", key)
}
}
return nil
}
func (r *Resolver) Resolve(context *kong.Context, parent *kong.Path, flag *kong.Flag) (interface{}, error) { // nolint: golint
path := r.pathForFlag(parent, flag)
return find(r.config, path)
}
// Build a string path up to this flag.
func (r *Resolver) pathForFlag(parent *kong.Path, flag *kong.Flag) []string {
path := []string{}
for n := parent.Node(); n != nil && n.Type != kong.ApplicationNode; n = n.Parent {
path = append([]string{n.Name}, path...)
}
if flag.Group != "" {
path = append([]string{flag.Group}, path...)
}
path = append(path, flag.Name)
return path
}
// Find the value that path maps to.
func find(config map[string]interface{}, path []string) (interface{}, error) {
if len(path) == 0 {
return config, nil
}
key := strings.Join(path, "-")
parts := strings.SplitN(key, "-", -1)
for i := len(parts); i > 0; i-- {
prefix := strings.Join(parts[:i], "-")
if sub := config[prefix]; sub != nil {
if sub, ok := sub.([]map[string]interface{}); ok {
if len(sub) > 1 {
return sub, nil
}
return find(sub[0], parts[i:])
}
return sub, nil
}
}
return nil, nil
}
func flattenConfig(schema map[string]bool, config map[string]interface{}) map[string]bool {
out := map[string]bool{}
next:
for _, path := range flattenNode(config) {
for i := len(path) - 1; i >= 0; i-- {
candidate := strings.Join(path[:i], "-")
if schema[candidate] {
out[candidate] = true
continue next
}
}
out[strings.Join(path, "-")] = true
}
return out
}
func flattenNode(config interface{}) [][]string {
out := [][]string{}
switch config := config.(type) {
case []map[string]interface{}:
for _, group := range config {
out = append(out, flattenNode(group)...)
}
case map[string]interface{}:
for key, value := range config {
children := flattenNode(value)
if len(children) == 0 {
out = append(out, []string{key})
} else {
for _, childValue := range children {
out = append(out, append([]string{key}, childValue...))
}
}
}
case []interface{}:
for _, el := range config {
out = flattenNode(el)
}
case bool, float64, int, string:
return nil
default:
panic(fmt.Sprintf("unsupported type %T", config))
}
return out
}
|