Skip to content

Commit

Permalink
chore: Add lint rules (#5502)
Browse files Browse the repository at this point in the history
  • Loading branch information
Jason3S authored Apr 19, 2024
1 parent 7966d30 commit 58063a1
Show file tree
Hide file tree
Showing 157 changed files with 898 additions and 760 deletions.
1 change: 1 addition & 0 deletions cspell-dict.txt
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ globby
globstar
gzipped
Harakat
iife
jamstack
lcov
licia
Expand Down
106 changes: 97 additions & 9 deletions eslint.config.mjs
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
// @ts-check

import eslint from '@eslint/js';
import nodePlugin from 'eslint-plugin-n';
import eslintPluginPrettierRecommended from 'eslint-plugin-prettier/recommended';
Expand All @@ -12,6 +10,8 @@ import tsEslint from 'typescript-eslint';
// const __dirname = fileURLToPath(new URL('.', import.meta.url));
// const compat = new FlatCompat({baseDirectory: __dirname, recommendedConfig: eslint.configs.recommended});

// @ts-check

export default tsEslint.config(
eslint.configs.recommended,
nodePlugin.configs['flat/recommended'],
Expand All @@ -26,24 +26,36 @@ export default tsEslint.config(
// Disable these rules
'unicorn/catch-error-name': 'off',
'unicorn/consistent-function-scoping': 'off',
'unicorn/explicit-length-check': 'off',
'unicorn/filename-case': 'off',
'unicorn/import-style': 'off',
'unicorn/no-array-callback-reference': 'off',
'unicorn/prevent-abbreviations': 'off',
'unicorn/no-array-reduce': 'off',
'unicorn/explicit-length-check': 'off',
'unicorn/no-nested-ternary': 'off',
'unicorn/no-await-expression-member': 'off',
'unicorn/no-nested-ternary': 'off',
'unicorn/no-new-array': 'off', // new Array(size) is 10x faster than Array.from({length: size})
'unicorn/no-useless-spread': 'off', // makes dangerous fixes
'unicorn/no-useless-undefined': 'off', // Breaks return types and other things
'unicorn/no-zero-fractions': 'off',
'unicorn/number-literal-case': 'off', // doesn't fix anything, might conflict with other rules.
'unicorn/prefer-event-target': 'off', // It is broken
'unicorn/prefer-logical-operator-over-ternary': 'off', // single line ternary is fine
'unicorn/prefer-math-trunc': 'off', // incorrectly sets Enums.
'unicorn/prefer-native-coercion-functions': 'off', // Makes some strange choices
'unicorn/prefer-string-slice': 'off', // substring is used where it make the most sense.
'unicorn/prefer-top-level-await': 'off', // it will be possible to require a module that does not use top level await.
'unicorn/prevent-abbreviations': 'off',

// Maybe later
'unicorn/better-regex': 'off', // Not sure if it is an improvement.
'unicorn/new-for-builtins': 'off',
'unicorn/no-array-for-each': 'off',
'unicorn/prefer-at': 'off',
'unicorn/no-array-method-this-argument': 'off', // Too many false positives
'unicorn/no-for-loop': 'off',
'unicorn/new-for-builtins': 'off',
'unicorn/better-regex': 'off', // Not sure if it is an improvement.
'unicorn/no-negated-condition': 'off', // Too picky - works against implying the most common branch.
'unicorn/prefer-at': 'off',

// Enable these rules to help with on boarding eslint.
'unicorn/no-instanceof-array': 'error',
'unicorn/numeric-separators-style': [
'error',
{
Expand All @@ -53,11 +65,85 @@ export default tsEslint.config(
},
},
],
'unicorn/empty-brace-spaces': 'error',
'unicorn/error-message': 'error',
'unicorn/escape-case': 'error',
'unicorn/expiring-todo-comments': 'error',
'unicorn/no-abusive-eslint-disable': 'error',
'unicorn/no-anonymous-default-export': 'error',
'unicorn/no-array-push-push': 'error', // This isn't really a problem
'unicorn/no-await-in-promise-methods': 'error',
'unicorn/no-console-spaces': 'error',
'unicorn/no-document-cookie': 'error',
'unicorn/no-empty-file': 'error',
'unicorn/no-hex-escape': 'error',
'unicorn/no-instanceof-array': 'error',
'unicorn/no-invalid-remove-event-listener': 'error',
'unicorn/no-lonely-if': 'error',
'unicorn/no-new-buffer': 'error',
'unicorn/no-null': 'error',
'unicorn/no-object-as-default-parameter': 'error',
'unicorn/no-process-exit': 'error',
'unicorn/no-single-promise-in-promise-methods': 'error',
'unicorn/no-static-only-class': 'error',
'unicorn/no-thenable': 'error',
'unicorn/no-this-assignment': 'error',
'unicorn/no-typeof-undefined': 'error',
'unicorn/no-unnecessary-await': 'error',
'unicorn/no-unnecessary-polyfills': 'error',
'unicorn/no-unreadable-array-destructuring': 'error',
'unicorn/no-unreadable-iife': 'error',
'unicorn/no-useless-fallback-in-spread': 'error',
'unicorn/no-useless-length-check': 'error',
'unicorn/no-useless-promise-resolve-reject': 'error',
'unicorn/no-useless-switch-case': 'error',
'unicorn/prefer-add-event-listener': 'error',
'unicorn/prefer-array-find': 'error',
'unicorn/prefer-array-flat-map': 'error',
'unicorn/prefer-array-flat': 'error',
'unicorn/prefer-array-index-of': 'error',
'unicorn/prefer-array-some': 'error',
'unicorn/prefer-blob-reading-methods': 'error',
'unicorn/prefer-code-point': 'error',
'unicorn/prefer-date-now': 'error',
'unicorn/prefer-default-parameters': 'error',
'unicorn/prefer-dom-node-append': 'error',
'unicorn/prefer-dom-node-dataset': 'error',
'unicorn/prefer-dom-node-remove': 'error',
'unicorn/prefer-dom-node-text-content': 'error',
'unicorn/prefer-export-from': 'error',
'unicorn/prefer-includes': 'error',
'unicorn/prefer-keyboard-event-key': 'error',
'unicorn/prefer-modern-dom-apis': 'error',
'unicorn/prefer-modern-math-apis': 'error',
'unicorn/prefer-module': 'error',
'unicorn/prefer-negative-index': 'error',
'unicorn/prefer-node-protocol': 'error',
'unicorn/prefer-number-properties': 'error',
'unicorn/prefer-object-from-entries': 'error',
'unicorn/prefer-optional-catch-binding': 'error',
'unicorn/prefer-prototype-methods': 'error',
'unicorn/prefer-query-selector': 'error',
'unicorn/prefer-reflect-apply': 'error',
'unicorn/prefer-regexp-test': 'error',
'unicorn/prefer-set-has': 'error',
'unicorn/prefer-set-size': 'error',
'unicorn/prefer-spread': 'error',
'unicorn/prefer-string-replace-all': 'error',
'unicorn/prefer-string-starts-ends-with': 'error',
'unicorn/prefer-string-trim-start-end': 'error',
'unicorn/prefer-switch': 'error',
'unicorn/prefer-ternary': 'error',
'unicorn/prefer-type-error': 'error',
'unicorn/relative-url-style': 'error',
'unicorn/require-array-join-separator': 'error',
'unicorn/require-number-to-fixed-digits-argument': 'error',
'unicorn/switch-case-braces': 'error',
'unicorn/template-indent': 'error',
'unicorn/text-encoding-identifier-case': 'error',
'unicorn/throw-new-error': 'error',

// To be evaluated
},
},
{
Expand Down Expand Up @@ -162,6 +248,8 @@ export default tsEslint.config(
'@typescript-eslint/no-explicit-any': 'off', // any is allowed in tests
'unicorn/no-null': 'off', // null is allowed in tests
'unicorn/prefer-module': 'off', // require.resolve is allowed in tests
'unicorn/error-message': 'off',
'unicorn/no-useless-undefined': 'off', // undefined is allowed in tests
},
},
{
Expand Down
13 changes: 6 additions & 7 deletions integration-tests/src/check.ts
Original file line number Diff line number Diff line change
Expand Up @@ -73,9 +73,9 @@ async function execCheckAndUpdate(rep: Repository, options: CheckAndUpdateOption
try {
const updatedRep = mustBeDefined(await addRepository(logger, rep.url, rep.branch));
rep = resolveRepArgs(updatedRep);
} catch (_) {
} catch {
log(color`******** fail ********`);
return Promise.resolve({ success: false, rep, elapsedTime: 0 });
return { success: false, rep, elapsedTime: 0 };
}
log(color`******** Updating Repo Complete ********`);
if (rep.commit !== oldCommit) {
Expand Down Expand Up @@ -111,12 +111,12 @@ async function execCheck(context: CheckContext, update: boolean): Promise<CheckR
log(time());
if (!(await checkoutRepositoryAsync(logger, rep.url, rep.path, rep.commit, rep.branch))) {
logger.log('******** fail ********');
return Promise.resolve({ success: false, rep, elapsedTime: 0 });
return { success: false, rep, elapsedTime: 0 };
}
log(time());
if (!(await execPostCheckoutSteps(context))) {
logger.log('******** fail ********');
return Promise.resolve({ success: false, rep, elapsedTime: 0 });
return { success: false, rep, elapsedTime: 0 };
}
log(time());
const cspellResult = await execCommand(logger, path, cmdToExec, rep.args);
Expand Down Expand Up @@ -217,7 +217,7 @@ function report(reposChecked: Repository[], results: CheckResult[]) {
const resultsByRep = new Map(results.map((r) => [r.rep, r]));
const w = Math.max(...reposChecked.map((r) => r.path.length));
const r = sorted.map((r) => {
const { success = undefined, elapsedTime = 0 } = resultsByRep.get(r) || {};
const { success, elapsedTime = 0 } = resultsByRep.get(r) || {};
const mark = success === undefined ? '🛑' : success === false ? '❌' : '✅';
const time = chalk.gray(rightJustify(elapsedTime ? `${(elapsedTime / 1000).toFixed(3)}s` : '', 9));
const padding = ' '.repeat(w - r.path.length);
Expand Down Expand Up @@ -363,8 +363,7 @@ function tfn(colorFn: ChalkInstance): (strings: string | TemplateStringsArray, .
const parts: string[] = [];
let i = 0;
for (; i < strings.length - 1; ++i) {
parts.push(strings[i]);
parts.push(rest[i] as string);
parts.push(strings[i], rest[i] as string);
}
if (i < strings.length) {
parts.push(strings[i]);
Expand Down
4 changes: 2 additions & 2 deletions integration-tests/src/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,10 +23,10 @@ const defaultConfig: Config = {

export function readConfig(): Config {
try {
const file = fs.readFileSync(configFile, 'utf-8');
const file = fs.readFileSync(configFile, 'utf8');
const cfg = JSON.parse(file);
return cfg;
} catch (_) {
} catch {
return JSON.parse(JSON.stringify(defaultConfig));
}
}
Expand Down
2 changes: 1 addition & 1 deletion integration-tests/src/reporter/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -164,7 +164,7 @@ function getPerfCsvFileUrl(root: vscodeUri.URI): URL {
*/
async function createCsvFile(csvUrl: URL): Promise<void> {
if (!reformatCsv) return;
const csvFile = await fs.readFile(csvUrl, 'utf-8').catch(() => undefined);
const csvFile = await fs.readFile(csvUrl, 'utf8').catch(() => undefined);
if (!csvFile) {
return fs.writeFile(csvUrl, stringifyCsv([csvHeaders]));
}
Expand Down
6 changes: 3 additions & 3 deletions integration-tests/src/run.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,14 +11,14 @@ import { addRepository, listRepositories } from './repositoryHelper.js';
const defaultParallel = Math.max(os.cpus().length / 2, 1);

function processParallelArg(value: string): number {
const v = parseInt(value, 10);
const v = Number.parseInt(value, 10);
return v < 1 ? defaultParallel : v;
}

function validateParallelArg(value: string) {
// parseInt takes a string and a radix
const parsedValue = parseInt(value, 10);
if (isNaN(parsedValue) || parsedValue < 1) {
const parsedValue = Number.parseInt(value, 10);
if (Number.isNaN(parsedValue) || parsedValue < 1) {
throw new InvalidArgumentError('Must be a number >= 1');
}
return value;
Expand Down
4 changes: 2 additions & 2 deletions integration-tests/src/snapshots.ts
Original file line number Diff line number Diff line change
Expand Up @@ -66,8 +66,8 @@ export function readSnapshot(rep: Repository): string {
const dir = Path.join(snapshotDir, rep.path);
const filename = Path.join(dir, snapshotFileName);
try {
return fs.readFileSync(filename, 'utf-8');
} catch (_) {
return fs.readFileSync(filename, 'utf8');
} catch {
return '';
}
}
Expand Down
3 changes: 2 additions & 1 deletion packages/cspell-bundled-dicts/tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,5 +4,6 @@
"declaration": false,
"declarationMap": false,
"sourceMap": false
}
},
"files": ["cspell-default.config.ts"]
}
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ export class CSpellConfigFileJson extends ImplCSpellConfigFile {
}

serialize() {
return stringify(this.settings, null, this.indent) + '\n';
return stringify(this.settings, undefined, this.indent) + '\n';
}

public static parse(file: TextFile): CSpellConfigFileJson {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,14 +28,14 @@ export function parseCSpellConfigFilePackageJson(file: TextFile): CSpellConfigFi
packageJson['cspell'] = packageJson['cspell'] || {};
const cspell = packageJson['cspell'];
if (typeof cspell !== 'object' || Array.isArray(cspell)) {
throw new Error(`Unable to parse ${url}`);
throw new TypeError(`Unable to parse ${url}`);
}

const indent = detectIndent(content);

function serialize(settings: CSpellSettings) {
packageJson['cspell'] = settings;
return JSON.stringify(packageJson, null, indent) + '\n';
return JSON.stringify(packageJson, undefined, indent) + '\n';
}

return new CSpellConfigFilePackageJson(url, cspell, serialize);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,7 @@ export class CSpellConfigFileReaderWriterImpl implements CSpellConfigFileReaderW
}

setTrustedUrls(urls: readonly (URL | string)[]): this {
this._trustedUrls = [...new Set([...urls.map((url) => new URL(url).href)])].sort();
this._trustedUrls = [...new Set(urls.map((url) => new URL(url).href))].sort();
return this;
}

Expand Down
2 changes: 1 addition & 1 deletion packages/cspell-config-lib/src/defaultIO.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ export const defaultIO: IO = {
};

async function readFile(url: URL): Promise<TextFile> {
const content = await fs.readFile(url, 'utf-8');
const content = await fs.readFile(url, 'utf8');
return { url, content };
}

Expand Down
2 changes: 1 addition & 1 deletion packages/cspell-config-lib/src/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,6 @@ describe('cspell-config', () => {
assert(cfg instanceof CSpellConfigFile);
cfg.addWords(addWords);
await rw.writeConfig(cfg);
expect(await fs.readFile(tempFile, 'utf-8')).toMatchSnapshot();
expect(await fs.readFile(tempFile, 'utf8')).toMatchSnapshot();
});
});
3 changes: 2 additions & 1 deletion packages/cspell-config-lib/src/loaders/loaderJavaScript.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,8 +36,9 @@ export class LoaderJavaScript implements FileLoaderMiddleware {
switch (ext) {
case '.js':
case '.cjs':
case '.mjs':
case '.mjs': {
return importJavaScript(url, this.hashSuffix);
}
}
return next(req);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -125,7 +125,7 @@ describe('Verify using multiple dictionaries', () => {
});

test('checks mapWord is identity', async () => {
const dicts = await Promise.all([createSpellingDictionary(wordsA, 'wordsA', 'test', opts())]);
const dicts = [createSpellingDictionary(wordsA, 'wordsA', 'test', opts())];

const dictCollection = createCollection(dicts, 'test');
expect(dictCollection.mapWord('Hello')).toBe('Hello');
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -236,10 +236,8 @@ function findCache(fn: FindFunction, size = 2000): FindFunction {
ignoreCase: boolean,
): FindAnyFormResult | undefined {
const r = cache.get(word);
if (r !== undefined) {
if (r.useCompounds === useCompounds && r.ignoreCase === ignoreCase) {
return r.findResult;
}
if (r !== undefined && r.useCompounds === useCompounds && r.ignoreCase === ignoreCase) {
return r.findResult;
}
const findResult = fn(word, useCompounds, ignoreCase);
cache.set(word, { useCompounds, ignoreCase, findResult });
Expand Down
19 changes: 8 additions & 11 deletions packages/cspell-dictionary/src/util/braceExpansion.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,8 @@ export interface Options {
sep: string;
}

function expand(
pattern: string,
options: Options = { begin: '(', end: ')', sep: '|' },
start = 0,
): { parts: string[]; idx: number } {
function expand(pattern: string, options?: Options, start = 0): { parts: string[]; idx: number } {
const _options = options ?? { begin: '(', end: ')', sep: '|' };
const len = pattern.length;
const parts: string[] = [];
function push(word: string | string[]) {
Expand All @@ -22,16 +19,16 @@ function expand(
let curWord: string | string[] = '';
while (i < len) {
const ch = pattern[i++];
if (ch === options.end) {
if (ch === _options.end) {
break;
}
if (ch === options.begin) {
const nested = expand(pattern, options, i);
if (ch === _options.begin) {
const nested = expand(pattern, _options, i);
i = nested.idx;
curWord = nested.parts.flatMap((p) => (Array.isArray(curWord) ? curWord.map((w) => w + p) : [curWord + p]));
continue;
}
if (ch === options.sep) {
if (ch === _options.sep) {
push(curWord);
curWord = '';
continue;
Expand All @@ -42,6 +39,6 @@ function expand(
return { parts, idx: i };
}

export function expandBraces(pattern: string, options: Options = { begin: '(', end: ')', sep: '|' }): string[] {
return expand(pattern, options).parts;
export function expandBraces(pattern: string, options?: Options): string[] {
return expand(pattern, options ?? { begin: '(', end: ')', sep: '|' }).parts;
}
Loading

0 comments on commit 58063a1

Please sign in to comment.