-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.go
176 lines (142 loc) · 5.17 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
package main
import (
"encoding/json"
"fmt"
"os"
"regexp"
"strings"
"log/slog"
"github.com/caarlos0/env"
)
var desiredFormat string = "<type>(optional: <scope>): <message>"
var defaultConventionTypes []string = []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"`
Scope string `env:"INPUT_SCOPE"`
}
type PullRequest struct {
Title string `json:"title"`
}
type Event struct {
PullRequest PullRequest `json:"pull_request"`
}
// The pull-request-title-validator function mankes sure that for each pull request created the
// title of the pull request adheres to a desired structure, in this case convention commit style.
func main() {
var cfg config
if err := env.Parse(&cfg); err != nil {
fmt.Printf("unable to parse the environment variables: %v", err)
os.Exit(1)
}
logHandler := slog.NewJSONHandler(os.Stdout, &slog.HandlerOptions{
AddSource: false,
Level: slog.LevelInfo,
})
logger := slog.New(logHandler)
logger.Info("starting pull-request-title-validator", slog.String("event", cfg.GithubEventName))
if cfg.GithubEventName != "pull_request" && cfg.GithubEventName != "pull_request_target" {
logger.Error("invalid event type", slog.String("event", cfg.GithubEventName))
os.Exit(1)
}
title := fetchTitle(logger, cfg.GithubEventPath)
titleType, titleScope, titleMessage := splitTitle(logger, title)
parsedTypes := parseTypes(logger, cfg.Types, defaultConventionTypes)
parsedScope := parseScopes(logger, cfg.Scope)
if err := checkAgainstConventionTypes(logger, titleType, parsedTypes); err != nil {
logger.Error("error while checking the type against the allowed types",
slog.String("event name", cfg.GithubEventName),
slog.String("event path", cfg.GithubEventPath),
slog.Any("convention types", parsedTypes),
)
os.Exit(1)
}
if err := checkAgainstScopes(logger, titleScope, parsedScope); err != nil && len(parsedScope) >= 1 {
logger.Error("error while checking the scope against the allowed scopes", slog.Any("error", err))
os.Exit(1)
}
logger.Info("commit title validated successfully",
slog.String("type", titleType),
slog.String("scope", titleScope),
slog.String("message", titleMessage),
)
logger.Info("the commit message adheres to the configured standard")
}
func fetchTitle(logger *slog.Logger, githubEventPath string) string {
var event Event
var eventData []byte
var err error
if eventData, err = os.ReadFile(githubEventPath); err != nil {
logger.Error("Problem reading the event JSON file", slog.String("path", githubEventPath), slog.Any("error", err))
os.Exit(1) // You might want to return an empty string or handle this error upstream instead.
}
if err = json.Unmarshal(eventData, &event); err != nil {
logger.Error("Failed to unmarshal JSON", slog.Any("error", err))
os.Exit(1)
}
return event.PullRequest.Title
}
func splitTitle(logger *slog.Logger, title string) (titleType string, titleScope string, titleMessage string) {
if index := strings.Index(title, "("); strings.Contains(title, "(") {
titleType = title[:index]
} else if index := strings.Index(title, ":"); strings.Contains(title, ":") {
titleType = title[:index]
} else {
logger.Error("No type was included in the pull request title.", slog.String("desired format", desiredFormat))
os.Exit(1)
}
if strings.Contains(title, "(") && strings.Contains(title, ")") {
scope := regexp.MustCompile(`\(([^)]+)\)`)
if matches := scope.FindStringSubmatch(title); len(matches) > 1 {
titleScope = matches[1]
}
}
if strings.Contains(title, ":") {
titleMessage = strings.SplitAfter(title, ":")[1]
titleMessage = strings.TrimSpace(titleMessage)
} else {
logger.Error("No message was included in the pull request title.", slog.String("desired format", desiredFormat))
os.Exit(1)
}
return
}
func checkAgainstConventionTypes(logger *slog.Logger, titleType string, conventionTypes []string) error {
for _, conventionType := range conventionTypes {
if titleType == conventionType {
return nil
}
}
logger.Error("Type not allowed by the convention", slog.String("type", titleType), slog.Any("allowedTypes", conventionTypes))
return fmt.Errorf("type '%s' is not allowed", titleType)
}
func checkAgainstScopes(logger *slog.Logger, titleScope string, scopes []string) error {
for _, scope := range scopes {
if regexp.MustCompile("(?i)" + scope + "$").MatchString(titleScope) {
return nil
}
}
return fmt.Errorf("scope '%s' is not allowed", titleScope)
}
func parseTypes(logger *slog.Logger, input string, fallback []string) []string {
if input == "" {
logger.Warn("No custom list of commit types passed, using fallback.")
return fallback
}
types := strings.Split(input, ",")
for i := range types {
types[i] = strings.TrimSpace(types[i])
}
return types
}
func parseScopes(logger *slog.Logger, input string) []string {
if input == "" {
logger.Warn("No custom list of commit scopes passed, using fallback.")
return []string{}
}
scopes := strings.Split(input, ",")
for i := range scopes {
scopes[i] = strings.TrimSpace(scopes[i])
}
return scopes
}