feat: apply config from stdin

This commit is contained in:
Mikaël Cluseau 2018-07-07 10:12:08 +11:00
parent 083d03e034
commit 9c9ccf622a
4 changed files with 58 additions and 21 deletions

View File

@ -14,13 +14,24 @@ var (
)
func main() {
configPath := flag.String("config", "config.yaml", "config to load")
configPath := flag.String("config", "config.yaml", "config to load (\"-\" for stdin)")
doFiles := flag.Bool("files", false, "apply files")
flag.Parse()
log.SetConsole(os.Stderr)
cfg, err := config.Load(*configPath)
var (
cfg *config.Config
err error
)
if *configPath == "-" {
cfg, err = config.Read(os.Stdin)
} else {
cfg, err = config.Load(*configPath)
}
if err != nil {
log.Print("failed to load config: ", err)
}

2
go.mod
View File

@ -3,5 +3,5 @@ module novit.nc/direktil/inits
require (
github.com/sparrc/go-ping v0.0.0-20160208162908-416e72114cd1
golang.org/x/net v0.0.0-20180706051357-32a936f46389
novit.nc/direktil/pkg v0.0.0-20180703072055-a44d1cbe7fbb
novit.nc/direktil/pkg v0.0.0-20180706230842-852aa03280f9
)

View File

@ -2,12 +2,54 @@ package config
import (
"fmt"
"io/ioutil"
"io"
"os"
yaml "gopkg.in/yaml.v2"
)
// Load a config from a file.
func Load(file string) (config *Config, err error) {
f, err := os.Open(file)
if err != nil {
return
}
defer f.Close()
config, err = Read(f)
if err != nil {
return nil, fmt.Errorf("failed to parse %s: %v", file, err)
}
return
}
// Read a config from a reader.
func Read(reader io.Reader) (config *Config, err error) {
config = &Config{}
err = yaml.NewDecoder(reader).Decode(config)
if err != nil {
return nil, err
}
return
}
// Parse the config in data.
func Parse(data []byte) (config *Config, err error) {
config = &Config{}
err = yaml.Unmarshal(data, config)
if err != nil {
return nil, err
}
return
}
// Config represent this system's configuration
type Config struct {
Vars []VarDefault
@ -83,19 +125,3 @@ type NetworkDef struct {
Optional bool
Script string
}
func Load(file string) (config *Config, err error) {
config = &Config{}
configData, err := ioutil.ReadFile(file)
if err != nil {
return nil, fmt.Errorf("failed to read %s: %v", file, err)
}
err = yaml.Unmarshal(configData, config)
if err != nil {
return nil, fmt.Errorf("failed to parse %s: %v", file, err)
}
return
}

2
vendor/vgo.list vendored
View File

@ -18,7 +18,7 @@ golang.org/x/net/ipv6
gopkg.in/check.v1
# gopkg.in/yaml.v2 v2.2.1
gopkg.in/yaml.v2
# novit.nc/direktil/pkg v0.0.0-20180703072055-a44d1cbe7fbb
# novit.nc/direktil/pkg v0.0.0-20180706230842-852aa03280f9
novit.nc/direktil/pkg/color
novit.nc/direktil/pkg/config
novit.nc/direktil/pkg/log