fx/index.js

99 lines
1.7 KiB
JavaScript
Raw Normal View History

2018-10-26 10:59:46 +00:00
#!/usr/bin/env node
2018-03-13 03:28:40 +00:00
'use strict'
2018-11-10 10:31:26 +00:00
const os = require('os')
const fs = require('fs')
2018-11-10 10:31:26 +00:00
const path = require('path')
const {stdin, stdout, stderr} = process
try {
require(path.join(os.homedir(), '.fxrc'))
} catch (err) {
if (err.code !== 'MODULE_NOT_FOUND') {
throw err
}
}
const print = require('./print')
const reduce = require('./reduce')
2018-01-25 17:30:05 +00:00
2018-09-14 17:00:36 +00:00
const usage = `
2018-01-25 17:30:05 +00:00
Usage
$ fx [code ...]
Examples
2018-01-26 02:35:58 +00:00
$ echo '{"key": "value"}' | fx 'x => x.key'
2018-08-30 15:09:12 +00:00
value
$ echo '{"key": "value"}' | fx .key
value
2018-01-25 17:30:05 +00:00
2018-01-26 02:35:58 +00:00
$ echo '[1,2,3]' | fx 'this.map(x => x * 2)'
2018-01-25 17:30:05 +00:00
[2, 4, 6]
2018-01-26 02:35:58 +00:00
$ echo '{"items": ["one", "two"]}' | fx 'this.items' 'this[1]'
2018-08-30 15:09:12 +00:00
two
2018-01-25 17:30:05 +00:00
2018-01-26 02:35:58 +00:00
$ echo '{"count": 0}' | fx '{...this, count: 1}'
2018-01-25 17:30:05 +00:00
{"count": 1}
2018-08-30 15:09:12 +00:00
$ echo '{"foo": 1, "bar": 2}' | fx ?
["foo", "bar"]
2018-09-14 17:00:36 +00:00
`
2018-01-25 17:30:05 +00:00
2018-09-14 17:00:36 +00:00
function main(input) {
let args = process.argv.slice(2)
let filename = 'fx'
2018-09-14 17:00:36 +00:00
if (input === '') {
if (args.length === 0) {
stderr.write(usage)
process.exit(2)
}
input = fs.readFileSync(args[0])
filename = path.basename(args[0])
args = args.slice(1)
2018-01-25 17:30:05 +00:00
}
2018-09-14 17:00:36 +00:00
const json = JSON.parse(input)
2018-11-02 18:24:56 +00:00
if (args.length === 0 && stdout.isTTY) {
require('./fx')(filename, json)
2018-11-02 18:24:56 +00:00
return
}
const output = args.reduce(reduce, json)
2018-01-25 17:30:05 +00:00
if (typeof output === 'undefined') {
2018-11-02 18:24:56 +00:00
stderr.write('undefined\n')
} else if (typeof output === 'string') {
console.log(output)
2018-01-25 17:30:05 +00:00
} else {
const [text] = print(output)
console.log(text)
2018-01-25 17:30:05 +00:00
}
}
2018-11-02 18:24:56 +00:00
function run() {
stdin.setEncoding('utf8')
2018-09-14 17:00:36 +00:00
2018-11-02 18:24:56 +00:00
if (stdin.isTTY) {
main('')
return
2018-11-02 18:24:56 +00:00
}
2018-09-14 17:00:36 +00:00
2018-11-10 10:31:26 +00:00
let buff = ''
2018-11-02 18:24:56 +00:00
stdin.on('readable', () => {
let chunk
2018-09-14 17:00:36 +00:00
2018-11-02 18:24:56 +00:00
while ((chunk = stdin.read())) {
buff += chunk
}
})
stdin.on('end', () => {
main(buff)
})
}
2018-09-14 17:00:36 +00:00
2018-11-02 18:24:56 +00:00
run()