This repository was archived by the owner on Apr 8, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 18
/
Copy pathvalidate-yaml.ts
261 lines (244 loc) · 6.85 KB
/
validate-yaml.ts
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
import { danger, warn } from "danger"
import { load as yamlLoad } from "js-yaml"
import * as Joi from "joi"
import * as path from "path"
const supportedImageExts = [".jpg", ".jpeg", ".gif", ".png"]
const uriOptions = { scheme: [`https`, `http`] }
const githubRepoRegex: RegExp = new RegExp(
`^https?:\/\/github.com\/[^/]+/[^/]+$`
)
const getExistingFiles = async (path: string, base: string) => {
const [owner, repo] = danger.github.pr.head.repo.full_name.split("/")
const imagesDirReponse: {
data: { name: string }[]
} = await danger.github.api.repos.getContent({
repo,
owner,
path,
ref: danger.github.pr.head.ref,
})
const files = imagesDirReponse.data.map(({ name }) => `${base}/${name}`)
return files
}
const customJoi = Joi.extend((joi: any) => ({
base: joi.string(),
name: "string",
language: {
supportedExtension: "need to use supported extension {{q}}",
fileExists: "need to point to existing file",
},
rules: [
{
name: "supportedExtension",
params: {
q: joi.array().items(joi.string()),
},
validate(
this: Joi.ExtensionBoundSchema,
params: { q: string[] },
value: string,
state: any,
options: any
): any {
if (!params.q.includes(path.extname(value))) {
return this.createError(
"string.supportedExtension",
{ v: value, q: params.q },
state,
options
)
}
return value
},
},
{
name: "fileExists",
params: {
q: joi.array().items(joi.string()),
},
validate(
this: Joi.ExtensionBoundSchema,
params: { q: string[] },
value: string,
state: any,
options: any
): any {
if (!params.q.includes(value)) {
return this.createError(
"string.fileExists",
{ v: value, q: params.q },
state,
options
)
}
return value
},
},
],
}))
const getSitesSchema = () => {
return Joi.array()
.items(
Joi.object().keys({
title: Joi.string().required(),
url: Joi.string()
.uri(uriOptions)
.required(),
main_url: Joi.string()
.uri(uriOptions)
.required(),
source_url: Joi.string().uri(uriOptions),
description: Joi.string(),
categories: Joi.array()
.items(Joi.string())
.required(),
built_by: Joi.string(),
built_by_url: Joi.string().uri(uriOptions),
featured: Joi.boolean(),
})
)
.unique("title")
.unique("url")
.unique("main_url")
}
const getCreatorsSchema = async () => {
return Joi.array()
.items(
Joi.object().keys({
name: Joi.string().required(),
type: Joi.string()
.valid(["individual", "agency", "company"])
.required(),
description: Joi.string(),
location: Joi.string(),
// need to explicitely allow `null` to not fail on github: null fields
github: Joi.string()
.uri(uriOptions)
.allow(null),
website: Joi.string().uri(uriOptions),
for_hire: Joi.boolean(),
portfolio: Joi.boolean(),
hiring: Joi.boolean(),
image: customJoi
.string()
.supportedExtension(supportedImageExts)
.fileExists(await getExistingFiles("docs/community/images", "images"))
.required(),
})
)
.unique("name")
}
const getAuthorsSchema = async () => {
return Joi.array()
.items(
Joi.object().keys({
id: Joi.string().required(),
bio: Joi.string().required(),
avatar: customJoi
.string()
.supportedExtension(supportedImageExts)
.fileExists(await getExistingFiles("docs/blog/avatars", "avatars"))
.required(),
twitter: Joi.string().regex(/^@/),
})
)
.unique("id")
}
const getStartersSchema = () => {
return Joi.array()
.items(
Joi.object().keys({
url: Joi.string()
.uri(uriOptions)
.required(),
repo: Joi.string()
.uri(uriOptions)
.regex(githubRepoRegex)
.required(),
description: Joi.string().required(),
tags: Joi.array()
.items(Joi.string())
.required(),
features: Joi.array()
.items(Joi.string())
.required(),
})
)
.unique("url")
.unique("repo")
}
const fileSchemas = {
"docs/sites.yml": getSitesSchema,
"docs/community/creators.yml": getCreatorsSchema,
"docs/blog/author.yaml": getAuthorsSchema,
"docs/starters.yml": getStartersSchema,
}
export const utils = {
addErrorMsg: (
index: string,
message: string,
customErrors: { [id: string]: string[] }
) => {
if (!customErrors[index]) {
customErrors[index] = []
}
customErrors[index].push(message)
},
}
export const validateYaml = async () => {
return Promise.all(
Object.entries(fileSchemas).map(async ([filePath, schemaFn]) => {
if (!danger.git.modified_files.includes(filePath)) {
return
}
const textContent = await danger.github.utils.fileContents(filePath)
let content: any
try {
content = yamlLoad(textContent)
} catch (e) {
warn(
`## ${filePath} is not valid YAML file:\n\n\`\`\`${e.message}\n\`\`\``
)
return
}
const result = Joi.validate(content, await schemaFn(), {
abortEarly: false,
})
if (result.error) {
const customErrors: { [id: string]: string[] } = {}
result.error.details.forEach(detail => {
if (detail.path.length > 0) {
const index = detail.path[0]
let message = detail.message
if (detail.type === "array.unique" && detail.context) {
// by default it doesn't say what field is not unique
message = `"${detail.context.path}" is not unique`
}
utils.addErrorMsg(index, message, customErrors)
} else {
utils.addErrorMsg("root", detail.message, customErrors)
}
})
const errors = Object.entries(customErrors).map(
([index, errors]: [string, string[]]) => {
if (index === "root") {
return errors.map(msg => ` - ${msg}`).join("\n")
} else {
const errorsString = errors.map(msg => ` - ${msg}`).join("\n")
return `- \`\`\`json\n${JSON.stringify(content[index], null, 2)
.split("\n")
.map(line => ` ${line}`)
.join("\n")}\n \`\`\`\n **Errors**:\n${errorsString}`
}
}
)
warn(
`## ${filePath} didn't pass validation:\n\n${errors.join("\n---\n")}`
)
}
})
)
}
export default async () => {
return await validateYaml()
}