|
| 1 | +package cmduser |
| 2 | + |
| 3 | +import ( |
| 4 | + "errors" |
| 5 | + |
| 6 | + "github.com/spf13/cobra" |
| 7 | +) |
| 8 | + |
| 9 | +var createLong = `Use create to add a new user to the system. The user email |
| 10 | +must be unique for every user. |
| 11 | +
|
| 12 | +Example: |
| 13 | + ./shelf user create -n "Bill Kennedy" -e "[email protected]" -p "yefc*7fdf92" |
| 14 | +` |
| 15 | + |
| 16 | +// create contains the state for this command. |
| 17 | +var create struct { |
| 18 | + name string |
| 19 | + pass string |
| 20 | + email string |
| 21 | +} |
| 22 | + |
| 23 | +// addCreate handles the creation of users. |
| 24 | +func addCreate() { |
| 25 | + cmd := &cobra.Command{ |
| 26 | + Use: "create", |
| 27 | + Short: "Add a new user to the system.", |
| 28 | + Long: createLong, |
| 29 | + Run: runCreate, |
| 30 | + } |
| 31 | + |
| 32 | + cmd.Flags().StringVarP(&create.name, "name", "n", "", "Full name for the user.") |
| 33 | + cmd.Flags().StringVarP(&create.email, "email", "e", "", "Email for the user.") |
| 34 | + cmd.Flags().StringVarP(&create.pass, "pass", "p", "", "Password for the user.") |
| 35 | + |
| 36 | + userCmd.AddCommand(cmd) |
| 37 | +} |
| 38 | + |
| 39 | +// runCreate is the code that implements the create command. |
| 40 | +func runCreate(cmd *cobra.Command, args []string) { |
| 41 | + cmd.Printf("Creating User : Name[%s] Email[%s] Pass[%s]\n", create.name, create.email, create.pass) |
| 42 | + |
| 43 | + if create.name == "" && create.email == "" && create.pass == "" { |
| 44 | + cmd.Help() |
| 45 | + return |
| 46 | + } |
| 47 | + |
| 48 | + u := User{ |
| 49 | + Status: 1, |
| 50 | + Name: "Bill", |
| 51 | + |
| 52 | + Password: "my passoword", |
| 53 | + } |
| 54 | + |
| 55 | + if err := createUser(&u); err != nil { |
| 56 | + cmd.Println("Creating User : ", err) |
| 57 | + return |
| 58 | + } |
| 59 | + |
| 60 | + cmd.Println("Creating User : Created") |
| 61 | +} |
| 62 | + |
| 63 | +//============================================================================== |
| 64 | + |
| 65 | +// User represents a sample user model. |
| 66 | +type User struct { |
| 67 | + Status int |
| 68 | + Name string |
| 69 | + Email string |
| 70 | + Password string |
| 71 | +} |
| 72 | + |
| 73 | +// createUser is a sample function to simulate a user creation. |
| 74 | +func createUser(u *User) error { |
| 75 | + if u.Status == 0 { |
| 76 | + return errors.New("Invalid user value") |
| 77 | + } |
| 78 | + |
| 79 | + return nil |
| 80 | +} |
0 commit comments