-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathloxfmt.js
executable file
·83 lines (74 loc) · 1.95 KB
/
loxfmt.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
#! /usr/bin/env node
const fs = require('fs')
const chalk = require('chalk')
const { parse } = require('./index')
const { printLoxAST } = require('./transpilers/lox')
const { formatLoxError } = require('./errors')
let options = {}
const printErrorMessage = (e, code) => {
const { oneLiner, preErrorSection, errorSection, postErrorSection } = formatLoxError(e, code)
console.error(oneLiner)
if (errorSection) {
console.error(preErrorSection + chalk.bgRed(errorSection) + postErrorSection)
}
}
const fmtFile = filename => {
try {
const file = fs.readFileSync(filename, 'utf8')
try {
const newText = parse(file)
.map(stmt => printLoxAST(stmt, 0, options))
.join('\n')
if (!options.silent) console.log(newText)
if (options.write) {
fs.writeFileSync(filename, newText)
}
} catch (e) {
printErrorMessage(e, file)
}
} catch (e) {
console.error(`YALI could not read the file ${filename}`)
console.error(e)
}
}
const optionRegex = /--(\w+)(?:=(.+))?/
const processOptions = args =>
args
.map(arg => {
const match = optionRegex.exec(arg)
if (match) {
const [, option, value] = match
if (!value) {
options[option] = !options[option]
} else {
options[option] = value
}
} else {
return arg
}
})
.filter(Boolean)
const main = argv => {
process.title = 'loxfmt'
const args = processOptions(argv.slice(2))
if (options.help) {
console.log(
`
Usage: loxfmt [script]*
Options:
--write Writes linting to files
--indent="{indentstring}" Defines indent string to use
--spaceBeforeParams Adds space before params. fun hello() { => fun hello () {
--functionNewlines Adds an extra newline after function bodies
`
)
return 0
}
if (args.length >= 1) {
args.forEach(fmtFile)
} else {
console.error('Usage: loxfmt [script]*')
return 64
}
}
main(process.argv)