-
Notifications
You must be signed in to change notification settings - Fork 0
/
setup.go
140 lines (110 loc) · 2.56 KB
/
setup.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
package cmd
import (
"fmt"
"os"
"github.com/anned20/kicli/kimai"
"github.com/fatih/color"
"github.com/sirupsen/logrus"
"github.com/spf13/cobra"
survey "github.com/AlecAivazis/survey/v2"
yaml "gopkg.in/yaml.v3"
)
// setupCmd represents the setup command
var setupCmd = &cobra.Command{
Use: "setup",
Short: "Setup the application",
Long: `Before using the application, some variables need to be configured.
This command will help you to configure the application. It will ask you for
the following variables:
- Base URL
- Username
- API token
`,
Run: func(cmd *cobra.Command, args []string) {
var config struct {
BaseURL string `yaml:"kimai_base_url"`
Username string `yaml:"kimai_username"`
Token string `yaml:"kimai_api_token"`
}
// Check if file kicli.yaml exists, if it does not, create it
if _, err := os.Stat(cfgFile); os.IsNotExist(err) {
// Create file
file, err := os.Create(cfgFile)
if err != nil {
logrus.Fatal(err)
}
defer file.Close()
logrus.Debugf("Created config file %s", cfgFile)
// Write default config to file
err = yaml.NewEncoder(file).Encode(config)
if err != nil {
logrus.Fatal(err)
}
} else {
// Read config from file
file, err := os.Open(cfgFile)
if err != nil {
logrus.Fatal(err)
}
defer file.Close()
logrus.Debug("Config file exists, reading it")
// Decode config from file
err = yaml.NewDecoder(file).Decode(&config)
if err != nil {
logrus.Fatal(err)
}
}
questions := []*survey.Question{
{
Name: "baseURL",
Prompt: &survey.Input{
Message: "Base URL:",
Default: config.BaseURL,
},
},
{
Name: "username",
Prompt: &survey.Input{
Message: "Username:",
Default: config.Username,
},
},
{
Name: "token",
Prompt: &survey.Input{
Message: "API token:",
Default: config.Token,
},
},
}
err := survey.Ask(questions, &config)
if err != nil {
logrus.Fatal(err)
}
// Open file
file, err := os.OpenFile(cfgFile, os.O_RDWR, 0644)
if err != nil {
logrus.Fatal(err)
}
defer file.Close()
kimaiClient := kimai.NewKimaiClient(
config.BaseURL,
config.Username,
config.Token,
)
// Get me
me, err := kimaiClient.GetMe()
if err != nil {
logrus.Fatal(err)
}
fmt.Printf("You are logged in as %s (%s)", color.YellowString(me.Alias), color.YellowString(me.Username))
// Write default config to file
err = yaml.NewEncoder(file).Encode(config)
if err != nil {
logrus.Fatal(err)
}
},
}
func init() {
rootCmd.AddCommand(setupCmd)
}