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

94 lines
1.7 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
}
func Save() error {
2020-06-28 23:01:08 +00:00
return MarshalToFile(ConfigFile, sections)
}
func Restore() error {
2020-06-28 23:01:08 +00:00
return UnmarshalFromFile(ConfigFile, &sections)
}