-
Notifications
You must be signed in to change notification settings - Fork 1.7k
Expand file tree
/
Copy pathcommon.ts
More file actions
362 lines (300 loc) · 12.3 KB
/
common.ts
File metadata and controls
362 lines (300 loc) · 12.3 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
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
/* --------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All Rights Reserved.
* See 'LICENSE' in the project root for license information.
* ------------------------------------------------------------------------------------------ */
import { Command, CommandFunction } from '../src/Utility/Process/program';
import { ok } from 'assert';
import { CommentJSONValue, parse, stringify } from 'comment-json';
import { mkdir as md, readFile, rm, writeFile } from 'fs/promises';
import { IOptions, glob as globSync } from 'glob';
import { dirname, resolve } from 'path';
import { chdir, cwd, env } from 'process';
import { setImmediate } from 'timers/promises';
import { promisify } from 'util';
import { filepath } from '../src/Utility/Filesystem/filepath';
import { is } from '../src/Utility/System/guards';
import { verbose } from '../src/Utility/Text/streams';
export const $root = resolve(`${__dirname}/..`);
export let $cmd = 'main';
export let $scenario = '';
// loop through the args and pick out --scenario=... and remove it from the $args and set $scenario
process.argv.slice(2).filter(each => !(each.startsWith('--scenario=') && ($scenario = each.substring('--scenario='.length))));
export const $args = process.argv.slice(2).filter(each => !each.startsWith('--'));
export const $switches = process.argv.slice(2).filter(each => each.startsWith('--'));
/** enqueue the call to the callback function to happen on the next available tick, and return a promise to the result */
export function then<T>(callback: () => Promise<T> | T): Promise<T> {
return setImmediate().then(callback);
}
export const pwd = env.INIT_CWD ?? cwd();
verbose(yellow(`pwd: ${pwd}`));
// ensure we're in the extension folder.
chdir($root);
// dump unhandled async errors to the console and exit.
process.on('unhandledRejection', (reason: any, _promise) => {
error(`${reason?.stack?.split(/\r?\n/).filter(l => !l.includes('node:internal') && !l.includes('node_modules')).join('\n')}`);
process.exit(1);
});
const git = new Command('git');
export const Git = async (...args: Parameters<Awaited<CommandFunction>>) => (await git)(...args);
export const GitClean = async (...args: Parameters<Awaited<CommandFunction>>) => (await new Command(await git, 'clean'))(...args);
export async function getModifiedIgnoredFiles() {
const { code, error, stdio } = await GitClean('-Xd', '-n');
if (code) {
throw new Error(`\n${error.all().join('\n')}`);
}
// return the full path of files that would be removed.
// eslint-disable-next-line @typescript-eslint/no-misused-promises
return Promise.all(stdio.filter("Would remove").map((s) => filepath.exists(s.replace(/^Would remove /, ''), $root)).filter(p => p));
}
export async function rimraf(...paths: string[]) {
const all: Promise<void>[] = [];
for (const each of paths) {
if (!each) {
continue;
}
if (await filepath.isFolder(each)) {
verbose(`Removing folder ${red(each)}`);
all.push(rm(each, { recursive: true, force: true }));
continue;
}
verbose(`Removing file ${red(each)}`);
all.push(rm(each, { force: true }));
}
await Promise.all(all);
}
export async function mkdir(filePath: string) {
const [fullPath, info] = await filepath.stats(filePath, $root);
if (info) {
if (info.isDirectory()) {
return fullPath;
}
throw new Error(`Cannot create directory '${filePath}' because there is a file there.`);
}
if (!fullPath) {
throw new Error(`Cannot create directory '${filePath}' because the path is invalid.`);
}
await md(fullPath, { recursive: true });
return fullPath;
}
export const glob: (pattern: string, options?: IOptions) => Promise<string[]> = promisify(globSync);
export async function write(filePath: string, data: Buffer | string) {
await mkdir(dirname(filePath));
if (await filepath.isFile(filePath)) {
const content = await readFile(filePath);
if (is.string(data)) {
// if we're passed a text file, we should match the line endings of the existing file.
const textContent = content.toString();
// normalize the line endings to the same as the current file.
data = textContent.indexOf('\r\n') > -1 ? data.replace(/\r\n|\n/g, '\r\n') : data.replace(/\r\n|\n/g, '\n');
// if the text content is a match, we don't have to change anything
if (textContent === data) {
verbose(`Text file at '${filePath}' is up to date.`);
return;
}
} else {
// if the binary content is a match, we don't have to change anything
if (content.equals(data)) {
verbose(`File at '${filePath}' is up to date.`);
return;
}
}
}
verbose(`Writing file '${filePath}'`);
await writeFile(filePath, data);
}
export async function updateFiles(files: string[], dest: string | Promise<string>) {
const target = is.promise(dest) ? await dest : dest;
await Promise.all(files.map(async (each) => {
const sourceFile = await filepath.isFile(each, $root);
if (sourceFile) {
const targetFile = resolve(target, each);
await write(targetFile, await readFile(sourceFile));
}
}));
}
export async function go() {
if (require.main) {
// loop through the args and pick out the first non --arg and remove it from the $args and set $cmd
for (let i = 0; i < $args.length; i++) {
const each = $args[i];
if (!each.startsWith('--') && require.main.exports[each]) {
$cmd = each;
$args.splice(i, 1);
break;
}
}
verbose(`${yellow("Running task:")} ${green($cmd)} ${green($args.join(' '))}`);
require.main.exports[$cmd](...$args);
}
}
void then(go);
export async function read(filename: string) {
const content = await readFile(filename);
ok(content, `File '${filename}' has no content`);
return content.toString();
}
export async function readJson(filename: string, fallback = {}): Promise<CommentJSONValue> {
try {
return parse(await read(filename));
} catch {
return fallback as CommentJSONValue;
}
}
export async function writeJson(filename: string, object: CommentJSONValue) {
await write(filename, stringify(object, null, 4));
}
export function error(text: string) {
console.error(`\n${red('ERROR')}: ${text}`);
return true;
}
export function warn(text: string) {
console.error(`\n${yellow('WARNING')}: ${text}`);
return true;
}
export function note(text: string) {
console.error(`\n${cyan('NOTE')}: ${text}`);
}
export function underline(text: string) {
return `\u001b[4m${text}\u001b[0m`;
}
export function bold(text: string) {
return `\u001b[1m${text}\u001b[0m`;
}
export function dim(text: string) {
return `\u001b[2m${text}\u001b[0m`;
}
export function brightGreen(text: string) {
return `\u001b[38;2;19;161;14m${text}\u001b[0m`;
}
export function green(text: string) {
return `\u001b[38;2;78;154;6m${text}\u001b[0m`;
}
export function brightWhite(text: string) {
return `\u001b[38;2;238;238;236m${text}\u001b[0m`;
}
export function gray(text: string) {
return `\u001b[38;2;117;113;94m${text}\u001b[0m`;
}
export function yellow(text: string) {
return `\u001b[38;2;252;233;79m${text}\u001b[0m`;
}
export function red(text: string) {
return `\u001b[38;2;197;15;31m${text}\u001b[0m`;
}
export function cyan(text: string) {
return `\u001b[38;2;0;174;239m${text}\u001b[0m`;
}
export const hr = "===============================================================================";
export function heading(text: string, level = 1) {
switch (level) {
case 1:
return `${underline(bold(text))}`;
case 2:
return `${brightGreen(text)}`;
case 3:
return `${green(text)}`;
}
return `${bold(text)}\n`;
}
export function optional(text: string) {
return gray(text);
}
export function cmdSwitch(text: string) {
return optional(`--${text}`);
}
export function command(text: string) {
return brightWhite(bold(text));
}
export function hint(text: string) {
return green(dim(text));
}
export function count(num: number) {
return gray(`${num}`);
}
export function position(text: string) {
return gray(`${text}`);
}
export async function assertAnyFolder(oneOrMoreFolders: string | string[], errorMessage?: string): Promise<string | undefined> {
oneOrMoreFolders = is.array(oneOrMoreFolders) ? oneOrMoreFolders : [oneOrMoreFolders];
for (const each of oneOrMoreFolders) {
const result = await filepath.isFolder(each, $root);
if (result) {
verbose(`Folder ${brightGreen(each)} exists.`);
return result;
}
}
if (errorMessage) {
if (!$switches.includes('--quiet')) {
error(errorMessage);
}
process.exit(1);
}
}
export async function assertAnyFile(oneOrMoreFiles: string | string[], errorMessage?: string): Promise<string | undefined> {
oneOrMoreFiles = is.array(oneOrMoreFiles) ? oneOrMoreFiles : [oneOrMoreFiles];
for (const each of oneOrMoreFiles) {
const result = await filepath.isFile(each, $root);
if (result) {
verbose(`Folder ${brightGreen(each)} exists.`);
return result;
}
}
if (errorMessage) {
if (!$switches.includes('--quiet')) {
error(errorMessage);
}
process.exit(1);
}
}
const quiet = process.argv.includes('--quiet');
export async function checkPrep() {
let failing = false;
failing = !await assertAnyFolder('dist/test') && (quiet || warn(`The compiled test files are not in place.`)) || failing;
failing = !await assertAnyFolder('dist/walkthrough') && (quiet || warn(`The walkthrough files are not in place.`)) || failing;
failing = !await assertAnyFolder('dist/html') && (quiet || warn(`The html files are not in place.`)) || failing;
failing = !await assertAnyFolder('dist/schema') && (quiet || warn(`The schema files are not in place.`)) || failing;
failing = !await assertAnyFile('dist/nls.metadata.json') && (quiet || warn(`The extension translation file '${$root}/dist/nls.metadata.json is missing.`)) || failing;
failing = await checkDTS() || failing;
if (!failing) {
verbose('Prep files appear to be in place.');
}
return failing;
}
export async function checkCompiled() {
let failing = false;
failing = await checkDTS() || failing;
failing = !await assertAnyFile('dist/src/main.js') && (quiet || warn(`The extension entry point '${$root}/dist/src/main.js is missing.`)) || failing;
if (!failing) {
verbose('Compiled files appear to be in place.');
}
return failing;
}
export async function checkDTS() {
let failing = false;
failing = !await assertAnyFile('vscode.d.ts') && (quiet || warn(`The VSCode import file '${$root}/dist/src/vscode.d.ts is missing.`)) || failing;
failing = !await assertAnyFile('vscode.proposed.terminalDataWriteEvent.d.ts') && (quiet || warn(`The VSCode import file '${$root}/dist/src/vscode.proposed.terminalDataWriteEvent.d.ts is missing.`)) || failing;
if (!failing) {
verbose('VSCode d.ts files appear to be in place.');
}
return failing;
}
export async function checkBinaries() {
if ($switches.includes('--skipCheckBinaries')) {
return false;
}
let failing = false;
failing = !await assertAnyFile(['bin/cpptools.exe', 'bin/cpptools']) && (quiet || warn(`The native binary files are not present. You should either build or install the native binaries\n\n.`)) || failing;
if (!failing) {
verbose('Native binary files appear to be in place.');
}
return failing;
}
export async function checkProposals() {
let failing = false;
await rm(`${$root}/vscode.proposed.chatParticipantAdditions.d.ts`);
failing = await assertAnyFile('vscode.proposed.chatParticipantAdditions.d.ts') && (quiet || warn(`The VSCode import file '${$root}/vscode.proposed.chatParticipantAdditions.d.ts' should not be present.`)) || failing;
if (!failing) {
verbose('VSCode proposals appear to be in place.');
}
return failing;
}