|
| 1 | +package cli |
| 2 | + |
| 3 | +import ( |
| 4 | + "fmt" |
| 5 | + |
| 6 | + "github.com/google/uuid" |
| 7 | + |
| 8 | + "github.com/coder/coder/v2/cli/clibase" |
| 9 | + "github.com/coder/coder/v2/cli/cliui" |
| 10 | + "github.com/coder/coder/v2/codersdk" |
| 11 | + "github.com/coder/pretty" |
| 12 | +) |
| 13 | + |
| 14 | +func (r *RootCmd) createOrganization() *clibase.Cmd { |
| 15 | + client := new(codersdk.Client) |
| 16 | + |
| 17 | + cmd := &clibase.Cmd{ |
| 18 | + Use: "create <organization name>", |
| 19 | + Short: "Create a new organization.", |
| 20 | + // This action is currently irreversible, so it's hidden until we have a way to delete organizations. |
| 21 | + Hidden: true, |
| 22 | + Middleware: clibase.Chain( |
| 23 | + r.InitClient(client), |
| 24 | + clibase.RequireNArgs(1), |
| 25 | + ), |
| 26 | + Options: clibase.OptionSet{ |
| 27 | + cliui.SkipPromptOption(), |
| 28 | + }, |
| 29 | + Handler: func(inv *clibase.Invocation) error { |
| 30 | + orgName := inv.Args[0] |
| 31 | + |
| 32 | + // This check is not perfect since not all users can read all organizations. |
| 33 | + // So ignore the error and if the org already exists, prevent the user |
| 34 | + // from creating it. |
| 35 | + existing, _ := client.OrganizationByName(inv.Context(), orgName) |
| 36 | + if existing.ID != uuid.Nil { |
| 37 | + return fmt.Errorf("organization %q already exists", orgName) |
| 38 | + } |
| 39 | + |
| 40 | + _, err := cliui.Prompt(inv, cliui.PromptOptions{ |
| 41 | + Text: fmt.Sprintf("Are you sure you want to create an organization with the name %s?\n%s", |
| 42 | + pretty.Sprint(cliui.DefaultStyles.Code, orgName), |
| 43 | + pretty.Sprint(cliui.BoldFmt(), "This action is irreversible."), |
| 44 | + ), |
| 45 | + IsConfirm: true, |
| 46 | + Default: cliui.ConfirmNo, |
| 47 | + }) |
| 48 | + if err != nil { |
| 49 | + return err |
| 50 | + } |
| 51 | + |
| 52 | + organization, err := client.CreateOrganization(inv.Context(), codersdk.CreateOrganizationRequest{ |
| 53 | + Name: orgName, |
| 54 | + }) |
| 55 | + if err != nil { |
| 56 | + return fmt.Errorf("failed to create organization: %w", err) |
| 57 | + } |
| 58 | + |
| 59 | + _, _ = fmt.Fprintf(inv.Stdout, "Organization %s (%s) created.\n", organization.Name, organization.ID) |
| 60 | + return nil |
| 61 | + }, |
| 62 | + } |
| 63 | + |
| 64 | + return cmd |
| 65 | +} |
0 commit comments