-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
286 lines (252 loc) · 7.32 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
package main
import (
"bufio"
"encoding/json"
"fmt"
"os"
"os/exec"
"strings"
"time"
"github.com/fatih/color"
"github.com/spf13/cobra"
)
type Owner struct {
ID string `json:"id"`
Login string `json:"login"`
}
type Repo struct {
Name string `json:"name"`
Owner Owner `json:"owner"`
NameWithOwner string `json:"nameWithOwner"`
UpdatedAt string `json:"updatedAt"`
}
type PullRequestInfo struct {
HeadRepository struct {
NameWithOwner string `json:"nameWithOwner"`
} `json:"headRepository"`
Number int `json:"number"`
Title string `json:"title"`
Url string `json:"url"`
}
func showSpinner(done chan bool) {
spinner := []string{"⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"}
i := 0
for {
select {
case <-done:
fmt.Print("\r") // Clear the spinner
return
default:
fmt.Printf("\r%s Fetching forks", spinner[i])
i = (i + 1) % len(spinner)
time.Sleep(100 * time.Millisecond)
}
}
}
func getReposWithOpenPRs() (map[string][]PullRequestInfo, error) {
// GraphQL query to get all open PRs
query := `
query {
viewer {
pullRequests(states: [OPEN], first: 100) {
nodes {
headRepository {
nameWithOwner
}
number
title
url
}
}
}
}
`
cmd := exec.Command("gh", "api", "graphql", "-f", fmt.Sprintf("query=%s", query))
out, err := cmd.CombinedOutput()
if err != nil {
return nil, fmt.Errorf("error fetching open PRs: %v\nOutput: %s", err, string(out))
}
// Parse the GraphQL response
type Response struct {
Data struct {
Viewer struct {
PullRequests struct {
Nodes []PullRequestInfo `json:"nodes"`
} `json:"pullRequests"`
} `json:"viewer"`
} `json:"data"`
}
var resp Response
if err := json.Unmarshal(out, &resp); err != nil {
return nil, fmt.Errorf("error parsing GraphQL response: %v", err)
}
// Create a map of repos with open PRs and their info
reposWithPRs := make(map[string][]PullRequestInfo)
for _, node := range resp.Data.Viewer.PullRequests.Nodes {
if node.HeadRepository.NameWithOwner != "" {
reposWithPRs[node.HeadRepository.NameWithOwner] = append(
reposWithPRs[node.HeadRepository.NameWithOwner],
PullRequestInfo{
HeadRepository: node.HeadRepository,
Number: node.Number,
Title: node.Title,
Url: node.Url,
},
)
}
}
return reposWithPRs, nil
}
func getForks() ([]Repo, error) {
// GraphQL query to get all forks with pagination
query := `
query($after: String) {
viewer {
repositories(first: 100, after: $after, isFork: true, orderBy: {field: UPDATED_AT, direction: DESC}) {
nodes {
name
nameWithOwner
updatedAt
owner {
login
id
}
}
pageInfo {
hasNextPage
endCursor
}
}
}
}
`
var forks []Repo
var cursor string
hasNextPage := true
for hasNextPage {
// Build the command with the cursor
args := []string{"api", "graphql", "-f", fmt.Sprintf("query=%s", query)}
if cursor != "" {
args = append(args, "-f", fmt.Sprintf("after=%s", cursor))
}
cmd := exec.Command("gh", args...)
out, err := cmd.CombinedOutput()
if err != nil {
return nil, fmt.Errorf("error fetching forks: %v\nOutput: %s", err, string(out))
}
// Parse the GraphQL response
type Response struct {
Data struct {
Viewer struct {
Repositories struct {
Nodes []Repo `json:"nodes"`
PageInfo struct {
HasNextPage bool `json:"hasNextPage"`
EndCursor string `json:"endCursor"`
} `json:"pageInfo"`
} `json:"repositories"`
} `json:"viewer"`
} `json:"data"`
}
var resp Response
if err := json.Unmarshal(out, &resp); err != nil {
return nil, fmt.Errorf("error parsing GraphQL response: %v", err)
}
// Append the forks from this page
forks = append(forks, resp.Data.Viewer.Repositories.Nodes...)
// Update pagination info
hasNextPage = resp.Data.Viewer.Repositories.PageInfo.HasNextPage
if hasNextPage {
cursor = resp.Data.Viewer.Repositories.PageInfo.EndCursor
}
}
return forks, nil
}
var rootCmd = &cobra.Command{
Use: "gh-fork-cleanup",
Short: "Clean up your GitHub forks",
Long: `A CLI tool to help you clean up your GitHub forks.
It shows you all your forks, highlighting those that haven't been updated recently
and allows you to delete them if they don't have any open pull requests.`,
Run: cleanupForks,
}
func init() {
rootCmd.Flags().BoolP("skip-confirmation", "s", false, "Skip confirmation for forks with open pull requests")
rootCmd.Flags().BoolP("force", "f", false, "It will automatically delete all forks. Be careful when using this option.")
}
func cleanupForks(cmd *cobra.Command, args []string) {
// Start spinner
done := make(chan bool)
go showSpinner(done)
// Get flags
force, _ := cmd.Flags().GetBool("force")
skipConfirmation, _ := cmd.Flags().GetBool("skip-confirmation")
// Get all repos with open PRs
color.New(color.FgBlue).Println("Fetching repositories with open pull requests...")
reposWithPRs, err := getReposWithOpenPRs()
if err != nil {
fmt.Fprintf(os.Stderr, "%v\n", err)
os.Exit(1)
}
// Fetch all forks using GraphQL
forks, err := getForks()
if err != nil {
fmt.Fprintf(os.Stderr, "%v\n", err)
os.Exit(1)
}
// Stop spinner
done <- true
if len(forks) == 0 {
fmt.Println("No forked repositories found.")
os.Exit(0)
}
color.New(color.FgCyan, color.Bold).Printf("📦 Found %d forks\n", len(forks))
scanner := bufio.NewScanner(os.Stdin)
for _, fork := range forks {
fmt.Print("\n")
color.New(color.FgGreen, color.Bold).Printf("📂 Repository: %s\n", fork.Name)
color.New(color.FgYellow).Printf(" Last updated: %s\n", fork.UpdatedAt)
// Show PR information upfront
if prs, hasPRs := reposWithPRs[fork.NameWithOwner]; hasPRs {
color.New(color.FgRed).Printf(" ⚠️ Has %d open pull request(s):\n", len(prs))
for _, pr := range prs {
color.New(color.FgYellow).Printf(" #%d: %s\n", pr.Number, pr.Title)
color.New(color.FgBlue).Printf(" URL: %s\n", pr.Url)
}
}
if !force {
color.New(color.FgMagenta).Print("❔ Delete this repository? (y/n, default n): ")
scanner.Scan()
answer := strings.ToLower(strings.TrimSpace(scanner.Text()))
if answer != "y" {
color.New(color.FgBlue).Printf("⏭️ Skipping %s...\n", fork.Name)
continue
}
// Double confirm if there are open PRs and skip-confirmation is not set
if _, hasPRs := reposWithPRs[fork.NameWithOwner]; hasPRs && !skipConfirmation {
color.New(color.FgRed, color.Bold).Print("❗ This fork has open PRs. Are you ABSOLUTELY sure you want to delete it? (yes/N): ")
scanner.Scan()
confirm := strings.ToLower(strings.TrimSpace(scanner.Text()))
if confirm != "yes" {
color.New(color.FgBlue).Printf("⏭️ Skipping %s...\n", fork.Name)
continue
}
}
}
color.New(color.FgRed).Printf("🗑️ Deleting %s...\n", fork.Name)
deleteCmd := exec.Command("gh", "repo", "delete", fork.Name, "--yes")
if err := deleteCmd.Run(); err != nil {
fmt.Fprintf(os.Stderr, "Error deleting %s: %v\n", fork.Name, err)
} else {
color.New(color.FgGreen).Printf("✅ Successfully deleted %s.\n", fork.Name)
}
}
fmt.Println()
color.New(color.FgCyan, color.Bold).Println("✨ Process complete!")
}
func main() {
if err := rootCmd.Execute(); err != nil {
fmt.Println(err)
os.Exit(1)
}
}