grim/convey

closing merged branch
hostnames
2017-10-13, Gary Kramlich
33eae19fcbbe
closing merged branch
/*
* Convey
* Copyright 2016-2017 Gary Kramlich <grim@reaperworld.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package config
import (
"fmt"
"io/ioutil"
"os"
"path/filepath"
"strings"
"bitbucket.org/rw_grim/convey/state"
)
type Loader interface {
Load(path, base string, data []byte) (*Config, error)
LoadOverride(path, base string, data []byte, config *Config)
Filenames() []string
OverrideSuffix() string
DefaultPlan() string
ResolvePlanName(plan string, cfg *Config, st *state.State) string
}
func determineFilename(filename string, loader Loader) string {
ext := filepath.Ext(filename)
base := strings.TrimSuffix(filename, ext)
return base + loader.OverrideSuffix() + ext
}
func loadOverride(path, base string, loader Loader, cfg *Config) {
overrideFilename := determineFilename(base, loader)
absName := filepath.Join(path, overrideFilename)
if _, err := os.Stat(absName); os.IsNotExist(err) {
// no override so bail
return
}
data, err := ioutil.ReadFile(absName)
if err != nil {
fmt.Printf("error in override file '%s' : %s", absName, err)
return
}
loader.LoadOverride(path, base, data, cfg)
}
func LoadFile(file string, loader Loader) (*Config, error) {
// split the filename into our parts
path, base := filepath.Split(file)
data, err := ioutil.ReadFile(file)
if err != nil {
return nil, fmt.Errorf("failed to read config file '%s'", file)
}
cfg, err := loader.Load(path, base, data)
if err != nil {
return cfg, err
}
loadOverride(path, base, loader, cfg)
return cfg, nil
}