-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.go
109 lines (92 loc) · 2.22 KB
/
app.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 (
"context"
"os"
"path"
"github.com/spf13/afero"
"github.com/srvc/fail/v4"
)
const appName = "esa"
type DiApp struct {
Config *Config
Client *Client
PostService *PostService
ConfigManager *ConfigManager
Editor Editor
}
func NewDiApp(ctx context.Context, fs afero.Fs) (*DiApp, error) {
configDirPath, err := getConfigDirPath()
if err != nil {
return nil, fail.Wrap(err)
}
cacheDirPath, err := getCacheDirPath()
if err != nil {
return nil, fail.Wrap(err)
}
defaultEditor := os.Getenv("EDITOR")
if defaultEditor == "" {
defaultEditor = "vim"
}
configManager := NewConfigManager(fs, configDirPath, NewEditor(defaultEditor))
cfg, err := configManager.Load(ctx)
if err != nil {
return nil, fail.Wrap(err)
}
editor := NewEditor(cfg.Editor)
client, err := NewClient(cfg.AccessToken, cfg.TeamName)
if err != nil {
return nil, fail.Wrap(err)
}
postSrv := NewPostService(fs, client, cacheDirPath, editor)
return &DiApp{
Config: cfg,
Client: client,
PostService: postSrv,
ConfigManager: configManager,
Editor: editor,
}, nil
}
func getConfigDirPath() (string, error) {
// ESA_CONFIG_DIR
cfgDirPath := os.Getenv("ESA_CONFIG_DIR")
if cfgDirPath != "" {
return path.Join(cfgDirPath, appName), nil
}
// XDG
cfgDirPath = os.Getenv("XDG_CONFIG_HOME")
if cfgDirPath != "" {
return path.Join(cfgDirPath, appName), nil
}
cfgDirPath = os.Getenv("HOME")
if cfgDirPath != "" {
return path.Join(cfgDirPath, ".config", appName), nil
}
// Default
cfgDirPath, err := os.UserConfigDir()
if err != nil {
return "", fail.Wrap(err)
}
return path.Join(cfgDirPath, appName), nil
}
func getCacheDirPath() (string, error) {
// ESA_CONFIG_DIR
cacheDirPath := os.Getenv("ESA_CACHE_DIR")
if cacheDirPath != "" {
return path.Join(cacheDirPath, appName), nil
}
// XDG
cacheDirPath = os.Getenv("XDG_CACHE_HOME")
if cacheDirPath != "" {
return path.Join(cacheDirPath, appName), nil
}
cacheDirPath = os.Getenv("HOME")
if cacheDirPath != "" {
return path.Join(cacheDirPath, ".cache", appName), nil
}
// Default
cacheDirPath, err := os.UserCacheDir()
if err != nil {
return "", fail.Wrap(err)
}
return path.Join(cacheDirPath, appName), nil
}