Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor: Refactor cspell-config-lib #4978

Merged
merged 9 commits into from
Nov 16, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 3 additions & 11 deletions .eslintrc.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ const config = {
ignorePatterns: [
'**/[Ss]amples/**', // cspell:disable-line
'**/[Tt]emp/**',
'**/.temp/**',
'**/*.d.ts',
'**/*.d.cts',
'**/*.d.mts',
Expand Down Expand Up @@ -74,17 +75,6 @@ const config = {
'simple-import-sort/exports': 'error',
},
},
{
files: ['**/*.test.ts', '**/*.spec.ts'],
excludedFiles: ['**/cspell-gitignore/**'],
extends: 'plugin:jest/recommended',
env: {
jest: true,
},
rules: {
'jest/valid-title': 'warn',
},
},
{
files: ['packages/cspell-pipe/**/*.ts'],
extends: ['plugin:unicorn/recommended'],
Expand Down Expand Up @@ -113,6 +103,8 @@ const config = {
'**/test.*',
'**/rollup.*',
'**/*.spec.*',
'**/test-helpers/**',
'**/test-utils/**',
'**/src/test/**',
'**/src/perf/**',
],
Expand Down
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ out
# And temp files

temp
.temp
tmp
*.log

Expand Down
1 change: 0 additions & 1 deletion packages/cspell-config-lib/jest.config.js

This file was deleted.

17 changes: 8 additions & 9 deletions packages/cspell-config-lib/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,10 @@
"author": "Jason Dent <jason@streetsidesoftware.nl>",
"homepage": "https://github.com/streetsidesoftware/cspell/tree/main/packages/cspell-config#readme",
"license": "MIT",
"main": "dist/index.js",
"type": "module",
"exports": {
".": "./dist/index.js"
},
"directories": {
"dist": "dist"
},
Expand All @@ -27,9 +30,9 @@
"watch": "tsc -p . -w",
"clean": "shx rm -rf dist temp coverage \"*.tsbuildInfo\"",
"clean-build": "pnpm run clean && pnpm run build",
"coverage": "jest --coverage",
"test-watch": "jest --watch",
"test": "jest"
"coverage": "vitest run --coverage",
"test-watch": "vitest",
"test": "vitest run"
},
"repository": {
"type": "git",
Expand All @@ -44,11 +47,7 @@
"dependencies": {
"@cspell/cspell-types": "workspace:*",
"comment-json": "^4.2.3",
"vscode-uri": "^3.0.8",
"yaml": "^1.10.2"
},
"devDependencies": {
"@types/jest": "^29.5.8",
"jest": "^29.7.0"
}
"devDependencies": {}
}
3 changes: 2 additions & 1 deletion packages/cspell-config-lib/src/CSpellConfigFile.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { parse, stringify } from 'comment-json';
import { describe, expect, test } from 'vitest';

import { __testing__ } from './CSpellConfigFile';
import { __testing__ } from './CSpellConfigFile.js';

const { addUniqueWordsToListAndSort } = __testing__;

Expand Down
30 changes: 18 additions & 12 deletions packages/cspell-config-lib/src/CSpellConfigFile.ts
Original file line number Diff line number Diff line change
@@ -1,23 +1,28 @@
import type { CSpellSettings } from '@cspell/cspell-types';

import type { Serializer } from './Serializer';
export interface CSpellConfigFileReference {
readonly url: URL;
}

export interface CSpellConfigFile {
readonly uri: string;
export interface ICSpellConfigFile {
readonly url: URL;
readonly settings: CSpellSettings;
serialize(): string;
addWords(words: string[]): this;
readonly readonly?: boolean;
}

export class ImplCSpellConfigFile implements CSpellConfigFile {
export abstract class CSpellConfigFile implements ICSpellConfigFile {
constructor(readonly url: URL) {}

abstract readonly settings: CSpellSettings;
abstract addWords(words: string[]): this;
}

export abstract class ImplCSpellConfigFile extends CSpellConfigFile {
constructor(
readonly uri: string,
readonly url: URL,
readonly settings: CSpellSettings,
readonly serializer: Serializer,
) {}

serialize(): string {
return this.serializer(this.settings);
) {
super(url);
}

addWords(words: string[]): this {
Expand All @@ -30,6 +35,7 @@ export class ImplCSpellConfigFile implements CSpellConfigFile {

/**
* Adds words to a list, sorts the list and makes sure it is unique.
* Note: this method is used to try and preserve comments in the config file.
* @param list - list to be modified
* @param toAdd - words to add
*/
Expand Down
40 changes: 40 additions & 0 deletions packages/cspell-config-lib/src/CSpellConfigFileJson.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
import type { CSpellSettings } from '@cspell/cspell-types';
import { parse, stringify } from 'comment-json';

import { ImplCSpellConfigFile } from './CSpellConfigFile.js';
import type { SerializeSettingsFn } from './Serializer.js';
import { detectIndent } from './serializers/util.js';
import type { TextFile } from './TextFile.js';

export class CSpellConfigFileJson extends ImplCSpellConfigFile {
constructor(
readonly url: URL,
readonly settings: CSpellSettings,
readonly serializer: SerializeSettingsFn,
) {
super(url, settings);
}

serialize() {
return this.serializer(this.settings);
}
}

export function parseCSpellConfigFileJson(file: TextFile): CSpellConfigFileJson {
const cspell: CSpellSettings | unknown = parse(file.content);
if (!isCSpellSettings(cspell)) {
throw new Error(`Unable to parse ${file.url}`);
}

const indent = detectIndent(file.content);

function serialize(settings: CSpellSettings) {
return stringify(settings, null, indent) + '\n';
}

return new CSpellConfigFileJson(file.url, cspell, serialize);
}

function isCSpellSettings(cfg: unknown): cfg is CSpellSettings {
return !(!cfg || typeof cfg !== 'object' || Array.isArray(cfg));
}
42 changes: 42 additions & 0 deletions packages/cspell-config-lib/src/CSpellConfigFilePackageJson.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import type { CSpellSettings } from '@cspell/cspell-types';

import { ImplCSpellConfigFile } from './CSpellConfigFile.js';
import type { SerializeSettingsFn } from './Serializer.js';
import { detectIndent } from './serializers/util.js';
import type { TextFile } from './TextFile.js';

export class CSpellConfigFilePackageJson extends ImplCSpellConfigFile {
constructor(
readonly url: URL,
readonly settings: CSpellSettings,
readonly serializer: SerializeSettingsFn,
) {
super(url, settings);
}

serialize() {
return this.serializer(this.settings);
}
}

export function parseCSpellConfigFilePackageJson(file: TextFile): CSpellConfigFilePackageJson {
const { url, content } = file;
const packageJson = JSON.parse(content);
if (!packageJson || typeof packageJson !== 'object' || Array.isArray(packageJson)) {
throw new Error(`Unable to parse ${url}`);
}
packageJson['cspell'] = packageJson['cspell'] || {};
const cspell = packageJson['cspell'];
if (typeof cspell !== 'object' || Array.isArray(cspell)) {
throw new Error(`Unable to parse ${url}`);
}

const indent = detectIndent(content);

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

return new CSpellConfigFilePackageJson(url, cspell, serialize);
}
72 changes: 47 additions & 25 deletions packages/cspell-config-lib/src/CSpellConfigFileReaderWriter.test.ts
Original file line number Diff line number Diff line change
@@ -1,54 +1,76 @@
import type { CSpellConfigFile } from './CSpellConfigFile';
import { CSpellConfigFileReaderWriterImpl } from './CSpellConfigFileReaderWriter';
import { defaultDeserializers } from './deserializers';
import type { IO } from './IO';
import { json } from './test-helpers/util';
import type { CSpellSettings } from '@cspell/cspell-types';
import { describe, expect, test, vi } from 'vitest';

import { CSpellConfigFile } from './CSpellConfigFile.js';
import { CSpellConfigFileReaderWriterImpl } from './CSpellConfigFileReaderWriter.js';
import type { IO } from './IO.js';
import { defaultDeserializers } from './serializers/index.js';
import { json } from './test-helpers/util.js';

const oc = expect.objectContaining;

describe('CSpellConfigFileReaderWriter', () => {
test.each`
uri | content | expected
${'file://package.json'} | ${json({ name: 'name' })} | ${oc({ uri: 'file://package.json', settings: {} })}
uri | content | expected
${'file:///package.json'} | ${json({ name: 'name' })} | ${oc({ url: new URL('file:///package.json'), settings: {} })}
`('readConfig', async ({ uri, content, expected }) => {
const io: IO = {
readFile: jest.fn(() => content),
writeFile: jest.fn(),
readFile: vi.fn((url) => Promise.resolve({ url, content })),
writeFile: vi.fn(),
};
const rw = new CSpellConfigFileReaderWriterImpl(io, defaultDeserializers);
expect(await rw.readConfig(uri)).toEqual(expected);
});

test.each`
uri | content | expected
${'file://cspell.js'} | ${''} | ${new Error('Unable to parse config file: "file://cspell.js"')}
uri | content | expected
${'file:///cspell.js'} | ${''} | ${new Error('Unable to parse config file: "file:///cspell.js"')}
`('fail readConfig', async ({ uri, content, expected }) => {
const io: IO = {
readFile: jest.fn(() => content),
writeFile: jest.fn(),
readFile: vi.fn((url) => Promise.resolve({ url, content })),
writeFile: vi.fn(),
};
const rw = new CSpellConfigFileReaderWriterImpl(io, defaultDeserializers);
await expect(rw.readConfig(uri)).rejects.toEqual(expected);
});

test.each`
uri | content
${'file://cspell.js'} | ${'content'}
uri | content
${'file:///cspell.json'} | ${'{}\n'}
`('writeConfig', async ({ uri, content }) => {
const io: IO = {
readFile: jest.fn(() => content),
writeFile: jest.fn(() => Promise.resolve()),
readFile: vi.fn((url) => Promise.resolve({ url, content })),
writeFile: vi.fn((ref) => Promise.resolve(ref)),
};

const rw = new CSpellConfigFileReaderWriterImpl(io, defaultDeserializers);
const cf: CSpellConfigFile = {
uri,
settings: {},
serialize: jest.fn(() => content),
addWords: jest.fn(),
const cf = await rw.readConfig(uri);
const url = new URL(uri);
await expect(rw.writeConfig(cf)).resolves.toEqual({ url });
expect(io.writeFile).toHaveBeenCalledWith({ url, content });
});

test('Fail to serialize', async () => {
const io: IO = {
readFile: vi.fn((url) => Promise.resolve({ url, content: '' })),
writeFile: vi.fn((ref) => Promise.resolve(ref)),
};
await expect(rw.writeConfig(cf)).resolves.toBeUndefined();
expect(io.writeFile).toHaveBeenCalledWith(uri, content);
expect(cf.serialize).toHaveBeenCalledTimes(1);

const rw = new CSpellConfigFileReaderWriterImpl(io, defaultDeserializers);
const cf = new Cfg(new URL('file:///cspell.js'), {});
await expect(rw.writeConfig(cf)).rejects.toThrowError('Unable to serialize config file: "file:///cspell.js"');
});
});

class Cfg extends CSpellConfigFile {
constructor(
public readonly url: URL,
public readonly settings: CSpellSettings = {},
) {
super(url);
}

addWords(_words: string[]): this {
return this;
}
}
Loading