-
Notifications
You must be signed in to change notification settings - Fork 299
/
Copy pathhelpers.ts
382 lines (342 loc) · 11.7 KB
/
helpers.ts
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
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
import * as vscode from 'vscode';
import { platform } from 'os';
import { existsSync, readFileSync, mkdirSync, writeFileSync } from 'fs';
import { join, resolve, normalize, isAbsolute } from 'path';
import { ExtensionContext } from 'vscode';
import { TestIdentifier } from './TestResults';
import { TestStats } from './types';
import { LoginShell } from 'jest-editor-support';
import { WorkspaceManager } from './workspace-manager';
/**
* Known binary names of `react-scripts` forks
*/
const createReactAppBinaryNames = [
'react-scripts',
'react-native-scripts',
'react-scripts-ts',
'react-app-rewired',
];
/**
* File extension for npm binaries
*/
export const nodeBinExtension: string = platform() === 'win32' ? '.cmd' : '';
/**
* Resolves the location of an npm binary
*
* Returns the path if it exists, or `undefined` otherwise
*/
function getLocalPathForExecutable(rootPath: string, executable: string): string | undefined {
const absolutePath = resolve(rootPath, 'node_modules', '.bin', executable + nodeBinExtension);
return existsSync(absolutePath) ? absolutePath : undefined;
}
/**
* Tries to read the test command from the scripts section within `package.json`
*
* Returns the test command in case of success,
* `undefined` otherwise
*/
export function getTestCommand(rootPath: string): string | undefined {
const packageJSON = getPackageJson(rootPath);
if (packageJSON && packageJSON.scripts && packageJSON.scripts.test) {
return packageJSON.scripts.test;
}
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export function getPackageJson(rootPath: string): any | undefined {
try {
const packagePath = resolve(rootPath, 'package.json');
return JSON.parse(readFileSync(packagePath, 'utf8'));
} catch {
return undefined;
}
}
/**
* Checks if the supplied test command could have been generated by create-react-app
*/
export function isCreateReactAppTestCommand(testCommand?: string | null): boolean {
return (
!!testCommand &&
createReactAppBinaryNames.some((binary) => testCommand.includes(`${binary} test`))
);
}
export function hasReactBinary(rootPath: string): boolean {
return createReactAppBinaryNames.some((binary) => getLocalPathForExecutable(rootPath, binary));
}
function checkPackageTestScript(rootPath: string): string | undefined {
const testCommand = getTestCommand(rootPath);
if (!testCommand) {
return;
}
if (
isCreateReactAppTestCommand(testCommand) ||
testCommand.includes('jest') ||
// for react apps, even if we don't recognize the test script pattern, still better to use the test script
// than running the binary with hard coded parameters ourselves.
hasReactBinary(rootPath)
) {
const pm = getPM(rootPath) ?? 'npm';
if (pm === 'npm') {
return 'npm test --';
}
return 'yarn test';
}
}
const PMInfo: Record<string, string> = {
yarn: 'yarn.lock',
npm: 'package-lock.json',
};
function getPM(rootPath: string): string | undefined {
return Object.keys(PMInfo).find((pm) => {
const lockFile = PMInfo[pm];
const absolutePath = resolve(rootPath, lockFile);
return existsSync(absolutePath);
});
}
/**
* construct a default jest command from rootPath, currently support any configurations that match any of the following:
* 1. a "test" script in package.json that contains CRA or "jest" command
* 2. a jest binary in local node_modules
* 3. CRA scripts in local node_modules.
*
* @param rootPath an absolute path from where the search starts.
* @returns the verified jest command for jest or CRA apps, if found; otherwise return undefined
*/
export const getDefaultJestCommand = (rootPath = ''): string | undefined => {
const _rootPath = resolve(rootPath);
const pmScript = checkPackageTestScript(_rootPath);
if (pmScript) {
return pmScript;
}
const cmd = getLocalPathForExecutable(rootPath, 'jest');
if (cmd) {
return `"${cmd}"`;
}
};
/**
* Taken From https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions
*/
export function escapeRegExp(str: string): string {
return str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); // $& means the whole matched string
}
/**
* ANSI colors/characters cleaning based on http://stackoverflow.com/questions/25245716/remove-all-ansi-colors-styles-from-strings
*/
export function cleanAnsi(str: string|undefined|null): string {
if(!str) {
return "";
}
return str.replace(
// eslint-disable-next-line no-control-regex
/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/g,
''
);
}
export type IdStringType = 'display' | 'display-reverse' | 'full-name';
export function testIdString(type: IdStringType, identifier: TestIdentifier): string {
if (!identifier.ancestorTitles.length) {
return identifier.title;
}
const parts = [...identifier.ancestorTitles, identifier.title];
switch (type) {
case 'display':
return parts.join(' > ');
case 'display-reverse':
return parts.reverse().join(' < ');
case 'full-name':
return parts.join(' ');
}
}
/** convert the upper-case drive letter filePath to lower-case. If path does not contain upper-case drive letter, returns undefined. */
// note: this should probably be replaced by vscode.URI.file(filePath).fsPath ...
export function toLowerCaseDriveLetter(filePath: string): string | undefined {
const match = filePath.match(/^([A-Z]:\\)(.*)$/);
if (match) {
return `${match[1].toLowerCase()}${match[2]}`;
}
}
/** convert the lower-case drive letter filePath (like vscode.URI.fsPath) to lower-case. If path does not contain lower-case drive letter, returns undefined. */
export function toUpperCaseDriveLetter(filePath: string): string | undefined {
const match = filePath.match(/^([a-z]:\\)(.*)$/);
if (match) {
return `${match[1].toUpperCase()}${match[2]}`;
}
}
/**
* convert vscode.URI.fsPath to the actual file system file-path, i.e. convert drive letter to upper-case for windows
* @param filePath
*/
export function toFilePath(filePath: string): string {
return toUpperCaseDriveLetter(filePath) || filePath;
}
/**
* Generate path to icon used in decorations
* NOTE: Should not be called repeatedly for the performance reasons. Cache your results.
*/
export function prepareIconFile(
context: ExtensionContext,
iconName: string,
source: string,
color?: string
): string {
const iconsPath = join('generated-icons');
const resolvePath = (...args: string[]): string => {
return context.asAbsolutePath(join(...args));
};
const resultIconPath = resolvePath(iconsPath, `${iconName}.svg`);
let result = source.toString();
if (color) {
result = result.replace('fill="currentColor"', `fill="${color}"`);
}
if (!existsSync(resultIconPath) || readFileSync(resultIconPath).toString() !== result) {
if (!existsSync(resolvePath(iconsPath))) {
mkdirSync(resolvePath(iconsPath));
}
writeFileSync(resultIconPath, result);
}
return resultIconPath;
}
const SurroundingQuoteRegex = /^["']|["']$/g;
export const removeSurroundingQuote = (command: string): string =>
command.replace(SurroundingQuoteRegex, '');
// TestStats
/* istanbul ignore next */
export const emptyTestStats = (): TestStats => {
return { success: 0, fail: 0, unknown: 0 };
};
const getShellPath = (shell?: string | LoginShell): string | undefined => {
if (!shell) {
return;
}
if (typeof shell === 'string') {
return shell;
}
return shell.path;
};
/**
* quoting a given string for it to be used as shell command arguments.
*
* Note: the logic is based on vscode's debug argument handling:
* https://github.com/microsoft/vscode/blob/c0001d7becf437944f5898a7c9485922d60dd8d3/src/vs/workbench/contrib/debug/node/terminals.ts#L82
* However, had to modify a few places for windows platform.
*
* updated 10/22/2022 based on https://github.com/microsoft/vscode/blob/d1f38520db76f0e80e3cdcbb35b95651afe802ae/src/vs/workbench/contrib/debug/node/terminals.ts#L60
*
**/
export const shellQuote = (str: string, shell?: string | LoginShell): string => {
const targetShell = getShellPath(shell)?.trim().toLowerCase();
// try to determine the shell type
let shellType: 'powershell' | 'cmd' | 'sh';
if (!targetShell) {
shellType = platform() === 'win32' ? 'cmd' : 'sh';
} else if (targetShell.indexOf('powershell') >= 0 || targetShell.indexOf('pwsh') >= 0) {
shellType = 'powershell';
} else if (targetShell.indexOf('cmd.exe') >= 0) {
shellType = 'cmd';
} else {
shellType = 'sh';
}
switch (shellType) {
case 'powershell': {
const s = str.replace(/(['"])/g, '$1$1');
if (s.length > 2 && s.slice(-2) === '\\\\') {
return `'${s}\\\\'`;
}
return `'${s}'`;
}
case 'cmd': {
let s = str.replace(/"/g, '""');
s = s.replace(/([><!^&|])/g, '^$1');
if (s.length > 2 && s.slice(-2) === '\\\\') {
s = `${s}\\\\`;
}
return s.indexOf(' ') >= 0 || s.indexOf('"') >= 0 || s.length === 0 ? `"${s}"` : s;
}
default: {
//'sh'
const s = str.replace(/(["'\\$!><#()[\]*&^| ;{}`])/g, '\\$1');
return s.length === 0 ? `""` : s;
}
}
};
export const toErrorString = (e: unknown): string => {
if (e == null) {
return '';
}
if (typeof e === 'string') {
return e;
}
if (e instanceof Error) {
return e.stack ?? e.toString();
}
return JSON.stringify(e);
};
// regex that match single, double quotes and "\" escape char"
const cmdSplitRegex = /"([^"\\]*(?:\\.[^"\\]*)*)"|'([^'\\]*(?:\\.[^'\\]*)*)'|([^\s'"]+)/g;
export const parseCmdLine = (cmdLine: string): string[] => {
const parts = cmdLine.match(cmdSplitRegex) || [];
// clean up command
if (parts.length > 0 && parts[0]) {
parts[0] = removeSurroundingQuote(normalize(parts[0]));
}
return parts;
};
/**
* Converts a relative or absolute root path to an absolute root path based on the provided workspace folder.
* If no root path is provided, returns the absolute path of the workspace folder.
* @param workspace The workspace folder to use as a base for the absolute root path.
* @param rootPath The relative or absolute root path to convert to an absolute root path.
* @returns The absolute root path.
*/
export const toAbsoluteRootPath = (
workspace: vscode.WorkspaceFolder,
rootPath?: string
): string => {
if (!rootPath) {
return workspace.uri.fsPath;
}
return isAbsolute(rootPath) ? normalize(rootPath) : resolve(workspace.uri.fsPath, rootPath);
};
export interface JestCommandSettings {
rootPath: string;
jestCommandLine: string;
}
export interface JestCommandResult {
uris?: vscode.Uri[];
validSettings: JestCommandSettings[];
}
/**
* generate a valid jest command settings beyond the static "defaultJestCommand" by doing a deep search from the workspace-root/rootPath down
* @param workspace
* @param workspaceManager
* @param rootPath
* @returns
*/
export const getValidJestCommand = async (
workspace: vscode.WorkspaceFolder,
workspaceManager: WorkspaceManager,
rootPath?: string
): Promise<JestCommandResult> => {
const absoluteRootPath = toAbsoluteRootPath(workspace, rootPath);
let jestCommandLine = getDefaultJestCommand(absoluteRootPath);
if (jestCommandLine) {
return Promise.resolve({ validSettings: [{ rootPath: absoluteRootPath, jestCommandLine }] });
}
// see if we can get a valid command by examining the file system
const uris = await workspaceManager.getFoldersFromFilesystem(workspace);
const validSettings: JestCommandSettings[] = [];
for (const uri of uris) {
const p = uri.fsPath;
if (p === absoluteRootPath) {
continue;
}
jestCommandLine = getDefaultJestCommand(p);
if (jestCommandLine) {
const settings = { jestCommandLine, rootPath: p };
validSettings.push(settings);
if (validSettings.length > 1) {
break;
}
}
}
return { uris, validSettings };
};