-
Notifications
You must be signed in to change notification settings - Fork 22
/
logger.js
86 lines (80 loc) · 2.65 KB
/
logger.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
const chalk = require('chalk')
let stdout = process.stdout
let stderr = process.stderr
let defaultLogger = console
if (global.__DEV__) {
const fs = require('fs')
const { Console } = require('console')
stdout = fs.createWriteStream('./stdout.log', { encoding: 'utf-8' })
stderr = fs.createWriteStream('./stderr.log', { encoding: 'utf-8' })
defaultLogger = new Console({ stdout, stderr })
}
const parsePosition = (str, index) => {
const rows = str.split('\n')
const rowLengthList = rows.map(substr => substr.length)
let row = 0
let column = 0
let line = ''
while (index >= 0 && rows.length) {
row++
column = index
line = rows.shift()
index -= rowLengthList.shift() + 1
}
return {
offset: index,
row,
column,
line
}
}
const reportSingleResult = (file, str, validations, logger = defaultLogger) => {
validations.forEach(v => {
const { index, length, target } = v
const finalIndex = (target === 'spaceAfter' || target === 'endContent') ? index + length : index
const { row, column, line } = parsePosition(str, finalIndex)
const offset = 20
const start = column - offset < 0 ? 0 : column - offset
const end = column + length + offset > line.length - 1 ? line.length : column + length + offset
const fragment = line.substring(start, end).replace(/\n/g, '\\n')
const output = {
file: `${chalk.blue.bgWhite(file || '')}${file ? ':' : ''}`,
position: `${chalk.yellow(row)}:${chalk.yellow(column)}`,
marker: `${chalk.black.bgBlack(fragment.substr(0, column - start))}${chalk.red('^')}`,
oldPosition: `${chalk.yellow(finalIndex)}`,
oldMarker: `${' '.repeat(column - start)}${chalk.red('^')}`
}
output.headline = `${output.file}${output.position} - ${v.message}`
logger.error(`${output.headline}\n\n${fragment}\n${output.marker}\n`)
})
}
const report = (resultList, logger = defaultLogger) => {
let errorCount = 0
resultList
.filter(({ file, disabled }) => {
if (disabled) {
logger.log(`${chalk.blue.bgWhite(file || '')}${file ? ':' : ''} disabled`)
return false
}
return true
}).map(({ file, origin, validations }) => {
reportSingleResult(file, origin, validations, logger)
errorCount += validations.length
return validations.length ? file : ''
}).filter(Boolean)
if (errorCount) {
logger.error('Invalid files:')
logger.error('- ' + invalidFiles.join('\n- ') + '\n')
logger.error(`Found ${errorCount} ${errorCount > 1 ? 'errors' : 'error'}.`)
return 1
} else {
logger.log(`No error found.`)
}
}
module.exports = {
defaultLogger,
stdout,
stderr,
reportSingleResult,
report
}