refactor-for-testability (#3)
Co-authored-by: jdl <jdl@desktop> Co-authored-by: jdl <jdl@crumpington.com> Reviewed-on: #3
This commit is contained in:
90
peer/files.go
Normal file
90
peer/files.go
Normal file
@@ -0,0 +1,90 @@
|
||||
package peer
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"log"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"vppn/m"
|
||||
)
|
||||
|
||||
type localConfig struct {
|
||||
m.PeerConfig
|
||||
PubKey []byte
|
||||
PrivKey []byte
|
||||
PubSignKey []byte
|
||||
PrivSignKey []byte
|
||||
}
|
||||
|
||||
func configDir(netName string) string {
|
||||
d, err := os.UserHomeDir()
|
||||
if err != nil {
|
||||
log.Fatalf("Failed to get user home directory: %v", err)
|
||||
}
|
||||
return filepath.Join(d, ".vppn", netName)
|
||||
}
|
||||
|
||||
func peerConfigPath(netName string) string {
|
||||
return filepath.Join(configDir(netName), "peer-config.json")
|
||||
}
|
||||
|
||||
func peerStatePath(netName string) string {
|
||||
return filepath.Join(configDir(netName), "peer-state.json")
|
||||
}
|
||||
|
||||
func storeJson(x any, outPath string) error {
|
||||
outDir := filepath.Dir(outPath)
|
||||
_ = os.MkdirAll(outDir, 0700)
|
||||
|
||||
tmpPath := outPath + ".tmp"
|
||||
buf, err := json.Marshal(x)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
f, err := os.Create(tmpPath)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if _, err := f.Write(buf); err != nil {
|
||||
f.Close()
|
||||
return err
|
||||
}
|
||||
|
||||
if err := f.Sync(); err != nil {
|
||||
f.Close()
|
||||
return err
|
||||
}
|
||||
|
||||
if err := f.Close(); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return os.Rename(tmpPath, outPath)
|
||||
}
|
||||
|
||||
func storePeerConfig(netName string, pc localConfig) error {
|
||||
return storeJson(pc, peerConfigPath(netName))
|
||||
}
|
||||
|
||||
func storeNetworkState(netName string, ps m.NetworkState) error {
|
||||
return storeJson(ps, peerStatePath(netName))
|
||||
}
|
||||
|
||||
func loadJson(dataPath string, ptr any) error {
|
||||
data, err := os.ReadFile(dataPath)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return json.Unmarshal(data, ptr)
|
||||
}
|
||||
|
||||
func loadPeerConfig(netName string) (pc localConfig, err error) {
|
||||
return pc, loadJson(peerConfigPath(netName), &pc)
|
||||
}
|
||||
|
||||
func loadNetworkState(netName string) (ps m.NetworkState, err error) {
|
||||
return ps, loadJson(peerStatePath(netName), &ps)
|
||||
}
|
||||
Reference in New Issue
Block a user