Skip to content

Commit

Permalink
Merge 64b02ad into 5aa84b5
Browse files Browse the repository at this point in the history
  • Loading branch information
Jason3S committed Mar 8, 2022
2 parents 5aa84b5 + 64b02ad commit 858d3de
Show file tree
Hide file tree
Showing 11 changed files with 1,371 additions and 117 deletions.
1 change: 1 addition & 0 deletions .eslintrc.js
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ const config = {
'**/node_modules/**',
'docs/_site/**',
'integration-tests/repositories/**',
'packages/*/fixtures/**',
'test-fixtures/**',
'test-packages/yarn2/**',
],
Expand Down
1 change: 1 addition & 0 deletions cspell.json
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,7 @@
"lcov.info",
"package.json",
"package-lock.json",
"packages/*/fixtures/**",
"packages/*/samples/**",
"packages/Samples/**",
"packages/cspell-lib/fixtures/**",
Expand Down
19 changes: 19 additions & 0 deletions packages/cspell-eslint-plugin/fixtures/with-errors/sampleESM.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import { promises as fs } from 'fs';

export const LITERAL_NUM = 42;
export const LITERAL_STR_SINGLE = 'Guuide to the Gallaxy'
export const LITERAL_STR_DOUBLE = "To Infinity and Beyond";
export const LITERAL_COOKED = 'cafe\u0301';
export const UNDEFINED = undefined;
export const NULL = null;
export const BIG_INT = 1n;

function mapDir(dir) {
return `type: ${dir.isFile ? 'F' : ' '}${dir.isDirectory() ? 'D' :' '} name: ${dir.name}`;
}

export async function listFiles() {
const dirs = await fs.readdir('.', { withFileTypes: true });
const entries = dirs.map(mapDir);
console.log(entries.join('\n'));
}
1,365 changes: 1,270 additions & 95 deletions packages/cspell-eslint-plugin/package-lock.json

Large diffs are not rendered by default.

3 changes: 3 additions & 0 deletions packages/cspell-eslint-plugin/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -67,5 +67,8 @@
"rimraf": "^3.0.2",
"rollup": "^2.70.0",
"rollup-plugin-dts": "^4.2.0"
},
"dependencies": {
"cspell-lib": "^5.18.5"
}
}
31 changes: 20 additions & 11 deletions packages/cspell-eslint-plugin/src/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,18 +3,14 @@ import * as rule from './index';
import * as fs from 'fs';
import * as path from 'path';

let _sampleTs: string | undefined;
const root = path.resolve(__dirname, '..');
const samplesDir = path.join(root, 'samples');
const fixturesDir = path.join(root, 'fixtures');

const parsers: Record<string, string | undefined> = {
'.ts': resolveFromMonoRepo('node_modules/@typescript-eslint/parser'),
};
interface CachedSample {
code: string;
filename: string;
parser?: string;
}

type CachedSample = RuleTester.ValidTestCase;

const sampleFiles = new Map<string, CachedSample>();

Expand Down Expand Up @@ -47,23 +43,24 @@ ruleTester.run('cspell', rule.rules.cspell, {
// 'async function* values(iter) { yield* iter; }',
// 'var foo = true',
// 'const x = `It is now time to add everything up: \\` ${y} + ${x}`',
// readSample('sample.js'),
readSample('sample.js'),
readSample('sample.ts'),
readSample('sampleESM.mjs'),
// readSample('sample.json'),
],
invalid: [],
// cspell:ignore Guuide Gallaxy
invalid: [readInvalid('with-errors/sampleESM.mjs', ['Unknown word: "Guuide"', 'Unknown word: "Gallaxy"'])],
});

function resolveFromMonoRepo(file: string): string {
return path.resolve(root, file);
}

function readSample(_filename: string): CachedSample {
function readFix(_filename: string): CachedSample {
const s = sampleFiles.get(_filename);
if (s) return s;

const filename = path.resolve(samplesDir, _filename);
const filename = path.resolve(fixturesDir, _filename);
const code = fs.readFileSync(filename, 'utf-8');

const sample: CachedSample = {
Expand All @@ -78,3 +75,15 @@ function readSample(_filename: string): CachedSample {

return sample;
}

function readSample(sampleFile: string) {
return readFix(path.join('samples', sampleFile));
}

function readInvalid(filename: string, errors: RuleTester.InvalidTestCase['errors']) {
const sample = readFix(filename);
return {
...sample,
errors,
};
}
68 changes: 57 additions & 11 deletions packages/cspell-eslint-plugin/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import type { Rule } from 'eslint';
// eslint-disable-next-line node/no-missing-import
import type { Comment, Identifier, Literal, Node, TemplateElement } from 'estree';
import { format } from 'util';
import { createTextDocument, DocumentValidator, ValidationIssue } from 'cspell-lib';

interface PluginRules {
['cspell']: Rule.RuleModule;
Expand All @@ -16,10 +17,18 @@ const meta: Rule.RuleMetaData = {
},
};

const isDebugMode = false;

const log: typeof console.log = isDebugMode ? console.log : () => undefined;

function create(context: Rule.RuleContext): Rule.RuleListener {
console.log('Source code: \n ************************ \n\n');
console.log(context.getSourceCode().getText());
console.log(`
const doc = createTextDocument({ uri: context.getFilename(), content: context.getSourceCode().getText() });
const validator = new DocumentValidator(doc, {}, {});
validator.prepareSync();

log('Source code: \n ************************ \n\n');
log(doc.text);
log(`
id: ${context.id}
cwd: ${context.getCwd()}
Expand All @@ -29,23 +38,50 @@ scope: ${context.getScope().type}
`);

function checkLiteral(node: Literal & Rule.NodeParentExtension) {
const val = format('%o', node.value);
console.log(`${inheritance(node)}: ${val}`);
if (typeof node.value === 'string') {
checkNodeText(node, node.value);
}
debugNode(node, node.value);
}

function checkTemplateElement(node: TemplateElement & Rule.NodeParentExtension) {
const val = format('%o', node.value);
console.log(`${inheritance(node)}: ${val}`);
debugNode(node, node.value);
}

function checkIdentifier(node: Identifier & Rule.NodeParentExtension) {
const val = format('%o', node.name);
console.log(`${inheritance(node)}: ${val}`);
debugNode(node, node.name);
}

function checkComment(node: Comment) {
const val = format('%o', node);
console.log(`Comment: ${val}`);
log(`Comment: ${val}`);
}

function checkNodeText(node: Node, text: string) {
if (!node.range || !node.loc) return;

const scope = inheritance(node);
const result = validator.checkText(node.range, text, scope);
if (result.length) {
console.error('%o', result);
}
result.forEach((issue) => reportIssue(node, issue));
}

function reportIssue(node: Node, issue: ValidationIssue) {
// const messageId = issue.isFlagged ? 'cspell-forbidden-word' : 'cspell-unknown-word';
const messageType = issue.isFlagged ? 'Forbidden' : 'Unknown';
const message = `${messageType} word: "${issue.text}"`;
const code = context.getSourceCode();
const start = code.getLocFromIndex(issue.offset);
const end = code.getLocFromIndex(issue.offset + (issue.length || issue.text.length));
const loc = { start, end };

const des: Rule.ReportDescriptor = {
message,
loc,
};
context.report(des);
}

context
Expand Down Expand Up @@ -99,7 +135,17 @@ scope: ${context.getScope().type}

function inheritance(node: Node) {
const a = [...context.getAncestors(), node];
return a.map(mapNode).join(' ');
return a.map(mapNode);
}

function inheritanceSummary(node: Node) {
return inheritance(node).join(' ');
}

function debugNode(node: Node, value: unknown) {
if (!isDebugMode) return;
const val = format('%o', value);
log(`${inheritanceSummary(node)}: ${val}`);
}
}

Expand Down

0 comments on commit 858d3de

Please sign in to comment.