This repository has been archived by the owner on Nov 22, 2022. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 161
/
config.go
370 lines (316 loc) · 8.52 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
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
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
package config
import (
"errors"
"fmt"
"io/ioutil"
"log"
"os"
"os/user"
"path/filepath"
"strings"
"github.com/profclems/glab/internal/manip"
"github.com/google/renameio"
"github.com/logrusorgru/aurora"
"github.com/spf13/cobra"
"github.com/tcnksm/go-gitconfig"
)
var (
// UseGlobalConfig : use the global configuration file
UseGlobalConfig bool
globalPathDir = ""
configFileFileParentDir = ".glab-cli"
configFile = configFileFileParentDir + "/config/.env"
globalConfigFile = configFile
aliasFile = configFileFileParentDir + "/config/aliases.format"
)
func getOldGlobalConfigDir() string {
usr, err := user.Current()
if err != nil {
log.Fatal(err)
}
return filepath.Join(usr.HomeDir, ".glab-cli", "config")
}
func getXdgGlobalConfigDir() string {
cfgDir := os.Getenv("XDG_CONFIG_HOME")
if cfgDir == "" {
homeDir := os.Getenv("HOME")
if homeDir == "" {
if usr, err := user.Current(); err == nil {
homeDir = usr.HomeDir
}
}
if homeDir != "" {
cfgDir = filepath.Join(homeDir, ".config/")
}
}
if cfgDir == "" {
log.Fatal("Could not determine XDG_CONFIG_HOME directory.")
}
return filepath.Join(cfgDir, "glab-cli")
}
func migrateGlobalConfigDir() {
// check if xdg directory exists, bail if so.
newConfigDir := getXdgGlobalConfigDir()
if CheckPathExists(newConfigDir) {
return
}
// check if old config dir exists, or there's nothing to migrate.
oldConfigDir := getOldGlobalConfigDir()
if !CheckPathExists(oldConfigDir) {
return
}
// do the migration
log.Println("Migrating config dir to XDG_CONFIG_HOME.")
// First make sure parent directory exists
if !CheckPathExists(filepath.Join(newConfigDir, "..")) {
if err := os.MkdirAll(filepath.Join(newConfigDir, ".."), os.ModePerm); err != nil {
fmt.Println("Failed to create new parent config dir:", err)
}
}
if err := os.Rename(oldConfigDir, newConfigDir); err != nil {
fmt.Println("Failed to move config dir:", err)
}
// cleanup: remove parent directory tree of oldConfigDir if empty
_ = os.Remove(filepath.Join(oldConfigDir, ".."))
}
func SetGlobalPathDir() {
migrateGlobalConfigDir()
globalPathDir = getXdgGlobalConfigDir()
if !CheckPathExists(globalPathDir) && CheckPathExists(getOldGlobalConfigDir()) {
// Migration apparently failed, use old dir.
globalPathDir = getOldGlobalConfigDir()
}
globalConfigFile = filepath.Join(globalPathDir, filepath.Base(configFile))
aliasFile = filepath.Join(globalPathDir, "aliases.format")
}
// GetEnv : returns env variable value
func GetEnv(key string) string {
if key != "" {
env := os.Getenv(key) //first get user defined variable via export
if env == "" {
env = GetKeyValueInFile(configFile, key) //Find variable in local env
if env == "NOTFOUND" || env == "OK" {
env = GetKeyValueInFile(globalConfigFile, key) //Find variable in global env
if env == "NOTFOUND" || env == "OK" {
//log.Fatal("Configuration not set for ", key)
return ""
}
}
}
return env
}
return ""
}
// SetEnv : sets env variable
func SetEnv(key, value string) {
cFile := configFile
if UseGlobalConfig {
cFile = globalConfigFile
}
defer InvalidateEnvCacheForFile(cFile)
data, err := ioutil.ReadFile(cFile)
if err != nil && !os.IsNotExist(err) {
log.Println("Failed to read/update env config:", err)
return
}
file := string(data)
temp := strings.Split(file, "\n")
newData := ""
keyExists := false
newConfig := key + "=" + (value) + "\n"
for _, item := range temp {
if item == "" {
continue
}
env := strings.Split(item, "=")
if env[0] == key {
newData += newConfig
keyExists = true
} else {
newData += item + "\n"
}
}
if !keyExists {
newData += newConfig
}
_ = os.MkdirAll(filepath.Join(cFile, ".."), 0755)
if err = renameio.WriteFile(cFile, []byte(newData), 0666); err != nil {
log.Println("Failed to update config file:", err)
return
}
if !UseGlobalConfig && !CheckFileHasLine(".gitignore", configFileFileParentDir) {
ReadAndAppend(".gitignore", configFileFileParentDir+"\n")
}
}
// SetAlias sets an alias for a command
func SetAlias(name string, command string) error {
if !CheckFileExists(aliasFile) {
aliasDir := filepath.Join(aliasFile, "..")
if !CheckPathExists(aliasDir) {
errDir := os.MkdirAll(aliasDir, 0700)
if errDir != nil {
return errDir
}
}
f, err := os.Create(aliasFile)
if err != nil {
return err
}
err = f.Close()
if err != nil {
return err
}
}
contents, err := ioutil.ReadFile(aliasFile)
if err != nil {
return err
}
lines := strings.Split(string(contents), "\n")
if len(lines) == 1 && lines[0] == "" {
lines = []string{}
}
set := false
for i, line := range lines {
aliasSplit := strings.SplitN(line, ":", 2)
if aliasSplit[0] == name {
lines[i] = name + ":" + command
set = true
break
}
}
if !set {
lines = append(lines, name+":"+command)
}
output := strings.Join(lines, "\n")
err = ioutil.WriteFile(aliasFile, []byte(output), 0644)
if err != nil {
return err
}
return nil
}
// GetAllAliases retrieves all of the aliases.
func GetAllAliases() map[string]string {
if !CheckFileExists(aliasFile) {
return nil
}
contents, err := ioutil.ReadFile(aliasFile)
if err != nil {
log.Fatalln(err)
}
lines := strings.Split(string(contents), "\n")
if len(lines) == 0 {
return nil
}
aliasMap := make(map[string]string)
for _, line := range lines {
if line != "" {
aliasSplit := strings.SplitN(line, ":", 2)
aliasMap[aliasSplit[0]] = aliasSplit[1]
}
}
return aliasMap
}
// GetAlias retrieves the command for an alias
func GetAlias(name string) string {
if !CheckFileExists(aliasFile) {
return ""
}
contents, err := ioutil.ReadFile(aliasFile)
if err != nil {
log.Fatalln(err)
}
lines := strings.Split(string(contents), "\n")
for _, line := range lines {
aliasSplit := strings.SplitN(line, ":", 2)
if aliasSplit[0] == name {
return aliasSplit[1]
}
}
return ""
}
// DeleteAlias deletes an alias
func DeleteAlias(name string) error {
if !CheckFileExists(aliasFile) {
return errors.New("No aliases are currently set")
}
contents, err := ioutil.ReadFile(aliasFile)
if err != nil {
log.Fatalln(err)
}
lines := strings.Split(string(contents), "\n")
if len(lines) == 1 && lines[0] == "" {
lines = []string{}
}
deleted := false
for i, line := range lines {
aliasSplit := strings.SplitN(line, ":", 2)
if aliasSplit[0] == name {
copy(lines[i:], lines[i+1:])
lines[len(lines)-1] = ""
lines = lines[:len(lines)-1]
deleted = true
break
}
}
if !deleted {
return errors.New("That alias does not exist")
}
output := strings.Join(lines, "\n")
err = ioutil.WriteFile(aliasFile, []byte(output), 0644)
if err != nil {
log.Fatalln(err)
}
return nil
}
func GetRepo() string {
gitRemoteVar, err := gitconfig.Entire("remote." + GetEnv("GIT_REMOTE_URL_VAR") + ".url")
if err != nil {
log.Fatal("Could not find remote url for gitlab. Run git config init")
}
repoBaseUrl := strings.Trim(GetEnv("GITLAB_URI"), "/ ")
repoBaseUrl = strings.TrimPrefix(repoBaseUrl, "https://")
repoBaseUrl = strings.TrimPrefix(repoBaseUrl, "http://")
repo := strings.TrimSuffix(gitRemoteVar, ".git")
repo = strings.TrimPrefix(repo, repoBaseUrl)
repo = strings.TrimPrefix(repo, "https://"+repoBaseUrl)
repo = strings.TrimPrefix(repo, "http://"+repoBaseUrl)
repo = strings.TrimPrefix(repo, "git@"+repoBaseUrl+":")
return strings.Trim(repo, "/")
}
func readAndSetEnv(question, env string) string {
envDefVal := GetEnv(env)
envVal := manip.AskQuestionWithInput(question, envDefVal, false)
SetEnv(env, envVal)
return envVal
}
func Set(cmd *cobra.Command, args []string) {
var isUpdated bool
if b, _ := cmd.Flags().GetBool("global"); b {
UseGlobalConfig = true
}
if b, _ := cmd.Flags().GetString("token"); b != "" {
SetEnv("GITLAB_TOKEN", b)
isUpdated = true
}
if b, _ := cmd.Flags().GetString("url"); b != "" {
SetEnv("GITLAB_URI", b)
isUpdated = true
}
if b, _ := cmd.Flags().GetString("remote-var"); b != "" {
SetEnv("GIT_REMOTE_URL_VAR", b)
isUpdated = true
}
if b, _ := cmd.Flags().GetString("pid"); b != "" {
SetEnv("GITLAB_PROJECT_ID", b)
isUpdated = true
}
if !isUpdated {
readAndSetEnv(fmt.Sprintf("Enter default Gitlab Host (Current Value: %s): ", GetEnv("GITLAB_URI")), "GITLAB_URI")
readAndSetEnv("Enter default Gitlab Token: ", "GITLAB_TOKEN")
readAndSetEnv(fmt.Sprintf("Enter Git remote url variable (Current Value: %s): ", GetEnv("GIT_REMOTE_URL_VAR")), "GIT_REMOTE_URL_VAR")
isUpdated = true
}
if isUpdated {
fmt.Println(aurora.Green("Environment variable(s) updated"))
}
}