hlctl/config/config.go

102 lines
2.0 KiB
Go

package config
import (
"errors"
"fmt"
"strconv"
"sectorinf.com/emilis/hlctl/hlcl"
"sectorinf.com/emilis/hlctl/hlcl/cmd"
)
const (
Term = "Term"
Font = "Font"
FontBold = "FontBold"
ModKey = "ModKey"
TermSpawnKey = "TermSpawnKey"
GroupCount = "GroupCount"
TagsPerGroup = "TagsPerGroup"
ActiveGroup = "ActiveGroup"
Services = "Services"
// Colors
ColorActive = "ColorActive"
ColorNormal = "ColorNormal"
ColorUrgent = "ColorUrgent"
ColorText = "ColorText"
)
const (
settingFmt = "settings.my_%s"
)
var (
ErrInvalidType = errors.New("invalid type")
)
type Setting struct {
raw string
valueType string
}
func (s Setting) String() string {
return s.raw
}
func (s Setting) Uint() (uint8, error) {
if s.valueType != "uint" {
return 0, fmt.Errorf("%s: %w", s.valueType, ErrInvalidType)
}
val, err := strconv.ParseUint(s.raw, 10, 8)
if err != nil {
panic(fmt.Sprintf(
"hc uint setting[%s] failed to parse: %s",
s.raw,
err.Error(),
))
}
return uint8(val), nil
}
func GetFocusedTag() (uint8, error) {
attr, err := hlcl.GetAttr("tags.focus.index")
if err != nil {
return 0, err
}
val, err := strconv.ParseUint(attr, 10, 8)
if err != nil {
return 0, fmt.Errorf("parsing [%s] to uint8: %w", attr, err)
}
return uint8(val), nil
}
func Get(name string) (Setting, error) {
attrPath := fmt.Sprintf(settingFmt, name)
attr, err := hlcl.GetAttr(attrPath)
if err != nil {
return Setting{}, err
}
attrType, err := hlcl.AttrType(attrPath)
if err != nil {
// Default to string, silently
attrType = "string"
}
return Setting{
raw: attr,
valueType: attrType,
}, nil
}
func Set(name string, value string) error {
return hlcl.SetAttr(fmt.Sprintf(settingFmt, name), value)
}
func New(name string, value string, attrType cmd.AttributeType) error {
if _, err := Get(name); err == nil {
// Already exists, just set value
return Set(name, value)
}
return hlcl.NewAttr(fmt.Sprintf(settingFmt, name), value, attrType)
}