/* Copyright © 2023 Philipp Wolfer 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 . */ package config import ( "os" "path" "path/filepath" "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 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()) }