-
Notifications
You must be signed in to change notification settings - Fork 17
/
common.go
221 lines (196 loc) · 5.99 KB
/
common.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
package subcommands
import (
"bytes"
"fmt"
"io"
"os"
"path/filepath"
"text/tabwriter"
"github.com/cheynewallace/tabby"
canonical "github.com/docker/go/canonical/json"
homedir "github.com/mitchellh/go-homedir"
"github.com/shurcooL/go/indentwriter"
"github.com/sirupsen/logrus"
"github.com/spf13/cobra"
"github.com/spf13/viper"
"gopkg.in/yaml.v2"
"github.com/foundriesio/fioctl/client"
"github.com/foundriesio/fioctl/subcommands/version"
)
var (
Config client.Config
)
func RequireFactory(cmd *cobra.Command) {
cmd.PersistentFlags().StringP("factory", "f", "", "Factory to list targets for")
cmd.PersistentFlags().StringP("token", "t", "", "API token from https://app.foundries.io/settings/tokens/")
}
func Login(cmd *cobra.Command) *client.Api {
ca := os.Getenv("CACERT")
DieNotNil(viper.BindPFlags(cmd.Flags()))
Config.Token = viper.GetString("token")
url := os.Getenv("API_URL")
if len(url) == 0 {
url = "https://api.foundries.io"
}
if len(Config.Token) > 0 {
if cmd.Flags().Lookup("factory") != nil && len(viper.GetString("factory")) == 0 {
DieNotNil(fmt.Errorf("Required flag \"factory\" not set"))
}
return client.NewApiClient(url, Config, ca, version.Commit)
}
if len(Config.ClientCredentials.ClientId) == 0 {
DieNotNil(fmt.Errorf("Please run: \"fioctl login\" first"))
}
if cmd.Flags().Lookup("factory") != nil && len(viper.GetString("factory")) == 0 {
DieNotNil(fmt.Errorf("Required flag \"factory\" not set"))
}
creds := client.NewClientCredentials(Config.ClientCredentials)
expired, err := creds.IsExpired()
DieNotNil(err)
if !expired && len(creds.Config.AccessToken) > 0 {
return client.NewApiClient(url, Config, ca, version.Commit)
}
if len(creds.Config.AccessToken) == 0 {
DieNotNil(creds.Get())
} else if creds.HasRefreshToken() {
DieNotNil(creds.Refresh())
} else {
DieNotNil(fmt.Errorf("Missing refresh token"))
}
SaveOauthConfig(creds.Config)
Config.ClientCredentials = creds.Config
return client.NewApiClient(url, Config, ca, version.Commit)
}
func SaveOauthConfig(c client.OAuthConfig) {
viper.Set("clientcredentials.client_id", c.ClientId)
viper.Set("clientcredentials.client_secret", c.ClientSecret)
viper.Set("clientcredentials.access_token", c.AccessToken)
viper.Set("clientcredentials.refresh_token", c.RefreshToken)
viper.Set("clientcredentials.token_type", c.TokenType)
viper.Set("clientcredentials.expires_in", c.ExpiresIn)
viper.Set("clientcredentials.created", c.Created)
// viper.WriteConfig isn't so great for this. It doesn't just write
// these values but any other flags that were present when this runs.
// This gets run automatically when "logging in". So you sometimes
// accidentally write CLI flags viper finds to the file, that you
// don't intend to be saved. So we do it the hard way:
name := viper.ConfigFileUsed()
if len(name) == 0 {
logrus.Debug("Guessing config file from path")
path, err := homedir.Expand("~/.config")
DieNotNil(err)
name = filepath.Join(path, "fioctl.yaml")
}
// Try to read in config
cfg := make(map[string]interface{})
buf, err := os.ReadFile(name)
if err == nil {
DieNotNil(yaml.Unmarshal(buf, &cfg), "Unable unmarshal configuration:")
}
val := viper.Get("clientcredentials")
cfg["clientcredentials"] = val
if len(c.DefaultOrg) > 0 {
cfg["factory"] = c.DefaultOrg
}
buf, err = yaml.Marshal(cfg)
DieNotNil(err, "Unable to marshall oauth config:")
DieNotNil(os.WriteFile(name, buf, os.FileMode(0644)), "Unable to update config: ")
}
// An os.Exit exits immediately, skipping all deferred functions
// We need a way to execute the finalizing code in some cases.
type LastWill = func()
var onLastWill []LastWill
func AddLastWill(lastWill LastWill) {
onLastWill = append(onLastWill, lastWill)
}
func DieNotNil(err error, message ...string) {
if err != nil {
parts := []interface{}{"ERROR:"}
for _, p := range message {
parts = append(parts, p)
}
parts = append(parts, err)
fmt.Println(parts...)
for _, w := range onLastWill {
w()
}
os.Exit(1)
}
}
func Tabby(indent int, columns ...interface{}) *tabby.Tabby {
var out io.Writer = os.Stdout
if indent > 0 {
out = indentwriter.New(out, indent)
}
tab := tabby.NewCustom(tabwriter.NewWriter(out, 0, 0, 2, ' ', 0))
if len(columns) > 0 {
tab.AddHeader(columns...)
}
return tab
}
// Copied from canonical.MarshalIndent, but replaced the Marshal call with MarshalCanonical.
func MarshalIndent(v interface{}, prefix, indent string) ([]byte, error) {
b, err := canonical.MarshalCanonical(v)
if err != nil {
return nil, err
}
var buf bytes.Buffer
err = canonical.Indent(&buf, b, prefix, indent)
if err != nil {
return nil, err
}
return buf.Bytes(), nil
}
func AssertWritable(path string) {
st, err := os.Stat(path)
DieNotNil(err)
f, err := os.OpenFile(path, os.O_APPEND|os.O_WRONLY, st.Mode())
if err != nil {
fmt.Println("ERROR: File is not writeable:", path)
os.Exit(1)
}
f.Close()
}
func IsSliceSetEqual(first, second []string) bool {
// Verify that two slices are equal as sets in just 3 O(1) iterations.
// firstMap[key] = false <- key present in first;
// firstMap[key] = true <- key present in both first and second.
firstMap := make(map[string]bool, len(first))
for _, val := range first {
firstMap[val] = false
}
for _, val := range second {
if _, inFirst := firstMap[val]; !inFirst {
return false
}
firstMap[val] = true
}
for _, inSecond := range firstMap {
if !inSecond {
return false
}
}
return true
}
type MutuallyExclusiveFlags struct {
flags map[string]*bool
}
func (f *MutuallyExclusiveFlags) Add(cmd *cobra.Command, flagName, helpText string) {
if f.flags == nil {
f.flags = make(map[string]*bool)
}
val := false
f.flags[flagName] = &val
cmd.Flags().BoolVarP(f.flags[flagName], flagName, "", false, helpText)
}
func (f *MutuallyExclusiveFlags) GetFlag() (string, error) {
flagName := ""
for k, v := range f.flags {
if *v && len(flagName) == 0 {
flagName = k
} else if *v {
return "", fmt.Errorf("--%s and --%s are mutually exclusive", flagName, k)
}
}
return flagName, nil
}