1
0
Fork 0
mirror of https://github.com/diamondburned/cchat-gtk.git synced 2024-12-23 12:46:45 +00:00
cchat-gtk/internal/ui/config/config.go

115 lines
2.3 KiB
Go
Raw Normal View History

2020-06-20 04:40:34 +00:00
// Package config provides the repository for configuration and preferences.
package config
import (
2020-06-28 23:01:08 +00:00
"encoding/json"
"sort"
2020-06-28 23:01:08 +00:00
"github.com/diamondburned/cchat-gtk/internal/log"
"github.com/pkg/errors"
)
const ConfigFile = "config.json"
2020-06-20 04:40:34 +00:00
// List of config sections.
type Section uint8
const (
Appearance Section = iota
sectionLen
)
func (s Section) String() string {
switch s {
case Appearance:
return "Appearance"
default:
return "???"
}
}
2020-06-28 23:01:08 +00:00
type SectionEntries map[string]EntryValue
// UnmarshalJSON ignores all JSON entries with unknown keys.
func (s SectionEntries) UnmarshalJSON(b []byte) error {
var entries map[string]json.RawMessage
if err := json.Unmarshal(b, &entries); err != nil {
return err
}
for k, entry := range s {
v, ok := entries[k]
if ok {
if err := entry.UnmarshalJSON(v); err != nil {
// Non-fatal error.
log.Error(errors.Wrapf(err, "Failed to unmarshal key %q", k))
}
}
}
return nil
}
var sections = [sectionLen]SectionEntries{}
2020-06-20 04:40:34 +00:00
2020-06-28 23:01:08 +00:00
func AppearanceAdd(name string, value EntryValue) {
sc := sections[Appearance]
if sc == nil {
sc = make(SectionEntries, 1)
sections[Appearance] = sc
}
sc[name] = value
2020-06-20 04:40:34 +00:00
}
type Entry struct {
Name string
Value EntryValue
}
2020-06-28 23:01:08 +00:00
func Sections() (sects [sectionLen][]Entry) {
for i, section := range sections {
var sect = make([]Entry, 0, len(section))
for k, v := range section {
sect = append(sect, Entry{k, v})
}
sort.Slice(sect, func(i, j int) bool {
return sect[i].Name < sect[j].Name
})
sects[i] = sect
}
return
2020-06-20 04:40:34 +00:00
}
// Save the global config.
func Save() error {
2020-06-28 23:01:08 +00:00
return MarshalToFile(ConfigFile, sections)
}
// Restore the global config. IsNotExist is not an error and will not be
// logged.
func Restore() {
if err := UnmarshalFromFile(ConfigFile, &sections); err != nil {
log.Error(errors.Wrap(err, "Failed to unmarshal main config.json"))
}
log.Printlnf("To restore: %#v", toRestore)
for path, v := range toRestore {
if err := UnmarshalFromFile(path, v); err != nil {
log.Error(errors.Wrapf(err, "Failed to unmarshal %s", path))
}
}
}
var toRestore = map[string]interface{}{}
// RegisterConfig adds the config filename into the registry of value pointers
// to unmarshal configs to.
func RegisterConfig(filename string, jsonValue interface{}) {
toRestore[filename] = jsonValue
}