81 lines
1.9 KiB
Go
81 lines
1.9 KiB
Go
|
// Copyright (c) 2024 mStar
|
||
|
//
|
||
|
// Licensed under the EUPL, Version 1.2
|
||
|
//
|
||
|
// You may not use this work except in compliance with the Licence.
|
||
|
// You should have received a copy of the Licence along with this work. If not, see:
|
||
|
// <https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12>.
|
||
|
// See the Licence for the specific language governing permissions and limitations under the Licence.
|
||
|
//
|
||
|
|
||
|
package config
|
||
|
|
||
|
import (
|
||
|
"flag"
|
||
|
"os"
|
||
|
|
||
|
"github.com/BurntSushi/toml"
|
||
|
"github.com/kelseyhightower/envconfig"
|
||
|
log "github.com/sirupsen/logrus"
|
||
|
)
|
||
|
|
||
|
type CLIArguments struct {
|
||
|
// Path to a config file
|
||
|
ConfigFile string
|
||
|
// Path to a postgres database
|
||
|
// Nil if not provided
|
||
|
DbPath *string
|
||
|
}
|
||
|
|
||
|
type Config struct {
|
||
|
General struct {
|
||
|
DbPath string `envconfig:"database" toml:"database_path"`
|
||
|
}
|
||
|
}
|
||
|
|
||
|
// Reads arguments passed to the application
|
||
|
func ReadCLIArguments() CLIArguments {
|
||
|
configFlag := flag.String("config", "config.toml", "Path to a config file")
|
||
|
dbFlag := flag.String("db", "", "Path to a postgres database")
|
||
|
|
||
|
flag.Parse()
|
||
|
|
||
|
var dbString *string
|
||
|
if *dbFlag != "" {
|
||
|
dbString = dbFlag
|
||
|
}
|
||
|
|
||
|
return CLIArguments{
|
||
|
ConfigFile: *configFlag,
|
||
|
DbPath: dbString,
|
||
|
}
|
||
|
}
|
||
|
|
||
|
// Read a config from the given CLI arguments as well as the config file specified in the cli args (default is config.toml)
|
||
|
func ReadConfig(cliArgs *CLIArguments) Config {
|
||
|
file, err := os.Open(cliArgs.ConfigFile)
|
||
|
if err != nil {
|
||
|
log.Fatalf("Failed to open file %s with error %v. Does it exist?\n", cliArgs.ConfigFile, err)
|
||
|
}
|
||
|
defer file.Close()
|
||
|
|
||
|
var cfg Config
|
||
|
|
||
|
decoder := toml.NewDecoder(file)
|
||
|
_, err = decoder.Decode(&cfg)
|
||
|
if err != nil {
|
||
|
log.Fatalf("Failed to parse config file %s with error %v\n", cliArgs.ConfigFile, err)
|
||
|
}
|
||
|
|
||
|
err = envconfig.Process("", &cfg)
|
||
|
if err != nil {
|
||
|
log.Fatalf("Failed to overwrite config from env. Error %v\n", err)
|
||
|
}
|
||
|
|
||
|
if cliArgs.DbPath != nil && *cliArgs.DbPath != "" {
|
||
|
cfg.General.DbPath = *cliArgs.DbPath
|
||
|
}
|
||
|
|
||
|
return cfg
|
||
|
}
|