-
Notifications
You must be signed in to change notification settings - Fork 221
/
file.go
106 lines (85 loc) · 1.99 KB
/
file.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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
package config
import (
"bytes"
"context"
"os"
"path/filepath"
"gopkg.in/yaml.v3"
"github.com/superfly/flyctl/internal/filemu"
)
// SetAccessToken sets the value of the access token at the configuration file
// found at path.
func SetAccessToken(path, token string) error {
return set(path, map[string]interface{}{
AccessTokenFileKey: token,
})
}
// Clear clears the access token and wireguard-related keys of the configuration
// file found at path.
func Clear(path string) (err error) {
return set(path, map[string]interface{}{
AccessTokenFileKey: "",
WireGuardStateFileKey: map[string]interface{}{},
})
}
func set(path string, vals map[string]interface{}) error {
m := make(map[string]interface{})
switch err := unmarshal(path, &m); {
case err == nil, os.IsNotExist(err):
break
default:
return err
}
for k, v := range vals {
m[k] = v
}
return marshal(path, m)
}
var lockPath = filepath.Join(os.TempDir(), "flyctl.config.lock")
func unmarshal(path string, v interface{}) (err error) {
var unlock filemu.UnlockFunc
if unlock, err = filemu.RLock(context.Background(), lockPath); err != nil {
return
}
defer func() {
if e := unlock(); err == nil {
err = e
}
}()
err = unmarshalUnlocked(path, v)
return
}
func unmarshalUnlocked(path string, v interface{}) (err error) {
var f *os.File
if f, err = os.Open(path); err != nil {
return
}
defer func() {
if e := f.Close(); err == nil {
err = e
}
}()
err = yaml.NewDecoder(f).Decode(v)
return
}
func marshal(path string, v interface{}) (err error) {
var unlock filemu.UnlockFunc
if unlock, err = filemu.Lock(context.Background(), lockPath); err != nil {
return
}
defer func() {
if e := unlock(); err == nil {
err = e
}
}()
err = marshalUnlocked(path, v)
return
}
func marshalUnlocked(path string, v interface{}) (err error) {
var b bytes.Buffer
if err = yaml.NewEncoder(&b).Encode(v); err == nil {
// TODO: os.WriteFile does not flush
err = os.WriteFile(path, b.Bytes(), 0o600)
}
return
}