diff --git a/internal/cnf/common.go b/internal/cnf/common.go index d754956..d62e128 100644 --- a/internal/cnf/common.go +++ b/internal/cnf/common.go @@ -4,16 +4,6 @@ import ( "io" ) -// Field generic representation (root, branch or leaf) -type Field struct { - // Label of the current field - Label string - // Value of the current field - Value string - // Children of the current field or NIL if none - Children []Field -} - // ConfigurationFormat is the common interface for all configuration parser type ConfigurationFormat interface { // Parse the given file diff --git a/internal/cnf/loader.go b/internal/cnf/loader.go new file mode 100644 index 0000000..21ff420 --- /dev/null +++ b/internal/cnf/loader.go @@ -0,0 +1,81 @@ +package cnf + +import ( + "errors" + "fmt" + "io" + "os" + "path/filepath" +) + +var ErrUnknownExtension = errors.New("unknown extension format") + +// Load the current file and create the configuration format accordingly +func Load(path string) (ConfigurationFormat, error) { + + var confFormat ConfigurationFormat + + // 1. check file + if _, err := os.Stat(path); os.IsNotExist(err) { + return nil, fmt.Errorf("cannot find file '%s'", path) + } + + // 2. Try to load from extension + extension := filepath.Ext(path) + if len(extension) > 0 { + + confFormat = loadFromExtension(extension) + if confFormat == nil { + return nil, ErrUnknownExtension + } + + // open file + file, err := os.Open(path) + if err != nil { + return nil, err + } + defer file.Close() + + // parse + err = confFormat.Parse(file) + if err != nil { + return nil, fmt.Errorf("cannot parse file as '%s' | %s", extension, err) + } + + return confFormat, nil + + } + + // 3. open file + file, err := os.Open(path) + if err != nil { + return nil, err + } + defer file.Close() + + // 4. Try to guess from the content + confFormat = loadFromContent(file) + if confFormat == nil { + return nil, fmt.Errorf("cannot infer format from content") + } + + return confFormat, nil +} + +func loadFromExtension(ext string) ConfigurationFormat { + + var confFormat ConfigurationFormat + + // select configuration or fail if not known + switch ext { + case "json": + return new(Json) + default: + return nil + } + +} + +func loadFromContent(file io.Reader) ConfigurationFormat { + return nil +}