scotty/internal/config/config.go
2023-12-07 22:20:27 +01:00

100 lines
2.4 KiB
Go

/*
Copyright © 2023 Philipp Wolfer <phw@uploadedlobster.com>
Scotty 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.
Scotty 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
Scotty. If not, see <https://www.gnu.org/licenses/>.
*/
package config
import (
"fmt"
"os"
"path"
"path/filepath"
"regexp"
"github.com/spf13/cobra"
"github.com/spf13/viper"
"go.uploadedlobster.com/scotty/internal/version"
)
const (
defaultDatabase = "scotty.sqlite3"
defaultOAuthHost = "127.0.0.1:2369"
)
func DefaultConfigDir() string {
configDir, err := os.UserConfigDir()
cobra.CheckErr(err)
return path.Join(configDir, version.AppName)
}
// initConfig reads in config file and ENV variables if set.
func InitConfig(cfgFile string) error {
configDir := DefaultConfigDir()
if cfgFile != "" {
// Use given config file
viper.SetConfigFile(cfgFile)
} else {
viper.AddConfigPath(configDir)
viper.SetConfigType("toml")
viper.SetConfigName(version.AppName)
viper.SetConfigPermissions(0640)
}
setDefaults()
// Create global config if it does not exist
if viper.ConfigFileUsed() == "" && cfgFile == "" {
if err := os.MkdirAll(configDir, 0750); err == nil {
viper.SafeWriteConfig()
}
}
// read in environment variables that match
viper.AutomaticEnv()
// If a config file is found, read it in.
return viper.ReadInConfig()
}
func DatabasePath() string {
path := viper.GetString("database")
if filepath.IsAbs(path) {
return path
}
return filepath.Join(getConfigDir(), path)
}
func ValidateKey(key string) error {
found, err := regexp.MatchString("^[A-Za-z0-9_-]+$", key)
if err != nil {
return err
} else if found {
return nil
} else {
return fmt.Errorf("key must only consist of A-Za-z0-9_-")
}
}
func setDefaults() {
viper.SetDefault("database", defaultDatabase)
viper.SetDefault("oauth-host", defaultOAuthHost)
// Always configure the dump backend as a default service
viper.SetDefault("service.dump.backend", "dump")
}
func getConfigDir() string {
return filepath.Dir(viper.ConfigFileUsed())
}