-
Notifications
You must be signed in to change notification settings - Fork 219
/
index.ts
178 lines (147 loc) · 6.01 KB
/
index.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
import ts from 'typescript';
import path from 'path';
import log from 'updatable-log';
import { TSServer, CommandTypes } from '../index';
import MigrateConfig from './MigrateConfig';
import { parseTSConfig } from './ParseTSConfig';
import PerfTimer from '../utils/PerfTimer';
import { PluginParams } from '../../types';
interface MigrateParams {
rootDir: string;
config: MigrateConfig;
server: TSServer;
}
export default async function migrate({ rootDir, config, server }: MigrateParams): Promise<number> {
let exitCode = 0;
const parseResult = parseTSConfig(rootDir);
const { options } = parseResult;
const projectFileName = path.resolve(rootDir, '../..', parseResult.configFile);
const fileNames = parseResult.fileNames.map((fileName) =>
path.resolve(rootDir, '../..', fileName),
);
const serverInitTimer = new PerfTimer();
await server.sendRequest(CommandTypes.Configure, { hostInfo: 'ts-migrate' });
const status = await server.sendRequest(CommandTypes.Status, {});
log.info(`TypeScript version: ${status.version}`);
// Notify the server that the client has file open.
// The server will not monitor the filesystem for changes in this file and will assume that the client
// is updating the server (using the change and/or reload messages) when the file changes.
// eslint-disable-next-line no-restricted-syntax
for (const file of fileNames) {
// eslint-disable-next-line no-await-in-loop
await server.sendRequest(CommandTypes.Open, {
file,
projectFileName,
projectRootPath: rootDir,
});
}
log.info(`Initialized tsserver project in ${serverInitTimer.elapsedStr()}.`);
const filesToProcess = fileNames.filter((fileName) => !/(\.d\.ts|\.json)$/.test(fileName));
const sourceFiles: { [fileName: string]: { sourceFile: ts.SourceFile; updated: boolean } } = {};
const scriptTarget = options.target != null ? options.target : ts.ScriptTarget.Latest;
const getOrCreateSourceFile = (fileName: string) => {
if (sourceFiles[fileName] == null) {
sourceFiles[fileName] = {
sourceFile: ts.createSourceFile(
fileName,
ts.sys.readFile(fileName) || '',
scriptTarget,
/* setParentNodes */ true,
),
updated: false,
};
}
return sourceFiles[fileName];
};
const setSourceFile = (fileName: string, sourceFile: ts.SourceFile) => {
const prevText = sourceFiles[fileName] ? sourceFiles[fileName].sourceFile.text : undefined;
const prevUpdated = sourceFiles[fileName] ? sourceFiles[fileName].updated : false;
const updated = prevUpdated || prevText !== sourceFile.text;
sourceFiles[fileName] = { sourceFile, updated };
};
log.info('Start...');
const pluginsTimer = new PerfTimer();
for (let i = 0; i < config.plugins.length; i += 1) {
const { plugin, options: pluginOptions } = config.plugins[i];
const pluginLogPrefix = `[${plugin.name}]`;
const pluginTimer = new PerfTimer();
log.info(`${pluginLogPrefix} Plugin ${i + 1} of ${config.plugins.length}. Start...`);
// eslint-disable-next-line no-restricted-syntax
for (const file of filesToProcess) {
const relFile = path.relative(rootDir, file);
const fileLogPrefix = `${pluginLogPrefix}[${relFile}]`;
// const fileTimer = new PerfTimer();
// log.info(`${fileLogPrefix} Start...`);
const { sourceFile } = getOrCreateSourceFile(file);
const updateFile = async (newText: string) => {
ts.sys.writeFile(file, newText);
await server.sendRequest(CommandTypes.Reload, {
file,
projectFileName,
tmpfile: file,
});
};
const { text } = sourceFile;
const params: PluginParams<unknown> = {
options: pluginOptions,
fileName: sourceFile.fileName,
rootDir,
text,
sourceFile,
async getDiagnostics() {
const semanticDiagnostics = await server.sendRequest(
CommandTypes.SemanticDiagnosticsSync,
{ file, projectFileName, includeLinePosition: true },
);
const syntacticDiagnostics = await server.sendRequest(
CommandTypes.SyntacticDiagnosticsSync,
{ file, projectFileName, includeLinePosition: true },
);
const suggestionDiagnostics = await server.sendRequest(
CommandTypes.SuggestionDiagnosticsSync,
{ file, projectFileName, includeLinePosition: true },
);
return {
semanticDiagnostics: semanticDiagnostics || [],
syntacticDiagnostics: syntacticDiagnostics || [],
suggestionDiagnostics: suggestionDiagnostics || [],
};
},
};
try {
// eslint-disable-next-line no-await-in-loop
const result = await plugin.run(params);
if (typeof result === 'string') {
if (result !== text) {
setSourceFile(
file,
sourceFile.update(result, {
newLength: result.length,
span: { start: 0, length: text.length },
}),
);
// eslint-disable-next-line no-await-in-loop
await updateFile(result);
}
}
} catch (pluginErr) {
log.error(`${fileLogPrefix} Error:\n`, pluginErr);
exitCode = -1;
}
// log.info(`${fileLogPrefix} Finished in ${fileTimer.elapsedStr()}.`);
}
log.info(`${pluginLogPrefix} Finished in ${pluginTimer.elapsedStr()}.`);
}
log.info(`Finished in ${pluginsTimer.elapsedStr()}, for ${config.plugins.length} plugin(s).`);
const writeTimer = new PerfTimer();
const updatedSourceFiles = Object.values(sourceFiles)
.filter(({ updated }) => updated)
.map(({ sourceFile }) => sourceFile);
log.info(`Writing ${updatedSourceFiles.length} updated file(s)...`);
updatedSourceFiles.forEach((sourceFile) => {
ts.sys.writeFile(sourceFile.fileName, sourceFile.text);
});
log.info(`Wrote ${updatedSourceFiles.length} updated file(s) in ${writeTimer.elapsedStr()}.`);
return exitCode;
}
export { MigrateConfig };