-
Notifications
You must be signed in to change notification settings - Fork 52
/
utils.ts
70 lines (58 loc) · 2.53 KB
/
utils.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
import * as ts from "typescript";
import * as fs from "fs";
import * as path from "path";
export function createDefaultFormatCodeSettings(): ts.FormatCodeSettings {
return {
indentSize: 4,
tabSize: 4,
indentStyle: ts.IndentStyle.Smart,
newLineCharacter: "\r\n",
convertTabsToSpaces: true,
insertSpaceAfterCommaDelimiter: true,
insertSpaceAfterSemicolonInForStatements: true,
insertSpaceBeforeAndAfterBinaryOperators: true,
insertSpaceAfterKeywordsInControlFlowStatements: true,
insertSpaceAfterFunctionKeywordForAnonymousFunctions: false,
insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis: false,
insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets: false,
insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces: false,
placeOpenBraceOnNewLineForFunctions: false,
placeOpenBraceOnNewLineForControlBlocks: false,
};
}
export function getConfigFileName(baseDir: string, configFileName: string): string | null {
let configFilePath = path.resolve(baseDir, configFileName);
if (fs.existsSync(configFilePath)) {
return configFilePath;
}
if (baseDir.length === path.dirname(baseDir).length) {
return null;
}
return getConfigFileName(path.resolve(baseDir, "../"), configFileName);
}
export function readFilesFromTsconfig(configPath: string): string[] {
return readTsconfig(configPath).fileNames;
}
export function readTsconfig(configPath: string): ts.ParsedCommandLine {
// for `extends` support. It supported from TypeScript 2.1.1.
// `& { readFile(path: string): string; }` is backword compat for TypeScript compiler 2.0.3 support.
const host: ts.ParseConfigHost & { readFile(path: string): string; } = {
useCaseSensitiveFileNames: ts.sys.useCaseSensitiveFileNames,
readDirectory: ts.sys.readDirectory,
fileExists: path => fs.existsSync(path),
readFile: (path: string) => fs.readFileSync(path, "utf-8"),
};
let rootConfig = parseJSON(fs.readFileSync(configPath, "utf-8"));
let parsed = ts.parseJsonConfigFileContent(rootConfig, host, path.dirname(configPath));
if (parsed.errors && parsed.errors.length !== 0) {
throw new Error(parsed.errors.map(e => e.messageText).join("\n"));
}
return parsed;
}
export function parseJSON(jsonText: string): any {
let result = ts.parseConfigFileTextToJson("tmp.json", jsonText);
if (result.error) {
throw new Error("JSON parse error");
}
return result.config;
}