-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathvalidate.js
162 lines (129 loc) · 4.4 KB
/
validate.js
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
/* eslint-disable no-undef */
const { readFile } = require('fs/promises')
const core = require('@actions/core')
const Messages = require('./messages')
const GitHubClient = require('./githubClient')
const rules = [
['wrong_answers', '( )'],
['right_answers', '(x)'],
['open_curly', '{{'],
['close_curly', '}}'],
['codeblocks_count', '```'],
['codestring_count', '`'],
['open_question', '<<'],
['close_question', '>>']
]
const invalidFiles = [
'template.md',
'repo.md',
'metadados.md',
'README.md',
'index.md'
]
const buildChecks = (questionCount) => [
['check_answers', [questionCount - 1, 1], ['wrong_answers', 'right_answers']],
['check_codestrings', null, ['codestring_count']],
['check_feedbacks', [questionCount, questionCount], ['open_curly', 'close_curly']],
['check_codeblocks', null, ['codeblocks_count']],
['check_question', [1,1], ['open_question', 'close_question']]
]
async function validate(){
try {
const files = getFiles()
if(!files.length){
core.info('\u001b[38;5;6m 🤷 Nenhum Arquivo Encontrado')
await maybeDeletePreviousComment()
return false
}
core.info(`\u001b[38;5;6m 📃 Arquivos -> ${files}`)
const checkResult = await validateRules(files)
const fullComment = buildFullComment(checkResult)
core.debug(`💬 Comentário -> ${fullComment}`)
await maybeDeletePreviousComment()
await GitHubClient.createComment(fullComment)
core.info('\u001b[38;5;6m 💬 Cria comentário no PR')
return checkResult
} catch (error) {
core.setFailed(`${error}`)
}
}
function getFiles() {
return process.env.INPUT_FILES
.split(' ')
.filter(isMarkdown)
.filter(file => !invalidFiles.includes(file))
.filter(isNumericPath)
}
async function maybeDeletePreviousComment(){
try {
const comments = await GitHubClient.listComments()
const commentIssue = comments?.data.find(comment =>
comment.body.includes(Messages.error) || comment.body.includes(Messages.success)
)
if (commentIssue) {
core.info(`\u001b[38;5;6m 🗑 Deleta comentário antigo -> ${commentIssue.id}`)
await GitHubClient.deleteComment(commentIssue.id)
}
} catch (error) {
core.warning(`🗑 Erro ao deletar comentário -> ${error}`)
}
}
async function validateRules(files){
const promises = files.map(async (filename) => {
const checks_result = await evaluate(filename)
return { tableText: buildTable(checks_result, filename), objectResult: checks_result }
})
return await Promise.all(promises)
}
function buildFullComment(checkResult){
const tables = checkResult.map((item) => item.tableText)
const tableComment = tables.join('\n').trim()
core.debug(`tableComment(${tableComment.length}) -> ${tableComment}`)
if(tableComment === '') return `${Messages.success}\n${Messages.supported}`
return `${Messages.error}\n${Messages.sac}\n${tableComment}\n${Messages.observation}\n${Messages.supported}`
}
async function evaluate (filename){
const root = process.env.GITHUB_WORKSPACE || process.cwd()
const file = await readFile(`${root}/${filename}`, 'utf8' )
const result = rules.reduce((acc, rule) => split_and_count_by_separator(file, acc, rule[0], rule[1]), {})
const checks = buildChecks(result['wrong_answers'] + 1)
return checks.reduce((acc, check) => {
const check_name = check[0]
const check_expected = check[1]
const check_rule = check[2]
acc[check_name] = check_expected !== null? check_compare(result, check_expected, check_rule) : check_remainder(result, check_rule)
return acc
}, {})
}
function buildTable(checks_result, filename){
const checks = Object.entries(checks_result)
if(isSuccessfulQuiz(checks)) return ''
const headTable = `| *${filename}* |\n| ------------- |\n`
const table = Object
.entries(checks_result)
.reduce((acc, check) => `${acc}| ${Messages[check[0]][check[1]]} |\n`, '')
return `${headTable}${table}`
}
function isSuccessfulQuiz(checks){
return !checks.some((check) => !check[1])
}
function check_compare(result, expected, rule){
return expected[0] == result[rule[0]] && result[rule[1]] == expected[1]
}
function check_remainder(result, rule){
return result[rule[0]] % 2 == 0
}
function split_and_count_by_separator(file, object, key, separator){
const value = file.split(separator).length
object[key] = value - 1
return object
}
function isNumericPath(path) {
const filename = path.split('/').pop()
const name = filename.split('.')[0]
return !isNaN(name)
}
function isMarkdown(path){
return path.includes('.md')
}
module.exports = validate