-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
executable file
·218 lines (175 loc) · 5.1 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
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
#!/usr/bin/env node
const yargs = require('yargs');
const Fuse = require('fuse.js');
const fs = require('fs');
const { promisify } = require('util');
const readFileAsync = promisify(fs.readFile); // (A)
const { isUndefined, get, camelCase, map, toString } = require('lodash');
const main = async () => {
if(!process.argv[2]) return;
const rawArgs = yargs
.usage('\necho "Food" | ish "fodd"\n')
.option('json-string', {
alias: 'jsonString',
type: 'string',
describe: 'Whether or not to return in string-json format',
coerce: trueIfDefined,
})
.option('json', {
type: 'boolean',
describe: 'Whether or not to return in json format',
coerce: trueIfDefined,
})
.option('json-string', {
type: 'boolean',
describe: 'Whether or not to return in json string format',
coerce: trueIfDefined,
})
.option('all', {
type: 'boolean',
describe: 'Whether or not to return ALL matches, ranked best to worst, left to right',
coerce: trueIfDefined,
})
.option('opts', {
type: 'array',
describe: 'Custom options for underlying fusejs, passed to initialization',
coerce: args => toOpts(args),
})
.option('line', {
alias: 'l',
type: 'boolean',
describe: 'whether to process per line',
coerce: trueIfDefined,
})
.epilogue(help())
.argv;
const args = normalizeArgs(rawArgs);
const stdin = await readFileAsync(0, 'utf8');
const matches = args.line ? getLineMatches(args, stdin) : getMatches(args, stdin);
if (args.json && args.all) {
printJSON(matches);
}
else if (args.jsonString && args.all) {
printEscapedJson(matches);
}
else if(args.json) {
printJSON(JSON.stringify(get(matches, 0, '')));
}
else if (args.jsonString) {
printEscapedJson(get(matches, 0, ''));
}
else if(args.all) {
matches.forEach(match => console.log(match));
}
else {
console.log(get(matches, 0, ''));
}
}
const getMatches = (args, stdin) => {
return findMatch({
searchStrings: args._,
listToSearch: stdin.toString().split('\n'),
opts: get(args, 'opts', {}),
})
}
const getLineMatches = (args, stdin) => (
stdin.trim().split("\n").map(line => {
return findMatch({
searchStrings: args._,
listToSearch: line.split(' '),
opts: get(args, 'opts', {})
})[0]
}).filter(match => match)
);
const findMatch = ({ searchStrings, listToSearch, opts }) => {
const fuse = new Fuse(
listToSearch.map(item => ({ item, })),
{
...opts,
keys: ['item'],
id: 'item',
shouldSort: true,
includeScore: true,
findAllMatches: true,
},
);
return searchStrings
.map(string => fuse.search(string))
.flat()
.map(({ item }) => item);
}
const normalizeArgs = (args) => ({
...args,
...(args.line && { all: true }),
_: map(args._, toString),
})
const printEscapedJson = (obj) => console.log(JSON.stringify(JSON.stringify(obj)));
const printJSON = (obj) => console.log(JSON.stringify(obj));
const trueIfDefined = (arg) => !isUndefined(arg);
const toOpts = (arg) => (
arg.map(item => item.split('='))
.reduce((opts, [key, value]) => ({
...opts,
[camelCase(key)]: safeEval(value),
}), {})
)
const safeEval = (value) => {
try {
return eval(value);
} catch(error) {
return false;
}
}
//polyfill from stackoverflow
Object.defineProperty(Array.prototype, 'flat', {
value: function(depth = 1) {
return this.reduce(function (flat, toFlatten) {
return flat.concat((Array.isArray(toFlatten) && (depth>1)) ? toFlatten.flat(depth-1) : toFlatten);
}, []);
}
});
const help = () => `
Example (Single Match):
echo -e "Food\\nDrink\\nSnacks" | ish 'fod'
# Food
Example (Multi Matching)
echo -e "Food\\nDrink\\nSnacks" | ish 'fodd' 'Drink'
# Food
echo -e "Food\\nDrink\\nSnacks" | ish 'fdd' 'Dink'
# Drink
Example (JSON output) Usefull for chaining with jq, fx, etc
echo -e "Food\\nDrink\\nSnacks" | ish 'fodd' --json
# "Food"
echo "Food" | ish 'food' --json-string
# "\\"Food\\""
Listing all possible matches, left to right, best to worst.
echo -e "Food\\nFodge\\nFreak" | ish 'fodd' --all --json
# [ "Food", 'Fodge', "Freak" ]
echo -e "Foood\\nFodge\\nFreak" | ish 'fodd' --all
# Food
# Fodge
# Freak
Line matching mode
You can also match each line, individually, from a stream of lines.
Each line is matched individually against the possible matches, left to right, best to worse.
echo -e "cat cat kat\\nkat kat kat\\ndog dog alligator | ish --line 'dog' 'cat'
# cat
# kat
# dog
Supported Options
- case-sensitive
- distance
- threshold
- tokenize
- location
- max-pattern-length
- min-match-char-length
echo "FOOD" | ish "food" --opts case-sensitive=true
#
echo "FOOD" | ish "FOOD" --opts case-sensitive=true
# FOOD
For more information on Fusejs options, see:
https://fusejs.io
`;
// -----------------------------------------------------------------------------
main();