feed-to-muc/openConfig.go

77 lines
1.8 KiB
Go
Raw Permalink Normal View History

package main
import (
"encoding/json"
"log"
"os"
"os/user"
)
func openConfig(configFilePtr *string) configuration {
var (
configFile string
configPath string
)
if *configFilePtr != "none" {
configFile = *configFilePtr
} else {
// Get systems user config path.
osConfigDir := os.Getenv("$XDG_CONFIG_HOME")
if osConfigDir != "" {
// Create configPath if not yet existing.
configPath = osConfigDir + "/.config/feed-to-muc/"
if _, err := os.Stat(configPath); os.IsNotExist(err) {
err = os.MkdirAll(configPath, 0700)
if err != nil {
log.Fatal("Error: Can't create config path: ", err)
}
}
} else { // Get the current user.
curUser, err := user.Current()
if err != nil {
log.Fatal("Error: Can't get current user: ", err)
}
// Get home directory.
home := curUser.HomeDir
if home == "" {
log.Fatal("Error: No home directory available.")
}
// Create configPath if not yet existing.
configPath = home + "/.config/feed-to-muc/"
if _, err := os.Stat(configPath + "config.json"); os.IsNotExist(err) {
err = os.MkdirAll(configPath, 0700)
if err != nil {
log.Fatal("Error: Can't create config path: ", err)
}
}
}
configFile = configPath + "config.json"
}
// Check that config file is existing.
if _, err := os.Stat(configFile); os.IsNotExist(err) {
log.Fatal("Error: Can't find config file: ", err)
}
// Read configuration file into variable config.
file, _ := os.Open(configFile)
defer file.Close()
decoder := json.NewDecoder(file)
config := configuration{}
if err := decoder.Decode(&config); err != nil {
log.Fatal("Error: Can't decode config: ", err)
}
if _, err := os.Stat(configFile); os.IsNotExist(err) {
err = os.MkdirAll(configPath, 0700)
if err != nil {
log.Fatal("Error: Can't create config path: ", err)
}
}
return config
}