summaryrefslogtreecommitdiffstats
path: root/cmd/config.go
blob: 56745ad777ada9b73cab7f140e681a38d03e896a (plain)
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
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
package cmd

import (
	"bytes"
	"fmt"
	"io/ioutil"
	"os"
	"path/filepath"

	"strings"

	"github.com/Phantas0s/devdash/internal"
	"github.com/adrg/xdg"
	"github.com/spf13/viper"
)

const (
	// keys
	kQuit      = "C-c"
	kHotReload = "C-r"
	kEdit      = "C-e"
)

type config struct {
	General  General   `mapstructure:"general"`
	Projects []Project `mapstructure:"projects"`
}

type General struct {
	Keys    map[string]string `mapstructure:"keys"`
	Refresh int64             `mapstructure:"refresh"`
	Editor  string            `mapstructure:"editor"`
}

// RefreshTime return the duration before refreshing the data of all widgets, in seconds.
func (c config) RefreshTime() int64 {
	if c.General.Refresh == 0 {
		return 60
	}

	return c.General.Refresh
}

type Project struct {
	Name        string                       `mapstructure:"name"`
	NameOptions map[string]string            `mapstructure:"name_options"`
	Services    Services                     `mapstructure:"services"`
	Themes      map[string]map[string]string `mapstructure:"themes"`
	Widgets     []Row                        `mapstructure:"widgets"`
}

// Row is constitued of columns
type Row struct {
	Row []Column `mapstructure:"row"`
}

// Col is constitued of widgets
type Column struct {
	Col []Widgets `mapstructure:"col"`
}

type Widgets struct {
	Size     string            `mapstructure:"size"`
	Elements []internal.Widget `mapstructure:"elements"`
}

type Services struct {
	GoogleAnalytics     GoogleAnalytics `mapstructure:"google_analytics"`
	GoogleSearchConsole SearchConsole   `mapstructure:"google_search_console"`
	Monitor             Monitor         `mapstructure:"monitor"`
	Github              Github          `mapstructure:"github"`
	TravisCI            TravisCI        `mapstructure:"travis"`
	Feedly              Feedly          `mapstructure:"feedly"`
	Git                 Git             `mapstructure:"git"`
	RemoteHost          RemoteHost      `mapstructure:"remote_host"`
	Localhost           RemoteHost      `mapstructure:"local_host"`
}

type GoogleAnalytics struct {
	Keyfile string `mapstructure:"keyfile"`
	ViewID  string `mapstructure:"view_id"`
}

type SearchConsole struct {
	Keyfile string `mapstructure:"keyfile"`
	Address string `mapstructure:"address"`
}

type Monitor struct {
	Address string `mapstructure:"address"`
}

type Github struct {
	Token      string `mapstructure:"token"`
	Owner      string `mapstructure:"owner"`
	Repository string `mapstructure:"repository"`
}

type TravisCI struct {
	Token string `mapstructure:"token"`
}

type Feedly struct {
	Address string `mapstructure:"address"`
}

type RemoteHost struct {
	Username string `mapstructure:"username"`
	Address  string `mapstructure:"address"`
}

type Git struct {
	Path string `mapstructure:"path"`
}

func (g GoogleAnalytics) empty() bool {
	return g == GoogleAnalytics{}
}

func (m Monitor) empty() bool {
	return m == Monitor{}
}
func (s SearchConsole) empty() bool {
	return s == SearchConsole{}
}

func (g Github) empty() bool {
	return g == Github{}
}

func (t TravisCI) empty() bool {
	return t == TravisCI{}
}

func (f Feedly) empty() bool {
	return f == Feedly{}
}

func (g Git) empty() bool {
	return g == Git{}
}

func (g RemoteHost) empty() bool {
	return g == RemoteHost{}
}

// OrderWidgets add the widgets to a three dimensional slice.
// First dimension: index of the rows (ir or indexRows).
// Second dimension: index of the columns (ic or indexColumn).
// Third dimension: index of the widget.
func (p Project) OrderWidgets() ([][][]internal.Widget, [][]string) {
	rows := make([][][]internal.Widget, len(p.Widgets))
	sizes := make([][]string, len(p.Widgets))
	for ir, r := range p.Widgets {
		for ic, c := range r.Row {
			rows[ir] = append(rows[ir], []internal.Widget{}) // add columns to rows
			for _, ws := range c.Col {
				// keep sizes of columns and good order of widgets in a separate slice
				sizes[ir] = append(sizes[ir], ws.Size)

				// add widgets to columns
				rows[ir][ic] = append(rows[ir][ic], ws.Elements...)
			}
		}
	}

	return rows, sizes
}

func dashPath() string {
	return filepath.Join(xdg.ConfigHome, "devdash")
}

// Map config and return it with the config path
func mapConfig(cfgFile string) (config, string) {
	if cfgFile == "" {
		cfgFile = createConfig(dashPath(), "default.yml", defaultConfig())
	}

	// viper.AddConfigPath(home)
	viper.AddConfigPath(".")
	viper.AddConfigPath(dashPath())

	viper.SetConfigName(removeExt(cfgFile))
	err := viper.ReadInConfig()
	if err != nil {
		tryReadFile(cfgFile)
	}

	var cfg config
	if err := viper.Unmarshal(&cfg); err != nil {
		panic(err)
	}

	prefix := "DEVDASH"
	for k, _ := range cfg.Projects {
		if cfg.Projects[k].Services.GoogleAnalytics.Keyfile == "" {
			cfg.Projects[k].Services.GoogleAnalytics.Keyfile = os.Getenv(prefix + "_GA_KEYFILE")
		}

		if cfg.Projects[k].Services.GoogleSearchConsole.Keyfile == "" {
			cfg.Projects[k].Services.GoogleSearchConsole.Keyfile = os.Getenv(prefix + "_GSC_KEYFILE")
		}

		if cfg.Projects[k].Services.Github.Token == "" {
			cfg.Projects[k].Services.Github.Token = os.Getenv(prefix + "_GITHUB_TOKEN")
		}
	}

	return cfg, viper.ConfigFileUsed()
}

func removeExt(filepath string) string {
	ext := []string{".json", ".yml", ".yaml"}
	for _, v := range ext {
		filepath = strings.Replace(filepath, v, "", -1)
	}

	return filepath
}

func createConfig(path string, filename string, template string) string {
	if _, err := os.Stat(path); os.IsNotExist(err) {
		os.MkdirAll(path, 0755)
	}

	f := filepath.Join(path, filename)
	if _, err := os.Stat(f); os.IsNotExist(err) {
		file, _ := os.Create(f)
		defer file.Close()

		if file != nil {
			_, err := file.Write([]byte(template))
			if err != nil {
				panic(err)
			}
		}
	}

	return f
}

func tryReadFile(cfgFile string) {
	if _, err := os.Stat(cfgFile); os.IsNotExist(err) {
		panic(fmt.Errorf("config %s doesnt exists", cfgFile))
	}

	f, err := ioutil.ReadFile(cfgFile)
	if err != nil {
		panic(fmt.Errorf("could not read file %s data", cfgFile))
	}

	viper.SetConfigType(strings.Trim(filepath.Ext(cfgFile), "."))
	err = viper.ReadConfig(bytes.NewBuffer(f))
	if err != nil {
		panic(fmt.Errorf("could not read config %s data", string(f)))
	}
}

// Keyboard events
func (c config) KQuit() string {
	if ok := c.General.Keys["quit"]; ok != "" {
		return c.General.Keys["quit"]
	}

	return kQuit
}

func (c config) KHotReload() string {
	if ok := c.General.Keys["hot_reload"];