Add filter function in groups list command

This commit is contained in:
PiMaDaum 2023-01-18 23:58:59 +01:00
parent e7c6be7b5e
commit faa0b5330c

View file

@ -4,6 +4,7 @@ import (
"context" "context"
"encoding/json" "encoding/json"
"fmt" "fmt"
"regexp"
"strings" "strings"
"time" "time"
@ -25,6 +26,7 @@ var GroupListCmd = &cobra.Command{
} }
func init() { func init() {
GroupListCmd.Flags().String("filter", "", "Filtercriteria on group name by a regular expression.\nExample:--filter '.*somegroup?'")
GroupListCmd.Flags().StringArrayP("user", "u", []string{}, "Groups that are shared with group") GroupListCmd.Flags().StringArrayP("user", "u", []string{}, "Groups that are shared with group")
GroupListCmd.Flags().StringArrayP("manager", "m", []string{}, "Groups that are in folder") GroupListCmd.Flags().StringArrayP("manager", "m", []string{}, "Groups that are in folder")
@ -51,6 +53,10 @@ func GroupList(cmd *cobra.Command, args []string) error {
if err != nil { if err != nil {
return err return err
} }
filter, err := cmd.Flags().GetString("filter")
if err != nil {
return err
}
ctx := util.GetContext() ctx := util.GetContext()
@ -69,9 +75,14 @@ func GroupList(cmd *cobra.Command, args []string) error {
return fmt.Errorf("Listing Group: %w", err) return fmt.Errorf("Listing Group: %w", err)
} }
filteredGroups, err := filteredGroups(&groups, filter)
if err != nil {
return fmt.Errorf("Listing filtered Groups: %w", err)
}
if jsonOutput { if jsonOutput {
outputGroups := []GroupJsonOutput{} outputGroups := []GroupJsonOutput{}
for i := range groups { for i := range *filteredGroups {
outputGroups = append(outputGroups, GroupJsonOutput{ outputGroups = append(outputGroups, GroupJsonOutput{
ID: &groups[i].ID, ID: &groups[i].ID,
Name: &groups[i].Name, Name: &groups[i].Name,
@ -87,7 +98,7 @@ func GroupList(cmd *cobra.Command, args []string) error {
} else { } else {
data := pterm.TableData{columns} data := pterm.TableData{columns}
for _, group := range groups { for _, group := range *filteredGroups {
entry := make([]string, len(columns)) entry := make([]string, len(columns))
for i := range columns { for i := range columns {
switch strings.ToLower(columns[i]) { switch strings.ToLower(columns[i]) {
@ -111,3 +122,24 @@ func GroupList(cmd *cobra.Command, args []string) error {
} }
return nil return nil
} }
func filteredGroups(groups *[]api.Group, filter string) (*[]api.Group, error) {
if filter == "" {
return groups, nil
}
filteredGroups := []api.Group{}
for _, group := range *groups {
matches, err := regexp.MatchString(filter, group.Name)
if err != nil {
return nil, err
}
if matches {
filteredGroups = append(filteredGroups, group)
}
}
return &filteredGroups, nil
}