forked from acacode/swagger-typescript-api
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathformatFileContent.js
More file actions
74 lines (63 loc) · 1.91 KB
/
Copy pathformatFileContent.js
File metadata and controls
74 lines (63 loc) · 1.91 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
const _ = require("lodash");
const prettier = require("prettier");
const { config } = require("./config");
const ts = require("typescript");
class LanguageServiceHost {
constructor(fileName, content) {
const tsconfig = ts.findConfigFile(fileName, ts.sys.fileExists);
Object.assign(this, {
fileName,
content,
compilerOptions: tsconfig
? ts.convertCompilerOptionsFromJson(
ts.readConfigFile(tsconfig, ts.sys.readFile).config.compilerOptions,
).options
: ts.getDefaultCompilerOptions(),
});
}
getNewLine() {
return "\n";
}
getScriptFileNames() {
return [this.fileName];
}
getCompilationSettings() {
return this.compilerOptions;
}
getDefaultLibFileName() {
return ts.getDefaultLibFileName(this.getCompilationSettings());
}
getCurrentDirectory() {
return process.cwd();
}
getScriptVersion() {
return ts.version;
}
getScriptSnapshot() {
return ts.ScriptSnapshot.fromString(this.content);
}
}
const removeUnusedImports = (content) => {
const tempFileName = "file.ts";
const host = new LanguageServiceHost(tempFileName, content);
const languageService = ts.createLanguageService(host);
const fileTextChanges = languageService.organizeImports(
{ type: "file", fileName: tempFileName },
{ newLineCharacter: ts.sys.newLine },
)[0];
if (fileTextChanges && fileTextChanges.textChanges.length) {
return _.reduceRight(
fileTextChanges.textChanges,
(content, { span, newText }) =>
`${content.slice(0, span.start)}${newText}${content.slice(span.start + span.length)}`,
content,
);
}
return content;
};
const prettierFormat = (content) => {
return prettier.format(content, config.prettierOptions);
};
const formatters = [removeUnusedImports, prettierFormat];
module.exports = (content) =>
formatters.reduce((fixedContent, formatter) => formatter(fixedContent), content);