forked from antonmedv/fx
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
executable file
·131 lines (103 loc) · 2.42 KB
/
index.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
#!/usr/bin/env node
'use strict'
const os = require('os')
const fs = require('fs')
const path = require('path')
const skip = Symbol('skip')
global.select = function select(cb) {
return json => {
if (!cb(json)) {
throw skip
}
return json
}
}
try {
require(path.join(os.homedir(), '.fxrc')) // Should be required before config.js usage.
} catch (err) {
if (err.code !== 'MODULE_NOT_FOUND') {
throw err
}
}
const print = require('./print')
const reduce = require('./reduce')
const stream = require('./stream')
const usage = `
Usage
$ fx [code ...]
Examples
$ echo '{"key": "value"}' | fx 'x => x.key'
value
$ echo '{"key": "value"}' | fx .key
value
$ echo '[1,2,3]' | fx 'this.map(x => x * 2)'
[2, 4, 6]
$ echo '{"items": ["one", "two"]}' | fx 'this.items' 'this[1]'
two
$ echo '{"count": 0}' | fx '{...this, count: 1}'
{"count": 1}
$ echo '{"foo": 1, "bar": 2}' | fx ?
["foo", "bar"]
`
const {stdin, stdout, stderr} = process
const args = process.argv.slice(2)
void function main() {
stdin.setEncoding('utf8')
if (stdin.isTTY) {
handle('')
return
}
const reader = stream(stdin, apply)
stdin.on('readable', reader.read)
stdin.on('end', () => {
if (!reader.isStream()) {
handle(reader.value())
}
})
}()
function handle(input) {
let filename = 'fx'
if (input === '') {
if (args.length === 0 || (args.length === 1 && (args[0] === '-h' || args[0] === '--help'))) {
stderr.write(usage)
process.exit(2)
}
if (args.length === 1 && (args[0] === '-v' || args[0] === '--version')) {
stderr.write(require('./package.json').version + '\n')
process.exit(2)
}
if (args.length === 1 && args[0] === '--life') {
require('./bang')
return
}
input = fs.readFileSync(args[0])
filename = path.basename(args[0])
args.shift()
}
const json = JSON.parse(input)
if (args.length === 0 && stdout.isTTY) {
require('./fx')(filename, json)
return
}
apply(json)
}
function apply(json) {
let output
try {
output = args.reduce(reduce, json)
} catch (e) {
if (e !== skip) {
throw e
} else {
return
}
}
if (typeof output === 'undefined') {
stderr.write('undefined\n')
} else if (typeof output === 'string') {
console.log(output)
} else {
const [text] = print(output)
console.log(text)
}
}