feat: convert entire CLI to clibase (#6491)

I'm sorry.
This commit is contained in:
Ammar Bandukwala
2023-03-23 17:42:20 -05:00
committed by GitHub
parent b71b8daa21
commit 2bd6d2908e
345 changed files with 9965 additions and 9082 deletions
+36 -22
View File
@@ -8,45 +8,44 @@ import (
"net/http"
"strings"
"github.com/spf13/cobra"
"golang.org/x/xerrors"
agpl "github.com/coder/coder/cli"
"github.com/coder/coder/cli/clibase"
"github.com/coder/coder/cli/cliui"
"github.com/coder/coder/codersdk"
)
func features() *cobra.Command {
cmd := &cobra.Command{
func (r *RootCmd) features() *clibase.Cmd {
cmd := &clibase.Cmd{
Short: "List Enterprise features",
Use: "features",
Aliases: []string{"feature"},
RunE: func(cmd *cobra.Command, args []string) error {
return cmd.Help()
Handler: func(inv *clibase.Invocation) error {
return inv.Command.HelpHandler(inv)
},
Children: []*clibase.Cmd{
r.featuresList(),
},
}
cmd.AddCommand(
featuresList(),
)
return cmd
}
func featuresList() *cobra.Command {
func (r *RootCmd) featuresList() *clibase.Cmd {
var (
featureColumns = []string{"Name", "Entitlement", "Enabled", "Limit", "Actual"}
columns []string
outputFormat string
)
client := new(codersdk.Client)
cmd := &cobra.Command{
cmd := &clibase.Cmd{
Use: "list",
Aliases: []string{"ls"},
RunE: func(cmd *cobra.Command, args []string) error {
client, err := agpl.CreateClient(cmd)
if err != nil {
return err
}
entitlements, err := client.Entitlements(cmd.Context())
Middleware: clibase.Chain(
r.InitClient(client),
),
Handler: func(inv *clibase.Invocation) error {
entitlements, err := client.Entitlements(inv.Context())
var apiError *codersdk.Error
if errors.As(err, &apiError) && apiError.StatusCode() == http.StatusNotFound {
return xerrors.New("You are on the AGPL licensed version of Coder that does not have Enterprise functionality!")
@@ -77,15 +76,30 @@ func featuresList() *cobra.Command {
return xerrors.Errorf(`unknown output format %q, only "table" and "json" are supported`, outputFormat)
}
_, err = fmt.Fprintln(cmd.OutOrStdout(), out)
_, err = fmt.Fprintln(inv.Stdout, out)
return err
},
}
cmd.Flags().StringArrayVarP(&columns, "column", "c", featureColumns,
fmt.Sprintf("Specify a column to filter in the table. Available columns are: %s",
strings.Join(featureColumns, ", ")))
cmd.Flags().StringVarP(&outputFormat, "output", "o", "table", "Output format. Available formats are: table, json.")
cmd.Options = clibase.OptionSet{
{
Flag: "column",
FlagShorthand: "c",
Description: fmt.Sprintf("Specify a column to filter in the table. Available columns are: %s.",
strings.Join(featureColumns, ", "),
),
Default: strings.Join(featureColumns, ","),
Value: clibase.StringArrayOf(&columns),
},
{
Flag: "output",
FlagShorthand: "o",
Description: "Output format. Available formats are: table, json.",
Default: "table",
Value: clibase.StringOf(&outputFormat),
},
}
return cmd
}
+8 -15
View File
@@ -11,7 +11,6 @@ import (
"github.com/coder/coder/cli/clitest"
"github.com/coder/coder/coderd/coderdtest"
"github.com/coder/coder/codersdk"
"github.com/coder/coder/enterprise/cli"
"github.com/coder/coder/enterprise/coderd/coderdenttest"
"github.com/coder/coder/pty/ptytest"
)
@@ -22,16 +21,10 @@ func TestFeaturesList(t *testing.T) {
t.Parallel()
client := coderdenttest.New(t, nil)
coderdtest.CreateFirstUser(t, client)
cmd, root := clitest.NewWithSubcommands(t, cli.EnterpriseSubcommands(), "features", "list")
clitest.SetupConfig(t, client, root)
pty := ptytest.New(t)
cmd.SetIn(pty.Input())
cmd.SetOut(pty.Output())
errC := make(chan error)
go func() {
errC <- cmd.Execute()
}()
require.NoError(t, <-errC)
inv, conf := newCLI(t, "features", "list")
clitest.SetupConfig(t, client, conf)
pty := ptytest.New(t).Attach(inv)
clitest.Start(t, inv)
pty.ExpectMatch("user_limit")
pty.ExpectMatch("not_entitled")
})
@@ -40,15 +33,15 @@ func TestFeaturesList(t *testing.T) {
client := coderdenttest.New(t, nil)
coderdtest.CreateFirstUser(t, client)
cmd, root := clitest.NewWithSubcommands(t, cli.EnterpriseSubcommands(), "features", "list", "-o", "json")
clitest.SetupConfig(t, client, root)
inv, conf := newCLI(t, "features", "list", "-o", "json")
clitest.SetupConfig(t, client, conf)
doneChan := make(chan struct{})
buf := bytes.NewBuffer(nil)
cmd.SetOut(buf)
inv.Stdout = buf
go func() {
defer close(doneChan)
err := cmd.Execute()
err := inv.Run()
assert.NoError(t, err)
}()
+22 -16
View File
@@ -3,48 +3,54 @@ package cli
import (
"fmt"
"github.com/spf13/cobra"
"golang.org/x/xerrors"
agpl "github.com/coder/coder/cli"
"github.com/coder/coder/cli/cliflag"
"github.com/coder/coder/cli/clibase"
"github.com/coder/coder/cli/cliui"
"github.com/coder/coder/codersdk"
)
func groupCreate() *cobra.Command {
func (r *RootCmd) groupCreate() *clibase.Cmd {
var avatarURL string
cmd := &cobra.Command{
client := new(codersdk.Client)
cmd := &clibase.Cmd{
Use: "create <name>",
Short: "Create a user group",
Args: cobra.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
ctx := cmd.Context()
Middleware: clibase.Chain(
clibase.RequireNArgs(1),
r.InitClient(client),
),
Handler: func(inv *clibase.Invocation) error {
ctx := inv.Context()
client, err := agpl.CreateClient(cmd)
if err != nil {
return xerrors.Errorf("create client: %w", err)
}
org, err := agpl.CurrentOrganization(cmd, client)
org, err := agpl.CurrentOrganization(inv, client)
if err != nil {
return xerrors.Errorf("current organization: %w", err)
}
group, err := client.CreateGroup(ctx, org.ID, codersdk.CreateGroupRequest{
Name: args[0],
Name: inv.Args[0],
AvatarURL: avatarURL,
})
if err != nil {
return xerrors.Errorf("create group: %w", err)
}
_, _ = fmt.Fprintf(cmd.OutOrStdout(), "Successfully created group %s!\n", cliui.Styles.Keyword.Render(group.Name))
_, _ = fmt.Fprintf(inv.Stdout, "Successfully created group %s!\n", cliui.Styles.Keyword.Render(group.Name))
return nil
},
}
cliflag.StringVarP(cmd.Flags(), &avatarURL, "avatar-url", "u", "CODER_AVATAR_URL", "", "set an avatar for a group")
cmd.Options = clibase.OptionSet{
{
Flag: "avatar-url",
Description: `Set an avatar for a group.`,
FlagShorthand: "u",
Env: "CODER_AVATAR_URL",
Value: clibase.StringOf(&avatarURL),
},
}
return cmd
}
+4 -5
View File
@@ -10,7 +10,6 @@ import (
"github.com/coder/coder/cli/cliui"
"github.com/coder/coder/coderd/coderdtest"
"github.com/coder/coder/codersdk"
"github.com/coder/coder/enterprise/cli"
"github.com/coder/coder/enterprise/coderd/coderdenttest"
"github.com/coder/coder/enterprise/coderd/license"
"github.com/coder/coder/pty/ptytest"
@@ -35,16 +34,16 @@ func TestCreateGroup(t *testing.T) {
avatarURL = "https://example.com"
)
cmd, root := clitest.NewWithSubcommands(t, cli.EnterpriseSubcommands(), "groups",
inv, conf := newCLI(t, "groups",
"create", groupName,
"--avatar-url", avatarURL,
)
pty := ptytest.New(t)
cmd.SetOut(pty.Output())
clitest.SetupConfig(t, client, root)
inv.Stdout = pty.Output()
clitest.SetupConfig(t, client, conf)
err := cmd.Execute()
err := inv.Run()
require.NoError(t, err)
pty.ExpectMatch(fmt.Sprintf("Successfully created group %s!", cliui.Styles.Keyword.Render(groupName)))
+14 -14
View File
@@ -3,30 +3,30 @@ package cli
import (
"fmt"
"github.com/spf13/cobra"
"golang.org/x/xerrors"
agpl "github.com/coder/coder/cli"
"github.com/coder/coder/cli/clibase"
"github.com/coder/coder/cli/cliui"
"github.com/coder/coder/codersdk"
)
func groupDelete() *cobra.Command {
cmd := &cobra.Command{
func (r *RootCmd) groupDelete() *clibase.Cmd {
client := new(codersdk.Client)
cmd := &clibase.Cmd{
Use: "delete <name>",
Short: "Delete a user group",
Args: cobra.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
Middleware: clibase.Chain(
clibase.RequireNArgs(1),
r.InitClient(client),
),
Handler: func(inv *clibase.Invocation) error {
var (
ctx = cmd.Context()
groupName = args[0]
ctx = inv.Context()
groupName = inv.Args[0]
)
client, err := agpl.CreateClient(cmd)
if err != nil {
return xerrors.Errorf("create client: %w", err)
}
org, err := agpl.CurrentOrganization(cmd, client)
org, err := agpl.CurrentOrganization(inv, client)
if err != nil {
return xerrors.Errorf("current organization: %w", err)
}
@@ -41,7 +41,7 @@ func groupDelete() *cobra.Command {
return xerrors.Errorf("delete group: %w", err)
}
_, _ = fmt.Fprintf(cmd.OutOrStdout(), "Successfully deleted group %s!\n", cliui.Styles.Keyword.Render(group.Name))
_, _ = fmt.Fprintf(inv.Stdout, "Successfully deleted group %s!\n", cliui.Styles.Keyword.Render(group.Name))
return nil
},
}
+11 -10
View File
@@ -10,7 +10,6 @@ import (
"github.com/coder/coder/cli/cliui"
"github.com/coder/coder/coderd/coderdtest"
"github.com/coder/coder/codersdk"
"github.com/coder/coder/enterprise/cli"
"github.com/coder/coder/enterprise/coderd/coderdenttest"
"github.com/coder/coder/enterprise/coderd/license"
"github.com/coder/coder/pty/ptytest"
@@ -32,22 +31,22 @@ func TestGroupDelete(t *testing.T) {
},
})
ctx, _ := testutil.Context(t)
ctx := testutil.Context(t, testutil.WaitLong)
group, err := client.CreateGroup(ctx, admin.OrganizationID, codersdk.CreateGroupRequest{
Name: "alpha",
})
require.NoError(t, err)
cmd, root := clitest.NewWithSubcommands(t, cli.EnterpriseSubcommands(),
inv, conf := newCLI(t,
"groups", "delete", group.Name,
)
pty := ptytest.New(t)
cmd.SetOut(pty.Output())
clitest.SetupConfig(t, client, root)
inv.Stdout = pty.Output()
clitest.SetupConfig(t, client, conf)
err = cmd.Execute()
err = inv.Run()
require.NoError(t, err)
pty.ExpectMatch(fmt.Sprintf("Successfully deleted group %s", cliui.Styles.Keyword.Render(group.Name)))
@@ -65,12 +64,14 @@ func TestGroupDelete(t *testing.T) {
},
})
cmd, root := clitest.NewWithSubcommands(t, cli.EnterpriseSubcommands(),
"groups", "delete")
inv, conf := newCLI(
t,
"groups", "delete",
)
clitest.SetupConfig(t, client, root)
clitest.SetupConfig(t, client, conf)
err := cmd.Execute()
err := inv.Run()
require.Error(t, err)
})
}
+40 -19
View File
@@ -5,38 +5,36 @@ import (
"net/mail"
"github.com/google/uuid"
"github.com/spf13/cobra"
"golang.org/x/xerrors"
agpl "github.com/coder/coder/cli"
"github.com/coder/coder/cli/cliflag"
"github.com/coder/coder/cli/clibase"
"github.com/coder/coder/cli/cliui"
"github.com/coder/coder/codersdk"
)
func groupEdit() *cobra.Command {
func (r *RootCmd) groupEdit() *clibase.Cmd {
var (
avatarURL string
name string
addUsers []string
rmUsers []string
)
cmd := &cobra.Command{
client := new(codersdk.Client)
cmd := &clibase.Cmd{
Use: "edit <name>",
Short: "Edit a user group",
Args: cobra.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
Middleware: clibase.Chain(
clibase.RequireNArgs(1),
r.InitClient(client),
),
Handler: func(inv *clibase.Invocation) error {
var (
ctx = cmd.Context()
groupName = args[0]
ctx = inv.Context()
groupName = inv.Args[0]
)
client, err := agpl.CreateClient(cmd)
if err != nil {
return xerrors.Errorf("create client: %w", err)
}
org, err := agpl.CurrentOrganization(cmd, client)
org, err := agpl.CurrentOrganization(inv, client)
if err != nil {
return xerrors.Errorf("current organization: %w", err)
}
@@ -74,15 +72,38 @@ func groupEdit() *cobra.Command {
return xerrors.Errorf("patch group: %w", err)
}
_, _ = fmt.Fprintf(cmd.OutOrStdout(), "Successfully patched group %s!\n", cliui.Styles.Keyword.Render(group.Name))
_, _ = fmt.Fprintf(inv.Stdout, "Successfully patched group %s!\n", cliui.Styles.Keyword.Render(group.Name))
return nil
},
}
cliflag.StringVarP(cmd.Flags(), &name, "name", "n", "", "", "Update the group name")
cliflag.StringVarP(cmd.Flags(), &avatarURL, "avatar-url", "u", "", "", "Update the group avatar")
cliflag.StringArrayVarP(cmd.Flags(), &addUsers, "add-users", "a", "", nil, "Add users to the group. Accepts emails or IDs.")
cliflag.StringArrayVarP(cmd.Flags(), &rmUsers, "rm-users", "r", "", nil, "Remove users to the group. Accepts emails or IDs.")
cmd.Options = clibase.OptionSet{
{
Flag: "name",
FlagShorthand: "n",
Description: "Update the group name.",
Value: clibase.StringOf(&name),
},
{
Flag: "avatar-url",
FlagShorthand: "u",
Description: "Update the group avatar.",
Value: clibase.StringOf(&avatarURL),
},
{
Flag: "add-users",
FlagShorthand: "a",
Description: "Add users to the group. Accepts emails or IDs.",
Value: clibase.StringArrayOf(&addUsers),
},
{
Flag: "rm-users",
FlagShorthand: "r",
Description: "Remove users to the group. Accepts emails or IDs.",
Value: clibase.StringArrayOf(&rmUsers),
},
}
return cmd
}
+14 -14
View File
@@ -10,7 +10,6 @@ import (
"github.com/coder/coder/cli/cliui"
"github.com/coder/coder/coderd/coderdtest"
"github.com/coder/coder/codersdk"
"github.com/coder/coder/enterprise/cli"
"github.com/coder/coder/enterprise/coderd/coderdenttest"
"github.com/coder/coder/enterprise/coderd/license"
"github.com/coder/coder/pty/ptytest"
@@ -32,7 +31,7 @@ func TestGroupEdit(t *testing.T) {
},
})
ctx, _ := testutil.Context(t)
ctx := testutil.Context(t, testutil.WaitLong)
_, user1 := coderdtest.CreateAnotherUser(t, client, admin.OrganizationID)
_, user2 := coderdtest.CreateAnotherUser(t, client, admin.OrganizationID)
_, user3 := coderdtest.CreateAnotherUser(t, client, admin.OrganizationID)
@@ -51,7 +50,8 @@ func TestGroupEdit(t *testing.T) {
expectedName := "beta"
cmd, root := clitest.NewWithSubcommands(t, cli.EnterpriseSubcommands(),
inv, conf := newCLI(
t,
"groups", "edit", group.Name,
"--name", expectedName,
"--avatar-url", "https://example.com",
@@ -62,10 +62,10 @@ func TestGroupEdit(t *testing.T) {
pty := ptytest.New(t)
cmd.SetOut(pty.Output())
clitest.SetupConfig(t, client, root)
inv.Stdout = pty.Output()
clitest.SetupConfig(t, client, conf)
err = cmd.Execute()
err = inv.Run()
require.NoError(t, err)
pty.ExpectMatch(fmt.Sprintf("Successfully patched group %s", cliui.Styles.Keyword.Render(expectedName)))
@@ -83,21 +83,22 @@ func TestGroupEdit(t *testing.T) {
},
})
ctx, _ := testutil.Context(t)
ctx := testutil.Context(t, testutil.WaitLong)
group, err := client.CreateGroup(ctx, admin.OrganizationID, codersdk.CreateGroupRequest{
Name: "alpha",
})
require.NoError(t, err)
cmd, root := clitest.NewWithSubcommands(t, cli.EnterpriseSubcommands(),
inv, conf := newCLI(
t,
"groups", "edit", group.Name,
"-a", "foo",
)
clitest.SetupConfig(t, client, root)
clitest.SetupConfig(t, client, conf)
err = cmd.Execute()
err = inv.Run()
require.Error(t, err)
require.Contains(t, err.Error(), "must be a valid UUID or email address")
})
@@ -114,11 +115,10 @@ func TestGroupEdit(t *testing.T) {
},
})
cmd, root := clitest.NewWithSubcommands(t, cli.EnterpriseSubcommands(), "groups", "edit")
inv, conf := newCLI(t, "groups", "edit")
clitest.SetupConfig(t, client, conf)
clitest.SetupConfig(t, client, root)
err := cmd.Execute()
err := inv.Run()
require.Error(t, err)
})
}
+16 -17
View File
@@ -5,33 +5,32 @@ import (
"github.com/fatih/color"
"github.com/google/uuid"
"github.com/spf13/cobra"
"golang.org/x/xerrors"
agpl "github.com/coder/coder/cli"
"github.com/coder/coder/cli/clibase"
"github.com/coder/coder/cli/cliui"
"github.com/coder/coder/codersdk"
)
func groupList() *cobra.Command {
func (r *RootCmd) groupList() *clibase.Cmd {
formatter := cliui.NewOutputFormatter(
cliui.TableFormat([]groupTableRow{}, nil),
cliui.JSONFormat(),
)
cmd := &cobra.Command{
client := new(codersdk.Client)
cmd := &clibase.Cmd{
Use: "list",
Short: "List user groups",
Args: cobra.NoArgs,
RunE: func(cmd *cobra.Command, args []string) error {
ctx := cmd.Context()
Middleware: clibase.Chain(
clibase.RequireNArgs(0),
r.InitClient(client),
),
Handler: func(inv *clibase.Invocation) error {
ctx := inv.Context()
client, err := agpl.CreateClient(cmd)
if err != nil {
return xerrors.Errorf("create client: %w", err)
}
org, err := agpl.CurrentOrganization(cmd, client)
org, err := agpl.CurrentOrganization(inv, client)
if err != nil {
return xerrors.Errorf("current organization: %w", err)
}
@@ -42,23 +41,23 @@ func groupList() *cobra.Command {
}
if len(groups) == 0 {
_, _ = fmt.Fprintf(cmd.ErrOrStderr(), "%s No groups found in %s! Create one:\n\n", agpl.Caret, color.HiWhiteString(org.Name))
_, _ = fmt.Fprintln(cmd.ErrOrStderr(), color.HiMagentaString(" $ coder groups create <name>\n"))
_, _ = fmt.Fprintf(inv.Stderr, "%s No groups found in %s! Create one:\n\n", agpl.Caret, color.HiWhiteString(org.Name))
_, _ = fmt.Fprintln(inv.Stderr, color.HiMagentaString(" $ coder groups create <name>\n"))
return nil
}
rows := groupsToRows(groups...)
out, err := formatter.Format(cmd.Context(), rows)
out, err := formatter.Format(inv.Context(), rows)
if err != nil {
return xerrors.Errorf("display groups: %w", err)
}
_, _ = fmt.Fprintln(cmd.OutOrStdout(), out)
_, _ = fmt.Fprintln(inv.Stdout, out)
return nil
},
}
formatter.AttachFlags(cmd)
formatter.AttachOptions(&cmd.Options)
return cmd
}
+9 -10
View File
@@ -8,7 +8,6 @@ import (
"github.com/coder/coder/cli/clitest"
"github.com/coder/coder/coderd/coderdtest"
"github.com/coder/coder/codersdk"
"github.com/coder/coder/enterprise/cli"
"github.com/coder/coder/enterprise/coderd/coderdenttest"
"github.com/coder/coder/enterprise/coderd/license"
"github.com/coder/coder/pty/ptytest"
@@ -30,7 +29,7 @@ func TestGroupList(t *testing.T) {
},
})
ctx, _ := testutil.Context(t)
ctx := testutil.Context(t, testutil.WaitLong)
_, user1 := coderdtest.CreateAnotherUser(t, client, admin.OrganizationID)
_, user2 := coderdtest.CreateAnotherUser(t, client, admin.OrganizationID)
@@ -57,14 +56,14 @@ func TestGroupList(t *testing.T) {
})
require.NoError(t, err)
cmd, root := clitest.NewWithSubcommands(t, cli.EnterpriseSubcommands(), "groups", "list")
inv, conf := newCLI(t, "groups", "list")
pty := ptytest.New(t)
cmd.SetOut(pty.Output())
clitest.SetupConfig(t, client, root)
inv.Stdout = pty.Output()
clitest.SetupConfig(t, client, conf)
err = cmd.Execute()
err = inv.Run()
require.NoError(t, err)
matches := []string{
@@ -90,14 +89,14 @@ func TestGroupList(t *testing.T) {
},
})
cmd, root := clitest.NewWithSubcommands(t, cli.EnterpriseSubcommands(), "groups", "list")
inv, conf := newCLI(t, "groups", "list")
pty := ptytest.New(t)
cmd.SetErr(pty.Output())
clitest.SetupConfig(t, client, root)
inv.Stderr = pty.Output()
clitest.SetupConfig(t, client, conf)
err := cmd.Execute()
err := inv.Run()
require.NoError(t, err)
pty.ExpectMatch("No groups found")
+13 -12
View File
@@ -1,23 +1,24 @@
package cli
import "github.com/spf13/cobra"
import (
"github.com/coder/coder/cli/clibase"
)
func groups() *cobra.Command {
cmd := &cobra.Command{
func (r *RootCmd) groups() *clibase.Cmd {
cmd := &clibase.Cmd{
Use: "groups",
Short: "Manage groups",
Aliases: []string{"group"},
RunE: func(cmd *cobra.Command, args []string) error {
return cmd.Help()
Handler: func(inv *clibase.Invocation) error {
return inv.Command.HelpHandler(inv)
},
Children: []*clibase.Cmd{
r.groupCreate(),
r.groupList(),
r.groupEdit(),
r.groupDelete(),
},
}
cmd.AddCommand(
groupCreate(),
groupList(),
groupEdit(),
groupDelete(),
)
return cmd
}
+68 -54
View File
@@ -9,55 +9,54 @@ import (
"strconv"
"strings"
"github.com/spf13/cobra"
"golang.org/x/xerrors"
agpl "github.com/coder/coder/cli"
"github.com/coder/coder/cli/clibase"
"github.com/coder/coder/cli/cliui"
"github.com/coder/coder/codersdk"
)
var jwtRegexp = regexp.MustCompile(`^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$`)
func licenses() *cobra.Command {
cmd := &cobra.Command{
func (r *RootCmd) licenses() *clibase.Cmd {
cmd := &clibase.Cmd{
Short: "Add, delete, and list licenses",
Use: "licenses",
Aliases: []string{"license"},
RunE: func(cmd *cobra.Command, args []string) error {
return cmd.Help()
Handler: func(inv *clibase.Invocation) error {
return inv.Command.HelpHandler(inv)
},
Children: []*clibase.Cmd{
r.licenseAdd(),
r.licensesList(),
r.licenseDelete(),
},
}
cmd.AddCommand(
licenseAdd(),
licensesList(),
licenseDelete(),
)
return cmd
}
func licenseAdd() *cobra.Command {
func (r *RootCmd) licenseAdd() *clibase.Cmd {
var (
filename string
license string
debug bool
)
cmd := &cobra.Command{
client := new(codersdk.Client)
cmd := &clibase.Cmd{
Use: "add [-f file | -l license]",
Short: "Add license to Coder deployment",
Args: cobra.ExactArgs(0),
RunE: func(cmd *cobra.Command, args []string) error {
client, err := agpl.CreateClient(cmd)
if err != nil {
return err
}
Middleware: clibase.Chain(
clibase.RequireNArgs(0),
r.InitClient(client),
),
Handler: func(inv *clibase.Invocation) error {
var err error
switch {
case filename != "" && license != "":
return xerrors.New("only one of (--file, --license) may be specified")
case filename == "" && license == "":
license, err = cliui.Prompt(cmd, cliui.PromptOptions{
license, err = cliui.Prompt(inv, cliui.PromptOptions{
Text: "Paste license:",
Secret: true,
Validate: validJWT,
@@ -69,7 +68,7 @@ func licenseAdd() *cobra.Command {
case filename != "" && license == "":
var r io.Reader
if filename == "-" {
r = cmd.InOrStdin()
r = inv.Stdin
} else {
f, err := os.Open(filename)
if err != nil {
@@ -91,24 +90,40 @@ func licenseAdd() *cobra.Command {
}
licResp, err := client.AddLicense(
cmd.Context(),
inv.Context(),
codersdk.AddLicenseRequest{License: license},
)
if err != nil {
return err
}
if debug {
enc := json.NewEncoder(cmd.OutOrStdout())
enc := json.NewEncoder(inv.Stdout)
enc.SetIndent("", " ")
return enc.Encode(licResp)
}
_, _ = fmt.Fprintf(cmd.OutOrStdout(), "License with ID %d added\n", licResp.ID)
_, _ = fmt.Fprintf(inv.Stdout, "License with ID %d added\n", licResp.ID)
return nil
},
}
cmd.Flags().StringVarP(&filename, "file", "f", "", "Load license from file")
cmd.Flags().StringVarP(&license, "license", "l", "", "License string")
cmd.Flags().BoolVar(&debug, "debug", false, "Output license claims for debugging")
cmd.Options = clibase.OptionSet{
{
Flag: "file",
FlagShorthand: "f",
Description: "Load license from file.",
Value: clibase.StringOf(&filename),
},
{
Flag: "license",
FlagShorthand: "l",
Description: "License string.",
Value: clibase.StringOf(&license),
},
{
Flag: "debug",
Description: "Output license claims for debugging.",
Value: clibase.BoolOf(&debug),
},
}
return cmd
}
@@ -119,19 +134,18 @@ func validJWT(s string) error {
return xerrors.New("Invalid license")
}
func licensesList() *cobra.Command {
cmd := &cobra.Command{
func (r *RootCmd) licensesList() *clibase.Cmd {
client := new(codersdk.Client)
cmd := &clibase.Cmd{
Use: "list",
Short: "List licenses (including expired)",
Aliases: []string{"ls"},
Args: cobra.ExactArgs(0),
RunE: func(cmd *cobra.Command, args []string) error {
client, err := agpl.CreateClient(cmd)
if err != nil {
return err
}
licenses, err := client.Licenses(cmd.Context())
Middleware: clibase.Chain(
clibase.RequireNArgs(0),
r.InitClient(client),
),
Handler: func(inv *clibase.Invocation) error {
licenses, err := client.Licenses(inv.Context())
if err != nil {
return err
}
@@ -140,7 +154,7 @@ func licensesList() *cobra.Command {
licenses = make([]codersdk.License, 0)
}
enc := json.NewEncoder(cmd.OutOrStdout())
enc := json.NewEncoder(inv.Stdout)
enc.SetIndent("", " ")
return enc.Encode(licenses)
},
@@ -148,26 +162,26 @@ func licensesList() *cobra.Command {
return cmd
}
func licenseDelete() *cobra.Command {
cmd := &cobra.Command{
func (r *RootCmd) licenseDelete() *clibase.Cmd {
client := new(codersdk.Client)
cmd := &clibase.Cmd{
Use: "delete <id>",
Short: "Delete license by ID",
Aliases: []string{"del", "rm"},
Args: cobra.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
client, err := agpl.CreateClient(cmd)
Aliases: []string{"del"},
Middleware: clibase.Chain(
clibase.RequireNArgs(1),
r.InitClient(client),
),
Handler: func(inv *clibase.Invocation) error {
id, err := strconv.ParseInt(inv.Args[0], 10, 32)
if err != nil {
return xerrors.Errorf("license ID must be an integer: %s", inv.Args[0])
}
err = client.DeleteLicense(inv.Context(), int32(id))
if err != nil {
return err
}
id, err := strconv.ParseInt(args[0], 10, 32)
if err != nil {
return xerrors.Errorf("license ID must be an integer: %s", args[0])
}
err = client.DeleteLicense(cmd.Context(), int32(id))
if err != nil {
return err
}
_, _ = fmt.Fprintf(cmd.OutOrStdout(), "License with ID %d deleted\n", id)
_, _ = fmt.Fprintf(inv.Stdout, "License with ID %d deleted\n", id)
return nil
},
}
+56 -72
View File
@@ -13,16 +13,14 @@ import (
"time"
"github.com/go-chi/chi/v5"
"github.com/spf13/cobra"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"golang.org/x/xerrors"
"github.com/coder/coder/cli/clibase"
"github.com/coder/coder/cli/clitest"
"github.com/coder/coder/coderd/coderdtest"
"github.com/coder/coder/coderd/httpapi"
"github.com/coder/coder/codersdk"
"github.com/coder/coder/enterprise/cli"
"github.com/coder/coder/enterprise/coderd/coderdenttest"
"github.com/coder/coder/pty/ptytest"
"github.com/coder/coder/testutil"
@@ -39,26 +37,20 @@ func TestLicensesAddFake(t *testing.T) {
// so instead we have to fake the HTTP interaction.
t.Run("LFlag", func(t *testing.T) {
t.Parallel()
ctx, cancel := context.WithTimeout(context.Background(), testutil.WaitLong)
defer cancel()
cmd := setupFakeLicenseServerTest(t, "licenses", "add", "-l", fakeLicenseJWT)
pty := attachPty(t, cmd)
errC := make(chan error)
go func() {
errC <- cmd.ExecuteContext(ctx)
}()
require.NoError(t, <-errC)
inv := setupFakeLicenseServerTest(t, "licenses", "add", "-l", fakeLicenseJWT)
pty := attachPty(t, inv)
clitest.Start(t, inv)
pty.ExpectMatch("License with ID 1 added")
})
t.Run("Prompt", func(t *testing.T) {
t.Parallel()
ctx, cancel := context.WithTimeout(context.Background(), testutil.WaitLong)
defer cancel()
cmd := setupFakeLicenseServerTest(t, "license", "add")
pty := attachPty(t, cmd)
inv := setupFakeLicenseServerTest(t, "license", "add")
pty := attachPty(t, inv)
errC := make(chan error)
go func() {
errC <- cmd.ExecuteContext(ctx)
errC <- inv.WithContext(ctx).Run()
}()
pty.ExpectMatch("Paste license:")
pty.WriteLine(fakeLicenseJWT)
@@ -73,27 +65,27 @@ func TestLicensesAddFake(t *testing.T) {
filename := filepath.Join(dir, "license.jwt")
err := os.WriteFile(filename, []byte(fakeLicenseJWT), 0o600)
require.NoError(t, err)
cmd := setupFakeLicenseServerTest(t, "license", "add", "-f", filename)
pty := attachPty(t, cmd)
inv := setupFakeLicenseServerTest(t, "license", "add", "-f", filename)
pty := attachPty(t, inv)
errC := make(chan error)
go func() {
errC <- cmd.ExecuteContext(ctx)
errC <- inv.WithContext(ctx).Run()
}()
require.NoError(t, <-errC)
pty.ExpectMatch("License with ID 1 added")
})
t.Run("StdIn", func(t *testing.T) {
t.Parallel()
cmd := setupFakeLicenseServerTest(t, "license", "add", "-f", "-")
inv := setupFakeLicenseServerTest(t, "license", "add", "-f", "-")
r, w := io.Pipe()
cmd.SetIn(r)
inv.Stdin = r
stdout := new(bytes.Buffer)
cmd.SetOut(stdout)
inv.Stdout = stdout
errC := make(chan error)
ctx, cancel := context.WithTimeout(context.Background(), testutil.WaitLong)
defer cancel()
go func() {
errC <- cmd.ExecuteContext(ctx)
errC <- inv.WithContext(ctx).Run()
}()
_, err := w.Write([]byte(fakeLicenseJWT))
require.NoError(t, err)
@@ -111,11 +103,11 @@ func TestLicensesAddFake(t *testing.T) {
t.Parallel()
ctx, cancel := context.WithTimeout(context.Background(), testutil.WaitLong)
defer cancel()
cmd := setupFakeLicenseServerTest(t, "licenses", "add", "-l", fakeLicenseJWT, "--debug")
pty := attachPty(t, cmd)
inv := setupFakeLicenseServerTest(t, "licenses", "add", "-l", fakeLicenseJWT, "--debug")
pty := attachPty(t, inv)
errC := make(chan error)
go func() {
errC <- cmd.ExecuteContext(ctx)
errC <- inv.WithContext(ctx).Run()
}()
require.NoError(t, <-errC)
pty.ExpectMatch("\"f2\": 2")
@@ -128,19 +120,15 @@ func TestLicensesAddReal(t *testing.T) {
t.Parallel()
client := coderdenttest.New(t, nil)
coderdtest.CreateFirstUser(t, client)
cmd, root := clitest.NewWithSubcommands(t, cli.EnterpriseSubcommands(),
"licenses", "add", "-l", fakeLicenseJWT)
clitest.SetupConfig(t, client, root)
inv, conf := newCLI(
t,
"licenses", "add", "-l", fakeLicenseJWT,
)
clitest.SetupConfig(t, client, conf)
ctx, cancel := context.WithTimeout(context.Background(), testutil.WaitLong)
defer cancel()
errC := make(chan error)
go func() {
errC <- cmd.ExecuteContext(ctx)
}()
err := <-errC
waiter := clitest.StartWithWaiter(t, inv)
var coderError *codersdk.Error
require.True(t, xerrors.As(err, &coderError))
waiter.RequireAs(&coderError)
assert.Equal(t, 400, coderError.StatusCode())
assert.Contains(t, "Invalid license", coderError.Message)
})
@@ -154,12 +142,12 @@ func TestLicensesListFake(t *testing.T) {
t.Parallel()
ctx, cancel := context.WithTimeout(context.Background(), testutil.WaitLong)
defer cancel()
cmd := setupFakeLicenseServerTest(t, "licenses", "list")
inv := setupFakeLicenseServerTest(t, "licenses", "list")
stdout := new(bytes.Buffer)
cmd.SetOut(stdout)
inv.Stdout = stdout
errC := make(chan error)
go func() {
errC <- cmd.ExecuteContext(ctx)
errC <- inv.WithContext(ctx).Run()
}()
require.NoError(t, <-errC)
var licenses []codersdk.License
@@ -179,18 +167,20 @@ func TestLicensesListReal(t *testing.T) {
t.Parallel()
client := coderdenttest.New(t, nil)
coderdtest.CreateFirstUser(t, client)
cmd, root := clitest.NewWithSubcommands(t, cli.EnterpriseSubcommands(),
"licenses", "list")
inv, conf := newCLI(
t,
"licenses", "list",
)
stdout := new(bytes.Buffer)
cmd.SetOut(stdout)
inv.Stdout = stdout
stderr := new(bytes.Buffer)
cmd.SetErr(stderr)
clitest.SetupConfig(t, client, root)
inv.Stderr = stderr
clitest.SetupConfig(t, client, conf)
ctx, cancel := context.WithTimeout(context.Background(), testutil.WaitLong)
defer cancel()
errC := make(chan error)
go func() {
errC <- cmd.ExecuteContext(ctx)
errC <- inv.WithContext(ctx).Run()
}()
require.NoError(t, <-errC)
assert.Equal(t, "[]\n", stdout.String())
@@ -204,15 +194,11 @@ func TestLicensesDeleteFake(t *testing.T) {
// so instead we have to fake the HTTP interaction.
t.Run("Mainline", func(t *testing.T) {
t.Parallel()
ctx, cancel := context.WithTimeout(context.Background(), testutil.WaitLong)
defer cancel()
cmd := setupFakeLicenseServerTest(t, "licenses", "delete", "55")
pty := attachPty(t, cmd)
errC := make(chan error)
go func() {
errC <- cmd.ExecuteContext(ctx)
}()
require.NoError(t, <-errC)
inv := setupFakeLicenseServerTest(t, "licenses", "delete", "55")
pty := attachPty(t, inv)
clitest.Start(t, inv)
pty.ExpectMatch("License with ID 55 deleted")
})
}
@@ -223,39 +209,37 @@ func TestLicensesDeleteReal(t *testing.T) {
t.Parallel()
client := coderdenttest.New(t, nil)
coderdtest.CreateFirstUser(t, client)
cmd, root := clitest.NewWithSubcommands(t, cli.EnterpriseSubcommands(),
inv, conf := newCLI(
t,
"licenses", "delete", "1")
clitest.SetupConfig(t, client, root)
ctx, cancel := context.WithTimeout(context.Background(), testutil.WaitLong)
defer cancel()
errC := make(chan error)
go func() {
errC <- cmd.ExecuteContext(ctx)
}()
err := <-errC
clitest.SetupConfig(t, client, conf)
var coderError *codersdk.Error
require.True(t, xerrors.As(err, &coderError))
clitest.StartWithWaiter(t, inv).RequireAs(&coderError)
assert.Equal(t, 404, coderError.StatusCode())
assert.Contains(t, "Unknown license ID", coderError.Message)
})
}
func setupFakeLicenseServerTest(t *testing.T, args ...string) *cobra.Command {
func setupFakeLicenseServerTest(t *testing.T, args ...string) *clibase.Invocation {
t.Helper()
s := httptest.NewServer(newFakeLicenseAPI(t))
t.Cleanup(s.Close)
cmd, root := clitest.NewWithSubcommands(t, cli.EnterpriseSubcommands(), args...)
err := root.URL().Write(s.URL)
inv, conf := newCLI(t, args...)
err := conf.URL().Write(s.URL)
require.NoError(t, err)
err = root.Session().Write("sessiontoken")
err = conf.Session().Write("sessiontoken")
require.NoError(t, err)
return cmd
return inv
}
func attachPty(t *testing.T, cmd *cobra.Command) *ptytest.PTY {
func attachPty(t *testing.T, inv *clibase.Invocation) *ptytest.PTY {
pty := ptytest.New(t)
cmd.SetIn(pty.Input())
cmd.SetOut(pty.Output())
inv.Stdin = pty.Input()
inv.Stdout = pty.Output()
return pty
}
+49 -25
View File
@@ -7,13 +7,12 @@ import (
"os/signal"
"time"
"github.com/spf13/cobra"
"golang.org/x/xerrors"
"cdr.dev/slog"
"cdr.dev/slog/sloggers/sloghuman"
agpl "github.com/coder/coder/cli"
"github.com/coder/coder/cli/cliflag"
"github.com/coder/coder/cli/clibase"
"github.com/coder/coder/cli/cliui"
"github.com/coder/coder/coderd/database"
"github.com/coder/coder/codersdk"
@@ -24,38 +23,40 @@ import (
"github.com/coder/coder/provisionersdk/proto"
)
func provisionerDaemons() *cobra.Command {
cmd := &cobra.Command{
func (r *RootCmd) provisionerDaemons() *clibase.Cmd {
cmd := &clibase.Cmd{
Use: "provisionerd",
Short: "Manage provisioner daemons",
Children: []*clibase.Cmd{
r.provisionerDaemonStart(),
},
}
cmd.AddCommand(provisionerDaemonStart())
return cmd
}
func provisionerDaemonStart() *cobra.Command {
func (r *RootCmd) provisionerDaemonStart() *clibase.Cmd {
var (
cacheDir string
rawTags []string
pollInterval time.Duration
pollJitter time.Duration
)
cmd := &cobra.Command{
client := new(codersdk.Client)
cmd := &clibase.Cmd{
Use: "start",
Short: "Run a provisioner daemon",
RunE: func(cmd *cobra.Command, args []string) error {
ctx, cancel := context.WithCancel(cmd.Context())
Middleware: clibase.Chain(
r.InitClient(client),
),
Handler: func(inv *clibase.Invocation) error {
ctx, cancel := context.WithCancel(inv.Context())
defer cancel()
notifyCtx, notifyStop := signal.NotifyContext(ctx, agpl.InterruptSignals...)
defer notifyStop()
client, err := agpl.CreateClient(cmd)
if err != nil {
return xerrors.Errorf("create client: %w", err)
}
org, err := agpl.CurrentOrganization(cmd, client)
org, err := agpl.CurrentOrganization(inv, client)
if err != nil {
return xerrors.Errorf("get current organization: %w", err)
}
@@ -77,7 +78,7 @@ func provisionerDaemonStart() *cobra.Command {
_ = terraformServer.Close()
}()
logger := slog.Make(sloghuman.Sink(cmd.ErrOrStderr()))
logger := slog.Make(sloghuman.Sink(inv.Stderr))
errCh := make(chan error, 1)
go func() {
defer cancel()
@@ -124,13 +125,13 @@ func provisionerDaemonStart() *cobra.Command {
select {
case <-notifyCtx.Done():
exitErr = notifyCtx.Err()
_, _ = fmt.Fprintln(cmd.OutOrStdout(), cliui.Styles.Bold.Render(
_, _ = fmt.Fprintln(inv.Stdout, cliui.Styles.Bold.Render(
"Interrupt caught, gracefully exiting. Use ctrl+\\ to force quit",
))
case exitErr = <-errCh:
}
if exitErr != nil && !xerrors.Is(exitErr, context.Canceled) {
cmd.Printf("Unexpected error, shutting down server: %s\n", exitErr)
cliui.Errorf(inv.Stderr, "Unexpected error, shutting down server: %s\n", exitErr)
}
shutdown, shutdownCancel := context.WithTimeout(ctx, time.Minute)
@@ -148,14 +149,37 @@ func provisionerDaemonStart() *cobra.Command {
},
}
cliflag.StringVarP(cmd.Flags(), &cacheDir, "cache-dir", "c", "CODER_CACHE_DIRECTORY", codersdk.DefaultCacheDir(),
"Specify a directory to cache provisioner job files.")
cliflag.StringArrayVarP(cmd.Flags(), &rawTags, "tag", "t", "CODER_PROVISIONERD_TAGS", []string{},
"Specify a list of tags to target provisioner jobs.")
cliflag.DurationVarP(cmd.Flags(), &pollInterval, "poll-interval", "", "CODER_PROVISIONERD_POLL_INTERVAL", time.Second,
"Specify the interval for which the provisioner daemon should poll for jobs.")
cliflag.DurationVarP(cmd.Flags(), &pollJitter, "poll-jitter", "", "CODER_PROVISIONERD_POLL_JITTER", 100*time.Millisecond,
"Random jitter added to the poll interval.")
cmd.Options = clibase.OptionSet{
{
Flag: "cache-dir",
FlagShorthand: "c",
Env: "CODER_CACHE_DIRECTORY",
Description: "Directory to store cached data.",
Default: codersdk.DefaultCacheDir(),
Value: clibase.StringOf(&cacheDir),
},
{
Flag: "tag",
FlagShorthand: "t",
Env: "CODER_PROVISIONERD_TAGS",
Description: "Tags to filter provisioner jobs by.",
Value: clibase.StringArrayOf(&rawTags),
},
{
Flag: "poll-interval",
Env: "CODER_PROVISIONERD_POLL_INTERVAL",
Default: time.Second.String(),
Description: "How often to poll for provisioner jobs.",
Value: clibase.DurationOf(&pollInterval),
},
{
Flag: "poll-jitter",
Env: "CODER_PROVISIONERD_POLL_JITTER",
Description: "How much to jitter the poll interval by.",
Default: (100 * time.Millisecond).String(),
Value: clibase.DurationOf(&pollJitter),
},
}
return cmd
}
+15 -12
View File
@@ -1,22 +1,25 @@
package cli
import (
"github.com/spf13/cobra"
agpl "github.com/coder/coder/cli"
"github.com/coder/coder/cli"
"github.com/coder/coder/cli/clibase"
)
func enterpriseOnly() []*cobra.Command {
return []*cobra.Command{
server(),
features(),
licenses(),
groups(),
provisionerDaemons(),
type RootCmd struct {
cli.RootCmd
}
func (r *RootCmd) enterpriseOnly() []*clibase.Cmd {
return []*clibase.Cmd{
r.server(),
r.features(),
r.licenses(),
r.groups(),
r.provisionerDaemons(),
}
}
func EnterpriseSubcommands() []*cobra.Command {
all := append(agpl.Core(), enterpriseOnly()...)
func (r *RootCmd) EnterpriseSubcommands() []*clibase.Cmd {
all := append(r.Core(), r.enterpriseOnly()...)
return all
}
+19
View File
@@ -0,0 +1,19 @@
package cli_test
import (
"testing"
"github.com/stretchr/testify/require"
"github.com/coder/coder/cli/clibase"
"github.com/coder/coder/cli/clitest"
"github.com/coder/coder/cli/config"
"github.com/coder/coder/enterprise/cli"
)
func newCLI(t *testing.T, args ...string) (*clibase.Invocation, config.Root) {
var root cli.RootCmd
cmd, err := root.Command(root.EnterpriseSubcommands())
require.NoError(t, err)
return clitest.NewWithCommand(t, cmd, args...)
}
+3 -4
View File
@@ -9,11 +9,11 @@ import (
"io"
"net/url"
"github.com/spf13/cobra"
"golang.org/x/xerrors"
"tailscale.com/derp"
"tailscale.com/types/key"
"github.com/coder/coder/cli/clibase"
"github.com/coder/coder/cryptorand"
"github.com/coder/coder/enterprise/audit"
"github.com/coder/coder/enterprise/audit/backends"
@@ -21,12 +21,11 @@ import (
"github.com/coder/coder/enterprise/trialer"
"github.com/coder/coder/tailnet"
agpl "github.com/coder/coder/cli"
agplcoderd "github.com/coder/coder/coderd"
)
func server() *cobra.Command {
cmd := agpl.Server(func(ctx context.Context, options *agplcoderd.Options) (*agplcoderd.API, io.Closer, error) {
func (r *RootCmd) server() *clibase.Cmd {
cmd := r.Server(func(ctx context.Context, options *agplcoderd.Options) (*agplcoderd.API, io.Closer, error) {
if options.DeploymentValues.DERP.Server.RelayURL.String() != "" {
_, err := url.Parse(options.DeploymentValues.DERP.Server.RelayURL.String())
if err != nil {
+3 -4
View File
@@ -8,13 +8,12 @@ import (
"golang.org/x/xerrors"
agpl "github.com/coder/coder/cli"
"github.com/coder/coder/cli/clibase"
agplcoderd "github.com/coder/coder/coderd"
"github.com/spf13/cobra"
)
func server() *cobra.Command {
cmd := agpl.Server(func(ctx context.Context, options *agplcoderd.Options) (*agplcoderd.API, io.Closer, error) {
func (r *RootCmd) server() *clibase.Cmd {
cmd := r.Server(func(ctx context.Context, options *agplcoderd.Options) (*agplcoderd.API, io.Closer, error) {
return nil, nil, xerrors.Errorf("slim build does not support `coder server`")
})
return cmd