Files
go-nc-files/defaultpath.go
T

68 lines
1.6 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package goncfiles
import (
"encoding/json"
"os"
"path/filepath"
"strings"
)
// DefaultPathStore persists the Saved Default Working Folder path (User Files Root–relative).
type DefaultPathStore interface {
// GetDefault returns the stored path, or empty when none is set yet.
GetDefault() (string, error)
// SetDefault writes a User Files Root–relative Working Folder path.
SetDefault(rel string) error
}
// FileStore is the local-adapter settings JSON file.
type FileStore struct {
Path string
}
type settingsFile struct {
DefaultPath string `json:"defaultPath"`
}
// GetDefault reads the saved default; empty means the caller should use the product initial default.
func (s FileStore) GetDefault() (string, error) {
body, err := os.ReadFile(s.Path)
if err != nil {
if os.IsNotExist(err) {
return "", nil
}
return "", err
}
var sf settingsFile
if err := json.Unmarshal(body, &sf); err != nil {
return "", err
}
return strings.TrimSpace(sf.DefaultPath), nil
}
// SetDefault writes the saved Working Folder path.
func (s FileStore) SetDefault(rel string) error {
body, err := json.MarshalIndent(settingsFile{DefaultPath: rel}, "", " ")
if err != nil {
return err
}
if err := os.MkdirAll(filepath.Dir(s.Path), 0o755); err != nil {
return err
}
return os.WriteFile(s.Path, append(body, '\n'), 0o644)
}
// Memory is an in-memory DefaultPathStore for tests.
type Memory struct {
Value string
}
// GetDefault returns the in-memory value.
func (m *Memory) GetDefault() (string, error) { return m.Value, nil }
// SetDefault stores the value in memory.
func (m *Memory) SetDefault(rel string) error {
m.Value = rel
return nil
}