forked from flow/flow-for-vscode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFlowHelpers.js
More file actions
257 lines (229 loc) · 7.91 KB
/
FlowHelpers.js
File metadata and controls
257 lines (229 loc) · 7.91 KB
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
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
'use babel';
/* @flow */
/*
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the license found in the LICENSE file in
* the root directory of this source tree.
*/
import type {LRUCache} from 'lru-cache';
import type {FlowLocNoSource} from './flowOutputTypes';
import nuclideUri from '../../nuclide-remote-uri/lib/main';
import {checkOutput} from '../../commons-node/process';
import fsPromise from '../../commons-node/fsPromise';
import LRU from 'lru-cache';
import invariant from 'assert';
const flowConfigDirCache: LRUCache<string, Promise<?string>> = LRU({
max: 10,
maxAge: 1000 * 30, //30 seconds
});
const flowPathCache: LRUCache<string, boolean> = LRU({
max: 10,
maxAge: 1000 * 30, // 30 seconds
});
function insertAutocompleteToken(contents: string, line: number, col: number): string {
const lines = contents.split('\n');
let theLine = lines[line];
theLine = theLine.substring(0, col) + 'AUTO332' + theLine.substring(col);
lines[line] = theLine;
return lines.join('\n');
}
/**
* Takes an autocomplete item from Flow and returns a valid autocomplete-plus
* response, as documented here:
* https://github.com/atom/autocomplete-plus/wiki/Provider-API
*/
function processAutocompleteItem(replacementPrefix: string, flowItem: Object): Object {
// Truncate long types for readability
const description = flowItem.type.length < 80
? flowItem.type
: flowItem.type.substring(0, 80) + ' ...';
let result = {
description,
displayText: flowItem.name,
replacementPrefix,
};
const funcDetails = flowItem.func_details;
if (funcDetails) {
// The parameters in human-readable form for use on the right label.
const rightParamStrings = funcDetails.params
.map(param => `${param.name}: ${param.type}`);
const snippetString = getSnippetString(funcDetails.params.map(param => param.name));
result = {
...result,
leftLabel: funcDetails.return_type,
rightLabel: `(${rightParamStrings.join(', ')})`,
snippet: `${flowItem.name}(${snippetString})`,
type: 'function',
};
} else {
result = {
...result,
rightLabel: flowItem.type,
text: flowItem.name,
};
}
return result;
}
function getSnippetString(paramNames: Array<string>): string {
const groupedParams = groupParamNames(paramNames);
// The parameters turned into snippet strings.
const snippetParamStrings = groupedParams
.map(params => params.join(', '))
.map((param, i) => `\${${i + 1}:${param}}`);
return snippetParamStrings.join(', ');
}
/**
* Group the parameter names so that all of the trailing optional parameters are together with the
* last non-optional parameter. That makes it easy to ignore the optional parameters, since they
* will be selected along with the last non-optional parameter and you can just type to overwrite
* them.
*/
function groupParamNames(paramNames: Array<string>): Array<Array<string>> {
// Split the parameters into two groups -- all of the trailing optional paramaters, and the rest
// of the parameters. Trailing optional means all optional parameters that have only optional
// parameters after them.
const [ordinaryParams, trailingOptional] =
paramNames.reduceRight(([ordinary, optional], param) => {
// If there have only been optional params so far, and this one is optional, add it to the
// list of trailing optional params.
if (isOptional(param) && ordinary.length === 0) {
optional.unshift(param);
} else {
ordinary.unshift(param);
}
return [ordinary, optional];
},
[[], []]
);
const groupedParams = ordinaryParams.map(param => [param]);
const lastParam = groupedParams[groupedParams.length - 1];
if (lastParam != null) {
lastParam.push(...trailingOptional);
} else if (trailingOptional.length > 0) {
groupedParams.push(trailingOptional);
}
return groupedParams;
}
function isOptional(param: string): boolean {
invariant(param.length > 0);
const lastChar = param[param.length - 1];
return lastChar === '?';
}
function clearWorkspaceCaches() {
flowPathCache.reset();
flowConfigDirCache.reset();
global.cachedPathToFlowBin = undefined;
}
async function isFlowInstalled(): Promise<boolean> {
const flowPath = await getPathToFlow();
if (!flowPathCache.has(flowPath)) {
flowPathCache.set(flowPath, await canFindFlow(flowPath));
}
return flowPathCache.get(flowPath);
}
async function canFindFlow(flowPath: string): Promise<boolean> {
try {
// https://github.com/facebook/nuclide/issues/561
const {command, args} = buildSearchFlowCommand(flowPath)
await checkOutput(command, args);
return true;
} catch (e) {
return false;
}
}
/**
* @return The path to Flow on the user's machine. First using the the user's
* config, then looking into the node_modules for the project.
*
* It is cached, so it is expected that changing the users settings will
* trigger a call to `clearWorkspaceCaches`.
*/
async function getPathToFlow(): Promise<string> {
if (global.cachedPathToFlowBin) { return global.cachedPathToFlowBin }
const config = global.vscode.workspace.getConfiguration('flow');
const shouldUseNodeModule = config.get('useNPMPackagedFlow');
if (shouldUseNodeModule && await canFindFlow(nodeModuleFlowLocation())){
global.cachedPathToFlowBin = nodeModuleFlowLocation();
return global.cachedPathToFlowBin
}
const userPath = config.get('pathToFlow');
if (await canFindFlow(userPath)) {
global.cachedPathToFlowBin = userPath
return global.cachedPathToFlowBin
}
// Final fallback, mainly so we complete the promise<string> implmentation
return "flow"
}
/**
* @return The potential path to Flow on the user's machine if they are using NPM/Yarn to manage
* their installs of flow.
*/
function nodeModuleFlowLocation(): string {
if (process.platform === 'win32') {
return `${global.vscode.workspace.rootPath}\\node_modules\\.bin\\flow.cmd`
} else {
return `${global.vscode.workspace.rootPath}/node_modules/.bin/flow`
}
}
/**
* @return The command and arguments used to test the presence of flow according to platform.
*/
function buildSearchFlowCommand(testPath: string): {command: string, args: Array<string>} {
if (process.platform !== 'win32') {
return {
command: 'which',
args: [testPath]
}
} else {
const splitCharLocation = testPath.lastIndexOf('\\')
const command = testPath.substring(splitCharLocation+1, testPath.length)
const searchDirectory = testPath.substring(0, splitCharLocation)
const args = !searchDirectory ? [command] : ['/r', searchDirectory, command]
return {
command: `${process.env.SYSTEMROOT || 'C:\\Windows'}\\System32\\where`,
args: args
}
}
}
function getStopFlowOnExit(): boolean {
// $UPFixMe: This should use nuclide-features-config
// Does not currently do so because this is an npm module that may run on the server.
if (global.vscode) {
return global.vscode.workspace.getConfiguration('flow').get('stopFlowOnExit')
}
return true;
}
function findFlowConfigDir(localFile: string): Promise<?string> {
if (!flowConfigDirCache.has(localFile)) {
const flowConfigDir = fsPromise.findNearestFile('.flowconfig', nuclideUri.dirname(localFile));
flowConfigDirCache.set(localFile, flowConfigDir);
}
return flowConfigDirCache.get(localFile);
}
function flowCoordsToAtomCoords(flowCoords: FlowLocNoSource): FlowLocNoSource {
return {
start: {
line: flowCoords.start.line - 1,
column: flowCoords.start.column - 1,
},
end: {
line: flowCoords.end.line - 1,
// Yes, this is inconsistent. Yes, it works as expected in practice.
column: flowCoords.end.column,
},
};
}
module.exports = {
buildSearchFlowCommand,
findFlowConfigDir,
getPathToFlow,
getStopFlowOnExit,
insertAutocompleteToken,
isFlowInstalled,
processAutocompleteItem,
groupParamNames,
flowCoordsToAtomCoords,
clearWorkspaceCaches
};