-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpreferences.go
More file actions
105 lines (88 loc) · 2.12 KB
/
Copy pathpreferences.go
File metadata and controls
105 lines (88 loc) · 2.12 KB
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
package main
import (
"bufio"
"encoding/json"
"fmt"
"io/ioutil"
"net/url"
"os"
)
const configFileName = ".jirb"
var cachedPrefs *Preferences = nil
func getConfigFilePath() string {
homedir, err := os.UserHomeDir()
check(err)
return fmt.Sprintf("%s/%s", homedir, configFileName)
}
func askSinglePreference(text, currentValue string) string {
var pref string
allowDefault := currentValue != ""
if allowDefault {
fmt.Printf("%s (%s): ", text, currentValue)
} else {
fmt.Printf("%s: ", text)
}
reader := bufio.NewReader(os.Stdin)
line, _, err := reader.ReadLine()
check(err)
pref = string(line)
if allowDefault && pref == "" {
pref = currentValue
}
return pref
}
func askPreferences(prefs Preferences) Preferences {
jiraURL := askSinglePreference("Jira Host URL", prefs.JiraHostURL)
parsedURL, err := url.ParseRequestURI(jiraURL)
check(err)
prefs.JiraHostURL = fmt.Sprintf("%s://%s%s", parsedURL.Scheme, parsedURL.Host, parsedURL.Path)
return prefs
}
func updateAllPreferences() Preferences {
prefs := readPrefsFileOrCreate()
updatedPrefs := askPreferences(prefs)
savePreferencesToFile(updatedPrefs)
return updatedPrefs
}
func deletePreferencesFile() {
err := os.Remove(getConfigFilePath())
if !os.IsNotExist(err) {
check(err)
}
}
func savePreferencesToFile(prefs Preferences) {
filePath := getConfigFilePath()
newFileBytes, err := json.MarshalIndent(&prefs, "", " ")
check(err)
err = ioutil.WriteFile(filePath, newFileBytes, 0660)
check(err)
}
func readPrefsFileOrCreate() Preferences {
filePath := getConfigFilePath()
file, err := os.OpenFile(filePath, os.O_CREATE|os.O_RDONLY, 0660)
check(err)
defer file.Close()
stat, err := file.Stat()
check(err)
prefs := Preferences{}
if stat.Size() > 0 {
err := json.NewDecoder(file).Decode(&prefs)
check(err)
}
if !prefs.isComplete() {
updatedPrefs := askPreferences(prefs)
savePreferencesToFile(updatedPrefs)
return updatedPrefs
}
return prefs
}
func getOrCreatePreferences() Preferences {
var prefs Preferences
if cachedPrefs != nil {
prefs = *cachedPrefs
} else {
prefs = readPrefsFileOrCreate()
}
cachedPrefs = &prefs
return prefs
}