-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
335 lines (270 loc) · 6.4 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
333
334
335
package main
import (
"bytes"
"crypto/rand"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"log"
"math"
"net/url"
"os"
"strings"
"github.com/charmbracelet/huh"
"github.com/charmbracelet/huh/spinner"
"github.com/cli/go-gh"
"github.com/cli/go-gh/v2/pkg/api"
)
var (
operation string
auth struct{ Login string }
selectedRepositories []string
confirmedRandomText string
actionLabels = map[string]interface{}{
"delete": "deleted",
"archive": "archived",
}
inProgressActionLabels = map[string]interface{}{
"delete": "Deleteing",
"archive": "Archiving",
}
)
func main() {
checkTokenScope()
client, err := api.DefaultRESTClient()
if err != nil {
fmt.Println("Error creating API client:", err)
os.Exit(0)
return
}
err = client.Get("user", &auth)
if err != nil {
fmt.Println(err)
os.Exit(0)
return
}
for {
operation = selectOperation()
if operation == "exit" {
os.Exit(0)
}
repoOptions := fetchReposOptions(client)
if len(repoOptions) == 0 {
fmt.Println("No Repositories Found.")
continue
}
selectedRepositories = selectRepositories(repoOptions)
if len(selectedRepositories) == 0 {
fmt.Println("No Repositories Found.")
continue
}
fmt.Println("Selected Repositories: ")
for _, repo := range selectedRepositories {
fmt.Println(repo)
}
confirmText()
isConfirmed := confirmAction()
if isConfirmed {
err = spinner.New().
Title(fmt.Sprintf("%s repositories...", inProgressActionLabels[operation])).
Action(func() {
if operation == "delete" {
deleteRepos(client, selectedRepositories)
} else if operation == "archive" {
archiveRepos(client, selectedRepositories)
}
}).
Run()
if err != nil {
log.Fatal(err)
}
}
}
}
func checkTokenScope() {
statusContent, _, err := gh.Exec("auth", "status")
if err != nil {
log.Fatal(err)
os.Exit(0)
}
// Convert output to string and split into lines
outputStr := string(statusContent.String())
lines := strings.Split(outputStr, "\n")
// Find the line that contains "Token scopes"
var scopesLine string
for _, line := range lines {
if strings.Contains(line, "Token scopes") {
scopesLine = line
break
}
}
if scopesLine == "" {
fmt.Println("No Token scopes found in the output.")
os.Exit(0)
}
// Check if "delete_repo" is in the scopes
hasDeleteRepo := strings.Contains(scopesLine, "delete_repo")
if !hasDeleteRepo {
fmt.Println("You don't have 'delete_repo' scope in your gh token.")
fmt.Println("Refresh your token by running `gh auth refresh -s delete_repo` in your cli.")
os.Exit(0)
}
}
func randomBase64String(l int) string {
buff := make([]byte, int(math.Ceil(float64(l)/float64(1.33333333333))))
rand.Read(buff)
str := base64.RawURLEncoding.EncodeToString(buff)
return str[:l] // strip 1 extra character we get from odd length results
}
func selectOperation() string {
var value string
form := huh.NewForm(
huh.NewGroup(
huh.NewSelect[string]().
Title("Choose operation").
Options(
huh.NewOption("Bulk: Delete repositories", "delete"),
huh.NewOption("Bulk: Archive repositories", "archive"),
huh.NewOption("Exit", "exit"),
).
Value(&value),
),
)
err := form.Run()
if err != nil {
os.Exit(0)
}
return value
}
func selectRepositories(repoOptions []huh.Option[string]) []string {
var selections []string
form := huh.NewForm(
huh.NewGroup(
huh.NewMultiSelect[string]().
Title("Select Repositories to Process").
Options(repoOptions...).
Filterable(false).
Value(&selections).
Height(8),
),
).
WithTheme(huh.ThemeDracula())
err := form.Run()
if err != nil {
os.Exit(0)
}
return selections
}
func confirmText() string {
randomText := randomBase64String(8)
form := huh.NewForm(
huh.NewGroup(
huh.NewInput().
Title("Confirm the text?").
Description(randomText).
Prompt("? ").
Validate(func(s string) error {
if s != randomText {
return errors.New("sorry, confirmation text didn't match")
}
return nil
}).
Value(&confirmedRandomText),
),
)
err := form.Run()
if err != nil {
os.Exit(0)
}
return confirmedRandomText
}
func confirmAction() bool {
var isConfirmed bool
repoLabel := "repo"
if len(selectedRepositories) > 1 {
repoLabel = "repos"
}
form := huh.NewForm(
huh.NewGroup(
huh.NewConfirm().
Title(fmt.Sprintf("❌ %d %s will be %s. Want to proceed? ❌", len(selectedRepositories), repoLabel, actionLabels[operation])).
Affirmative("Yes!").
Negative("No.").
Value(&isConfirmed),
),
)
err := form.Run()
if err != nil {
os.Exit(0)
}
return isConfirmed
}
func fetchReposOptions(client *api.RESTClient) []huh.Option[string] {
var searchQuery string
form := huh.NewForm(
huh.NewGroup(
huh.NewInput().
Title("Search").
Prompt("? ").
Description("Empty query will return 100 repositories").
Value(&searchQuery),
),
)
ierr := form.
Run()
if ierr != nil {
fmt.Println(ierr)
os.Exit(0)
}
fmt.Println("Fetching repositories...")
queryParams := url.QueryEscape(fmt.Sprintf("%s user:%s", searchQuery, auth.Login))
queryParams = strings.Trim(queryParams, " ")
var result map[string]interface{}
err := client.Get("search/repositories?q="+queryParams, &result)
if err != nil {
log.Panic("Error fetching repositories:", err)
os.Exit(0)
}
var opions []huh.Option[string]
// Extract repository names from the search result
if items, ok := result["items"].([]interface{}); ok {
for _, item := range items {
if repo, ok := item.(map[string]interface{}); ok {
if name, ok := repo["name"].(string); ok {
opions = append(opions, huh.NewOption(name, name))
}
}
}
}
return opions
}
func deleteRepos(client *api.RESTClient, repos []string) {
for _, repo := range repos {
var resp string
var err = client.Delete("repos/"+auth.Login+"/"+repo, &resp)
if err != nil {
fmt.Println(err)
return
}
fmt.Println("Deleted " + repo)
}
}
func archiveRepos(client *api.RESTClient, repos []string) {
body := map[string]interface{}{
"archived": true,
}
jsonBody, err := json.Marshal(body)
if err != nil {
log.Fatalf("impossible to build request: %s", err)
}
for _, repo := range repos {
var resp interface{}
err := client.Patch("repos/"+auth.Login+"/"+repo, bytes.NewReader(jsonBody), &resp)
if err != nil {
fmt.Println(err)
return
}
fmt.Println("Archived " + repo)
}
}