gmitohtml-upstream/pkg/gmitohtml/config.go

82 lines
1.4 KiB
Go
Raw Normal View History

2021-07-09 23:19:30 +02:00
package gmitohtml
2020-11-24 18:29:57 +01:00
import (
"crypto/tls"
"errors"
2020-11-27 05:43:03 +01:00
"fmt"
2020-11-24 18:29:57 +01:00
"io/ioutil"
2020-11-27 05:43:03 +01:00
"os"
"path"
2020-11-24 18:29:57 +01:00
"gopkg.in/yaml.v3"
)
type certConfig struct {
Cert string
Key string
cert tls.Certificate
}
type appConfig struct {
2020-11-27 05:43:03 +01:00
Bookmarks map[string]string
// Convert image links to images instead of normal links
ConvertImages bool
2020-11-24 18:29:57 +01:00
Certs map[string]*certConfig
}
2021-07-09 23:19:30 +02:00
var Config = &appConfig{
2020-11-27 05:43:03 +01:00
Bookmarks: make(map[string]string),
ConvertImages: false,
2020-11-24 18:29:57 +01:00
Certs: make(map[string]*certConfig),
}
2021-07-09 23:19:30 +02:00
func DefaultConfigPath() string {
2020-11-27 05:43:03 +01:00
homedir, err := os.UserHomeDir()
if err == nil && homedir != "" {
return path.Join(homedir, ".config", "gmitohtml", "config.yaml")
}
return ""
}
2021-07-09 23:19:30 +02:00
func ReadConfig(configPath string) error {
2020-11-24 18:29:57 +01:00
if configPath == "" {
return errors.New("file unspecified")
}
configData, err := ioutil.ReadFile(configPath)
if err != nil {
return err
}
var newConfig *appConfig
err = yaml.Unmarshal(configData, &newConfig)
if err != nil {
return err
}
2021-07-09 23:19:30 +02:00
Config = newConfig
2020-11-24 18:29:57 +01:00
return nil
}
2020-11-27 05:43:03 +01:00
2021-07-09 23:19:30 +02:00
func SaveConfig(configPath string) error {
Config.Bookmarks = GetBookmarks()
2020-11-27 05:43:03 +01:00
2021-07-09 23:19:30 +02:00
out, err := yaml.Marshal(Config)
2020-11-27 05:43:03 +01:00
if err != nil {
return fmt.Errorf("failed to marshal configuration: %s", err)
}
os.MkdirAll(path.Dir(configPath), 0755) // Ignore error
err = ioutil.WriteFile(configPath, out, 0644)
if err != nil {
return fmt.Errorf("failed to save configuration to %s: %s", configPath, err)
}
return nil
}