github.com/nats-io/nsc/v2@v2.8.7-0.20240307184528-efd7023c6896/cmd/accountcontextparams.go (about) 1 /* 2 * Copyright 2018 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 21 "github.com/nats-io/nsc/v2/cmd/store" 22 23 "github.com/spf13/cobra" 24 ) 25 26 type AccountContextParams struct { 27 Name string 28 } 29 30 func (p *AccountContextParams) BindFlags(cmd *cobra.Command) { 31 cmd.Flags().StringVarP(&p.Name, "account", "a", "", "account name") 32 } 33 34 func (p *AccountContextParams) SetDefaults(ctx ActionCtx) error { 35 config := GetConfig() 36 if p.Name != "" { 37 // if specified, sync the context 38 err := config.SetAccountTemp(p.Name) 39 if err != nil { 40 return err 41 } 42 ctx.StoreCtx().Account.Name = p.Name 43 } else { 44 if config.Account != "" { 45 ctx.StoreCtx().Account.Name = config.Account 46 p.Name = config.Account 47 } 48 } 49 if p.Name != "" { 50 return p.setAccount(ctx, p.Name) 51 } 52 53 return nil 54 } 55 56 func (p *AccountContextParams) Edit(ctx ActionCtx) error { 57 var err error 58 name, err := PickAccount(ctx.StoreCtx(), p.Name) 59 if err != nil { 60 return err 61 } 62 return p.setAccount(ctx, name) 63 } 64 65 func (p *AccountContextParams) Validate(ctx ActionCtx) error { 66 // default account was not found by get context, so we either we have none or many 67 if p.Name == "" { 68 ctx.CurrentCmd().SilenceUsage = false 69 return errors.New("an account is required") 70 } 71 return nil 72 } 73 74 func (p *AccountContextParams) setAccount(ctx ActionCtx, name string) error { 75 ac, err := ctx.StoreCtx().Store.ReadAccountClaim(name) 76 if err != nil && !store.IsNotExist(err) { 77 return err 78 } 79 p.Name = name 80 ctx.StoreCtx().Account.PublicKey = ac.Subject 81 return nil 82 }