-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
250 lines (203 loc) · 6.56 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
package main
import (
"bytes"
"encoding/json"
"flag"
"fmt"
"io"
"log"
"net/http"
"os"
"strings"
"time"
)
type Comment struct {
Body string `json:"body"`
User struct {
Login string `json:"login"`
} `json:"user"`
URL string `json:"url"`
}
type NewComment struct {
Body string `json:"body"`
}
func main() {
flag.Parse()
args := flag.Args()
showHelp := flag.Bool("help", false, "Show help message")
flag.BoolVar(showHelp, "h", false, "Show help message (shorthand)")
if len(args) < 1 {
fmt.Println("Usage: go run main.go <repo>")
fmt.Println()
fmt.Println("Arguments:")
fmt.Println(" <repo> The repository name in the format 'owner/repo'.")
fmt.Println("Environment variables:")
fmt.Println(" PR_NUMBER The pull request number to comment on.")
fmt.Println(" USER_LOGIN The GitHub user login.")
fmt.Println(" COMMIT_SHA The commit SHA.")
fmt.Println(" URL The deployment URL.")
fmt.Println(" TITLE The comment title. Default is '# Preview Deployment'.")
fmt.Println(" ASSETS_DIR Where to look for static assets. Default is '/'.")
fmt.Println(" DEBUG Set to 'true' to enable debug output. Default is 'false'.")
fmt.Println(" GITHUB_TOKEN GitHub API token with repo permissions.")
os.Exit(1)
}
if *showHelp {
flag.Usage()
os.Exit(0)
}
repo := args[0]
prNumber := os.Getenv("PR_NUMBER")
if prNumber == "" {
log.Fatal("PR_NUMBER environment variable is required")
}
userLogin := os.Getenv("USER_LOGIN")
if userLogin == "" {
log.Fatal("USER_LOGIN environment variable is required")
}
commitSha := os.Getenv("COMMIT_SHA")
if commitSha == "" {
log.Fatal("COMMIT_SHA environment variable is required")
}
url := os.Getenv("URL")
if url == "" {
log.Fatal("URL environment variable is required")
}
githubToken := os.Getenv("GITHUB_TOKEN")
if githubToken == "" {
log.Fatal("GITHUB_TOKEN environment variable is required")
}
title := os.Getenv("TITLE")
if title == "" {
title = "# Preview Deployment"
}
assetsDir := os.Getenv("ASSETS_DIR")
debug := os.Getenv("DEBUG") == "true"
if debug {
log.Println("Debug mode enabled")
log.Printf("Repository: %s\n", repo)
log.Printf("PR Number: %s\n", prNumber)
log.Printf("User Login: %s\n", userLogin)
log.Printf("Commit SHA: %s\n", commitSha)
log.Printf("URL: %s\n", url)
log.Printf("Title: %s\n", title)
log.Printf("Assets Dir: %s\n", assetsDir)
}
commentTemplatePath := assetsDir + "/preview-body.md.tpl"
httpClient := &http.Client{
Timeout: 30 * time.Second,
}
comments, err := getComments(httpClient, repo, prNumber, githubToken)
if err != nil {
log.Fatalf("Failed to get comments: %v", err)
}
var commentURLs []string
for _, comment := range comments {
if strings.HasPrefix(comment.Body, title) && comment.User.Login == userLogin {
commentURLs = append(commentURLs, comment.URL)
}
}
commentBody, err := processTemplate(commentTemplatePath, map[string]string{
"TITLE": title,
"COMMIT_SHA": commitSha,
"URL": url,
})
if err != nil {
log.Fatalf("Failed to process template: %v", err)
}
for _, commentURL := range commentURLs {
if err := deleteComment(httpClient, commentURL, githubToken); err != nil {
log.Printf("Warning: Failed to delete comment %s: %v", commentURL, err)
}
}
if err := createComment(httpClient, repo, prNumber, commentBody, githubToken); err != nil {
log.Fatalf("Failed to create comment: %v", err)
}
}
func getComments(client *http.Client, repo, prNumber, token string) ([]Comment, error) {
url := fmt.Sprintf("https://api.github.com/repos/%s/issues/%s/comments", repo, prNumber)
req, err := http.NewRequest("GET", url, nil)
if err != nil {
return nil, fmt.Errorf("failed to create request: %v", err)
}
req.Header.Set("Accept", "application/vnd.github.raw+json")
req.Header.Set("X-GitHub-Api-Version", "2022-11-28")
req.Header.Set("Authorization", "Bearer "+token)
resp, err := client.Do(req)
if err != nil {
return nil, fmt.Errorf("HTTP request failed: %v", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
body, _ := io.ReadAll(resp.Body)
return nil, fmt.Errorf("API request failed with status %d: %s", resp.StatusCode, body)
}
body, err := io.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("failed to read response body: %v", err)
}
if string(body) == "[]" {
return []Comment{}, nil
}
var comments []Comment
if err := json.Unmarshal(body, &comments); err != nil {
return nil, fmt.Errorf("failed to unmarshal comments: %v", err)
}
return comments, nil
}
func processTemplate(templatePath string, replacements map[string]string) (string, error) {
content, err := os.ReadFile(templatePath)
if err != nil {
return "", fmt.Errorf("failed to read template file: %v", err)
}
result := string(content)
for key, value := range replacements {
result = strings.ReplaceAll(result, "{{"+key+"}}", value)
}
return result, nil
}
func deleteComment(client *http.Client, commentURL, token string) error {
req, err := http.NewRequest("DELETE", commentURL, nil)
if err != nil {
return fmt.Errorf("failed to create request: %v", err)
}
req.Header.Set("Accept", "application/vnd.github.raw+json")
req.Header.Set("X-GitHub-Api-Version", "2022-11-28")
req.Header.Set("Authorization", "Bearer "+token)
resp, err := client.Do(req)
if err != nil {
return fmt.Errorf("HTTP request failed: %v", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusNoContent {
body, _ := io.ReadAll(resp.Body)
return fmt.Errorf("API request failed with status %d: %s", resp.StatusCode, body)
}
return nil
}
func createComment(client *http.Client, repo, prNumber, body, token string) error {
url := fmt.Sprintf("https://api.github.com/repos/%s/issues/%s/comments", repo, prNumber)
newComment := NewComment{Body: body}
commentData, err := json.Marshal(newComment)
if err != nil {
return fmt.Errorf("failed to marshal comment data: %v", err)
}
req, err := http.NewRequest("POST", url, bytes.NewBuffer(commentData))
if err != nil {
return fmt.Errorf("failed to create request: %v", err)
}
req.Header.Set("Accept", "application/vnd.github.raw+json")
req.Header.Set("X-GitHub-Api-Version", "2022-11-28")
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", "Bearer "+token)
resp, err := client.Do(req)
if err != nil {
return fmt.Errorf("HTTP request failed: %v", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusCreated {
body, _ := io.ReadAll(resp.Body)
return fmt.Errorf("API request failed with status %d: %s", resp.StatusCode, body)
}
return nil
}