-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcli.js
executable file
·115 lines (96 loc) · 2.43 KB
/
cli.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
#!/usr/bin/env node
const path = require('path')
const fs = require('fs').promises
const log = console.log
const validateFn = require('../index.js')
/**
* Returns the data piped into this process on stdin.
*
* @return {Promise}
*/
function captureInputFromStdIn () {
log('Validating XML from stdin...')
return new Promise((resolve, reject) => {
/**
* A list of {Buffer}s read from standard input.
* @type {Array}
*/
const input = []
process.stdin.on('readable', () => {
const data = process.stdin.read()
if (data != null) input.push(data)
})
process.stdin.on('error', (err) => {
reject(err)
})
process.stdin.on('end', () => {
resolve(input.join(''))
})
})
}
/**
* Returns the contents of the specified file.
*
* @param {String} p The path to the file.
*
* @return {Promise}
*/
function captureInputFromFile (p) {
const resolvedPath = path.resolve(p)
log('Validating the file at "%s"...', resolvedPath)
return fs.readFile(resolvedPath)
}
/**
* Outputs the results of the XML validation to the log.
*
* @return {undefined}
*/
function logResultOfXmlValidation (dtd, warnings, errors) {
log('')
if (errors.length === 0) {
log('Congratulations, the provided XML is well-formed and valid, according to the DTD at "%s"', dtd)
if (warnings.length > 0) {
log('')
log('However, please note the following warnings:')
warnings.forEach((msg) => { log(' -', msg) })
}
} else {
log('Unfortunately, the provided XML does not validate according to the DTD at "%s"', dtd)
log('')
log('The following errors were reported:')
errors.forEach((msg) => { log(' ✘', msg) })
if (warnings.length > 0) {
log('')
log('Also, please note the following warnings:')
warnings.forEach((msg) => { log(' -', msg) })
}
}
}
/**
* Entry point.
* @return {undefined}
*/
async function main () {
let xml = ''
const args = process.argv.slice(2)
try {
if (args.length === 0) {
xml = await captureInputFromStdIn()
} else {
xml = await captureInputFromFile(args[0])
}
const validationResult = await validateFn(xml)
logResultOfXmlValidation(
validationResult.doctype,
validationResult.warnings,
validationResult.errors
)
if (validationResult.errors.length > 0) {
process.exit(1)
}
} catch (err) {
console.error(err)
process.exit(1)
}
}
main()