From 7ceaf81ee5fbde2a0dcfca4d94b179f8f323b97f Mon Sep 17 00:00:00 2001 From: xdrm-brackets Date: Mon, 12 Nov 2018 20:01:07 +0100 Subject: [PATCH] update cnf/loader to infer parser (config format) from content --- internal/cnf/loader.go | 31 ++++++++++++++++++++++++++----- 1 file changed, 26 insertions(+), 5 deletions(-) diff --git a/internal/cnf/loader.go b/internal/cnf/loader.go index fefa723..7a669ac 100644 --- a/internal/cnf/loader.go +++ b/internal/cnf/loader.go @@ -42,11 +42,11 @@ func Load(path string) (ConfigurationFormat, error) { // parse _, err = confFormat.ReadFrom(file) - if err != nil { - return nil, fmt.Errorf("cannot parse file as '%s' | %s", extension, err) + if err == nil { + return confFormat, nil } - return confFormat, nil + // return nil, fmt.Errorf("cannot parse file as '%s' | %s", extension, err) } @@ -72,11 +72,11 @@ func loadFromExtension(ext string) ConfigurationFormat { switch ext { case ".json": return new(json) - case ".ini": + case ".ini", ".conf": return new(ini) case ".yaml": return new(yaml) - case ".conf": + case ".nginx": return new(nginx) default: return nil @@ -85,5 +85,26 @@ func loadFromExtension(ext string) ConfigurationFormat { } func loadFromContent(file io.Reader) ConfigurationFormat { + + // extensions ordered by unicity of the language's syntax + extensions := []string{".json", ".yaml", ".nginx", ".ini"} + + // try to load each available extension + for _, ext := range extensions { + + // load parser + c := loadFromExtension(ext) + if c == nil { + continue + } + + // parse + _, err := c.ReadFrom(file) + if err == nil { + return c + } + + } + return nil }