aboutsummaryrefslogtreecommitdiff
path: root/packages/iku/src/checker.ts
blob: 655204e90362d546c678b3e8b6eb6c8ebc011785 (plain) (blame)
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
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
import { readdirSync, statSync } from "node:fs";
import { extname, join } from "node:path";
import * as typescript from "typescript";

export interface CheckerOptions {
	noComments?: boolean;
}

const defaultOptions: CheckerOptions = {
	noComments: true,
};

type StatementCategory =
	| "import"
	| "variableDeclaration"
	| "typeAlias"
	| "if"
	| "for"
	| "while"
	| "return"
	| "throw"
	| "expression"
	| "other";

interface StatementInfo {
	category: StatementCategory;
	startLine: number;
	endLine: number;
	hasBlock: boolean;
}

function getStatementCategory(node: typescript.Statement): StatementCategory {
	if (typescript.isImportDeclaration(node)) {
		return "import";
	}

	if (typescript.isVariableStatement(node)) {
		return "variableDeclaration";
	}

	if (typescript.isTypeAliasDeclaration(node)) {
		return "typeAlias";
	}

	if (typescript.isIfStatement(node)) {
		return "if";
	}

	if (
		typescript.isForStatement(node) ||
		typescript.isForInStatement(node) ||
		typescript.isForOfStatement(node)
	) {
		return "for";
	}

	if (typescript.isWhileStatement(node) || typescript.isDoStatement(node)) {
		return "while";
	}

	if (typescript.isReturnStatement(node)) {
		return "return";
	}

	if (typescript.isThrowStatement(node)) {
		return "throw";
	}

	if (typescript.isExpressionStatement(node)) {
		return "expression";
	}

	return "other";
}

function statementHasBlock(node: typescript.Statement): boolean {
	if (typescript.isIfStatement(node)) {
		return typescript.isBlock(node.thenStatement);
	}

	if (
		typescript.isForStatement(node) ||
		typescript.isForInStatement(node) ||
		typescript.isForOfStatement(node)
	) {
		return typescript.isBlock(node.statement);
	}

	if (typescript.isWhileStatement(node)) {
		return typescript.isBlock(node.statement);
	}

	if (typescript.isDoStatement(node)) {
		return typescript.isBlock(node.statement);
	}

	if (typescript.isTypeAliasDeclaration(node)) {
		return typescript.isTypeLiteralNode(node.type);
	}

	return false;
}

function getStatementsFromBlock(
	block: typescript.Block | typescript.SourceFile,
	sourceFile: typescript.SourceFile,
): StatementInfo[] {
	const statements: StatementInfo[] = [];

	for (const statement of block.statements) {
		const category = getStatementCategory(statement);
		const startPosition = statement.getStart(sourceFile);
		const endPosition = statement.getEnd();
		const startLine =
			sourceFile.getLineAndCharacterOfPosition(startPosition).line + 1;
		const endLine =
			sourceFile.getLineAndCharacterOfPosition(endPosition).line + 1;
		const hasBlock = statementHasBlock(statement);

		statements.push({ category, startLine, endLine, hasBlock });
	}

	return statements;
}

function countBlankLinesBetween(
	previousEndLine: number,
	currentStartLine: number,
	sourceFile: typescript.SourceFile,
): number {
	const text = sourceFile.getFullText();
	const lines = text.split("\n");
	let blankCount = 0;

	for (
		let lineIndex = previousEndLine;
		lineIndex < currentStartLine - 1;
		lineIndex++
	) {
		const line = lines[lineIndex];

		if (line !== undefined && line.trim() === "") {
			blankCount++;
		}
	}

	return blankCount;
}

function hasCommentBetween(
	previousEndLine: number,
	currentStartLine: number,
	sourceFile: typescript.SourceFile,
): boolean {
	const text = sourceFile.getFullText();
	const lines = text.split("\n");

	for (
		let lineIndex = previousEndLine;
		lineIndex < currentStartLine - 1;
		lineIndex++
	) {
		const line = lines[lineIndex];

		if (line !== undefined) {
			const trimmed = line.trim();

			if (
				trimmed.startsWith("//") ||
				trimmed.startsWith("/*") ||
				trimmed.startsWith("*") ||
				trimmed.endsWith("*/")
			) {
				return true;
			}
		}
	}

	return false;
}

function checkStatementSpacing(
	statements: StatementInfo[],
	sourceFile: typescript.SourceFile,
	filePath: string,
	allowComments: boolean,
): string[] {
	const errors: string[] = [];

	for (let index = 1; index < statements.length; index++) {
		const previous = statements[index - 1];
		const current = statements[index];

		if (previous === undefined || current === undefined) {
			continue;
		}

		if (previous.category === "other" || current.category === "other") {
			continue;
		}

		const blankLines = countBlankLinesBetween(
			previous.endLine,
			current.startLine,
			sourceFile,
		);
		const sameCategory = previous.category === current.category;
		const hasComment = hasCommentBetween(
			previous.endLine,
			current.startLine,
			sourceFile,
		);

		if (previous.category === "import" && current.category === "import") {
			if (blankLines > 0 && !(allowComments && hasComment)) {
				errors.push(
					`${filePath}:${current.startLine}: Blank line between imports`,
				);
			}

			continue;
		}

		const eitherHasBlock = previous.hasBlock || current.hasBlock;

		if (eitherHasBlock && blankLines === 0) {
			errors.push(
				`${filePath}:${current.startLine}: Missing blank line around scoped block`,
			);

			continue;
		}

		if (
			sameCategory &&
			!eitherHasBlock &&
			blankLines > 0 &&
			!(allowComments && hasComment)
		) {
			errors.push(
				`${filePath}:${current.startLine}: Unnecessary blank line between same statement types (${current.category})`,
			);
		}

		if (!sameCategory && !eitherHasBlock && blankLines === 0 && !hasComment) {
			errors.push(
				`${filePath}:${current.startLine}: Missing blank line between different statement types (${previous.category} -> ${current.category})`,
			);
		}
	}

	return errors;
}

function visitBlocks(
	node: typescript.Node,
	sourceFile: typescript.SourceFile,
	filePath: string,
	errors: string[],
	allowComments: boolean,
): void {
	if (typescript.isBlock(node)) {
		const statements = getStatementsFromBlock(node, sourceFile);
		const blockErrors = checkStatementSpacing(
			statements,
			sourceFile,
			filePath,
			allowComments,
		);

		errors.push(...blockErrors);
	}

	typescript.forEachChild(node, (childNode) => {
		visitBlocks(childNode, sourceFile, filePath, errors, allowComments);
	});
}

function checkForComments(
	sourceFile: typescript.SourceFile,
	filePath: string,
): string[] {
	const errors: string[] = [];
	const text = sourceFile.getFullText();

	function visit(node: typescript.Node): void {
		const leadingComments = typescript.getLeadingCommentRanges(
			text,
			node.getFullStart(),
		);
		const trailingComments = typescript.getTrailingCommentRanges(
			text,
			node.getEnd(),
		);

		if (leadingComments) {
			for (const comment of leadingComments) {
				const line =
					sourceFile.getLineAndCharacterOfPosition(comment.pos).line + 1;

				errors.push(`${filePath}:${line}: Comment detected`);
			}
		}

		if (trailingComments) {
			for (const comment of trailingComments) {
				const line =
					sourceFile.getLineAndCharacterOfPosition(comment.pos).line + 1;

				errors.push(`${filePath}:${line}: Comment detected`);
			}
		}

		typescript.forEachChild(node, visit);
	}

	visit(sourceFile);

	const uniqueErrors = [...new Set(errors)];

	return uniqueErrors;
}

export function checkFile(
	filePath: string,
	options: CheckerOptions = defaultOptions,
): string[] {
	const program = typescript.createProgram([filePath], {
		target: typescript.ScriptTarget.ESNext,
		module: typescript.ModuleKind.ESNext,
		jsx: typescript.JsxEmit.ReactJSX,
		allowJs: true,
		noEmit: true,
		skipLibCheck: true,
	});
	const sourceFile = program.getSourceFile(filePath);

	if (!sourceFile) {
		return [];
	}

	const allowComments = !options.noComments;
	const errors: string[] = [];
	const topLevelStatements = getStatementsFromBlock(sourceFile, sourceFile);
	const topLevelErrors = checkStatementSpacing(
		topLevelStatements,
		sourceFile,
		filePath,
		allowComments,
	);

	errors.push(...topLevelErrors);
	visitBlocks(sourceFile, sourceFile, filePath, errors, allowComments);

	if (options.noComments) {
		const commentErrors = checkForComments(sourceFile, filePath);

		errors.push(...commentErrors);
	}

	return errors;
}

export function walkDirectory(directory: string): string[] {
	const files: string[] = [];

	for (const entry of readdirSync(directory)) {
		const fullPath = join(directory, entry);
		const stat = statSync(fullPath);

		if (stat.isDirectory()) {
			if (
				!entry.includes("node_modules") &&
				!entry.includes("dist") &&
				!entry.includes(".next")
			) {
				files.push(...walkDirectory(fullPath));
			}
		} else if (
			[".ts", ".tsx"].includes(extname(entry)) &&
			!entry.endsWith(".d.ts")
		) {
			files.push(fullPath);
		}
	}

	return files;
}

export function checkDirectory(
	directory: string,
	options: CheckerOptions = defaultOptions,
): { errors: string[]; hasErrors: boolean } {
	const files = walkDirectory(directory);
	const allErrors: string[] = [];

	for (const file of files) {
		const errors = checkFile(file, options);

		allErrors.push(...errors);
	}

	return { errors: allErrors, hasErrors: allErrors.length > 0 };
}