forked from cli/cli
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstatus.go
More file actions
619 lines (539 loc) · 14.7 KB
/
status.go
File metadata and controls
619 lines (539 loc) · 14.7 KB
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
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
package status
import (
"bytes"
"errors"
"fmt"
"net/http"
"net/url"
"sort"
"strings"
"time"
"github.com/MakeNowJust/heredoc"
"github.com/charmbracelet/lipgloss"
"github.com/cli/cli/v2/api"
"github.com/cli/cli/v2/internal/ghinstance"
"github.com/cli/cli/v2/pkg/cmdutil"
"github.com/cli/cli/v2/pkg/iostreams"
"github.com/cli/cli/v2/utils"
"github.com/spf13/cobra"
"golang.org/x/sync/errgroup"
)
type StatusOptions struct {
HttpClient func() (*http.Client, error)
CachedClient func(*http.Client, time.Duration) *http.Client
IO *iostreams.IOStreams
Org string
Exclude []string
}
func NewCmdStatus(f *cmdutil.Factory, runF func(*StatusOptions) error) *cobra.Command {
opts := &StatusOptions{
CachedClient: func(c *http.Client, ttl time.Duration) *http.Client {
return api.NewCachedClient(c, ttl)
},
}
opts.HttpClient = f.HttpClient
opts.IO = f.IOStreams
cmd := &cobra.Command{
Use: "status",
Short: "Print information about relevant issues, pull requests, and notifications across repositories",
Long: heredoc.Doc(`
The status command prints information about your work on GitHub across all the repositories you're subscribed to, including:
- Assigned Issues
- Assigned Pull Requests
- Review Requests
- Mentions
- Repository Activity (new issues/pull requests, comments)
`),
Example: heredoc.Doc(`
$ gh status -e cli/cli -e cli/go-gh # Exclude multiple repositories
$ gh status -o cli # Limit results to a single organization
`),
RunE: func(cmd *cobra.Command, args []string) error {
if runF != nil {
return runF(opts)
}
return statusRun(opts)
},
}
cmd.Flags().StringVarP(&opts.Org, "org", "o", "", "Report status within an organization")
cmd.Flags().StringSliceVarP(&opts.Exclude, "exclude", "e", []string{}, "Comma separated list of repos to exclude in owner/name format")
return cmd
}
type Notification struct {
Reason string
Subject struct {
Title string
LatestCommentURL string `json:"latest_comment_url"`
URL string
Type string
}
Repository struct {
Owner struct {
Login string
}
FullName string `json:"full_name"`
}
}
type StatusItem struct {
Repository string // owner/repo
Identifier string // eg cli/cli#1234 or just 1234
preview string // eg This is the truncated body of something...
Reason string // only used in repo activity
}
func (s StatusItem) Preview() string {
return strings.ReplaceAll(strings.ReplaceAll(s.preview, "\r", ""), "\n", " ")
}
type IssueOrPR struct {
Number int
Title string
}
type Event struct {
Type string
Org struct {
Login string
}
CreatedAt time.Time `json:"created_at"`
Repo struct {
Name string // owner/repo
}
Payload struct {
Action string
Issue IssueOrPR
PullRequest IssueOrPR `json:"pull_request"`
Comment struct {
Body string
HTMLURL string `json:"html_url"`
}
}
}
type SearchResult struct {
Type string `json:"__typename"`
UpdatedAt time.Time
Title string
Number int
Repository struct {
NameWithOwner string
}
}
type Results []SearchResult
func (rs Results) Len() int {
return len(rs)
}
func (rs Results) Less(i, j int) bool {
return rs[i].UpdatedAt.After(rs[j].UpdatedAt)
}
func (rs Results) Swap(i, j int) {
rs[i], rs[j] = rs[j], rs[i]
}
type StatusGetter struct {
Client *http.Client
cachedClient func(*http.Client, time.Duration) *http.Client
Org string
Exclude []string
AssignedPRs []StatusItem
AssignedIssues []StatusItem
Mentions []StatusItem
ReviewRequests []StatusItem
RepoActivity []StatusItem
}
func NewStatusGetter(client *http.Client, opts *StatusOptions) *StatusGetter {
return &StatusGetter{
Client: client,
Org: opts.Org,
Exclude: opts.Exclude,
cachedClient: opts.CachedClient,
}
}
func (s *StatusGetter) CachedClient(ttl time.Duration) *http.Client {
return s.cachedClient(s.Client, ttl)
}
func (s *StatusGetter) ShouldExclude(repo string) bool {
for _, exclude := range s.Exclude {
if repo == exclude {
return true
}
}
return false
}
func (s *StatusGetter) CurrentUsername() (string, error) {
cachedClient := s.CachedClient(time.Hour * 48)
cachingAPIClient := api.NewClientFromHTTP(cachedClient)
currentUsername, err := api.CurrentLoginName(cachingAPIClient, ghinstance.Default())
if err != nil {
return "", fmt.Errorf("failed to get current username: %w", err)
}
return currentUsername, nil
}
func (s *StatusGetter) ActualMention(n Notification) (string, error) {
currentUsername, err := s.CurrentUsername()
if err != nil {
return "", err
}
// long cache period since once a comment is looked up, it never needs to be
// consulted again.
cachedClient := s.CachedClient(time.Hour * 24 * 30)
c := api.NewClientFromHTTP(cachedClient)
resp := struct {
Body string
}{}
if err := c.REST(ghinstance.Default(), "GET", n.Subject.LatestCommentURL, nil, &resp); err != nil {
return "", err
}
var ret string
if strings.Contains(resp.Body, "@"+currentUsername) {
ret = resp.Body
}
return ret, nil
}
// These are split up by endpoint since it is along that boundary we parallelize
// work
// Populate .Mentions
func (s *StatusGetter) LoadNotifications() error {
perPage := 100
c := api.NewClientFromHTTP(s.Client)
query := url.Values{}
query.Add("per_page", fmt.Sprintf("%d", perPage))
query.Add("participating", "true")
query.Add("all", "true")
// this sucks, having to fetch so much :/ but it was the only way in my
// testing to really get enough mentions. I would love to be able to just
// filter for mentions but it does not seem like the notifications API can
// do that. I'd switch to the GraphQL version, but to my knowledge that does
// not work with PATs right now.
var ns []Notification
var resp []Notification
pages := 0
p := fmt.Sprintf("notifications?%s", query.Encode())
for pages < 3 {
next, err := c.RESTWithNext(ghinstance.Default(), "GET", p, nil, &resp)
if err != nil {
var httpErr api.HTTPError
if !errors.As(err, &httpErr) || httpErr.StatusCode != 404 {
return fmt.Errorf("could not get notifications: %w", err)
}
}
ns = append(ns, resp...)
if next == "" || len(resp) < perPage {
break
}
pages++
p = next
}
s.Mentions = []StatusItem{}
for _, n := range ns {
if n.Reason != "mention" {
continue
}
if s.Org != "" && n.Repository.Owner.Login != s.Org {
continue
}
if s.ShouldExclude(n.Repository.FullName) {
continue
}
if actual, err := s.ActualMention(n); actual != "" && err == nil {
// I'm so sorry
split := strings.Split(n.Subject.URL, "/")
s.Mentions = append(s.Mentions, StatusItem{
Repository: n.Repository.FullName,
Identifier: fmt.Sprintf("%s#%s", n.Repository.FullName, split[len(split)-1]),
preview: actual,
})
} else if err != nil {
return fmt.Errorf("could not fetch comment: %w", err)
}
}
return nil
}
func (s *StatusGetter) buildSearchQuery() string {
q := `
query AssignedSearch {
assignments: search(first: 25, type: ISSUE, query:"%s") {
edges {
node {
...on Issue {
__typename
updatedAt
title
number
repository {
nameWithOwner
}
}
...on PullRequest {
updatedAt
__typename
title
number
repository {
nameWithOwner
}
}
}
}
}
reviewRequested: search(first: 25, type: ISSUE, query:"%s") {
edges {
node {
...on PullRequest {
updatedAt
__typename
title
number
repository {
nameWithOwner
}
}
}
}
}
}`
assignmentsQ := `assignee:@me state:open%s%s`
requestedQ := `state:open review-requested:@me%s%s`
orgFilter := ""
if s.Org != "" {
orgFilter = " org:" + s.Org
}
excludeFilter := ""
for _, repo := range s.Exclude {
excludeFilter += " -repo:" + repo
}
assignmentsQ = fmt.Sprintf(assignmentsQ, orgFilter, excludeFilter)
requestedQ = fmt.Sprintf(requestedQ, orgFilter, excludeFilter)
return fmt.Sprintf(q, assignmentsQ, requestedQ)
}
// Populate .AssignedPRs, .AssignedIssues, .ReviewRequests
func (s *StatusGetter) LoadSearchResults() error {
q := s.buildSearchQuery()
c := api.NewClientFromHTTP(s.Client)
var resp struct {
Assignments struct {
Edges []struct {
Node SearchResult
}
}
ReviewRequested struct {
Edges []struct {
Node SearchResult
}
}
}
err := c.GraphQL(ghinstance.Default(), q, nil, &resp)
if err != nil {
return fmt.Errorf("could not search for assignments: %w", err)
}
prs := []SearchResult{}
issues := []SearchResult{}
reviewRequested := []SearchResult{}
for _, e := range resp.Assignments.Edges {
if e.Node.Type == "Issue" {
issues = append(issues, e.Node)
} else if e.Node.Type == "PullRequest" {
prs = append(prs, e.Node)
} else {
panic("you shouldn't be here")
}
}
for _, e := range resp.ReviewRequested.Edges {
reviewRequested = append(reviewRequested, e.Node)
}
sort.Sort(Results(issues))
sort.Sort(Results(prs))
sort.Sort(Results(reviewRequested))
s.AssignedIssues = []StatusItem{}
s.AssignedPRs = []StatusItem{}
s.ReviewRequests = []StatusItem{}
for _, i := range issues {
s.AssignedIssues = append(s.AssignedIssues, StatusItem{
Repository: i.Repository.NameWithOwner,
Identifier: fmt.Sprintf("%s#%d", i.Repository.NameWithOwner, i.Number),
preview: i.Title,
})
}
for _, pr := range prs {
s.AssignedPRs = append(s.AssignedPRs, StatusItem{
Repository: pr.Repository.NameWithOwner,
Identifier: fmt.Sprintf("%s#%d", pr.Repository.NameWithOwner, pr.Number),
preview: pr.Title,
})
}
for _, r := range reviewRequested {
s.ReviewRequests = append(s.ReviewRequests, StatusItem{
Repository: r.Repository.NameWithOwner,
Identifier: fmt.Sprintf("%s#%d", r.Repository.NameWithOwner, r.Number),
preview: r.Title,
})
}
return nil
}
// Populate .RepoActivity
func (s *StatusGetter) LoadEvents() error {
perPage := 100
c := api.NewClientFromHTTP(s.Client)
query := url.Values{}
query.Add("per_page", fmt.Sprintf("%d", perPage))
currentUsername, err := s.CurrentUsername()
if err != nil {
return err
}
var events []Event
var resp []Event
pages := 0
p := fmt.Sprintf("users/%s/received_events?%s", currentUsername, query.Encode())
for pages < 2 {
next, err := c.RESTWithNext(ghinstance.Default(), "GET", p, nil, &resp)
if err != nil {
var httpErr api.HTTPError
if !errors.As(err, &httpErr) || httpErr.StatusCode != 404 {
return fmt.Errorf("could not get events: %w", err)
}
}
events = append(events, resp...)
if next == "" || len(resp) < perPage {
break
}
pages++
p = next
}
s.RepoActivity = []StatusItem{}
for _, e := range events {
if s.Org != "" && e.Org.Login != s.Org {
continue
}
if s.ShouldExclude(e.Repo.Name) {
continue
}
si := StatusItem{}
var number int
switch e.Type {
case "IssuesEvent":
if e.Payload.Action != "opened" {
continue
}
si.Reason = "new issue"
si.preview = e.Payload.Issue.Title
number = e.Payload.Issue.Number
case "PullRequestEvent":
if e.Payload.Action != "opened" {
continue
}
si.Reason = "new PR"
si.preview = e.Payload.PullRequest.Title
number = e.Payload.PullRequest.Number
case "PullRequestReviewCommentEvent":
si.Reason = "comment on " + e.Payload.PullRequest.Title
si.preview = e.Payload.Comment.Body
number = e.Payload.PullRequest.Number
case "IssueCommentEvent":
si.Reason = "comment on " + e.Payload.Issue.Title
si.preview = e.Payload.Comment.Body
number = e.Payload.Issue.Number
default:
continue
}
si.Repository = e.Repo.Name
si.Identifier = fmt.Sprintf("%s#%d", e.Repo.Name, number)
s.RepoActivity = append(s.RepoActivity, si)
}
return nil
}
func statusRun(opts *StatusOptions) error {
client, err := opts.HttpClient()
if err != nil {
return fmt.Errorf("could not create client: %w", err)
}
sg := NewStatusGetter(client, opts)
// TODO break out sections into individual subcommands
g := new(errgroup.Group)
opts.IO.StartProgressIndicator()
g.Go(func() error {
err := sg.LoadNotifications()
if err != nil {
err = fmt.Errorf("could not load notifications: %w", err)
}
return err
})
g.Go(func() error {
err := sg.LoadEvents()
if err != nil {
err = fmt.Errorf("could not load events: %w", err)
}
return err
})
g.Go(func() error {
err := sg.LoadSearchResults()
if err != nil {
err = fmt.Errorf("failed to search: %w", err)
}
return err
})
err = g.Wait()
if err != nil {
return err
}
opts.IO.StopProgressIndicator()
cs := opts.IO.ColorScheme()
out := opts.IO.Out
fullWidth := opts.IO.TerminalWidth()
halfWidth := (fullWidth / 2) - 2
idStyle := cs.Cyan
leftHalfStyle := lipgloss.NewStyle().Width(halfWidth).Padding(0).MarginRight(1).BorderRight(true).BorderStyle(lipgloss.NormalBorder())
rightHalfStyle := lipgloss.NewStyle().Width(halfWidth).Padding(0)
section := func(header string, items []StatusItem, width, rowLimit int) (string, error) {
tableOut := &bytes.Buffer{}
fmt.Fprintln(tableOut, cs.Bold(header))
tp := utils.NewTablePrinterWithOptions(opts.IO, utils.TablePrinterOptions{
IsTTY: opts.IO.IsStdoutTTY(),
MaxWidth: width,
Out: tableOut,
})
if len(items) == 0 {
tp.AddField("Nothing here ^_^", nil, nil)
tp.EndRow()
} else {
for i, si := range items {
if i == rowLimit {
break
}
tp.AddField(si.Identifier, nil, idStyle)
if si.Reason != "" {
tp.AddField(si.Reason, nil, nil)
}
tp.AddField(si.Preview(), nil, nil)
tp.EndRow()
}
}
err := tp.Render()
if err != nil {
return "", err
}
return tableOut.String(), nil
}
mSection, err := section("Mentions", sg.Mentions, halfWidth, 5)
if err != nil {
return fmt.Errorf("failed to render 'Mentions': %w", err)
}
mSection = rightHalfStyle.Render(mSection)
rrSection, err := section("Review Requests", sg.ReviewRequests, halfWidth, 5)
if err != nil {
return fmt.Errorf("failed to render 'Review Requests': %w", err)
}
rrSection = leftHalfStyle.Render(rrSection)
prSection, err := section("Assigned Pull Requests", sg.AssignedPRs, halfWidth, 5)
if err != nil {
return fmt.Errorf("failed to render 'Assigned Pull Requests': %w", err)
}
prSection = rightHalfStyle.Render(prSection)
issueSection, err := section("Assigned Issues", sg.AssignedIssues, halfWidth, 5)
if err != nil {
return fmt.Errorf("failed to render 'Assigned Issues': %w", err)
}
issueSection = leftHalfStyle.Render(issueSection)
raSection, err := section("Repository Activity", sg.RepoActivity, fullWidth, 10)
if err != nil {
return fmt.Errorf("failed to render 'Repository Activity': %w", err)
}
fmt.Fprintln(out, lipgloss.JoinHorizontal(lipgloss.Top, issueSection, prSection))
fmt.Fprintln(out, lipgloss.JoinHorizontal(lipgloss.Top, rrSection, mSection))
fmt.Fprintln(out, raSection)
return nil
}