-
Notifications
You must be signed in to change notification settings - Fork 0
/
bin.ts
206 lines (187 loc) · 4.81 KB
/
bin.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
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
import { cli, io, path, ts, walk } from './src/deps.ts';
import {
hasShouldResolveImportedFiles,
resolvedModules,
} from './src/resolve_util.ts';
import { preserveNewLine, restoreNewLine } from './src/str.ts';
import { transform } from './src/transform.ts';
const flags = cli.parse(Deno.args, {
string: ['b', 'c'],
boolean: ['d', 'r'],
});
const main = async (args: {
basePath?: string;
options?: {
tsConfigPath?: string;
dryRun?: boolean;
repl?: boolean;
};
} = {
basePath: flags.b,
options: {
tsConfigPath: flags.c,
dryRun: flags.d ?? false,
repl: flags.r ?? false,
},
}) => {
const { basePath, options } = args;
const _basePath = basePath ?? '.';
const tsConfigPath = options?.tsConfigPath ?? './tsconfig.json';
const match = [/\.ts$/, /\.mts$/, /\.jsx$/, /\.tsx$/];
const skip = [/node_modules/];
const decoder = new TextDecoder('utf-8');
const tsConfigJson = await Deno.readFile(tsConfigPath);
const tsConfigObject = ts.parseJsonConfigFileContent(
JSON.parse(decoder.decode(tsConfigJson)),
ts.sys,
_basePath,
);
const printer = ts.createPrinter();
const transformedList: Array<{
path: string;
result: string;
}> = [];
console.log('processing...');
for await (const entry of walk(_basePath, { match, skip })) {
if (entry.isFile) {
const targetPath = entry.path;
const targetFileAbsPath = path.resolve(targetPath);
const fileContent = preserveNewLine(decoder.decode(
await Deno.readFile(targetFileAbsPath),
));
const { importedFiles } = ts.preProcessFile(fileContent, true, true);
if (
!hasShouldResolveImportedFiles({
importedFiles,
targetFileAbsPath,
tsConfigObject,
})
) continue;
const imports = resolvedModules({
importedFiles,
targetFileAbsPath,
tsConfigObject,
});
const sourceFile = ts.createSourceFile(
targetFileAbsPath,
fileContent,
ts.ScriptTarget.ESNext,
true,
);
const result = restoreNewLine(
// It seems like ts.Printer.printNode doesn't keep original source newline.🤔
transform({
sourceFile,
imports,
tsConfigObject,
printer,
}),
);
transformedList.push({
path: targetFileAbsPath,
result,
});
}
}
if (transformedList.length === 0) {
console.log(
`%cThere're no transform target files.`,
'color: green',
);
Deno.exit();
}
console.log(
`%ctransform target ${transformedList.length} files found.`,
'color: yellow',
);
const encoder = new TextEncoder();
const writeFiles = async (): Promise<void> => {
await Promise.all(transformedList.map((transformed) => {
return new Promise((resolve, reject) => {
const { path, result } = transformed;
try {
resolve(
Deno.writeFile(
path,
encoder.encode(result),
).then(),
);
} catch (error) {
reject(error);
}
});
})).then(() => {
console.log(
`%cupdate ${transformedList.length} files, finished.`,
'color: green',
);
}).catch((error) => {
throw new Error(error);
});
};
const LOG_FILE_NAME = 'module-specifier-resolver.log';
const writeLog = async (): Promise<void> => {
// try remove log file if it exsist or not
try {
await Deno.remove(LOG_FILE_NAME);
} catch (_) { /* noop */ }
await Promise.all(transformedList.map((transformed) => {
return new Promise((resolve, reject) => {
const { path, result } = transformed;
try {
resolve(
Deno.writeFile(
LOG_FILE_NAME,
encoder.encode(
`file: ${path}
${result}
`,
),
{
append: true,
},
).then(),
);
} catch (error) {
reject(error);
}
});
})).then(() => {
console.log(
`%cDry run: ${transformedList.length} files, finished.`,
'color: green',
);
console.log(
`%cInfo: ${LOG_FILE_NAME}`,
'color: blue',
);
}).catch((error) => {
throw new Error(error);
});
};
if (options?.dryRun) {
await writeLog();
Deno.exit();
}
if (options?.repl) {
console.log(
`%cAre you sure complement the extension of module specifier to files? (y/n)`,
'color: yellow',
);
for await (const line of io.readLines(Deno.stdin)) {
if (line.trim().toLowerCase() === 'y') {
await writeFiles();
Deno.exit();
} else {
Deno.exit();
}
}
} else {
await writeFiles();
Deno.exit();
}
};
if(import.meta.main) {
await main();
}
export { main };