Files
coder/enterprise/cli/grouplist.go
T
Mathias Fredriksson c750695d83 feat(cli/cliui): output empty string for empty table (#20967)
This changes makes it so that we output the empty string for Format
when there is no data. It turns out there are many places in the code
where we have such handling, but in a way that would break the JSON
formatter (since we'd output nothing on stdout or text rather than
`[]`/`null`).
2025-12-03 11:32:59 +02:00

98 lines
2.4 KiB
Go

package cli
import (
"fmt"
"github.com/fatih/color"
"github.com/google/uuid"
"golang.org/x/xerrors"
agpl "github.com/coder/coder/v2/cli"
"github.com/coder/coder/v2/cli/cliui"
"github.com/coder/coder/v2/codersdk"
"github.com/coder/serpent"
)
func (r *RootCmd) groupList() *serpent.Command {
formatter := cliui.NewOutputFormatter(
cliui.TableFormat([]groupTableRow{}, nil),
cliui.JSONFormat(),
)
orgContext := agpl.NewOrganizationContext()
cmd := &serpent.Command{
Use: "list",
Short: "List user groups",
Middleware: serpent.Chain(
serpent.RequireNArgs(0),
),
Handler: func(inv *serpent.Invocation) error {
ctx := inv.Context()
client, err := r.InitClient(inv)
if err != nil {
return err
}
org, err := orgContext.Selected(inv, client)
if err != nil {
return xerrors.Errorf("current organization: %w", err)
}
groups, err := client.GroupsByOrganization(ctx, org.ID)
if err != nil {
return xerrors.Errorf("get groups: %w", err)
}
rows := groupsToRows(groups...)
out, err := formatter.Format(inv.Context(), rows)
if err != nil {
return xerrors.Errorf("display groups: %w", err)
}
if out == "" {
_, _ = 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
}
_, _ = fmt.Fprintln(inv.Stdout, out)
return nil
},
}
formatter.AttachOptions(&cmd.Options)
orgContext.AttachOptions(cmd)
return cmd
}
type groupTableRow struct {
// For json output:
Group codersdk.Group `table:"-"`
// For table output:
Name string `json:"-" table:"name,default_sort"`
DisplayName string `json:"-" table:"display name"`
OrganizationID uuid.UUID `json:"-" table:"organization id"`
Members []string `json:"-" table:"members"`
AvatarURL string `json:"-" table:"avatar url"`
}
func groupsToRows(groups ...codersdk.Group) []groupTableRow {
rows := make([]groupTableRow, 0, len(groups))
for _, group := range groups {
members := make([]string, 0, len(group.Members))
for _, member := range group.Members {
members = append(members, member.Email)
}
rows = append(rows, groupTableRow{
Name: group.Name,
DisplayName: group.DisplayName,
OrganizationID: group.OrganizationID,
AvatarURL: group.AvatarURL,
Members: members,
})
}
return rows
}