From 8de77fe41747e5a8f53a807bbe0e3f2418872f21 Mon Sep 17 00:00:00 2001 From: Juliusz Chroboczek Date: Wed, 30 Oct 2024 17:34:18 +0100 Subject: [PATCH] Rework permissions formatting in galenectl. --- galenectl/galenectl.go | 27 ++++++++++++++++++++++++++- galenectl/galenectl_test.go | 28 ++++++++++++++++++++++++++++ 2 files changed, 54 insertions(+), 1 deletion(-) diff --git a/galenectl/galenectl.go b/galenectl/galenectl.go index 7538578..df6bd54 100644 --- a/galenectl/galenectl.go +++ b/galenectl/galenectl.go @@ -681,6 +681,29 @@ func parsePermissions(p string, expand bool) (any, error) { return pp.Permissions(nil), nil } +func formatRawPermissions(permissions []string) string { + var perms []byte + for _, p := range permissions { + if len(p) > 0 { + perms = append(perms, p[0]) + } else { + perms = append(perms, '?') + } + } + sort.Slice(perms, func(i, j int) bool { + return perms[i] < perms[j] + }) + return fmt.Sprintf("[%s]", perms) +} + +func formatPermissions(permissions group.Permissions) string { + s := permissions.String() + if len(s) > 0 && s[0] != '[' { + return s + } + return formatRawPermissions(permissions.Permissions(nil)) +} + func listUsersCmd(cmdname string, args []string) { var groupname string var long bool @@ -732,7 +755,9 @@ func listUsersCmd(cmdname string, args []string) { fmt.Printf("%-12s (ERROR=%v)\n", user, err) continue } - fmt.Printf("%-12s %v\n", user, d.Permissions) + fmt.Printf("%-12s %v\n", + user, formatPermissions(d.Permissions), + ) } } } diff --git a/galenectl/galenectl_test.go b/galenectl/galenectl_test.go index cb9431a..99dfcdd 100644 --- a/galenectl/galenectl_test.go +++ b/galenectl/galenectl_test.go @@ -1,6 +1,7 @@ package main import ( + "encoding/json" "testing" "github.com/jech/galene/group" @@ -38,3 +39,30 @@ func TestMakePassword(t *testing.T) { t.Errorf("Wildcard didn't match") } } + +func TestFormatPermissions(t *testing.T) { + tests := []struct{ j, v, p string }{ + {`"op"`, "op", "[mopt]"}, + {`"present"`, "present", "[mp]"}, + {`"observe"`, "observe", "[]"}, + {`"admin"`, "admin", "[a]"}, + {`["message", "present", "token"]`, "[mpt]", "[mpt]"}, + {`[]`, "[]", "[]"}, + } + for _, test := range tests { + var p group.Permissions + err := json.Unmarshal([]byte(test.j), &p) + if err != nil { + t.Errorf("Unmarshal %#v: %v", test.j, err) + continue + } + v := formatPermissions(p) + if v != test.v { + t.Errorf("Expected %v, got %v", test.v, v) + } + pp := formatRawPermissions(p.Permissions(nil)) + if pp != test.p { + t.Errorf("Expected %v, got %v", test.p, pp) + } + } +}