-
Notifications
You must be signed in to change notification settings - Fork 20
/
Copy pathindex.js
122 lines (111 loc) · 2.94 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
const fs = require('fs');
const path = require('path');
const util = require('util');
const Choices = require('inquirer/lib/objects/choices');
const InquirerAutocomplete = require('inquirer-autocomplete-prompt');
const stripAnsi = require('strip-ansi');
const style = require('ansi-styles');
const fuzzy = require('fuzzy');
const readdir = util.promisify(fs.readdir);
function getPaths(
rootPath,
pattern,
excludePath,
excludeFilter,
itemType,
defaultItem,
depthLimit,
) {
const fuzzOptions = {
pre: style.green.open,
post: style.green.close,
};
async function listNodes(nodePath, level) {
try {
if (excludePath(nodePath)) {
return [];
}
const nodes = await readdir(nodePath);
const currentNode = (itemType !== 'file' ? [nodePath] : []);
if (
nodes.length > 0
&& (depthLimit === undefined || level >= 0)
) {
const nodesWithPath = nodes.map(
nodeName => listNodes(
path.join(nodePath, nodeName),
depthLimit ? level - 1 : undefined,
),
);
const subNodes = await Promise.all(nodesWithPath);
return subNodes.reduce((acc, val) => acc.concat(val), currentNode);
}
return currentNode;
} catch (err) {
if (err.code === 'ENOTDIR') {
return itemType !== 'directory' ? [nodePath] : [];
}
return [];
}
}
const nodes = listNodes(rootPath, depthLimit);
const filterPromise = nodes.then(
(nodeList) => {
const preFilteredNodes =
!excludeFilter
? nodeList
: nodeList.filter(node => !excludeFilter(node));
const filteredNodes = fuzzy
.filter(pattern || '', preFilteredNodes, fuzzOptions)
.map(e => e.string);
if (!pattern && defaultItem) {
filteredNodes.unshift(defaultItem);
}
return filteredNodes;
},
);
return filterPromise;
}
class InquirerFuzzyPath extends InquirerAutocomplete {
constructor(question, rl, answers) {
const {
depthLimit,
itemType = 'any',
rootPath = '.',
excludePath = () => false,
excludeFilter = false
} = question;
const questionBase = Object.assign(
{},
question,
{
source: (_, pattern) => getPaths(
rootPath,
pattern,
excludePath,
excludeFilter,
itemType,
question.default,
depthLimit,
),
},
);
super(questionBase, rl, answers);
}
search(searchTerm) {
return super.search(searchTerm).then(() => {
this.currentChoices.getChoice = (choiceIndex) => {
const choice = Choices.prototype.getChoice.call(this.currentChoices, choiceIndex);
return {
value: stripAnsi(choice.value),
name: stripAnsi(choice.name),
short: stripAnsi(choice.name),
};
};
});
}
onSubmit(line) {
super.onSubmit(stripAnsi(line));
}
}
module.exports = InquirerFuzzyPath;