-
Notifications
You must be signed in to change notification settings - Fork 118
Expand file tree
/
Copy pathroot.go
More file actions
215 lines (185 loc) · 6.19 KB
/
Copy pathroot.go
File metadata and controls
215 lines (185 loc) · 6.19 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
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
package cmd
import (
"bufio"
"context"
"fmt"
"os"
"path/filepath"
"strings"
"time"
api "github.com/bootdotdev/bootdev/client"
"github.com/bootdotdev/bootdev/version"
"github.com/spf13/cobra"
"github.com/spf13/viper"
)
var cfgFile string
var rootCmd = &cobra.Command{
Use: "bootdev",
Short: "Official Boot.dev CLI",
Long: `The official CLI for Boot.dev. This program is meant
as a companion app (not a replacement) for the website.`,
}
// Execute adds all child commands to the root command and sets flags appropriately.
// This is called by main.main(). It only needs to happen once to the rootCmd.
func Execute(currentVersion string) error {
rootCmd.Version = currentVersion
info := version.FetchUpdateInfo(rootCmd.Version)
defer info.PromptUpdateIfAvailable()
ctx := version.WithContext(context.Background(), &info)
patchBashCompletionHelp()
return rootCmd.ExecuteContext(ctx)
}
func init() {
cobra.OnInitialize(initConfig)
rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default $HOME/.bootdev.yaml or $XDG_CONFIG_HOME/bootdev/config.yaml)")
}
func readViperConfig(paths []string) error {
for _, p := range paths {
if _, err := os.Stat(p); err == nil {
viper.SetConfigFile(p)
break
}
}
return viper.ReadInConfig()
}
// initConfig reads in config file and ENV variables if set.
func initConfig() {
viper.SetDefault("frontend_url", "https://boot.dev")
viper.SetDefault("api_url", "https://api.boot.dev")
viper.SetDefault("access_token", "")
viper.SetDefault("refresh_token", "")
viper.SetDefault("last_refresh", 0)
if cfgFile != "" {
// Use config file from the flag.
viper.SetConfigFile(filepath.Clean(cfgFile))
cobra.CheckErr(viper.ReadInConfig())
} else {
// find home dir
home, err := os.UserHomeDir()
cobra.CheckErr(err)
// collect paths where existing config files may be located
var configPaths []string
// first check XDG_CONFIG_HOME if set
xdgConfigHome := os.Getenv("XDG_CONFIG_HOME")
var xdgEnvPath string
if xdgConfigHome != "" {
xdgEnvPath = filepath.Join(xdgConfigHome, "bootdev", "config.yaml")
configPaths = append(configPaths, xdgEnvPath)
}
// then check legacy hard-coded "XDG" path, then home dotfile
xdgLegacyPath := filepath.Join(home, ".config", "bootdev", "config.yaml")
homeDotfilePath := filepath.Join(home, ".bootdev.yaml")
configPaths = append(configPaths, xdgLegacyPath)
configPaths = append(configPaths, homeDotfilePath)
if err := readViperConfig(configPaths); err != nil {
// no existing config found; try to create a new one
// respect XDG_CONFIG_HOME if set, otherwise use dotfile in home dir
var newConfigPath string
if xdgEnvPath != "" {
newConfigPath = xdgEnvPath
cobra.CheckErr(os.MkdirAll(filepath.Dir(newConfigPath), 0o755))
} else {
newConfigPath = homeDotfilePath
}
cobra.CheckErr(viper.SafeWriteConfigAs(newConfigPath))
viper.SetConfigFile(newConfigPath)
cobra.CheckErr(viper.ReadInConfig())
}
}
viper.SetEnvPrefix("bd")
viper.AutomaticEnv() // read in environment variables that match
}
// Chain multiple commands together.
func compose(commands ...func(cmd *cobra.Command, args []string)) func(cmd *cobra.Command, args []string) {
return func(cmd *cobra.Command, args []string) {
for _, command := range commands {
command(cmd, args)
}
}
}
// Call this function at the beginning of a command handler
// if you want to require the user to update their CLI first.
func requireUpdated(cmd *cobra.Command, args []string) {
info := version.FromContext(cmd.Context())
if info == nil {
if !promptToContinue(
"WARNING: Can't get version info",
"Unable to check whether your bootdev CLI is up to date.",
"Continue anyway?",
) {
os.Exit(1)
}
return
}
if info.FailedToFetch != nil {
if !promptToContinue(
"WARNING: Can't get version info",
fmt.Sprintf("Unable to check whether your bootdev CLI is up to date: %s", info.FailedToFetch.Error()),
"Continue anyway?",
) {
os.Exit(1)
}
return
}
if info.IsUpdateRequired {
info.PromptUpdateIfAvailable()
os.Exit(1)
}
}
func promptToContinue(title string, message string, prompt string) bool {
fmt.Fprintln(os.Stderr, title)
fmt.Fprintln(os.Stderr, message)
fmt.Fprintf(os.Stderr, "%s [y/N]: ", prompt)
reader := bufio.NewReader(os.Stdin)
response, err := reader.ReadString('\n')
if err != nil {
fmt.Fprintln(os.Stderr)
return false
}
response = strings.TrimSpace(strings.ToLower(response))
return response == "y" || response == "yes"
}
// Call this function at the beginning of a command handler
// if you need to make authenticated requests. This will
// automatically refresh the tokens, if necessary, and prompt
// the user to re-login if anything goes wrong.
func requireAuth(cmd *cobra.Command, args []string) {
promptLoginAndExitIf := func(condition bool) {
if condition {
fmt.Fprintln(os.Stderr, "You must be logged in to use that command.")
fmt.Fprintln(os.Stderr, "Please run 'bootdev login' first.")
os.Exit(1)
}
}
accessToken := viper.GetString("access_token")
promptLoginAndExitIf(accessToken == "")
// We only refresh if our token is getting stale.
lastRefresh := viper.GetInt64("last_refresh")
if time.Now().Add(-time.Minute*55).Unix() <= lastRefresh {
return
}
creds, err := api.FetchAccessToken()
promptLoginAndExitIf(err != nil)
if creds.AccessToken == "" || creds.RefreshToken == "" {
promptLoginAndExitIf(err != nil)
}
viper.Set("access_token", creds.AccessToken)
viper.Set("refresh_token", creds.RefreshToken)
viper.Set("last_refresh", time.Now().Unix())
err = viper.WriteConfig()
promptLoginAndExitIf(err != nil)
}
// patchBashCompletionHelp adjusts Cobra's generated bash completion help.
//
// Cobra's default Linux example redirects into /etc/bash_completion.d, which
// fails for non-root shells. Use sudo tee so only the file write is elevated.
func patchBashCompletionHelp() {
rootCmd.InitDefaultCompletionCmd()
bashCmd, _, err := rootCmd.Find([]string{"completion", "bash"})
if err != nil || bashCmd == nil {
return
}
old := "bootdev completion bash > /etc/bash_completion.d/bootdev"
new := "bootdev completion bash | sudo tee /etc/bash_completion.d/bootdev > /dev/null"
bashCmd.Long = strings.Replace(bashCmd.Long, old, new, 1)
}