-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathreflect.ts
50 lines (40 loc) · 1.29 KB
/
reflect.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
import fs from 'node:fs/promises';
import path from 'node:path';
import fg from 'fast-glob';
import { gray, green } from 'kolorist';
export type ReflectActionResult = string | false | undefined;
export interface ReflectOptions {
files: fg.Pattern | fg.Pattern[];
globOptions?: fg.Options;
name?: string;
reflect(code: string): Promise<ReflectActionResult> | ReflectActionResult;
silent?: boolean;
}
export const reflect = async (options: ReflectOptions) => {
const { globOptions = {}, name = 'reflect', reflect, silent } = options;
const cwd = process.cwd();
const files = await fg(options.files, {
cwd: path.resolve(cwd, 'dist'),
...globOptions,
absolute: true,
ignore: [...(globOptions.ignore || []), 'node_modules'],
});
const logger = (message: string) => {
if (!silent) console.log(`[${name}]`, message);
};
if (!files.length) logger(gray('No files matched'));
const output = [];
for (const file of files) {
const code = await fs.readFile(file, 'utf8');
const result = await reflect(code);
const filename = path.relative(cwd, file);
if (result) {
await fs.writeFile(file, result);
output.push(result);
logger(`${green('✔')} ${filename}`);
} else {
logger(gray(`skip ${filename}`));
}
}
return output;
};