-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
332 lines (310 loc) Β· 6.84 KB
/
main.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
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
package main
import (
"fmt"
"log"
"os"
"sort"
"sync"
"time"
"github.com/charmbracelet/bubbles/help"
"github.com/charmbracelet/bubbles/key"
"github.com/charmbracelet/bubbles/spinner"
"github.com/charmbracelet/bubbles/table"
tea "github.com/charmbracelet/bubbletea"
"github.com/charmbracelet/lipgloss"
"github.com/cli/go-gh"
"github.com/cli/go-gh/pkg/api"
"github.com/guptarohit/asciigraph"
"github.com/spf13/pflag"
"golang.org/x/sync/errgroup"
)
var (
debug = pflag.BoolP("debug", "d", false, "enable debug output")
)
const (
perPage = 100
reposPath = "repos/%s"
stargazersPath = "repos/%s/stargazers"
)
type view int
const (
viewGraph view = iota
viewTable
)
type state int
const (
stateInit state = iota
stateReady
stateError
)
type ErrorMsg error
type Stargazer struct {
StarredAt time.Time `json:"starred_at"`
}
type StargazersMsg map[string]int
type RepoMsg struct {
StargazersCount int `json:"stargazers_count"`
}
type Repo struct {
state state
view view
width int
height int
error error
name string
client api.RESTClient
stars int
stargazers map[string]int
spinner spinner.Model
table table.Model
help help.Model
showHelp bool
mu sync.Mutex
}
func NewRepo(name string) (*Repo, error) {
client, err := gh.RESTClient(&api.ClientOptions{
Headers: map[string]string{
"Accept": "application/vnd.github.v3.star+json",
},
})
if err != nil {
return nil, err
}
s := spinner.New(spinner.WithSpinner(spinner.Dot))
s.Style = lipgloss.NewStyle().Foreground(lipgloss.Color("205"))
t := table.New(
table.WithColumns(
[]table.Column{
{Title: "Date", Width: 20},
{Title: "Stars", Width: 10},
},
),
table.WithFocused(true),
)
h := help.New()
h.ShowAll = true
return &Repo{
name: name,
client: client,
spinner: s,
table: t,
help: h,
}, nil
}
func (r *Repo) TotalStargazerPages() int {
return r.stars / perPage
}
func (r *Repo) GetStargazers() ([]Stargazer, error) {
pages := r.TotalStargazerPages()
if pages >= 400 {
return nil, fmt.Errorf("Too many pages to fetch")
}
var errg errgroup.Group
stargazers := make([]Stargazer, 0)
for page := 1; page <= pages; page++ {
errg.Go(func(page int) func() error {
return func() error {
path := fmt.Sprintf(stargazersPath+"?page=%d&per_page=%d", r.name, page, perPage)
result := make([]Stargazer, 0)
err := r.client.Get(path, &result)
if err != nil {
return fmt.Errorf("Error fetching stargazers page %d: %w", page, err)
}
r.mu.Lock()
stargazers = append(stargazers, result...)
r.mu.Unlock()
return nil
}
}(page))
}
if err := errg.Wait(); err != nil {
return stargazers, err
}
sort.Slice(stargazers, func(i, j int) bool {
return stargazers[i].StarredAt.Before(stargazers[j].StarredAt)
})
return stargazers, nil
}
func (r *Repo) ShortHelp() []key.Binding {
return []key.Binding{
key.NewBinding(
key.WithKeys("tab", "shift+tab"),
key.WithHelp("tab", "section"),
),
key.NewBinding(
key.WithKeys("?"),
key.WithHelp("?", "help"),
),
key.NewBinding(
key.WithKeys("q", "ctrl+c"),
key.WithHelp("q", "quit"),
),
}
}
func (r *Repo) FullHelp() [][]key.Binding {
return [][]key.Binding{
r.ShortHelp(),
{
r.table.KeyMap.LineUp,
r.table.KeyMap.LineDown,
r.table.KeyMap.PageUp,
r.table.KeyMap.PageDown,
r.table.KeyMap.HalfPageUp,
r.table.KeyMap.HalfPageDown,
r.table.KeyMap.GotoTop,
r.table.KeyMap.GotoBottom,
},
}
}
func (r *Repo) Init() tea.Cmd {
return tea.Batch(func() tea.Msg {
repoMsg := RepoMsg{}
err := r.client.Get(fmt.Sprintf(reposPath, r.name), &repoMsg)
if err != nil {
return ErrorMsg(err)
}
return repoMsg
},
r.spinner.Tick,
)
}
func (r *Repo) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
cmds := make([]tea.Cmd, 0)
switch msg := msg.(type) {
case tea.WindowSizeMsg:
r.width = msg.Width
r.height = msg.Height
r.help.Width = r.width
r.table.SetWidth(r.width)
r.table.SetHeight(r.height - 1)
case tea.KeyMsg:
switch msg.String() {
case "q", "ctrl+c":
return r, tea.Quit
case "tab", "shift+tab":
r.view = (r.view + 1) % 2
case "?":
r.showHelp = !r.showHelp
}
if r.view == viewTable {
var cmd tea.Cmd
r.table, cmd = r.table.Update(msg)
cmds = append(cmds, cmd)
}
case ErrorMsg:
r.state = stateError
r.error = msg.(error)
case spinner.TickMsg:
var cmd tea.Cmd
r.spinner, cmd = r.spinner.Update(msg)
cmds = append(cmds, cmd)
case StargazersMsg:
r.stargazers = msg
case RepoMsg:
r.stars = msg.StargazersCount
r.state = stateReady
cmds = append(cmds, func() tea.Msg {
stargazers, err := r.GetStargazers()
if err != nil {
return ErrorMsg(err)
}
stars := make(map[string]int)
for _, s := range stargazers {
t := s.StarredAt.Format("2006-01-02")
stars[t]++
}
return StargazersMsg(stars)
})
}
return r, tea.Batch(cmds...)
}
func (r *Repo) View() string {
if (r.state != stateReady || r.stargazers == nil) && r.state != stateError {
return fmt.Sprintf("\n %s loading...\n", r.spinner.View())
}
if r.state == stateError {
return fmt.Sprintf("\n Error: %s", r.error)
}
if r.showHelp {
return lipgloss.Place(
r.width,
r.height,
lipgloss.Center,
lipgloss.Center,
r.help.View(r),
)
}
keys := make([]string, 0)
for k := range r.stargazers {
keys = append(keys, k)
}
sort.Strings(keys)
switch r.view {
case viewGraph:
if len(keys) == 0 {
return "\n No stargazers found.\n"
}
offset := 3
plot := make([]float64, len(keys))
for i, k := range keys {
o := fmt.Sprintf("%d", r.stargazers[k])
if len(o) > offset {
offset = len(o)
}
plot[i] = float64(r.stargazers[k])
}
graph := asciigraph.Plot(
plot,
asciigraph.SeriesColors(asciigraph.Blue),
asciigraph.Width(r.width-offset-1),
asciigraph.Height(r.height-2),
asciigraph.Caption(fmt.Sprintf("%s %d stargazers over time", r.name, r.stars)),
asciigraph.Precision(0),
asciigraph.Offset(offset),
)
return graph
case viewTable:
rows := make([]table.Row, len(keys))
for i, j := len(keys)-1, 0; i >= 0; i, j = i-1, j+1 {
k := keys[i]
rows[j] = table.Row{k, fmt.Sprintf("%d", r.stargazers[k])}
}
r.table.SetRows(rows)
return r.table.View()
default:
return ""
}
}
func main() {
var repo string
pflag.Parse()
r, err := gh.CurrentRepository()
if err == nil {
repo = fmt.Sprintf("%s/%s", r.Owner(), r.Name())
}
if len(pflag.Args()) > 0 {
repo = pflag.Args()[0]
}
if repo == "" {
fmt.Printf("Error: no repository specified\n\n%s\n", "Usage: gh stars [repository]")
os.Exit(1)
}
m, err := NewRepo(repo)
if err != nil {
log.Fatalln(err)
}
if *debug {
f, err := tea.LogToFile("debug.txt", "gh-stars")
if err != nil {
log.Fatalln(err)
}
defer f.Close()
}
p := tea.NewProgram(
m,
tea.WithAltScreen(),
)
if err := p.Start(); err != nil {
log.Fatalln(err)
}
}