/
list.go
73 lines (59 loc) · 1.42 KB
/
list.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
package cmd
import (
"encoding/json"
"github.com/frederikhs/pg_user/database"
"github.com/olekukonko/tablewriter"
"github.com/spf13/cobra"
"os"
"strings"
)
var listCmd = &cobra.Command{
Use: "list [host]",
Short: "List database users",
Long: `List database users for a specific database`,
Run: func(cmd *cobra.Command, args []string) {
if len(args) != 1 {
cmd.Println(cmd.UsageString())
os.Exit(1)
}
host := args[0]
withSSL := getUseSSL(cmd)
conn := database.GetDatabaseEntryConnection(host, withSSL)
if conn == nil {
cmd.Println("no hosts found by that name")
os.Exit(1)
}
users, err := conn.GetAllUsers()
if err != nil {
cmd.Println(err)
os.Exit(1)
}
output := getOutputType(cmd)
if output == OutputTypeJson {
outputListJson(users, cmd)
} else if output == OutputTypeTable {
outputListTable(users, cmd)
}
},
}
func outputListJson(users []database.User, cmd *cobra.Command) {
b, err := json.MarshalIndent(users, "", strings.Repeat(" ", 4))
if err != nil {
panic(err)
}
cmd.Println(string(b))
}
func outputListTable(users []database.User, cmd *cobra.Command) {
out := cmd.OutOrStdout()
table := tablewriter.NewWriter(out)
table.SetHeader([]string{"username", "valid until", "roles"})
for _, u := range users {
table.Append([]string{
u.Username, *u.ValidUntil, strings.Join(u.Roles, ", "),
})
}
table.Render()
}
func init() {
rootCmd.AddCommand(listCmd)
}