-
Notifications
You must be signed in to change notification settings - Fork 208
/
Copy pathutil.ts
167 lines (149 loc) · 4.67 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
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
/**
* Copyright 2017 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import * as fs from 'fs';
import * as path from 'path';
import * as rimraf from 'rimraf';
import {promisify} from 'util';
import * as ncp from 'ncp';
import * as JSON5 from 'json5';
export const readFilep = promisify(fs.readFile);
export const rimrafp = promisify(rimraf);
export const ncpp = promisify(ncp.ncp);
export interface Bag<T> {
[script: string]: T;
}
export interface DefaultPackage extends Bag<string> {
gts: string;
typescript: string;
'@types/node': string;
}
export async function readJsonp(jsonPath: string) {
const contents = await readFilep(jsonPath, {encoding: 'utf8'});
return JSON5.parse(contents);
}
export interface ReadFileP {
(path: string, encoding: string): Promise<string>;
}
export function nop() {
/* empty */
}
/**
* Recursively iterate through the dependency chain until we reach the end of
* the dependency chain or encounter a circular reference
* @param filePath Filepath of file currently being read
* @param customReadFilep The file reading function being used
* @param readFiles an array of the previously read files so we can check for
* circular references
* returns a ConfigFile object containing the data from all the dependencies
*/
async function getBase(
filePath: string,
customReadFilep: ReadFileP,
readFiles: Set<string>,
currentDir: string,
): Promise<ConfigFile> {
customReadFilep = customReadFilep || readFilep;
filePath = path.resolve(currentDir, filePath);
// An error is thrown if there is a circular reference as specified by the
// TypeScript doc
if (readFiles.has(filePath)) {
throw new Error(`Circular reference in ${filePath}`);
}
readFiles.add(filePath);
try {
const json = await customReadFilep(filePath, 'utf8');
// eslint-disable-next-line @typescript-eslint/no-explicit-any
let contents: any;
try {
contents = JSON5.parse(json);
} catch (e) {
const err = e as Error;
err.message = `Unable to parse ${filePath}!\n${err.message}`;
throw err;
}
if (contents.extends) {
const nextFile = await getBase(
contents.extends,
customReadFilep,
readFiles,
path.dirname(filePath),
);
contents = combineTSConfig(nextFile, contents);
}
return contents;
} catch (e) {
const err = e as Error;
err.message = `Error: ${filePath}\n${err.message}`;
throw err;
}
}
/**
* Takes in 2 config files
* @param base is loaded first
* @param inherited is then loaded and overwrites base
*/
function combineTSConfig(base: ConfigFile, inherited: ConfigFile): ConfigFile {
const result: ConfigFile = {compilerOptions: {}};
Object.assign(result, base, inherited);
Object.assign(
result.compilerOptions!,
base.compilerOptions!,
inherited.compilerOptions!,
);
delete result.extends;
return result;
}
/**
* An interface containing the top level data fields present in Config Files
*/
export interface ConfigFile {
files?: string[];
compilerOptions?: {};
include?: string[];
exclude?: string[];
extends?: string[];
}
/**
* Automatically defines npm or yarn is going to be used:
* - If only yarn.lock exists, use yarn
* - If only package-lock.json or both exist, use npm
*/
export function isYarnUsed(existsSync = fs.existsSync): boolean {
if (existsSync('package-lock.json')) {
return false;
}
return existsSync('yarn.lock');
}
export function getPkgManagerCommand(isYarnUsed?: boolean): string {
return (
(isYarnUsed ? 'yarn' : 'npm') + (process.platform === 'win32' ? '.cmd' : '')
);
}
/**
* Find the tsconfig.json, read it, and return parsed contents.
* @param rootDir Directory where the tsconfig.json should be found.
* If the tsconfig.json file has an "extends" field hop down the dependency tree
* until it ends or a circular reference is found in which case an error will be
* thrown
*/
export async function getTSConfig(
rootDir: string,
customReadFilep?: ReadFileP,
): Promise<ConfigFile> {
customReadFilep = (customReadFilep || readFilep) as ReadFileP;
const readArr = new Set<string>();
return getBase('tsconfig.json', customReadFilep, readArr, rootDir);
}