From 228b312cb71806741e0b77c680f8836542eeb437 Mon Sep 17 00:00:00 2001 From: Chris Marslender Date: Tue, 24 Sep 2024 10:39:53 -0500 Subject: [PATCH] Add helpers for saving the config (#160) --- pkg/config/config.go | 2 ++ pkg/config/load.go | 32 +++++++++++++++++++++++++++++++- 2 files changed, 33 insertions(+), 1 deletion(-) diff --git a/pkg/config/config.go b/pkg/config/config.go index 039f501..2b63992 100644 --- a/pkg/config/config.go +++ b/pkg/config/config.go @@ -8,6 +8,8 @@ import ( // ChiaConfig the chia config.yaml type ChiaConfig struct { + // Tracks where the config was loaded from so we can call Save() + configPath string ChiaRoot string `yaml:"-" json:"-"` MinMainnetKSize uint8 `yaml:"min_mainnet_k_size" json:"min_mainnet_k_size"` PingInterval uint16 `yaml:"ping_interval" json:"ping_interval"` diff --git a/pkg/config/load.go b/pkg/config/load.go index 6fa916a..6ad86a5 100644 --- a/pkg/config/load.go +++ b/pkg/config/load.go @@ -3,6 +3,7 @@ package config import ( // Need to embed the default config into the library _ "embed" + "errors" "fmt" "os" "path/filepath" @@ -37,7 +38,12 @@ func LoadConfigAtRoot(configPath, rootPath string) (*ChiaConfig, error) { return nil, err } - return commonLoad(configBytes, rootPath) + cfg, err := commonLoad(configBytes, rootPath) + if err != nil { + return nil, err + } + cfg.configPath = configPath + return cfg, nil } // LoadDefaultConfig loads the initial-config bundled in go-chia-libs @@ -64,6 +70,30 @@ func commonLoad(configBytes []byte, rootPath string) (*ChiaConfig, error) { return config, nil } +// Save saves the config at the path it was loaded from originally +func (c *ChiaConfig) Save() error { + if c.configPath == "" { + return errors.New("configPath is not set on config. Save can only be used with a config that was loaded by this library. Try SavePath(path) instead") + } + + return c.SavePath(c.configPath) +} + +// SavePath saves the config at the given path +func (c *ChiaConfig) SavePath(configPath string) error { + out, err := yaml.Marshal(c) + if err != nil { + return fmt.Errorf("error marshalling config: %w", err) + } + + err = os.WriteFile(configPath, out, 0655) + if err != nil { + return fmt.Errorf("error writing output file: %w", err) + } + + return nil +} + // GetChiaRootPath returns the root path for the chia installation func GetChiaRootPath() (string, error) { if root, ok := os.LookupEnv("CHIA_ROOT"); ok {