-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
output.go
111 lines (94 loc) · 2.59 KB
/
output.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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
package main
import (
"bytes"
"fmt"
"text/template"
"time"
"github.com/nilic/hntop-cli/htclient"
"github.com/nilic/hntop-cli/internal/mailer"
"github.com/sersh88/timeago"
"github.com/urfave/cli/v2"
)
const (
listTemplate = `{{if .FrontPage}}Displaying HN posts currently on the front page{{else}}Displaying top {{.ResultCount}} HN posts from {{.StartTime}} to {{.EndTime}}{{end -}}
{{if .Hits}}
{{range $i, $e := .Hits}}
{{increment $i}}. {{.Title}}{{if ne .BaseExternalURL ""}} ({{.BaseExternalURL}}){{end}}
{{.ExternalURL}}
{{- if ne .ItemURL .ExternalURL}}
{{.ItemURL}}
{{- end}}
{{.Points}} points by {{.Author}} {{timeAgo .CreatedAt}} | {{.NumComments}} comments
{{end}}
{{end}}`
)
var templateFuncs = template.FuncMap{
"increment": increment,
"mod": mod,
"timeAgo": timeAgo,
}
type templateData struct {
FrontPage bool
ResultCount int
StartTime string
EndTime string
Christmas bool
Hits []htclient.Hit
}
func output(cCtx *cli.Context, q *htclient.Query, h *htclient.Hits) error {
t := time.Now()
var td = templateData{
FrontPage: q.FrontPage,
ResultCount: q.ResultCount,
StartTime: (time.Unix(q.StartTime, 0)).Format(time.RFC822),
EndTime: (time.Unix(q.EndTime, 0)).Format(time.RFC822),
Christmas: t.Month().String() == "December" && t.Day() == 25,
Hits: h.Hits,
}
switch cCtx.String("output") {
case "list":
output, err := outputList(td)
if err != nil {
return fmt.Errorf("creating list output: %w", err)
}
fmt.Print(output)
return nil
case "mail":
mc, err := mailer.New(cCtx.String("mail-from"),
cCtx.String("mail-server"),
cCtx.Int("mail-port"),
cCtx.String("mail-username"),
cCtx.String("mail-password"),
cCtx.String("mail-auth"),
cCtx.String("mail-tls"))
if err != nil {
return fmt.Errorf("configuring mail client: %w", err)
}
if err := mc.SendTemplate(cCtx.String("mail-to"), "hntop.tmpl", templateFuncs, td); err != nil {
return fmt.Errorf("sending mail: %w", err)
}
return nil
default:
return fmt.Errorf("unknown output type: %q", cCtx.String("output"))
}
}
func outputList(td templateData) (string, error) {
t, err := template.New("list").Funcs(templateFuncs).Parse(listTemplate)
if err != nil {
return "", fmt.Errorf("creating template: %w", err)
}
buf := new(bytes.Buffer)
if err := t.ExecuteTemplate(buf, "list", td); err != nil {
return "", fmt.Errorf("executing template: %w", err)
}
return buf.String(), nil
}
func increment(i int) int {
return i + 1
}
func mod(i, j int) bool {
return i%j == 0
}
func timeAgo(t time.Time) string {
return timeago.New(t).Format()
}