isle/go/daemon/network/config.go

56 lines
1.4 KiB
Go

package network
import (
"errors"
"fmt"
"io/fs"
"isle/daemon/daecommon"
"isle/jsonutil"
"isle/toolkit"
"path/filepath"
)
func configPath(networkStateDir toolkit.Dir) string {
return filepath.Join(networkStateDir.Path, "config.json")
}
// loadConfig loads the stored NetworkConfig and returns it, or returns the
// default NetworkConfig if none is stored.
func loadConfig(networkStateDir toolkit.Dir) (daecommon.NetworkConfig, error) {
path := configPath(networkStateDir)
var config daecommon.NetworkConfig
if err := jsonutil.LoadFile(&config, path); errors.Is(err, fs.ErrNotExist) {
return daecommon.NewNetworkConfig(nil), nil
} else if err != nil {
return daecommon.NetworkConfig{}, fmt.Errorf(
"loading %q: %w", path, err,
)
}
return config, nil
}
// loadStoreConfig writes the given NetworkConfig to the networkStateDir if the
// config is non-nil. If the config is nil then a config is read from
// networkStateDir, returning the zero value if no config was previously
// stored.
func loadStoreConfig(
networkStateDir toolkit.Dir, config *daecommon.NetworkConfig,
) (
daecommon.NetworkConfig, error,
) {
if config == nil {
return loadConfig(networkStateDir)
}
path := configPath(networkStateDir)
if err := jsonutil.WriteFile(*config, path, 0600); err != nil {
return daecommon.NetworkConfig{}, fmt.Errorf(
"writing to %q: %w", path, err,
)
}
return *config, nil
}