-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcmd_log.go
82 lines (69 loc) · 1.98 KB
/
cmd_log.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
74
75
76
77
78
79
80
81
82
package main
import (
"fmt"
"github.com/alecthomas/kong"
"gorm.io/gorm"
"io"
"strings"
"time"
)
type CmdLog struct {
Last int `help:"Print the n-last log entries" default:"10"`
LogID string `arg optional help:"Print the bagels associated with a log. <logid> can either be \"last\" or the ID of a log."`
}
func (cmd *CmdLog) Run(ctx *kong.Context, db *gorm.DB) (err error) {
switch ctx.Command() {
case "log":
if cmd.Last < 1 {
_, err = io.WriteString(ctx.Stderr, "--last must be a positive integer")
return err
}
msg := fmt.Sprintf("| %5s | %s: %s\n", "id", "date", "invocation")
if _, err = io.WriteString(ctx.Stdout, msg); err != nil {
return err
}
var logs []BagelLog
db.Order("date desc").Limit(cmd.Last).Find(&logs)
for _, log := range logs {
t := time.Unix(log.Date, 0)
msg := fmt.Sprintf("| %5d | %s: %s\n", log.ID, t.Format(time.UnixDate), log.Invocation)
if _, err = io.WriteString(ctx.Stdout, msg); err != nil {
return err
}
}
case "log <log-id>":
log, err := BagelLog_Fetch(db, cmd.LogID)
if err != nil {
return err
}
if log.ID == 0 {
_, err = io.WriteString(ctx.Stderr, "no such log found\n")
return err
}
msg := fmt.Sprintf("invoked with: %s\n", log.Invocation)
if _, err = io.WriteString(ctx.Stdout, msg); err != nil {
return err
}
msg = fmt.Sprintf("| %5s | %s: %s\n", "id", "slack id", "usernames")
if _, err = io.WriteString(ctx.Stdout, msg); err != nil {
return err
}
var bagels []Bagel
db.Model(&log).Association("Bagels").Find(&bagels)
for _, bagel := range bagels {
var users []User
db.Model(&bagel).Association("Users").Find(&users)
var usernames []string
for _, user := range users {
usernames = append(usernames, user.Name)
}
msg := fmt.Sprintf("| %5d | %s: %s\n", bagel.ID, bagel.SlackConversationID, strings.Join(usernames, ", "))
if _, err = io.WriteString(ctx.Stdout, msg); err != nil {
return err
}
}
default:
panic(ctx.Command())
}
return nil
}