github.com/fastly/cli@v1.7.2-0.20240304164155-9d0f1d77c3bf/pkg/commands/user/create.go (about) 1 package user 2 3 import ( 4 "io" 5 6 "github.com/fastly/go-fastly/v9/fastly" 7 8 "github.com/fastly/cli/pkg/argparser" 9 "github.com/fastly/cli/pkg/global" 10 "github.com/fastly/cli/pkg/text" 11 ) 12 13 // NewCreateCommand returns a usable command registered under the parent. 14 func NewCreateCommand(parent argparser.Registerer, g *global.Data) *CreateCommand { 15 var c CreateCommand 16 c.CmdClause = parent.Command("create", "Create a user of the Fastly API and web interface").Alias("add") 17 c.Globals = g 18 19 // Required. 20 c.CmdClause.Flag("login", "The login associated with the user (typically, an email address)").Action(c.login.Set).StringVar(&c.login.Value) 21 c.CmdClause.Flag("name", "The real life name of the user").Action(c.name.Set).StringVar(&c.name.Value) 22 23 // Optional. 24 c.CmdClause.Flag("role", "The permissions role assigned to the user. Can be user, billing, engineer, or superuser").Action(c.role.Set).EnumVar(&c.role.Value, "user", "billing", "engineer", "superuser") 25 26 return &c 27 } 28 29 // CreateCommand calls the Fastly API to create an appropriate resource. 30 type CreateCommand struct { 31 argparser.Base 32 33 login argparser.OptionalString 34 name argparser.OptionalString 35 role argparser.OptionalString 36 } 37 38 // Exec invokes the application logic for the command. 39 func (c *CreateCommand) Exec(_ io.Reader, out io.Writer) error { 40 input := c.constructInput() 41 42 r, err := c.Globals.APIClient.CreateUser(input) 43 if err != nil { 44 c.Globals.ErrLog.AddWithContext(err, map[string]any{ 45 "User Login": c.login, 46 "User Name": c.name, 47 }) 48 return err 49 } 50 51 text.Success(out, "Created user '%s' (role: %s)", fastly.ToValue(r.Name), fastly.ToValue(r.Role)) 52 return nil 53 } 54 55 // constructInput transforms values parsed from CLI flags into an object to be used by the API client library. 56 func (c *CreateCommand) constructInput() *fastly.CreateUserInput { 57 var input fastly.CreateUserInput 58 if c.login.WasSet { 59 input.Login = &c.login.Value 60 } 61 if c.role.WasSet { 62 input.Role = &c.role.Value 63 } 64 if c.name.WasSet { 65 input.Name = &c.name.Value 66 } 67 68 return &input 69 }