This repository has been archived by the owner on Jul 2, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.go
292 lines (236 loc) · 6.15 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
package main
import (
"bufio"
"bytes"
"encoding/json"
"flag"
"fmt"
"io"
"io/ioutil"
"log"
"net/http"
"os"
"path/filepath"
"strings"
)
var (
targetFolder string
targetFile string
searchResult []string
)
var (
Trace *log.Logger
Info *log.Logger
Warning *log.Logger
Error *log.Logger
)
var manifestFileTypePatterns = [15]string{
"Gopkg.*",
"vendor/vendor.json",
"build.gradle",
"pom.xml",
"build.sbt",
"requirements.txt",
"Gemfile.lock",
"package.json",
"package-lock.json",
"yarn.lock",
"project.json",
"*.csproj",
"*.vbproj",
"*.fsproj",
"packages.config"}
var ignorePathPatterns []string
var repoBasePath string
func Init(
traceHandle io.Writer,
infoHandle io.Writer,
warningHandle io.Writer,
errorHandle io.Writer) {
Trace = log.New(traceHandle,
"",
0)
Info = log.New(infoHandle,
"INFO: ",
log.Ldate|log.Ltime|log.Lshortfile)
Warning = log.New(warningHandle,
"WARNING: ",
log.Ldate|log.Ltime|log.Lshortfile)
Error = log.New(errorHandle,
"ERROR: ",
log.Ldate|log.Ltime|log.Lshortfile)
}
func importProject(token string, orgId string, integrationId string, projectKey string, repoName string, repoSlug string, paths []string) {
type File struct {
Path string `json:"path"`
}
type Target struct {
ProjectKey string `json:"projectKey"`
Name string `json:"name"`
Branch string `json:"branch"`
}
type BodyStruct struct {
Target `json:"target"`
Files []File `json:"files"`
}
client := &http.Client{}
files := make([]File, 0)
for _, file := range paths {
files = append(files, File{Path: file})
}
body := BodyStruct{
Target: Target{
ProjectKey: projectKey,
Name: repoName,
Branch: repoSlug,
},
Files: files,
}
Trace.Println("Programmatically Importing into Snyk")
bodyJSON, _ := json.MarshalIndent(body, "", " ")
url := fmt.Sprintf("https://snyk.io/api/v1/org/%s/integrations/%s/import", orgId, integrationId)
req, _ := http.NewRequest("POST", url, bytes.NewBuffer(bodyJSON))
req.Header.Add("Content-Type", "application/json; charset=utf-8")
tokenString := fmt.Sprintf("token %s", token)
req.Header.Add("Authorization", tokenString)
resp, err := client.Do(req)
if err != nil {
Error.Println("Errored when sending request to the server")
return
}
defer resp.Body.Close()
respBody, _ := ioutil.ReadAll(resp.Body)
Info.Println(resp.Status)
Info.Println(string(respBody))
}
func findFile(path string, fileInfo os.FileInfo, err error) error {
if err != nil {
Error.Println(err)
return nil
}
// get absolute path of the folder that we are searching
absolute, err := filepath.Abs(path)
if err != nil {
Error.Println(err)
return nil
}
if fileInfo.IsDir() {
//fmt.Println("Searching directory ... ", absolute)
// correct permission to scan folder?
testDir, err := os.Open(absolute)
if err != nil {
if os.IsPermission(err) {
Warning.Println("No permission to scan ... ", absolute)
Error.Println(err)
}
}
testDir.Close()
return nil
} else {
// ok, we are dealing with a file
// is this the target file?
// yes, need to support wildcard search as well
// https://www.socketloop.com/tutorials/golang-match-strings-by-wildcard-patterns-with-filepath-match-function
//matched, err := filepath.Match("main.go", fileInfo.Name())
for _, pattern := range manifestFileTypePatterns {
matched, err := filepath.Match(pattern, fileInfo.Name())
if err != nil {
Error.Println(err)
}
if matched {
ignored := false
for _, pathPattern := range ignorePathPatterns {
if strings.Contains(absolute, pathPattern) {
ignored = true
Info.Printf("Ignoring %s\n", absolute)
}
}
if !ignored {
// yes, add into our search result
add := "/" + strings.Replace(absolute, repoBasePath, "", 1)
searchResult = append(searchResult, add)
}
}
}
}
return nil
}
func main() {
rootPathPtr := flag.String("path", "", "your repo root path")
ignorePathPtr := flag.String("excludeFile", "", "your ignore file path")
tokenPtr := flag.String("token", "", "your Snyk token")
orgIdPtr := flag.String("orgId", "", "your Organization ID")
integrationIdPtr := flag.String("intId", "", "your Integration ID")
projectKeyPtr := flag.String("projectkey", "", "your Integration ID")
repoNamePtr := flag.String("repo", "", "your Integration ID")
repoSlugPtr := flag.String("reposlug", "", "your Integration ID")
debugPtr := flag.Bool("d", false, "Debug")
flag.Parse()
targetFolder := *rootPathPtr
ignorePath := *ignorePathPtr
orgId := *orgIdPtr
integrationId := *integrationIdPtr
token := *tokenPtr
projectKey := *projectKeyPtr
repoName := *repoNamePtr
repoSlug := *repoSlugPtr
repoBasePath = targetFolder
debug := *debugPtr
if debug {
Init(os.Stdout, os.Stdout, os.Stdout, os.Stderr)
} else {
Init(os.Stdout, ioutil.Discard, ioutil.Discard, os.Stderr)
}
var paths []string
if ignorePath != "" {
file, err := os.Open(ignorePath)
if err != nil {
Error.Println(err)
}
defer file.Close()
scanner := bufio.NewScanner(file)
for scanner.Scan() {
ignorePathPatterns = append(ignorePathPatterns, scanner.Text())
}
if err := scanner.Err(); err != nil {
Error.Println(err)
}
Info.Println(ignorePathPatterns)
}
if targetFolder != "" {
// sanity check
testFile, err := os.Open(targetFolder)
if err != nil {
Error.Println(err)
os.Exit(-1)
}
defer testFile.Close()
testFileInfo, _ := testFile.Stat()
if !testFileInfo.IsDir() {
Info.Println(targetFolder, " is not a directory!")
os.Exit(-1)
}
err = filepath.Walk(targetFolder, findFile)
if err != nil {
Error.Println(err)
os.Exit(-1)
}
// display our search result
Trace.Println("\n\nFound ", len(searchResult), " hits!")
Info.Println("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@")
for _, v := range searchResult {
Info.Println(v)
}
Info.Println("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@")
} else {
reader := bufio.NewReader(os.Stdin)
for {
input, err := reader.ReadString('\n')
if err != nil && err == io.EOF {
break
}
paths = append(paths, strings.TrimSuffix(input, "\n"))
}
}
importProject(token, orgId, integrationId, projectKey, repoName, repoSlug, paths)
}