2018-11-08 12:40:36 +00:00
|
|
|
package cnf
|
|
|
|
|
|
|
|
import (
|
|
|
|
"errors"
|
|
|
|
"fmt"
|
|
|
|
"io"
|
|
|
|
"os"
|
|
|
|
"path/filepath"
|
|
|
|
)
|
|
|
|
|
|
|
|
var ErrUnknownExtension = errors.New("unknown extension format")
|
2018-11-10 18:04:16 +00:00
|
|
|
var ErrUnknownFormat = errors.New("cannot infer format from content")
|
2018-11-08 12:40:36 +00:00
|
|
|
|
|
|
|
// 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
|
2018-11-11 00:05:14 +00:00
|
|
|
_, err = confFormat.ReadFrom(file)
|
2018-11-08 12:40:36 +00:00
|
|
|
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 {
|
2018-11-10 18:04:16 +00:00
|
|
|
return nil, ErrUnknownFormat
|
2018-11-08 12:40:36 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
return confFormat, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func loadFromExtension(ext string) ConfigurationFormat {
|
|
|
|
|
|
|
|
// select configuration or fail if not known
|
|
|
|
switch ext {
|
2018-11-10 18:04:16 +00:00
|
|
|
case ".json":
|
2018-11-11 14:34:00 +00:00
|
|
|
return new(json)
|
2018-11-10 18:04:16 +00:00
|
|
|
case ".ini":
|
2018-11-11 14:34:00 +00:00
|
|
|
return new(ini)
|
2018-11-11 17:07:29 +00:00
|
|
|
case ".yaml":
|
|
|
|
return new(yaml)
|
2018-11-11 15:31:43 +00:00
|
|
|
case ".conf":
|
|
|
|
return new(confl)
|
2018-11-08 12:40:36 +00:00
|
|
|
default:
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
func loadFromContent(file io.Reader) ConfigurationFormat {
|
|
|
|
return nil
|
|
|
|
}
|