-
Notifications
You must be signed in to change notification settings - Fork 3
/
main.go
240 lines (209 loc) · 5.53 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
package main
import (
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"log"
"net/http"
"os"
"os/exec"
"strings"
"gopkg.in/yaml.v3"
"github.com/bmatcuk/doublestar/v4"
"github.com/gofiber/fiber/v2"
"github.com/mitchellh/go-homedir"
)
var (
clonePath = "./repo"
defaultConfigFile = "config.yaml"
refParam = "ref"
repoParam = "repo"
)
var (
EmptyPatternResponse = InterceptorResponse{
Extensions: fiber.Map{"paths": "EMPTY_PATTERN"},
Continue: true,
}
MatchResponse = InterceptorResponse{
Extensions: fiber.Map{"paths": "MATCH"},
Continue: true,
}
NotMatchResponse = InterceptorResponse{
Extensions: fiber.Map{"paths": "NOT_MATCH"},
Continue: false,
}
)
type repos struct {
Repos map[string]config `yaml:"repos"`
}
type config struct {
URL string `yaml:"url"`
Paths []string `yaml:"paths,omitempty"`
}
func fileChange(ctx *fiber.Ctx, repos *repos, repo, branch string) error {
var url string
var paths []string
val, ok := repos.Repos[repo]
if !ok {
return fiber.NewError(fiber.StatusInternalServerError, "repo not exist in config file")
}
url = val.URL
paths = val.Paths
paths = removeEmptyStrings(paths)
if len(paths) <= 0 {
log.Println(EmptyPatternResponse)
return ctx.JSON(EmptyPatternResponse)
}
// mkdir
if _, err := os.Stat(clonePath); os.IsNotExist(err) {
err := os.Mkdir(clonePath, 0700)
if err != nil {
return fiber.NewError(fiber.StatusInternalServerError, fmt.Sprint(err))
}
}
homepath, err := homedir.Dir()
if err != nil {
log.Printf("Unexpected error getting the user home directory: %v", err)
return fiber.NewError(fiber.StatusInternalServerError, fmt.Sprint(err))
}
if os.Geteuid() == 0 {
homepath = "/root"
}
ensureHomeEnv(homepath)
// git clone
log.Printf("cloning %s at branch %s", repo, branch)
clone := exec.Command("git", "clone", "-b", branch, "--depth", "2", url, clonePath)
out, err := clone.CombinedOutput()
log.Print(string(out))
if err != nil {
return fiber.NewError(fiber.StatusInternalServerError, fmt.Sprint(err))
}
// git diff
err = os.Chdir(clonePath)
if err != nil {
return fiber.NewError(fiber.StatusInternalServerError, fmt.Sprint(err))
}
cmd := exec.Command("git", "--no-pager", "diff", "--name-only", "HEAD^")
stdout, _ := cmd.CombinedOutput()
log.Printf("diff\n%s", string(stdout))
// remove dir
err = os.Chdir("../")
err = os.RemoveAll(clonePath)
if err != nil {
return fiber.NewError(fiber.StatusInternalServerError, fmt.Sprint(err))
}
// process output
output := strings.Split(strings.TrimSpace(string(stdout)), "\n")
for _, e := range output {
for _, path := range paths {
m, err := doublestar.PathMatch(path, e)
if err != nil {
return fiber.NewError(fiber.StatusInternalServerError, fmt.Sprint(err))
}
if m {
log.Printf("match: '%s' file with pattern '%s'", e, path)
return ctx.JSON(MatchResponse)
}
}
}
log.Println(NotMatchResponse)
return ctx.JSON(NotMatchResponse)
}
func validateSignature(token string, body string, headers http.Header) error {
if token != "" {
var signature string
sha1Header := headers.Get(SHA1SignatureHeader)
sha256Header := headers.Get(SHA256SignatureHeader)
if sha256Header != "" {
signature = sha256Header
} else {
signature = sha1Header
}
err := ValidateSignature(signature, []byte(body), []byte(token))
if err != nil {
return fiber.NewError(http.StatusBadRequest, err.Error())
}
return nil
}
return errors.New("SECRET_TOKEN not provided")
}
func parseReq(body []byte) (*InterceptorRequest, http.Header, error) {
req := new(InterceptorRequest)
err := json.Unmarshal(body, &req)
if err != nil {
return nil, nil, err
}
headers := Canonical(req.Header)
return req, headers, nil
}
func main() {
configFile := os.Getenv("CONFIG_FILE")
if configFile == "" {
configFile = defaultConfigFile
}
// read config.yaml
yamlFile, err := ioutil.ReadFile(configFile)
if err != nil {
panic(err)
}
var repos *repos
err = yaml.Unmarshal(yamlFile, &repos)
if err != nil {
panic(err)
}
app := fiber.New(fiber.Config{ErrorHandler: func(ctx *fiber.Ctx, err error) error {
code := fiber.StatusInternalServerError
// Retrieve the custom status code if it's a fiber.*Error
if e, ok := err.(*fiber.Error); ok {
code = e.Code
}
return ctx.Status(code).JSON(InterceptorResponse{
Continue: false,
Status: Status{
Code: Internal,
Message: err.Error(),
},
})
}})
app.Get("/", func(ctx *fiber.Ctx) error {
return ctx.SendString("hello world")
})
app.Post("/", func(ctx *fiber.Ctx) error {
var resErr error
byteBody := ctx.Body()
req, headers, parseErr := parseReq(byteBody)
if parseErr != nil {
return fiber.NewError(fiber.StatusInternalServerError, err.Error())
}
token := os.Getenv("SECRET_TOKEN")
if token != "" {
resErr = validateSignature(token, req.Body, headers)
if resErr != nil {
return resErr
}
}
var parsedBody map[string]interface{}
resErr = json.Unmarshal([]byte(req.Body), &parsedBody)
if resErr != nil {
return fiber.NewError(fiber.StatusInternalServerError, err.Error())
}
repo := fmt.Sprint(req.InterceptorParams[repoParam])
ref := fmt.Sprint(parsedBody[refParam])
branch := getBranch(ref)
return fileChange(ctx, repos, repo, branch)
})
if os.Getenv("APP_ENV") == "dev" {
app.Post("/local", func(ctx *fiber.Ctx) error {
repo := ctx.Query("repo")
ref := ctx.Query("ref")
branch := getBranch(ref)
return fileChange(ctx, repos, repo, branch)
})
}
port := os.Getenv("PORT")
if port == "" {
port = ":8080"
}
log.Fatal(app.Listen(port))
}