Skip to content

Commit

Permalink
Add helpers for saving the config (#160)
Browse files Browse the repository at this point in the history
  • Loading branch information
cmmarslender authored Sep 24, 2024
1 parent 8cbd751 commit 228b312
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 1 deletion.
2 changes: 2 additions & 0 deletions pkg/config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"`
Expand Down
32 changes: 31 additions & 1 deletion pkg/config/load.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package config
import (
// Need to embed the default config into the library
_ "embed"
"errors"
"fmt"
"os"
"path/filepath"
Expand Down Expand Up @@ -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
Expand All @@ -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 {
Expand Down

0 comments on commit 228b312

Please sign in to comment.