mirror of
https://github.com/hanzoai/ingress-parser.git
synced 2026-10-30 18:33:22 +00:00
Modules declare go 1.27.1 and the build images follow. go fix applied the modernizers; omitzero is not applied, since it changes what the JSON says. Co-Authored-By: Claude Opus 5 <[email protected]>
85 lines
2.2 KiB
Go
85 lines
2.2 KiB
Go
// Package file implements decoding between configuration in a file and a typed Configuration.
|
|
package file
|
|
|
|
import (
|
|
"fmt"
|
|
|
|
"github.com/BurntSushi/toml"
|
|
"github.com/hanzoai/ingress-parser/parser"
|
|
"gopkg.in/yaml.v3"
|
|
)
|
|
|
|
const defaultRawSliceSeparator = "║"
|
|
|
|
// Decode decodes the given configuration file into the given element.
|
|
// The operation goes through three stages roughly summarized as:
|
|
// - file contents -> tree of untyped nodes
|
|
// - untyped nodes -> nodes augmented with metadata such as kind (inferred from element)
|
|
// - "typed" nodes -> typed element.
|
|
func Decode(filePath string, element any) error {
|
|
if element == nil {
|
|
return nil
|
|
}
|
|
|
|
filters := getRootFieldNames(element)
|
|
|
|
root, err := decodeFileToNode(filePath, filters...)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
metaOpts := parser.MetadataOpts{TagName: parser.TagFile, AllowSliceAsStruct: false}
|
|
err = parser.AddMetadata(element, root, metaOpts)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
return parser.Fill(element, root, parser.FillerOpts{AllowSliceAsStruct: false, RawSliceSeparator: defaultRawSliceSeparator})
|
|
}
|
|
|
|
// DecodeContent decodes the given configuration file content into the given element.
|
|
// The operation goes through three stages roughly summarized as:
|
|
// - file contents -> tree of untyped nodes
|
|
// - untyped nodes -> nodes augmented with metadata such as kind (inferred from element)
|
|
// - "typed" nodes -> typed element.
|
|
func DecodeContent(content, extension string, element any) error {
|
|
data := make(map[string]any)
|
|
|
|
switch extension {
|
|
case ".toml":
|
|
_, err := toml.Decode(content, &data)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
case ".yml", ".yaml", ".json":
|
|
var err error
|
|
err = yaml.Unmarshal([]byte(content), &data)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
default:
|
|
return fmt.Errorf("unsupported file extension: %s", extension)
|
|
}
|
|
|
|
filters := getRootFieldNames(element)
|
|
|
|
node, err := decodeRawToNode(data, filters...)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
if len(node.Children) == 0 {
|
|
return nil
|
|
}
|
|
|
|
metaOpts := parser.MetadataOpts{TagName: parser.TagFile, AllowSliceAsStruct: false}
|
|
err = parser.AddMetadata(element, node, metaOpts)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
return parser.Fill(element, node, parser.FillerOpts{AllowSliceAsStruct: false, RawSliceSeparator: defaultRawSliceSeparator})
|
|
}
|