-
Notifications
You must be signed in to change notification settings - Fork 0
/
config.go
63 lines (52 loc) · 1.04 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
package main
import (
"errors"
"io/ioutil"
"os"
"path/filepath"
"runtime"
"strings"
)
const ConfigFileName = ".gist"
type Config struct {
Token string
file string
}
func NewConfig() *Config {
c := &Config{}
c.Load()
return c
}
func (c *Config) Update(Token string) error {
c.Token = strings.TrimSpace(Token)
return ioutil.WriteFile(c.file, []byte(c.Token), 0644)
}
func (c *Config) Load() {
c.file, _ = c.resolvePath(ConfigFileName)
apikey, _ := ioutil.ReadFile(c.file)
if len(apikey) > 0 {
c.Token = strings.TrimSpace(string(apikey))
}
}
func (c *Config) homeDir() (string, error) {
var dir string
if runtime.GOOS == "windows" {
dir = os.Getenv("USERPROFILE")
if dir == "" {
dir = os.Getenv("HOMEDRIVE") + os.Getenv("HOMEPATH")
}
} else {
dir = os.Getenv("HOME")
}
if dir == "" {
return dir, errors.New("Home not found")
}
return dir, nil
}
func (c *Config) resolvePath(argPath string) (string, error) {
homeDir, err := c.homeDir()
if err != nil {
return "", err
}
return filepath.Join(homeDir, argPath), nil
}