-
Notifications
You must be signed in to change notification settings - Fork 0
/
profile_store.go
95 lines (83 loc) · 2.35 KB
/
profile_store.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
package keep
import (
"encoding/json"
"fmt"
"io/ioutil"
"os"
"path/filepath"
)
const (
secringDefault = "$HOME/.gnupg/secring.gpg"
pubringDefault = "$HOME/.gnupg/pubring.gpg"
passwordDirDefault = "$HOME/.keep/passwords"
)
// Profile represents the information that can be persited to disk of a Config.
type Profile struct {
Name string
SecringDir string
PubringDir string
AccountDir string
RecipientKeyIds string
SignerKeyID string
}
// DefaultProfile returns the a Profile with customized information for a user.
func DefaultProfile() *Profile {
gpgkey := os.Getenv("GPGKEY")
pubring := os.ExpandEnv(pubringDefault)
secring := os.ExpandEnv(secringDefault)
accountDir := os.ExpandEnv(passwordDirDefault)
return &Profile{
Name: "default",
SecringDir: secring,
PubringDir: pubring,
AccountDir: accountDir,
RecipientKeyIds: gpgkey,
SignerKeyID: gpgkey,
}
}
// ProfileStore is type alias that we used to store Profile in the configuration file.
type ProfileStore []Profile
// GetConfigPaths returns the paths for the contifuration file and the accountDir.
func GetConfigPaths() (string, string) {
accountDir := os.ExpandEnv(passwordDirDefault)
return filepath.Join(filepath.Dir(accountDir), "keep.conf"), accountDir
}
func initProfileStore() (ProfileStore, error) {
configFile, accountDir := GetConfigPaths()
if _, err := os.Stat(configFile); !os.IsNotExist(err) {
return nil, fmt.Errorf("Do nothing because config file already exsit here : %s", configFile)
}
err := os.MkdirAll(accountDir, 0700)
if err != nil {
return nil, err
}
profile := DefaultProfile()
store := make(ProfileStore, 0)
store = append(store, *profile)
b, err := json.MarshalIndent(store, "", "\t")
if err != nil {
return nil, err
}
err = ioutil.WriteFile(configFile, b, 0700)
if err != nil {
return nil, err
}
return store, nil
}
// LoadProfileStore returns the ProfileStore with the information found in the configuration file.
func LoadProfileStore() (ProfileStore, error) {
configFile, _ := GetConfigPaths()
if _, err := os.Stat(configFile); os.IsNotExist(err) {
return initProfileStore()
}
store := make(ProfileStore, 0)
b, err := ioutil.ReadFile(configFile)
if err != nil {
return nil, err
}
err = json.Unmarshal(b, &store)
if err != nil {
return nil, err
}
return store, nil
}