erm/app/darktile/config/config.go

93 lines
1.9 KiB
Go
Raw Normal View History

2021-07-30 22:29:20 +00:00
package config
import (
"fmt"
"io/ioutil"
"os"
"path"
2023-01-16 02:07:04 +00:00
"sigs.k8s.io/yaml"
2021-07-30 22:29:20 +00:00
)
type Config struct {
2023-01-16 02:07:04 +00:00
Opacity float64 `json:"opacity"`
Font Font `json:"font"`
Cursor Cursor `json:"cursor"`
2023-01-16 06:32:17 +00:00
Vsync bool `json:"vsync"`
2021-07-30 22:29:20 +00:00
}
type Font struct {
2023-01-16 02:07:04 +00:00
Family string `json:"family"`
2023-01-16 06:03:38 +00:00
Style string `json:"style"`
2023-01-16 02:07:04 +00:00
Size float64 `json:"size"`
DPI float64 `json:"dpi"`
Ligatures bool `json:"ligatures"`
}
type Cursor struct {
2023-01-16 02:07:04 +00:00
Image string `json:"image"`
2021-07-30 22:29:20 +00:00
}
type ErrorFileNotFound struct {
2023-01-16 02:07:04 +00:00
Path string `json:"path"`
2021-07-30 22:29:20 +00:00
}
func (e *ErrorFileNotFound) Error() string {
return fmt.Sprintf("file was not found at '%s'", e.Path)
}
func getConfigPath() (string, error) {
return getPath("config.yaml")
}
func getPath(filename string) (string, error) {
baseDir, err := os.UserConfigDir()
if err != nil {
return "", fmt.Errorf("config directory missing: %w", err)
}
return path.Join(baseDir, "darktile", filename), nil
}
func LoadConfig() (*Config, error) {
configPath, err := getConfigPath()
if err != nil {
return nil, fmt.Errorf("failed to locate config path: %w", err)
}
if _, err := os.Stat(configPath); os.IsNotExist(err) {
return nil, &ErrorFileNotFound{Path: configPath}
}
configData, err := ioutil.ReadFile(configPath)
if err != nil {
return nil, fmt.Errorf("failed to read config file at '%s': %w", configPath, err)
}
config := defaultConfig
if err := yaml.Unmarshal(configData, &config); err != nil {
return nil, fmt.Errorf("invalid config file at '%s': %w", configPath, err)
}
return &config, nil
}
func (c *Config) Save() (string, error) {
configPath, err := getConfigPath()
if err != nil {
return "", fmt.Errorf("failed to locate config path: %w", err)
}
if err := os.MkdirAll(path.Dir(configPath), 0700); err != nil {
return "", err
}
data, err := yaml.Marshal(c)
if err != nil {
return "", err
}
return configPath, ioutil.WriteFile(configPath, data, 0600)
}