-
Notifications
You must be signed in to change notification settings - Fork 25
Expand file tree
/
Copy pathstate.go
More file actions
77 lines (64 loc) · 1.6 KB
/
state.go
File metadata and controls
77 lines (64 loc) · 1.6 KB
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
package client
import (
"encoding/json"
"os"
"path/filepath"
"time"
"github.com/DefangLabs/defang/src/pkg/types"
"github.com/google/uuid"
)
var (
stateDir, _ = userStateDir()
// StateDir is the directory where the state file is stored
StateDir = filepath.Join(stateDir, "defang")
statePath = filepath.Join(StateDir, "state.json")
state State
)
type State struct {
AnonID string
TermsAcceptedAt time.Time
Tenant types.TenantNameOrID
}
func initState(path string) State {
state := State{AnonID: uuid.NewString()}
if bytes, err := os.ReadFile(path); err == nil {
json.Unmarshal(bytes, &state)
} else { // could be not found or path error
state.write(path)
}
return state
}
func (state State) write(path string) error {
if bytes, err := json.MarshalIndent(state, "", " "); err != nil {
return err
} else {
os.MkdirAll(StateDir, 0700)
return os.WriteFile(path, bytes, 0600)
}
}
func (state *State) acceptTerms() error {
state.TermsAcceptedAt = time.Now()
return state.write(statePath)
}
func (state State) termsAccepted() bool {
// Consider the terms accepted if the timestamp is within the last 24 hours
return time.Since(state.TermsAcceptedAt) < 24*time.Hour
}
func GetAnonID() string {
state = initState(statePath)
return state.AnonID
}
func AcceptTerms() error {
return state.acceptTerms()
}
func TermsAccepted() bool {
return state.termsAccepted()
}
func SetCurrentTenant(tenant types.TenantNameOrID) error {
state.Tenant = tenant
return state.write(statePath)
}
func GetCurrentTenant() types.TenantNameOrID {
state = initState(statePath)
return state.Tenant
}