github.com/nats-io/nsc/v2@v2.8.7-0.20240307184528-efd7023c6896/cmd/usercontextparams.go (about) 1 /* 2 * Copyright 2018-2019 The NATS Authors 3 * Licensed under the Apache License, Version 2.0 (the "License"); 4 * you may not use this file except in compliance with the License. 5 * You may obtain a copy of the License at 6 * 7 * http://www.apache.org/licenses/LICENSE-2.0 8 * 9 * Unless required by applicable law or agreed to in writing, software 10 * distributed under the License is distributed on an "AS IS" BASIS, 11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 * See the License for the specific language governing permissions and 13 * limitations under the License. 14 */ 15 16 package cmd 17 18 import ( 19 "errors" 20 "fmt" 21 22 "github.com/nats-io/nsc/v2/cmd/store" 23 "github.com/spf13/cobra" 24 ) 25 26 type UserContextParams struct { 27 Name string 28 } 29 30 func (p *UserContextParams) BindFlags(cmd *cobra.Command) { 31 cmd.Flags().StringVarP(&p.Name, "user", "u", "", "user name") 32 } 33 34 func (p *UserContextParams) SetDefaults(ctx ActionCtx) error { 35 config := GetConfig() 36 if config.Operator == "" { 37 return fmt.Errorf("no operator set - `%s env --operator <name>`", GetToolName()) 38 } 39 if config.Account == "" { 40 return fmt.Errorf("no account set - `%s env --account <name>`", GetToolName()) 41 } 42 if p.Name == "" { 43 s, err := config.LoadStore(config.Operator) 44 if err != nil { 45 return err 46 } 47 names, err := s.ListEntries(store.Accounts, config.Account, store.Users) 48 if err != nil { 49 return err 50 } 51 if len(names) == 1 { 52 p.Name = names[0] 53 } 54 } 55 56 return nil 57 } 58 59 func (p *UserContextParams) Edit(ctx ActionCtx) error { 60 config := GetConfig() 61 var err error 62 p.Name, err = PickUser(ctx.StoreCtx(), config.Account) 63 if err != nil { 64 return err 65 } 66 return nil 67 } 68 69 func (p *UserContextParams) Validate(ctx ActionCtx) error { 70 // default account was not found by get context, so we either we have none or many 71 if p.Name == "" { 72 ctx.CurrentCmd().SilenceUsage = false 73 return errors.New("a user is required") 74 } 75 return nil 76 }