-
Notifications
You must be signed in to change notification settings - Fork 14
/
cli.js
217 lines (184 loc) · 5.54 KB
/
cli.js
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
#!/usr/bin/env node
const {
Project,
IndentationText,
NewLineKind,
QuoteKind
} = require("ts-morph"),
tsconfig = require("tsconfig"),
editorconfig = require("editorconfig"),
chalk = require("chalk"),
path = require("path");
if (process.argv.length < 3) {
console.error("No files specified.");
process.exit(1);
} else if (process.argv.includes("--help")) {
printUsage();
} else {
main(
process.argv.slice(2).filter(arg => arg !== "--list-different"),
process.argv.includes("--list-different")
);
}
/** @typedef { import('ts-morph').SourceFile } SourceFile */
/**
* @param {string[]} filePaths
* @param {boolean} listDifferent
*/
function main(filePaths, listDifferent) {
const logger = listDifferent
? {
write() {},
writeLine() {}
}
: {
write: process.stdout.write.bind(process.stdout),
writeLine: console.log.bind(console)
};
logger.writeLine(chalk`{yellowBright Organizing imports...}`);
/**
* @type {Record<string, {
* files: 'all' | SourceFile[]
* project: import('ts-morph').Project,
* detectNewLineKind: boolean,
* }>}
*/
const projects = {};
for (const filePath of filePaths) {
const tsConfigFilePath = tsconfig.findSync(path.dirname(filePath));
const projectEntry = tsConfigFilePath && projects[tsConfigFilePath];
if (projectEntry) {
const sourceFile = projectEntry.project.getSourceFile(filePath);
if (sourceFile) {
if (projectEntry.files !== "all") {
projectEntry.files.push(sourceFile);
}
continue;
}
}
const ec = editorconfig.parseSync(filePath);
const manipulationSettings = getManipulationSettings(ec);
const detectNewLineKind = !!ec.end_of_line;
if (tsConfigFilePath && !projectEntry) {
const project = new Project({ tsConfigFilePath, manipulationSettings });
if (/^tsconfig.*\.json$/gi.test(path.basename(filePath))) {
projects[tsConfigFilePath] = {
files: "all",
project,
detectNewLineKind
};
continue;
}
const sourceFile = project.getSourceFile(filePath);
if (sourceFile) {
projects[tsConfigFilePath] = {
files: [sourceFile],
project,
detectNewLineKind
};
continue;
}
}
const adHocProjectKey =
"\0" + JSON.stringify({ ...manipulationSettings, detectNewLineKind });
if (!projects[adHocProjectKey]) {
projects[adHocProjectKey] = {
files: [],
project: new Project({
manipulationSettings,
compilerOptions: { allowJs: true }
}),
detectNewLineKind
};
}
/** @type {SourceFile[]} */ (projects[adHocProjectKey].files).push(
projects[adHocProjectKey].project.addSourceFileAtPath(filePath)
);
}
for (const { files, project, detectNewLineKind } of Object.values(projects)) {
const sourceFiles = files === "all" ? project.getSourceFiles() : files;
const differentFiles = [];
let crLfWeight = 0;
for (const sourceFile of sourceFiles) {
logger.write(chalk`{gray ${sourceFile.getFilePath()}}`);
const fullText = sourceFile.getFullText();
if (fullText.includes("// organize-imports-ignore")) {
logger.writeLine(" (skipped)");
continue;
}
if (detectNewLineKind) {
crLfWeight += fullText.includes("\r\n") ? 1 : -1;
}
const importsBefore = listDifferent && serializeImports(sourceFile);
sourceFile.organizeImports();
if (
listDifferent
? importsBefore === serializeImports(sourceFile)
: fullText === sourceFile.getFullText()
) {
logger.writeLine("");
} else {
differentFiles.push(sourceFile.getFilePath());
logger.writeLine(`\r${sourceFile.getFilePath()} (modified)`);
}
}
if (differentFiles.length > 0) {
if (listDifferent) {
for (const filePath of differentFiles) {
console.log(filePath);
}
process.exit(2);
} else {
if (crLfWeight !== 0) {
project.manipulationSettings.set({
newLineKind:
crLfWeight > 0
? NewLineKind.CarriageReturnLineFeed
: NewLineKind.LineFeed
});
}
project.saveSync();
}
}
}
logger.writeLine(chalk`{yellowBright Done!}`);
}
/**
* @param {import('editorconfig').KnownProps} ec
*/
function getManipulationSettings(ec) {
return {
indentationText:
ec.indent_style === "tab"
? IndentationText.Tab
: ec.tab_width === 2
? IndentationText.TwoSpaces
: IndentationText.FourSpaces,
newLineKind:
ec.end_of_line === "crlf"
? NewLineKind.CarriageReturnLineFeed
: NewLineKind.LineFeed,
quoteKind: QuoteKind.Single
};
}
function printUsage() {
console.log(chalk`
Usage: organize-imports-cli [--list-different] files...
Files can be specific {yellow ts} and {yellow js} files or {yellow tsconfig.json}, in which case the whole project is processed.
Files containing the substring "{yellow // organize-imports-ignore}" are skipped.
The {yellow --list-different} flag prints a list of files with unorganized imports. No files are modified.
`);
}
/**
* @param {SourceFile} sourceFile
*/
function serializeImports(sourceFile) {
return sourceFile
.getImportDeclarations()
.map(importDeclaration => importDeclaration.getText())
.join("")
.replace(/'/g, '"')
.replace(/\s+/g, "\t")
.replace(/(\w)\t(\w)/g, "$1 $2")
.replace(/\t/g, "");
}