-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathmain.go
More file actions
259 lines (211 loc) · 6.29 KB
/
main.go
File metadata and controls
259 lines (211 loc) · 6.29 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
package main
import (
"encoding/json"
"fmt"
"log/slog"
"os"
"regexp"
"strings"
"github.com/caarlos0/env"
)
const (
desiredFormat = "<type>(optional: <scope>): <message>"
)
var defaultConventionTypes = []string{
"fix", "feat", "chore", "docs", "build", "ci", "refactor", "perf", "test",
}
type Config struct {
GithubEventName string `env:"GITHUB_EVENT_NAME"`
GithubEventPath string `env:"GITHUB_EVENT_PATH"`
Types string `env:"INPUT_TYPES"`
Scopes string `env:"INPUT_SCOPES"`
}
type PullRequest struct {
Title string `json:"title"`
}
type Event struct {
PullRequest PullRequest `json:"pull_request"`
}
type TitleComponents struct {
Type string
Scope string
Message string
}
type Validator struct {
logger *slog.Logger
config Config
}
func main() {
logger := setupLogger()
cfg, err := loadConfig()
if err != nil {
logger.Error("unable to parse environment variables", slog.Any("error", err))
os.Exit(1)
}
validator := &Validator{
logger: logger,
config: cfg,
}
if err := validator.run(); err != nil {
os.Exit(1)
}
}
func setupLogger() *slog.Logger {
logHandler := slog.NewJSONHandler(os.Stdout, &slog.HandlerOptions{
AddSource: false,
Level: slog.LevelInfo,
})
return slog.New(logHandler)
}
func loadConfig() (Config, error) {
var cfg Config
err := env.Parse(&cfg)
return cfg, err
}
func (v *Validator) run() error {
v.logger.Info("starting pull-request-title-validator",
slog.String("event", v.config.GithubEventName))
if err := v.validateEventType(); err != nil {
return err
}
title, err := v.fetchTitle()
if err != nil {
return err
}
components, err := v.parseTitle(title)
if err != nil {
return err
}
if err := v.validateTitle(components); err != nil {
return err
}
v.logger.Info("commit title validated successfully",
slog.String("type", components.Type),
slog.String("scope", components.Scope),
slog.String("message", components.Message),
)
v.logger.Info("the commit message adheres to the configured standard")
return nil
}
func (v *Validator) validateEventType() error {
if v.config.GithubEventName != "pull_request" && v.config.GithubEventName != "pull_request_target" {
v.logger.Error("invalid event type", slog.String("event", v.config.GithubEventName))
return fmt.Errorf("invalid event type: %s", v.config.GithubEventName)
}
return nil
}
func (v *Validator) fetchTitle() (string, error) {
eventData, err := os.ReadFile(v.config.GithubEventPath)
if err != nil {
v.logger.Error("problem reading the event JSON file",
slog.String("path", v.config.GithubEventPath),
slog.Any("error", err))
return "", err
}
var event Event
if err := json.Unmarshal(eventData, &event); err != nil {
v.logger.Error("failed to unmarshal JSON", slog.Any("error", err))
return "", err
}
return event.PullRequest.Title, nil
}
func (v *Validator) parseTitle(title string) (*TitleComponents, error) {
// Split title into prefix (type/scope) and message parts using colon as separator
prefix, message, found := strings.Cut(title, ":")
if !found {
v.logger.Error("title must include a message after the colon",
slog.String("desired format", desiredFormat),
slog.String("title", title))
return nil, fmt.Errorf("title missing colon separator")
}
// Clean up the message part
titleMessage := strings.TrimSpace(message)
// Extract type and scope from the prefix
titleType, titleScope := extractTypeAndScope(prefix)
// Validate that we found a type
if titleType == "" {
v.logger.Error("title must include a type",
slog.String("desired format", desiredFormat),
slog.String("title", title))
return nil, fmt.Errorf("title missing type")
}
return &TitleComponents{
Type: titleType,
Scope: titleScope,
Message: titleMessage,
}, nil
}
func extractTypeAndScope(prefix string) (titleType string, titleScope string) {
prefix = strings.TrimSpace(prefix)
// Check if prefix contains a scope in parentheses
if strings.Contains(prefix, "(") && strings.Contains(prefix, ")") {
// Extract scope using regex
scopeRegex := regexp.MustCompile(`\(([^)]+)\)`)
if matches := scopeRegex.FindStringSubmatch(prefix); len(matches) > 1 {
titleScope = matches[1]
titleType = strings.TrimSpace(strings.Split(prefix, "(")[0])
return titleType, titleScope
}
}
// If no scope found or invalid format, use entire prefix as type
titleType = prefix
return titleType, titleScope
}
func (v *Validator) validateTitle(components *TitleComponents) error {
parsedTypes := v.parseTypes()
parsedScopes := v.parseScopes()
if err := v.validateType(components.Type, parsedTypes); err != nil {
v.logger.Error("error while checking the type against the allowed types",
slog.String("event name", v.config.GithubEventName),
slog.String("event path", v.config.GithubEventPath),
slog.Any("convention types", parsedTypes),
)
return err
}
if err := v.validateScope(components.Scope, parsedScopes); err != nil && len(parsedScopes) >= 1 {
v.logger.Error("error while checking the scope against the allowed scopes",
slog.Any("error", err))
return err
}
return nil
}
func (v *Validator) validateType(titleType string, allowedTypes []string) error {
for _, allowedType := range allowedTypes {
if titleType == allowedType {
return nil
}
}
v.logger.Error("type not allowed by the convention",
slog.String("type", titleType),
slog.Any("allowedTypes", allowedTypes))
return fmt.Errorf("type '%s' is not allowed", titleType)
}
func (v *Validator) validateScope(titleScope string, allowedScopes []string) error {
for _, scope := range allowedScopes {
if regexp.MustCompile("(?i)" + scope + "$").MatchString(titleScope) {
return nil
}
}
return fmt.Errorf("scope '%s' is not allowed", titleScope)
}
func (v *Validator) parseTypes() []string {
if v.config.Types == "" {
v.logger.Warn("no custom list of commit types passed, using fallback")
return defaultConventionTypes
}
return parseCommaSeparatedList(v.config.Types)
}
func (v *Validator) parseScopes() []string {
if v.config.Scopes == "" {
v.logger.Warn("no custom list of commit scopes passed, using fallback")
return []string{}
}
return parseCommaSeparatedList(v.config.Scopes)
}
func parseCommaSeparatedList(input string) []string {
items := strings.Split(input, ",")
for i := range items {
items[i] = strings.TrimSpace(items[i])
}
return items
}