-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcli.go
More file actions
226 lines (206 loc) · 6.24 KB
/
Copy pathcli.go
File metadata and controls
226 lines (206 loc) · 6.24 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
package main
import (
"context"
"errors"
"flag"
"fmt"
"os"
"regexp"
"strings"
"time"
"github.com/toshonjennings/github-overview/internal/github"
"github.com/toshonjennings/github-overview/internal/store"
)
var repoPattern = regexp.MustCompile(`^[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+$`)
// reorderArgs moves flag tokens (and, for flags listed in valueFlags, the
// value token that follows them) ahead of positional arguments. The stdlib
// flag package stops recognizing flags at the first positional argument, but
// the CLI contract (§3) places flags after the repo argument, e.g.
// "remove owner/name -f".
func reorderArgs(args []string, valueFlags map[string]bool) []string {
var flags, positional []string
for i := 0; i < len(args); i++ {
a := args[i]
if !strings.HasPrefix(a, "-") {
positional = append(positional, a)
continue
}
flags = append(flags, a)
name := strings.TrimLeft(a, "-")
if !strings.Contains(name, "=") && valueFlags[name] && i+1 < len(args) {
i++
flags = append(flags, args[i])
}
}
return append(flags, positional...)
}
func runAdd(args []string) error {
args = reorderArgs(args, map[string]bool{"db": true, "interval": true})
fset := flag.NewFlagSet("add", flag.ContinueOnError)
dbPath := fset.String("db", "data/app.db", "path to sqlite database")
interval := fset.Duration("interval", 60*time.Second, "poll interval")
if err := fset.Parse(args); err != nil {
return err
}
if fset.NArg() != 1 {
return fmt.Errorf("usage: github-overview add <owner>/<name> [-interval 60s]")
}
repo := fset.Arg(0)
if !repoPattern.MatchString(repo) {
return fmt.Errorf("invalid repo %q: expected owner/name", repo)
}
if *interval < 15*time.Second {
return fmt.Errorf("interval must be at least 15s, got %s", *interval)
}
owner, name, _ := strings.Cut(repo, "/")
s, err := store.Open(*dbPath)
if err != nil {
return fmt.Errorf("open store: %w", err)
}
defer s.Close()
if _, err := s.AddRepo(owner, name, int(interval.Seconds())); err != nil {
if errors.Is(err, store.ErrDuplicate) {
fmt.Printf("already tracked: %s\n", repo)
return nil
}
return fmt.Errorf("add repo: %w", err)
}
fmt.Printf("tracking %s\n", repo)
return nil
}
// runImport tracks every repo the token's owner directly owns (affiliation
// "owner" -- not org repos merely collaborated on, to avoid an org member
// accidentally bulk-importing repos that aren't really "theirs"). Requires a
// token: GitHub has no way to list "my repos" unauthenticated.
func runImport(args []string) error {
args = reorderArgs(args, map[string]bool{"db": true, "interval": true})
fset := flag.NewFlagSet("import", flag.ContinueOnError)
dbPath := fset.String("db", "data/app.db", "path to sqlite database")
interval := fset.Duration("interval", 60*time.Second, "poll interval for imported repos")
if err := fset.Parse(args); err != nil {
return err
}
if *interval < 15*time.Second {
return fmt.Errorf("interval must be at least 15s, got %s", *interval)
}
token := os.Getenv("GITHUB_TOKEN")
if token == "" {
token = os.Getenv("GH_TOKEN")
}
if token == "" {
return fmt.Errorf("import requires GITHUB_TOKEN (or GH_TOKEN): GitHub has no way to list \"my repos\" unauthenticated")
}
repos, err := github.NewClient(token).FetchUserRepos(context.Background())
if err != nil {
return fmt.Errorf("list your GitHub repos: %w", err)
}
if len(repos) == 0 {
fmt.Println("no repos found for this token")
return nil
}
s, err := store.Open(*dbPath)
if err != nil {
return fmt.Errorf("open store: %w", err)
}
defer s.Close()
added, skipped := 0, 0
for _, r := range repos {
owner, name, ok := strings.Cut(r.FullName, "/")
if !ok {
continue
}
if _, err := s.AddRepo(owner, name, int(interval.Seconds())); err != nil {
if errors.Is(err, store.ErrDuplicate) {
skipped++
continue
}
return fmt.Errorf("add repo %s: %w", r.FullName, err)
}
added++
fmt.Printf("tracking %s\n", r.FullName)
}
fmt.Printf("imported %d repo(s), %d already tracked\n", added, skipped)
return nil
}
func runList(args []string) error {
fset := flag.NewFlagSet("list", flag.ContinueOnError)
dbPath := fset.String("db", "data/app.db", "path to sqlite database")
if err := fset.Parse(args); err != nil {
return err
}
s, err := store.Open(*dbPath)
if err != nil {
return fmt.Errorf("open store: %w", err)
}
defer s.Close()
repos, err := s.ListRepos()
if err != nil {
return fmt.Errorf("list repos: %w", err)
}
if len(repos) == 0 {
fmt.Println("no repos tracked")
return nil
}
for _, r := range repos {
lastPolled := r.LastPolledAt
if lastPolled == "" {
lastPolled = "never"
}
line := fmt.Sprintf("%s/%s\tlast_polled=%s", r.Owner, r.Name, lastPolled)
if r.LastError != "" {
line += fmt.Sprintf("\terror=%s", r.LastError)
}
fmt.Println(line)
}
return nil
}
func runRemove(args []string) error {
args = reorderArgs(args, map[string]bool{"db": true})
fset := flag.NewFlagSet("remove", flag.ContinueOnError)
dbPath := fset.String("db", "data/app.db", "path to sqlite database")
force := fset.Bool("f", false, "actually delete (required)")
if err := fset.Parse(args); err != nil {
return err
}
if fset.NArg() != 1 {
return fmt.Errorf("usage: github-overview remove <owner>/<name> -f")
}
repo := fset.Arg(0)
if !repoPattern.MatchString(repo) {
return fmt.Errorf("invalid repo %q: expected owner/name", repo)
}
owner, name, _ := strings.Cut(repo, "/")
s, err := store.Open(*dbPath)
if err != nil {
return fmt.Errorf("open store: %w", err)
}
defer s.Close()
repos, err := s.ListRepos()
if err != nil {
return fmt.Errorf("list repos: %w", err)
}
var target *store.Repo
for i := range repos {
if repos[i].Owner == owner && repos[i].Name == name {
target = &repos[i]
break
}
}
if target == nil {
return fmt.Errorf("not tracked: %s", repo)
}
if !*force {
commits, runs, deps, issues, prs, err := s.RepoHistoryCounts(target.ID)
if err != nil {
return fmt.Errorf("history counts: %w", err)
}
fmt.Printf("refusing to remove %s without -f (would delete: %d commits, %d runs, %d dependency alerts, %d issues, %d PRs)\n",
repo, commits, runs, deps, issues, prs)
return nil
}
if err := s.RemoveRepo(owner, name); err != nil {
return fmt.Errorf("remove repo: %w", err)
}
fmt.Printf("removed %s\n", repo)
return nil
}