hudly/config/config.go
2024-10-26 21:41:05 -06:00

115 lines
2.6 KiB
Go

package config
import (
"encoding/json"
"fmt"
"io/ioutil"
"os"
"path"
"runtime"
)
type FileConfig struct {
Path string
Name string
Type string
}
func GetDefaultConfigPath() string {
var filePath string
switch os_name := runtime.GOOS; os_name {
case "windows":
appData := os.Getenv("APPDATA")
filePath = path.Join(appData, "hudly", ".conf")
case "darwin":
homePath := os.Getenv("HOME")
filePath = path.Join(homePath, "Library", "Application Support", "hudly", ".conf")
case "linux":
homePath := os.Getenv("HOME")
filePath = path.Join(homePath, ".config", "hudly", ".conf")
default:
panic("unknown operating system")
}
return filePath
}
type Config struct {
ConfigVersion int
PlayerName string
PlayerUUID string
AltNames []string
AltUUIDs []string
AppFeaturesConfig AppFeaturesConfig
}
type AppFeaturesConfig struct {
CheckGuildChat bool
CheckOfficerChat bool
CheckPartyChat bool
CheckPartyList bool
CheckLobbyMessages bool
CheckQueueMessages bool
CheckInGameMessages bool
}
func GetDefaultConfig() *Config {
return &Config{
ConfigVersion: 1,
PlayerName: "",
PlayerUUID: "",
AltNames: []string{},
AltUUIDs: []string{},
AppFeaturesConfig: AppFeaturesConfig{
CheckGuildChat: true,
CheckOfficerChat: false,
CheckPartyChat: true,
CheckPartyList: true,
CheckLobbyMessages: false,
CheckQueueMessages: true,
CheckInGameMessages: true,
},
}
}
// SaveConfig saves the given config struct to the file in JSON format
func SaveConfig(config *Config, filePath string) error {
// Convert the config struct to JSON
data, err := json.MarshalIndent(config, "", " ")
if err != nil {
return fmt.Errorf("failed to serialize config: %v", err)
}
// Write the JSON data to a file
err = ioutil.WriteFile(filePath, data, 0644)
if err != nil {
return fmt.Errorf("failed to write config to file: %v", err)
}
return nil
}
// LoadConfig loads the config from the given file path
func LoadConfig(filePath string) (*Config, error) {
// Check if the file exists
if _, err := os.Stat(filePath); os.IsNotExist(err) {
return nil, fmt.Errorf("config file does not exist: %s", filePath)
}
// Read the file content
data, err := ioutil.ReadFile(filePath)
if err != nil {
return nil, fmt.Errorf("failed to read config file: %v", err)
}
// Create a Config object
config := &Config{}
// Deserialize the JSON data into the Config object
err = json.Unmarshal(data, config)
if err != nil {
return nil, fmt.Errorf("failed to deserialize config: %v", err)
}
return config, nil
}