-
Notifications
You must be signed in to change notification settings - Fork 117
/
cmdutil.go
388 lines (326 loc) · 8.78 KB
/
cmdutil.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
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
package cmdutil
import (
"context"
"fmt"
"os"
"path/filepath"
"strings"
"time"
"github.com/AlecAivazis/survey/v2"
"github.com/briandowns/spinner"
"github.com/fatih/color"
"github.com/lensesio/tableprinter"
"github.com/rilldata/rill/admin/client"
"github.com/rilldata/rill/cli/pkg/config"
adminv1 "github.com/rilldata/rill/proto/gen/rill/admin/v1"
"github.com/spf13/cobra"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)
const (
TSFormatLayout = "2006-01-02 15:04:05"
defaultProjectName = "rill-untitled"
)
type PreRunCheck func(cmd *cobra.Command, args []string) error
func CheckChain(chain ...PreRunCheck) PreRunCheck {
return func(cmd *cobra.Command, args []string) error {
for _, fn := range chain {
err := fn(cmd, args)
if err != nil {
return err
}
}
return nil
}
}
func CheckAuth(cfg *config.Config) PreRunCheck {
return func(cmd *cobra.Command, args []string) error {
// This will just check if token is present in the config
if cfg.IsAuthenticated() {
return nil
}
return fmt.Errorf("not authenticated, please run 'rill login'")
}
}
func CheckOrganization(cfg *config.Config) PreRunCheck {
return func(cmd *cobra.Command, args []string) error {
if cfg.Org != "" {
return nil
}
return fmt.Errorf("no organization is set, pass `--org` or run `rill org switch`")
}
}
func Spinner(prefix string) *spinner.Spinner {
// We can some other spinners from here https://github.com/briandowns/spinner#:~:text=90%20Character%20Sets.%20Some%20examples%20below%3A
sp := spinner.New(spinner.CharSets[9], 100*time.Millisecond)
sp.Prefix = prefix
// Other colour and font options can be changed
err := sp.Color("green", "bold")
if err != nil {
fmt.Println("invalid color and attribute list, Error: ", err)
}
return sp
}
func TablePrinter(v interface{}) {
var b strings.Builder
tableprinter.Print(&b, v)
fmt.Fprintln(os.Stdout, b.String())
}
func SuccessPrinter(str string) {
boldGreen := color.New(color.FgGreen).Add(color.Bold)
boldGreen.Fprintln(color.Output, str)
}
// Create admin client
func Client(cfg *config.Config) (*client.Client, error) {
cliVersion := cfg.Version.Number
if cfg.Version.Number == "" {
cliVersion = "unknown"
}
userAgent := fmt.Sprintf("rill-cli/%v", cliVersion)
c, err := client.New(cfg.AdminURL, cfg.AdminToken(), userAgent)
if err != nil {
return nil, err
}
return c, nil
}
func SelectPrompt(msg string, options []string, def string) string {
prompt := &survey.Select{
Message: msg,
Options: options,
}
if contains(options, def) {
prompt.Default = def
}
result := ""
if err := survey.AskOne(prompt, &result); err != nil {
fmt.Printf("Prompt failed %v\n", err)
os.Exit(1)
}
return result
}
func ConfirmPrompt(msg, help string, def bool) bool {
prompt := &survey.Confirm{
Message: msg,
Default: def,
}
if help != "" {
prompt.Help = help
}
result := def
if err := survey.AskOne(prompt, &result); err != nil {
fmt.Printf("Prompt failed %v\n", err)
os.Exit(1)
}
return result
}
func InputPrompt(msg, def string) (string, error) {
prompt := &survey.Input{
Message: msg,
Default: def,
}
result := def
if err := survey.AskOne(prompt, &result); err != nil {
fmt.Printf("Prompt failed %v\n", err)
return "", err
}
return result, nil
}
func StringPromptIfEmpty(input *string, msg string) {
if *input != "" {
return
}
prompt := []*survey.Question{{
Prompt: &survey.Input{Message: msg},
Validate: survey.Required,
}}
if err := survey.Ask(prompt, input); err != nil {
fmt.Printf("Prompt failed %v\n", err)
os.Exit(1)
}
}
func SelectPromptIfEmpty(input *string, msg string, options []string, def string) {
if *input != "" {
return
}
*input = SelectPrompt(msg, options, def)
}
func ProjectExists(ctx context.Context, c *client.Client, orgName, projectName string) (bool, error) {
_, err := c.GetProject(ctx, &adminv1.GetProjectRequest{OrganizationName: orgName, Name: projectName})
if err != nil {
if st, ok := status.FromError(err); ok {
if st.Code() == codes.NotFound {
return false, nil
}
}
return false, err
}
return true, nil
}
func OrgExists(ctx context.Context, c *client.Client, name string) (bool, error) {
_, err := c.GetOrganization(ctx, &adminv1.GetOrganizationRequest{Name: name})
if err != nil {
if st, ok := status.FromError(err); ok {
if st.Code() == codes.NotFound {
return false, nil
}
}
return false, err
}
return true, nil
}
func WarnPrinter(str string) {
boldYellow := color.New(color.FgYellow).Add(color.Bold)
boldYellow.Fprintln(color.Output, str)
}
func PrintMembers(members []*adminv1.Member) {
if len(members) == 0 {
WarnPrinter("No members found")
return
}
SuccessPrinter("Members list")
TablePrinter(toMemberTable(members))
}
func PrintInvites(invites []*adminv1.UserInvite) {
if len(invites) == 0 {
return
}
SuccessPrinter("Pending user invites")
TablePrinter(toInvitesTable(invites))
}
func toMemberTable(members []*adminv1.Member) []*member {
allMembers := make([]*member, 0, len(members))
for _, m := range members {
allMembers = append(allMembers, toMemberRow(m))
}
return allMembers
}
func toMemberRow(m *adminv1.Member) *member {
return &member{
Name: m.UserName,
Email: m.UserEmail,
RoleName: m.RoleName,
CreatedOn: m.CreatedOn.AsTime().Format(TSFormatLayout),
UpdatedOn: m.UpdatedOn.AsTime().Format(TSFormatLayout),
}
}
type member struct {
Name string `header:"name" json:"display_name"`
Email string `header:"email" json:"email"`
RoleName string `header:"role_name" json:"role_name"`
CreatedOn string `header:"created_on,timestamp(ms|utc|human)" json:"created_on"`
UpdatedOn string `header:"updated_on,timestamp(ms|utc|human)" json:"updated_on"`
}
func toInvitesTable(invites []*adminv1.UserInvite) []*userInvite {
allInvites := make([]*userInvite, 0, len(invites))
for _, i := range invites {
allInvites = append(allInvites, toInviteRow(i))
}
return allInvites
}
func toInviteRow(i *adminv1.UserInvite) *userInvite {
return &userInvite{
Email: i.Email,
RoleName: i.Role,
InvitedBy: i.InvitedBy,
}
}
type userInvite struct {
Email string `header:"email" json:"email"`
RoleName string `header:"role_name" json:"role_name"`
InvitedBy string `header:"invited_by" json:"invited_by"`
}
func contains(vals []string, key string) bool {
for _, s := range vals {
if key == s {
return true
}
}
return false
}
// ProjectNames returns names of all the projects in org deployed from githubURL
func ProjectNamesByGithubURL(ctx context.Context, c *client.Client, org, githubURL string) ([]string, error) {
resp, err := c.ListProjectsForOrganization(ctx, &adminv1.ListProjectsForOrganizationRequest{
OrganizationName: org,
})
if err != nil {
return nil, err
}
names := make([]string, 0)
for _, p := range resp.Projects {
if strings.EqualFold(p.GithubUrl, githubURL) {
names = append(names, p.Name)
}
}
if len(names) == 0 {
return nil, fmt.Errorf("No project with githubURL %q exist in org %q", githubURL, org)
}
return names, nil
}
func IsNameExistsErr(err error) bool {
if st, ok := status.FromError(err); ok && st != nil {
exists := strings.Contains(st.Message(), "violates unique constraint")
return exists
}
return false
}
func OrgNames(ctx context.Context, c *client.Client) ([]string, error) {
resp, err := c.ListOrganizations(ctx, &adminv1.ListOrganizationsRequest{})
if err != nil {
return nil, err
}
if len(resp.Organizations) == 0 {
return nil, fmt.Errorf("You are not a member of any orgs")
}
var orgNames []string
for _, org := range resp.Organizations {
orgNames = append(orgNames, org.Name)
}
return orgNames, nil
}
func ProjectNamesByOrg(ctx context.Context, c *client.Client, orgName string) ([]string, error) {
resp, err := c.ListProjectsForOrganization(ctx, &adminv1.ListProjectsForOrganizationRequest{OrganizationName: orgName})
if err != nil {
return nil, err
}
if len(resp.Projects) == 0 {
return nil, fmt.Errorf("No projects found for org %q", orgName)
}
var projNames []string
for _, proj := range resp.Projects {
projNames = append(projNames, proj.Name)
}
return projNames, nil
}
func DefaultProjectName() string {
// Get full path to project
absPath, err := filepath.Abs(defaultProjectName)
if err != nil {
return ""
}
_, err = os.Stat(absPath)
if os.IsNotExist(err) {
return defaultProjectName
}
num := 1
for err == nil {
absPath := fmt.Sprint(absPath, num)
_, err = os.Stat(absPath)
if os.IsNotExist(err) {
return fmt.Sprint(defaultProjectName, num)
}
num++
}
return ""
}
func FetchUserID(ctx context.Context, cfg *config.Config) (string, error) {
c, err := Client(cfg)
if err != nil {
return "", err
}
defer c.Close()
user, err := c.GetCurrentUser(ctx, &adminv1.GetCurrentUserRequest{})
if err != nil {
return "", err
}
return user.GetUser().GetId(), nil
}