multisql/cfg/config.go
Arkadiusz Rychliński 3d21c4f1c2 Wersja inicjalna
2022-11-08 11:16:29 +01:00

76 lines
1.7 KiB
Go

package cfg
import (
"encoding/json"
"fmt"
"os"
)
type Connection struct {
Host string `json:"Host,omitempty"`
User string `json:"User,omitempty"`
Port uint `json:"Port,omitempty"`
DbName string `json:"DbName,omitempty"`
}
type Config struct {
PassFile string `json:"Passfile"`
PsqlExec string `json:"PsqlExec"`
SqlDir string `json:"SqlDir"`
Defaults Connection `json:"Defaults"`
Connections []Connection `json:"Connections"`
}
func GetConfig(params Parameters) (config Config, err error) {
bytes, err := os.ReadFile(params.ConfigFile)
if err != nil {
return config, fmt.Errorf("błąd odczytu pliku konfiguracji: %w", err)
}
err = json.Unmarshal(bytes, &config)
if err != nil {
return config, fmt.Errorf("błąd parsowania pliku konfiguracji: %w", err)
}
if config.PassFile == "" && params.Passfile != "" {
config.PassFile = params.Passfile
}
if config.PassFile == "" {
return config, fmt.Errorf("nie podano Passfile (dodaj w konfiguracji lub użyj flag --passfile)")
}
if config.SqlDir == "" && params.SqlDir != "" {
config.SqlDir = params.SqlDir
}
err = fixConnections(&config)
return config, err
}
func fixConnections(config *Config) error {
def := config.Defaults
for i := range config.Connections {
con := &config.Connections[i]
if con.DbName == "" {
con.DbName = def.DbName
}
if con.User == "" {
con.User = def.User
}
if con.Host == "" {
con.Host = def.Host
}
if con.Port == 0 {
if def.Port != 0 {
con.Port = def.Port
} else {
con.Port = 5432 // domyślny dla PostgreSQL
}
}
if con.DbName == "" || con.Host == "" || con.User == "" {
return fmt.Errorf("opis połączenia z pozycji %d jest niekompletny: %#v", i+1, con)
}
}
return nil
}