-
Notifications
You must be signed in to change notification settings - Fork 4
/
config.go
109 lines (97 loc) · 2.22 KB
/
config.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
107
108
109
package main
import (
"bufio"
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"os"
"os/user"
"path"
"strings"
)
const (
defaultConfigFilename = ".gonote.json"
defaultMarkdownOption = true
)
// Main configuration interface used to interact with configuration file.
type MainConfig interface {
Load() error
GetUserConfig() *UserConfigFile
read() error
create() error
}
type mainConfig struct {
Path string
UserCfg *UserConfigFile
}
// Structure representing user configuration file.
type UserConfigFile struct {
Email string `json:"email"`
Password string `json:"password"`
Markdown bool `json:"markdown"`
}
// Return new configation instance.
func NewConfigFile() MainConfig {
usr, _ := user.Current()
return &mainConfig{
Path: path.Join(usr.HomeDir, defaultConfigFilename),
UserCfg: &UserConfigFile{
Markdown: defaultMarkdownOption,
},
}
}
// Retrieve user configuration file.
func (c *mainConfig) GetUserConfig() *UserConfigFile {
return c.UserCfg
}
// Load settings from configutation file.
func (c *mainConfig) Load() (err error) {
new_file := false
// Check if file exists
if _, err = os.Stat(c.Path); err != nil {
new_file = true
}
if new_file {
if err = c.create(); err != nil {
return
}
} else {
if err = c.read(); err != nil {
return
}
}
return
}
// Read configuration file from disk.
func (c *mainConfig) read() (err error) {
if c.Path == "" {
return errors.New("Missing path to configuration file")
}
file, err := os.Open(c.Path)
if err != nil {
return
}
decoder := json.NewDecoder(file)
err = decoder.Decode(&c.UserCfg)
return
}
// Create new configuration file if not found
// in user directory.
func (c *mainConfig) create() (err error) {
fmt.Println("Creating new GoNote configuration file")
reader := bufio.NewReader(os.Stdin)
fmt.Println("Enter SimpleNote email:")
// TODO: Refactor it
c.UserCfg.Email, err = reader.ReadString('\n')
c.UserCfg.Email = strings.TrimSpace(c.UserCfg.Email)
fmt.Println("Enter SimpleNote password:")
c.UserCfg.Password, err = reader.ReadString('\n')
c.UserCfg.Password = strings.TrimSpace(c.UserCfg.Password)
if err != nil {
return
}
f, err := json.MarshalIndent(c.UserCfg, "", "\t")
err = ioutil.WriteFile(c.Path, f, 0751)
return
}