-
-
Notifications
You must be signed in to change notification settings - Fork 580
/
file_storage.go
86 lines (65 loc) · 1.56 KB
/
file_storage.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
package storage
import (
"encoding/gob"
"os"
"github.com/ddev/ddev/pkg/config/remoteconfig/internal"
"github.com/ddev/ddev/pkg/config/remoteconfig/types"
)
func NewFileStorage(fileName string) types.RemoteConfigStorage {
return &fileStorage{
fileName: fileName,
loaded: false,
}
}
type fileStorage struct {
fileName string
loaded bool
data fileStorageData
}
// fileStorageData is the structure used for the file.
type fileStorageData struct {
RemoteConfig internal.RemoteConfig
}
func (s *fileStorage) Read() (remoteConfig internal.RemoteConfig, err error) {
err = s.loadData()
if err != nil {
return
}
return s.data.RemoteConfig, nil
}
func (s *fileStorage) Write(remoteConfig internal.RemoteConfig) (err error) {
s.data.RemoteConfig = remoteConfig
err = s.saveData()
return
}
// loadData reads the messages from the data file.
func (s *fileStorage) loadData() error {
// The cache is read once per run time, early exit if already loaded.
if s.loaded {
return nil
}
file, err := os.Open(s.fileName)
// If the file does not exists, early exit.
if err != nil {
s.loaded = true
return nil
}
defer file.Close()
decoder := gob.NewDecoder(file)
err = decoder.Decode(&s.data)
// If the file was properly read, mark the cache as loaded.
if err == nil {
s.loaded = true
}
return err
}
// saveData writes the messages to the message file.
func (s *fileStorage) saveData() error {
file, err := os.Create(s.fileName)
if err == nil {
defer file.Close()
encoder := gob.NewEncoder(file)
err = encoder.Encode(&s.data)
}
return err
}