-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathgithub.go
More file actions
95 lines (74 loc) · 1.95 KB
/
Copy pathgithub.go
File metadata and controls
95 lines (74 loc) · 1.95 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
package skills
import (
"context"
"encoding/json"
"errors"
"net/http"
"strings"
)
type gitHubTreeResponse struct {
SHA string `json:"sha"`
Tree []struct {
Path string `json:"path"`
Type string `json:"type"`
SHA string `json:"sha"`
} `json:"tree"`
}
func FetchGitHubSkillFolderHash(ctx context.Context, ownerRepo string, skillPath string, token string) (string, error) {
folderPath := strings.ReplaceAll(skillPath, "\\", "/")
if before, ok := strings.CutSuffix(folderPath, "/SKILL.md"); ok {
folderPath = before
} else if before, ok := strings.CutSuffix(folderPath, "SKILL.md"); ok {
folderPath = before
}
folderPath = strings.TrimSuffix(folderPath, "/")
branches := []string{"main", "master"}
var lastErr error
for _, branch := range branches {
u := "https://api.github.com/repos/" + ownerRepo + "/git/trees/" + branch + "?recursive=1"
req, err := http.NewRequestWithContext(ctx, http.MethodGet, u, nil)
if err != nil {
return "", err
}
req.Header.Set("Accept", "application/vnd.github.v3+json")
req.Header.Set("User-Agent", "skills-go")
if token != "" {
req.Header.Set("Authorization", "Bearer "+token)
}
resp, err := defaultHTTPClient.Do(req)
if err != nil {
lastErr = err
continue
}
defer func() { _ = resp.Body.Close() }()
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
lastErr = errors.New(resp.Status)
continue
}
var data gitHubTreeResponse
if err := json.NewDecoder(resp.Body).Decode(&data); err != nil {
lastErr = err
continue
}
if folderPath == "" {
if data.SHA == "" {
lastErr = errors.New("missing tree sha")
continue
}
return data.SHA, nil
}
for _, e := range data.Tree {
if e.Type == "tree" && e.Path == folderPath {
if e.SHA == "" {
break
}
return e.SHA, nil
}
}
lastErr = errors.New("folder not found in tree")
}
if lastErr == nil {
lastErr = errors.New("failed to fetch github tree")
}
return "", lastErr
}