forked from aws/aws-cdk
/
util.ts
65 lines (55 loc) · 1.57 KB
/
util.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
import * as fs from 'fs';
import * as path from 'path';
// From https://github.com/errwischt/stacktrace-parser/blob/master/src/stack-trace-parser.js
const STACK_RE = /^\s*at (?:((?:\[object object\])?[^\\/]+(?: \[as \S+\])?) )?\(?(.*?):(\d+)(?::(\d+))?\)?\s*$/i;
/**
* A parsed stack trace line
*/
export interface StackTrace {
readonly file: string;
readonly methodName?: string;
readonly lineNumber: number;
readonly column: number;
}
/**
* Parses the stack trace of an error
*/
export function parseStackTrace(error?: Error): StackTrace[] {
const err = error || new Error();
if (!err.stack) {
return [];
}
const lines = err.stack.split('\n');
const stackTrace: StackTrace[] = [];
for (const line of lines) {
const results = STACK_RE.exec(line);
if (results) {
stackTrace.push({
file: results[2],
methodName: results[1],
lineNumber: parseInt(results[3], 10),
column: parseInt(results[4], 10),
});
}
}
return stackTrace;
}
/**
* Returns the major version of node installation
*/
export function nodeMajorVersion(): number {
return parseInt(process.versions.node.split('.')[0], 10);
}
/**
* Find a file by walking up parent directories
*/
export function findUp(name: string, directory: string = process.cwd()): string | undefined {
const { root } = path.parse(directory);
if (directory === root && !fs.existsSync(path.join(directory, name))) {
return undefined;
}
if (fs.existsSync(path.join(directory, name))) {
return directory;
}
return findUp(name, path.dirname(directory));
}