matrixbotlib/config.go

65 lines
1.5 KiB
Go

package matrixbotlib
import (
"errors"
"os"
"github.com/kelseyhightower/envconfig"
"gopkg.in/yaml.v2"
)
// MatrixClientConfig represents the config requires to log into the matrix server
type MatrixClientConfig struct {
Homeserver string `required:"true" yaml:"homeserver"`
Domain string `required:"true" yaml:"domain"`
Dimension string `yaml:"dimension"`
Username string `required:"true" yaml:"username"`
Password string `required:"true" yaml:"password"`
Statefile string `yaml:"statefile,omitempty"`
Token string `yaml:"token"`
filename string
}
// LoadMatrixClientConfig reads info from a file
func LoadMatrixClientConfig(filename string) (*MatrixClientConfig, error) {
cnf := MatrixClientConfig{}
if filename != "" {
yamlFile, err := os.ReadFile(filename)
if err == nil {
err = yaml.Unmarshal(yamlFile, &cnf)
} else {
return &cnf, err
}
if err != nil {
return &cnf, err
}
cnf.filename = filename
} else {
err := envconfig.Process("matrix", &cnf)
if err != nil {
return nil, err
}
}
return &cnf, nil
}
// WriteMatrixClientConfig saves current running config to a file
func WriteMatrixClientConfig(cnf *MatrixClientConfig) error {
if cnf.filename == "" {
return errors.New("not loaded from config file")
}
file, err := os.OpenFile(cnf.filename, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0o600)
if err != nil {
return err
}
defer file.Close()
enc := yaml.NewEncoder(file)
err = enc.Encode(cnf)
if err != nil {
return err
}
return nil
}