-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
326 lines (275 loc) · 9.47 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
package main
import (
"bufio"
"bytes"
"encoding/json"
"flag"
"fmt"
"net/http"
"os"
"os/exec"
"path/filepath"
"regexp"
"sort"
"strings"
)
var (
debugMode bool
migrationDir string
compareBranch string
integration bool
)
const (
gitLabURLEnv = "GITLAB_URL"
gitLabTokenEnv = "GITLAB_TOKEN"
ciProjectIDEnv = "CI_PROJECT_ID"
ciMergeRequestIIDEnv = "CI_MERGE_REQUEST_IID"
)
type ValidationError struct {
Message string
MessageMD string
OldPath string
NewPath string
}
func init() {
flag.StringVar(&migrationDir, "migration-dir", ".", "Specify the migration directory (default: current directory)")
flag.StringVar(&compareBranch, "branch", "", "Specify the branch to compare against (default: empty, i.e., working directory)")
flag.BoolVar(&debugMode, "debug", false, "Enable debug mode")
flag.BoolVar(&integration, "integration", false, "Enable integration with GitLab merge request interface")
flag.Parse()
}
func main() {
if debugMode {
fmt.Println("Debug mode enabled")
fmt.Println("Migration directory: ", migrationDir)
fmt.Println("Compare branch: ", compareBranch)
fmt.Println("Integration enabled: ", integration)
}
// Read GitLab-related parameters from environment variables
gitLabURL := os.Getenv(gitLabURLEnv)
gitLabToken := os.Getenv(gitLabTokenEnv)
ciProjectID := os.Getenv(ciProjectIDEnv)
ciMergeRequestIID := os.Getenv(ciMergeRequestIIDEnv)
if integration && (gitLabURL == "" || gitLabToken == "" || ciProjectID == "" || ciMergeRequestIID == "") {
fmt.Println("Warning: GitLab-related environment variables not set.")
}
if debugMode {
fmt.Println("GitLab URL: ", gitLabURL)
fmt.Println("GitLab Token: ", len(gitLabToken))
fmt.Println("CI Project ID: ", ciProjectID)
fmt.Println("CI Merge Request IID: ", ciMergeRequestIID)
}
if _, err := os.Stat(migrationDir); os.IsNotExist(err) {
fmt.Println("Error: Migration directory does not exist:", migrationDir)
os.Exit(1)
}
if debugMode {
fmt.Printf("Verify dir :%s: \n", migrationDir)
}
cmdArgs := []string{"git", "diff", "--name-status"}
if compareBranch != "" {
cmdArgs = append(cmdArgs, compareBranch)
}
cmdArgs = append(cmdArgs, migrationDir)
cmd := exec.Command(cmdArgs[0], cmdArgs[1:]...)
output, err := cmd.Output()
if err != nil {
fmt.Println("Error running git diff:", err)
if debugMode {
fmt.Println(string(cmd.String()))
}
os.Exit(1)
}
var validationErrors []ValidationError
scanner := bufio.NewScanner(strings.NewReader(string(output)))
for scanner.Scan() {
line := scanner.Text()
fields := strings.Fields(line)
if len(fields) >= 2 {
status := fields[0]
oldFilePath := fields[1]
newFilePath := oldFilePath
if len(fields) == 3 {
newFilePath = fields[2]
}
relativeFilePath, err := filepath.Rel(migrationDir, newFilePath)
if err != nil {
validationErrors = append(validationErrors, ValidationError{
Message: fmt.Sprintf("Error getting relative path: %v", err),
})
continue
}
if debugMode {
fmt.Printf("Processing file: %s (status: %s)\n", newFilePath, status)
fmt.Printf("Conditions: isMigrationFile: %t, isAlphabeticallyLast: %t\n", isMigrationFile(relativeFilePath), isAlphabeticallyLast(relativeFilePath, migrationDir))
}
if isMatch(status, `^M`) {
if isMigrationFile(relativeFilePath) {
validationErrors = append(validationErrors, ValidationError{
Message: fmt.Sprintf("Error: Cannot modify migration file after it was applied"),
MessageMD: fmt.Sprintf(":warning: Error: Cannot **modify** migration file after it was applied"),
OldPath: oldFilePath,
NewPath: newFilePath,
})
}
} else if isMatch(status, `^A`) {
if isMigrationFile(relativeFilePath) && !isAlphabeticallyLast(relativeFilePath, migrationDir) {
validationErrors = append(validationErrors, ValidationError{
Message: fmt.Sprintf("Error: Added migration file not alphabetically last"),
MessageMD: fmt.Sprintf(":warning: Error: Added migration file **not** alphabetically **last**"),
OldPath: oldFilePath,
NewPath: newFilePath,
})
}
} else if isMatch(status, `^D`) {
if isMigrationFile(relativeFilePath) {
validationErrors = append(validationErrors, ValidationError{
Message: fmt.Sprintf("Error: Cannot remove migration file after it was applied"),
MessageMD: fmt.Sprintf(":warning: Error: Cannot **remove** migration file after it was applied"),
OldPath: oldFilePath,
NewPath: newFilePath,
})
}
} else if isMatch(status, `^R`) {
if isMigrationFile(relativeFilePath) {
validationErrors = append(validationErrors, ValidationError{
Message: fmt.Sprintf("Error: Cannot rename migration file after it was applied"),
MessageMD: fmt.Sprintf(":warning: Error: Cannot **rename** migration file after it was applied"),
OldPath: oldFilePath,
NewPath: newFilePath,
})
}
}
}
}
if len(validationErrors) > 0 {
fmt.Println("Validation errors:")
for _, err := range validationErrors {
fmt.Printf("%s\n %s\n\n", err.Message, err.NewPath)
}
if integration {
if err := integrateWithGitLab(gitLabURL, gitLabToken, ciProjectID, ciMergeRequestIID, validationErrors); err != nil {
fmt.Println("Warning: Error integrating with GitLab:", err)
}
}
os.Exit(1)
}
fmt.Println("Validation successful")
}
func RetrieveMergeRequestInfo(gitLabURL, gitLabToken, ciProjectID, ciMergeRequestIID string) (map[string]interface{}, error) {
url := fmt.Sprintf("%s/v4/projects/%s/merge_requests/%s", gitLabURL, ciProjectID, ciMergeRequestIID)
req, err := http.NewRequest("GET", url, nil)
if debugMode {
fmt.Println("Request URL:", url)
}
if err != nil {
return nil, fmt.Errorf("Error creating HTTP request: %v", err)
}
req.Header.Set("PRIVATE-TOKEN", gitLabToken)
client := &http.Client{}
resp, err := client.Do(req)
if debugMode {
fmt.Println("Response status code:", resp.StatusCode)
}
if err != nil {
return nil, fmt.Errorf("Error making HTTP request: %v", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("Error retrieving Merge Request info. Status code: %d", resp.StatusCode)
}
var mrInfo map[string]interface{}
decoder := json.NewDecoder(resp.Body)
if err := decoder.Decode(&mrInfo); err != nil {
if debugMode {
fmt.Println("Response body:", resp.Body)
}
return nil, fmt.Errorf("Error decoding Merge Request info: %v", err)
}
return mrInfo, nil
}
func integrateWithGitLab(gitLabURL, gitLabToken, ciProjectID, ciMergeRequestIID string, validationErrors []ValidationError) error {
mrInfo, err := RetrieveMergeRequestInfo(gitLabURL, gitLabToken, ciProjectID, ciMergeRequestIID)
if err != nil {
return fmt.Errorf("Error retrieving Merge Request info: %v", err)
}
for _, validationError := range validationErrors {
// Prepare the URL to post a discussion to the merge request with the validation result
url := fmt.Sprintf("%s/v4/projects/%s/merge_requests/%s/discussions", gitLabURL, ciProjectID, ciMergeRequestIID)
// Create a map for the JSON payload
payload := map[string]interface{}{
"body": validationError.MessageMD,
"position": map[string]interface{}{
"position_type": "file",
"base_sha": mrInfo["diff_refs"].(map[string]interface{})["base_sha"],
"head_sha": mrInfo["diff_refs"].(map[string]interface{})["head_sha"],
"start_sha": mrInfo["diff_refs"].(map[string]interface{})["start_sha"],
"new_path": validationError.NewPath,
"old_path": validationError.OldPath,
"old_line": nil,
"new_line": nil,
"line_range": map[string]interface{}{},
"ignore_whitespace_change": false,
},
}
// Marshal the payload into JSON
jsonPayload, err := json.Marshal(payload)
if err != nil {
return fmt.Errorf("Error marshalling JSON payload: %v", err)
}
// Create a new HTTP request with the JSON payload
req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonPayload))
if err != nil {
return fmt.Errorf("Error creating HTTP request: %v", err)
}
// Set headers for authentication and content type
req.Header.Set("PRIVATE-TOKEN", gitLabToken)
req.Header.Set("Content-Type", "application/json")
// Perform the HTTP request
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
return fmt.Errorf("Error making HTTP request: %v", err)
}
defer resp.Body.Close()
// Check the HTTP response status
if resp.StatusCode != http.StatusCreated {
return fmt.Errorf("Error posting discussion to merge request. Status code: %d", resp.StatusCode)
}
}
return nil
}
func isMigrationFile(filePath string) bool {
re := regexp.MustCompile(`^V\d+__`)
return re.MatchString(filepath.Base(filePath))
}
func isAlphabeticallyLast(filePath, migrationDir string) bool {
files, err := getMigrationFiles(migrationDir)
if err != nil {
return false
}
sort.Strings(files)
for i, file := range files {
if file == filePath {
return i == len(files)-1
}
}
return false
}
func getMigrationFiles(migrationDir string) ([]string, error) {
var files []string
err := filepath.Walk(migrationDir, func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
if !info.IsDir() && isMigrationFile(path) {
files = append(files, path)
}
return nil
})
return files, err
}
func isMatch(input, pattern string) bool {
re := regexp.MustCompile(pattern)
return re.MatchString(input)
}