-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathgithub.go
More file actions
281 lines (217 loc) · 6.33 KB
/
Copy pathgithub.go
File metadata and controls
281 lines (217 loc) · 6.33 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
package main
import (
"context"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"net/http"
"sort"
"strings"
"sync"
)
type GitHubRepo struct {
Name string `json:"name"`
HtmlURL string `json:"html_url"`
Description string `json:"description"`
Stargazers int `json:"stargazers_count"`
Forks int `json:"forks_count"`
Visibility string `json:"visibility"`
DefaultBranch string `json:"default_branch"`
}
type GitHubTreeItem struct {
Path string `json:"path"`
Type string `json:"type"`
}
type GitHubTreeResponse struct {
Truncated bool `json:"truncated"`
Tree []GitHubTreeItem `json:"tree"`
}
type GitHubReadme struct {
Path string `json:"path"`
Content string `json:"content"`
Encoding string `json:"encoding"`
}
var IgnoreGithubPaths = []string{
"node_modules/", "vendor/", ".git/", "dist/", "build/",
"bin/", "obj/", "out/", ".idea/", ".vscode/", "__pycache__/",
}
func (r *GitHubReadme) AsText() (string, error) {
if r.Encoding == "base64" {
content, err := base64.StdEncoding.DecodeString(r.Content)
if err != nil {
return "", err
}
return string(content), nil
}
return r.Content, nil
}
func NewGitHubRequest(ctx context.Context, path string) (*http.Request, error) {
req, err := http.NewRequest("GET", fmt.Sprintf("https://api.github.com%s", path), nil)
if err != nil {
return nil, err
}
req = req.WithContext(ctx)
req.Header.Set("Accept", "application/vnd.github+json")
if env.Tokens.GitHub != "" {
req.Header.Set("Authorization", "Bearer "+env.Tokens.GitHub)
}
return req, nil
}
func GitHubRepositoryJson(ctx context.Context, owner, repo string) (*GitHubRepo, error) {
req, err := NewGitHubRequest(ctx, fmt.Sprintf("/repos/%s/%s", owner, repo))
if err != nil {
return nil, err
}
resp, err := http.DefaultClient.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
var response GitHubRepo
err = json.NewDecoder(resp.Body).Decode(&response)
if err != nil {
return nil, err
}
if response.Name == "" {
return nil, errors.New("error getting data")
}
if response.Description == "" {
response.Description = "(none)"
}
return &response, nil
}
func GitHubRepositoryReadmeJson(ctx context.Context, owner, repo, branch string) (*GitHubReadme, error) {
req, err := NewGitHubRequest(ctx, fmt.Sprintf("/repos/%s/%s/readme?ref=%s", owner, repo, branch))
if err != nil {
return nil, err
}
resp, err := http.DefaultClient.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
var response GitHubReadme
err = json.NewDecoder(resp.Body).Decode(&response)
if err != nil {
return nil, err
}
return &response, nil
}
func GitHubRepositoryTreeJson(ctx context.Context, owner, repo, branch string) (*GitHubTreeResponse, error) {
req, err := NewGitHubRequest(ctx, fmt.Sprintf("/repos/%s/%s/git/trees/%s?recursive=1", owner, repo, branch))
if err != nil {
return nil, err
}
resp, err := http.DefaultClient.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
var response GitHubTreeResponse
err = json.NewDecoder(resp.Body).Decode(&response)
if err != nil {
return nil, err
}
return &response, nil
}
func RepoOverview(ctx context.Context, arguments *GitHubRepositoryArguments) (string, error) {
repository, err := GitHubRepositoryJson(ctx, arguments.Owner, arguments.Repo)
if err != nil {
return "", err
}
var (
wg sync.WaitGroup
readmeMarkdown string
files []string
treeTruncated bool
)
// fetch readme
wg.Go(func() {
readme, err := GitHubRepositoryReadmeJson(ctx, arguments.Owner, arguments.Repo, repository.DefaultBranch)
if err != nil {
log.Warnf("failed to get repository readme: %v\n", err)
readmeMarkdown = fmt.Sprintf("*Failed to load README: %v*", err)
return
}
markdown, err := readme.AsText()
if err != nil {
log.Warnf("failed to decode repository readme: %v\n", err)
readmeMarkdown = fmt.Sprintf("*Failed to load README: %v*", err)
return
}
readmeMarkdown = markdown
})
// fetch contents
wg.Go(func() {
tree, err := GitHubRepositoryTreeJson(ctx, arguments.Owner, arguments.Repo, repository.DefaultBranch)
if err != nil {
log.Warnf("failed to get repository contents: %v\n", err)
return
}
var validItems []GitHubTreeItem
for _, item := range tree.Tree {
if !shouldIgnoreGithubFile(item.Path) {
validItems = append(validItems, item)
}
}
sort.Slice(validItems, func(i, j int) bool {
depthI := strings.Count(validItems[i].Path, "/")
depthJ := strings.Count(validItems[j].Path, "/")
if depthI == depthJ {
return validItems[i].Path < validItems[j].Path
}
return depthI < depthJ
})
if len(validItems) > 256 {
validItems = validItems[:256]
treeTruncated = true
} else if tree.Truncated {
treeTruncated = true
}
for _, item := range validItems {
if item.Type == "tree" {
files = append(files, fmt.Sprintf(
"- [D] [%s](https://github.com/%s/%s/tree/%s/%s)",
item.Path, arguments.Owner, arguments.Repo, repository.DefaultBranch, item.Path,
))
} else { // "blob"
files = append(files, fmt.Sprintf(
"- [F] [%s](https://raw.githubusercontent.com/%s/%s/refs/heads/%s/%s)",
item.Path, arguments.Owner, arguments.Repo, repository.DefaultBranch, item.Path,
))
}
}
})
// wait and combine results
wg.Wait()
buf := GetFreeBuffer()
defer pool.Put(buf)
fmt.Fprintf(buf, "### %s (%s)\n", repository.Name, repository.Visibility)
fmt.Fprintf(buf, "- URL: %s\n", repository.HtmlURL)
fmt.Fprintf(buf, "- Description: %s\n", strings.ReplaceAll(repository.Description, "\n", " "))
fmt.Fprintf(buf, "- Default branch: %s\n", repository.DefaultBranch)
fmt.Fprintf(buf, "- Stars: %d | Forks: %d\n", repository.Stargazers, repository.Forks)
buf.WriteString("\n### Repository Structure\n")
if len(files) == 0 {
buf.WriteString("*No entries or insufficient permissions.*\n")
} else {
for _, file := range files {
fmt.Fprintf(buf, "%s\n", file)
}
if treeTruncated {
buf.WriteString("\n*... (repository tree truncated to save context) ...*\n")
}
}
buf.WriteString("\n### README\n")
buf.WriteString(readmeMarkdown)
return buf.String(), nil
}
func shouldIgnoreGithubFile(path string) bool {
for _, ignore := range IgnoreGithubPaths {
if strings.HasPrefix(path, ignore) || strings.Contains(path, "/"+ignore) {
return true
}
}
return false
}