Implemented service delete command

This commit is contained in:
Philipp Wolfer 2023-12-08 17:27:04 +01:00
parent 7f2db58462
commit 543a9c666d
No known key found for this signature in database
GPG key ID: 8FDF744D4919943B
5 changed files with 123 additions and 4 deletions

View file

@ -16,12 +16,15 @@ Scotty. If not, see <https://www.gnu.org/licenses/>.
package config
import (
"errors"
"fmt"
"os"
"path"
"path/filepath"
"regexp"
"strings"
"github.com/pelletier/go-toml/v2"
"github.com/spf13/cobra"
"github.com/spf13/viper"
"go.uploadedlobster.com/scotty/internal/version"
@ -30,6 +33,7 @@ import (
const (
defaultDatabase = "scotty.sqlite3"
defaultOAuthHost = "127.0.0.1:2369"
fileMode = 0640
)
func DefaultConfigDir() string {
@ -48,7 +52,7 @@ func InitConfig(cfgFile string) error {
viper.AddConfigPath(configDir)
viper.SetConfigType("toml")
viper.SetConfigName(version.AppName)
viper.SetConfigPermissions(0640)
viper.SetConfigPermissions(fileMode)
}
setDefaults()
@ -67,6 +71,43 @@ func InitConfig(cfgFile string) error {
return viper.ReadInConfig()
}
// Write the configuration except for removedKeys
func WriteConfig(removedKeys ...string) error {
file := viper.ConfigFileUsed()
if len(file) == 0 {
return errors.New("no configuration file defined, cannot write config")
}
configMap := viper.AllSettings()
for _, key := range removedKeys {
c := configMap
ok := true
subKeys := strings.Split(key, ".")
keyLen := len(subKeys)
// Deep search the key in the config and delete the deepest key, if it exists
for i, s := range subKeys {
if i == keyLen-1 {
// This is the final key, delete it from the map
delete(c, s)
} else {
// Use the child for next iteration if it is a map
c, ok = c[s].(map[string]any)
if !ok {
// Child is not a map, can't search deeper
break
}
}
}
}
content, err := toml.Marshal(configMap)
if err != nil {
return err
}
return os.WriteFile(file, content, fileMode)
}
func DatabasePath() string {
path := viper.GetString("database")
if filepath.IsAbs(path) {