Skip to content
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
13 changes: 13 additions & 0 deletions packages/cspell-lib/api/api.d.ts

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions packages/cspell-lib/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -102,6 +102,7 @@ export {
readSettingsFiles,
refreshDictionaryCache,
resolveConfigFileImports,
resolveConfigFiles,
resolveFile,
searchForConfig,
sectionCSpell,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -861,6 +861,66 @@ describe('ConfigLoader with VirtualFS', () => {
});
});

describe('mergeConfigFilesWithImports', () => {
test('merges in the order given', async () => {
const loader = createConfigLoader();
const base = loader.createCSpellConfigFile(new URL('base/cspell.json', import.meta.url), {
language: 'en',
words: ['base'],
});
const ci = loader.createCSpellConfigFile(new URL('ci/cspell.json', import.meta.url), {
language: 'en-GB',
words: ['ci'],
});

const settings = await loader.mergeConfigFilesWithImports([base, ci]);
const reversed = await loader.mergeConfigFilesWithImports([ci, base]);

expect(settings).toEqual(expect.objectContaining({ language: 'en-GB', words: ['base', 'ci'] }));
expect(reversed).toEqual(expect.objectContaining({ language: 'en', words: ['ci', 'base'] }));
});

test('resolves the imports of each file', async () => {
const loader = createConfigLoader();
const configFile = loader.createCSpellConfigFile(new URL('cspell.json', import.meta.url), {
import: [srcSampleSettingsFilename],
});
const other = loader.createCSpellConfigFile(new URL('other/cspell.json', import.meta.url), {
words: ['other'],
});

const settings = await loader.mergeConfigFilesWithImports([configFile, other]);
const imported = await loader.mergeConfigFileWithImports(configFile);

expect(settings.words).toEqual([...(imported.words ?? []), 'other']);
expect(getSources(settings)).toEqual(expect.arrayContaining(getSources(imported)));
});

test('keeps the error of an import that fails', async () => {
const loader = createConfigLoader();
const configFile = loader.createCSpellConfigFile(new URL('cspell.json', import.meta.url), {
import: ['./missing/cspell.json'],
});
const other = loader.createCSpellConfigFile(new URL('other/cspell.json', import.meta.url), {
words: ['other'],
});

const settings = await loader.mergeConfigFilesWithImports([configFile, other]);

expect(extractImportErrors(settings)).toEqual([
expect.objectContaining({ filename: expect.stringContaining('missing'), error: expect.any(Error) }),
]);
});

test('an empty list gives empty settings', async () => {
const loader = createConfigLoader();

const settings = await loader.mergeConfigFilesWithImports([]);

expect(Object.keys(settings)).toEqual([]);
});
});

function u(url: string | URL, ref?: string | URL): URL {
return new URL(url, ref);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -158,6 +158,13 @@ export interface IConfigLoader {
pnpSettings?: PnPSettingsOptional | undefined,
): Promise<CSpellSettingsI>;

/**
* Resolve the imports of each configuration file and merge the results in the order given.
* Later files override earlier ones.
* @param cfgFiles - configuration files to merge.
*/
mergeConfigFilesWithImports(cfgFiles: readonly (CSpellConfigFile | ICSpellConfigFile)[]): Promise<CSpellSettingsI>;

/**
* Create an in memory CSpellConfigFile.
* @param filename - URL to the file. Used to resolve imports.
Expand Down Expand Up @@ -499,6 +506,16 @@ export class ConfigLoader implements IConfigLoader {
return result;
}

public async mergeConfigFilesWithImports(
cfgFiles: readonly (CSpellConfigFile | ICSpellConfigFile)[],
): Promise<CSpellSettingsI> {
const settings = await Promise.all(
cfgFiles.map((cfgFile) => this.mergeConfigFileWithImports(cfgFile, undefined)),
);
if (!settings.length) return csi({});
return settings.reduce((merged, next) => mergeSettings(merged, next));
}

private async _mergeConfigFileWithImports(
cfgFile: CSpellConfigFile,
pnpSettings: PnPSettingsOptional | undefined,
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { describe, expect, test } from 'vitest';

import { getDefaultConfigLoader, resolveConfigFileImports } from './defaultConfigLoader.js';
import { getDefaultConfigLoader, resolveConfigFileImports, resolveConfigFiles } from './defaultConfigLoader.js';

describe('defaultConfigLoader', () => {
test('getDefaultConfigLoader', () => {
Expand All @@ -16,4 +16,10 @@ describe('defaultConfigLoader', () => {
};
expect(await resolveConfigFileImports(configFile)).toEqual(expect.objectContaining({ words: ['one'] }));
});

test('resolveConfigFiles', async () => {
const one = { url: new URL('one/cspell.json', import.meta.url), settings: { words: ['one'] } };
const two = { url: new URL('two/cspell.json', import.meta.url), settings: { words: ['two'] } };
expect(await resolveConfigFiles([one, two])).toEqual(expect.objectContaining({ words: ['one', 'two'] }));
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,18 @@ export async function resolveConfigFileImports(
return gcl().mergeConfigFileWithImports(configFile, configFile.settings);
}

/**
* Resolve the imports of each configuration file and merge the results in the order given.
* Later files override earlier ones.
* @param configFiles - configuration files to merge.
* @returns the merged settings.
*/
export async function resolveConfigFiles(
configFiles: readonly (CSpellConfigFile | ICSpellConfigFile)[],
): Promise<CSpellSettingsI> {
return gcl().mergeConfigFilesWithImports(configFiles);
}

/**
* Might throw if the settings have not yet been loaded.
* @deprecated use {@link getGlobalSettingsAsync} instead.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ export {
readConfigFile,
readRawSettings,
resolveConfigFileImports,
resolveConfigFiles,
resolveSettingsImports,
searchForConfig,
searchForConfigWithResolvedStops,
Expand Down
1 change: 1 addition & 0 deletions packages/cspell-lib/src/lib/Settings/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ export {
readSettings,
readSettingsFiles,
resolveConfigFileImports,
resolveConfigFiles,
resolveSettingsImports,
searchForConfig,
searchForConfigWithResolvedStops,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -279,6 +279,7 @@ exports[`Validate the cspell API > Verify API exports 1`] = `
"readSettingsFiles": [Function],
"refreshDictionaryCache": [Function],
"resolveConfigFileImports": [Function],
"resolveConfigFiles": [Function],
"resolveFile": [Function],
"searchForConfig": [Function],
"sectionCSpell": "cSpell",
Expand Down
1 change: 1 addition & 0 deletions packages/cspell-lib/src/lib/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,7 @@ export {
readSettings,
readSettingsFiles,
resolveConfigFileImports,
resolveConfigFiles,
searchForConfig,
sectionCSpell,
toCSpellSettingsWithOutSourceTrace,
Expand Down
97 changes: 96 additions & 1 deletion packages/cspell/src/__snapshots__/app.test.ts.snap
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,101 @@ error"

exports[`Validate cli > app '--config in a subfolder' Expect Error: [Function CheckFailed] 3`] = `""`;

exports[`Validate cli > app '--config once --verbose --verbose' Expect Error: [Function CheckFailed] 1`] = `[]`;

exports[`Validate cli > app '--config once --verbose --verbose' Expect Error: [Function CheckFailed] 2`] = `
"info
info cspell;
info Date: Sat, 03 Apr 2021 11:25:33 GMT
info Options:
info verbose: Yes
info config: ./samples/config-search/multiple-configs/cspell.base.json
info exclude: node_modules/**
info files: **/*.md
info wordsOnly: No
info unique: No
info
info Config Files Found:
info samples/config-search/multiple-configs/cspell.base.json
info
info Exclusion Globs:
info Glob: /**/.git/!(*MSG|EDIT_DESCRIPTION|worktrees) from ignorePathPresets.git
info Glob: /**/.git/worktrees/*/!(*MSG|EDIT_DESCRIPTION) from ignorePathPresets.git
info Glob: node_modules/** from command line
info
info
info File type: markdown, Language: en, Issues: 6 0.00ms
info Config file Used: packages/close/cspell.json
info Dictionaries Used:
info aws, coding-compound-terms, companies, computing-acronyms,
info cryptocurrencies, en-common-misspellings, en_us, filetypes, html,
info html-symbol-entities, npm, public-licenses, software-term-suggestions,
info software-tools, softwareTerms, web-services
error 1/3 packages/close/text.md 0.00ms X
error
log packages/close/text.md:1:1 - Unknown word (colour)
log
log packages/close/text.md:1:8 - Unknown word (rootword)
log
log packages/close/text.md:1:17 - Forbidden word (baseword)
log
log packages/close/text.md:1:26 - Unknown word (ciword)
log
log packages/close/text.md:1:33 - Forbidden word (closeword)
log
log packages/close/text.md:1:43 - Unknown word (fooword)
log
info
info File type: markdown, Language: en-GB, Issues: 5 0.00ms
info Config file Used: packages/foo/cspell.json
info Dictionaries Used:
info aws, coding-compound-terms, companies, computing-acronyms,
info cryptocurrencies, en-common-misspellings, en-gb,
info en-gb-common-misspellings, filetypes, html, html-symbol-entities, npm,
info public-licenses, software-term-suggestions, software-tools,
info softwareTerms, web-services
error 2/3 packages/foo/text.md 0.00ms X
error
log packages/foo/text.md:1:8 - Unknown word (rootword)
log
log packages/foo/text.md:1:17 - Forbidden word (baseword)
log
log packages/foo/text.md:1:26 - Unknown word (ciword)
log
log packages/foo/text.md:1:33 - Unknown word (closeword)
log
log packages/foo/text.md:1:43 - Forbidden word (fooword)
log
info
info File type: markdown, Language: en, Issues: 6 0.00ms
info Config file Used: cspell.base.json
info Dictionaries Used:
info aws, coding-compound-terms, companies, computing-acronyms,
info cryptocurrencies, en-common-misspellings, en_us, filetypes, html,
info html-symbol-entities, npm, public-licenses, software-term-suggestions,
info software-tools, softwareTerms, web-services
error 3/3 src/text.md 0.00ms X
error
log src/text.md:1:1 - Unknown word (colour)
log
log src/text.md:1:8 - Unknown word (rootword)
log
log src/text.md:1:17 - Forbidden word (baseword)
log
log src/text.md:1:26 - Unknown word (ciword)
log
log src/text.md:1:33 - Unknown word (closeword)
log
log src/text.md:1:43 - Unknown word (fooword)
log
error CSpell: Files checked: 3, Issues found: 17 in 3 files.
error
error Elapsed Time: 0.00ms
error"
`;

exports[`Validate cli > app '--config once --verbose --verbose' Expect Error: [Function CheckFailed] 3`] = `""`;

exports[`Validate cli > app '--config twice --verbose --verbose' Expect Error: [Function CheckFailed] 1`] = `[]`;

exports[`Validate cli > app '--config twice --verbose --verbose' Expect Error: [Function CheckFailed] 2`] = `
Expand Down Expand Up @@ -341,7 +436,7 @@ exports[`Validate cli > app '--config twice, one missing' Expect Error: [Functio

exports[`Validate cli > app '--config twice, one missing' Expect Error: [Function CheckFailed] 2`] = `
"error Configuration Error: Failed to read config file: "./samples/config-search/multiple-configs/missing.json"
error Failed to resolve configuration file: "./samples/config-search/multiple-configs/missing.json" referenced from "./"
error Failed to resolve configuration file: "samples/config-search/multiple-configs/missing.json" referenced from "./"
error
error -------------------------------------------
error
Expand Down
1 change: 1 addition & 0 deletions packages/cspell/src/app.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -314,6 +314,7 @@ describe('Validate cli', () => {
${'--config twice with a stop at the root'} | ${[...multiArgs('cspell.base.json', 'ci/cspell.ci.json'), '--stop-config-search-at', multiRoot]} | ${app.CheckFailed} | ${true} | ${true} | ${false}
${'--config twice, one missing'} | ${multiArgs('cspell.base.json', 'missing.json')} | ${app.CheckFailed} | ${true} | ${false} | ${false}
${'--config twice --verbose --verbose'} | ${[...multiArgs('cspell.base.json', 'ci/cspell.ci.json'), '-v', '-v']} | ${app.CheckFailed} | ${true} | ${true} | ${true}
${'--config once --verbose --verbose'} | ${['-r', multiRoot, '**/*.md', '--config', `./${multiRoot}/cspell.base.json`, '-v', '-v']} | ${app.CheckFailed} | ${true} | ${true} | ${true}
`('app $msg Expect Error: $errorCheck', async ({ testArgs, errorCheck, eError, eLog, eInfo }: TestCase) => {
chalk.level = 1;
const commander = getCommander();
Expand Down
23 changes: 21 additions & 2 deletions packages/cspell/src/application.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import { afterEach, describe, expect, test, vi } from 'vitest';

import * as App from './application.mjs';
import { console } from './console.js';
import type { LinterCliOptions, LinterOptions, TraceOptions } from './options.js';
import type { CSpellConfigFile, LinterCliOptions, LinterOptions, TraceOptions } from './options.js';
import { pathPackageRoot, pathSamples } from './test/test.helper.js';
import { asyncIterableToArray } from './util/async.js';
import { InMemoryReporter } from './util/InMemoryReporter.js';
Expand Down Expand Up @@ -201,6 +201,25 @@ describe('Validate the Application', () => {
expect(reporter.issues.map((issue) => issue.text).sort()).toEqual(['ciword', 'rootword']);
});

test.each`
order | expected
${'file, then object'} | ${['baseword', 'ciword', 'closeword', 'fooword', 'rootword']}
${'object, then file'} | ${['baseword', 'ciword', 'closeword', 'colour', 'fooword', 'rootword']}
`('a list of config files merges in order: $order', testOptions, async ({ order, expected }) => {
const root = j(searchRoot, 'multiple-configs');
const base = j(root, 'cspell.base.json');
const ci: CSpellConfigFile = {
url: pathToFileURL(j(root, 'ci/cspell.ci.json')),
settings: { language: 'en-GB', flagWords: ['ciword'] },
};
const config = order === 'file, then object' ? [base, ci] : [ci, base];
const reporter = new InMemoryReporter();
const result = await App.lint(['src/text.md'], { root, config }, reporter);
expect(reporter.errors).toEqual([]);
expect(result).toEqual(oc({ files: 1 }));
expect(reporter.issues.map((issue) => issue.text).sort()).toEqual(expected);
});

test('Tests running the application with no config search', testOptions, async () => {
const files = ['**/*.txt'];
const config = j(searchRoot, 'cspell.temp.json');
Expand Down Expand Up @@ -635,4 +654,4 @@ function sampleTests(): SampleTest[] {
// cspell:enable
}

// cspell:ignore rootword ciword nestedword
// cspell:ignore rootword ciword nestedword baseword closeword fooword colour
3 changes: 0 additions & 3 deletions packages/cspell/src/commandLint.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@ import { DEFAULT_CACHE_LOCATION } from './lint/index.js';
import type { LinterCliCommandOptions, LinterCliOptions } from './options.js';
import { cvtLinterCliCommandOptionsToLinterCliOptions, ReportChoicesAll } from './options.js';
import { canUseColor } from './util/canUseColor.js';
import { configForNamedFiles } from './util/configFileHelper.js';
import { CheckFailed } from './util/errors.js';
import { getOutputWidth } from './util/outputWidth.js';
import { validateUnitSize } from './util/unitNumbers.js';
Expand Down Expand Up @@ -236,8 +235,6 @@ export function commandLint(prog: Command, opts: CommandOptions): Command {

async function action(this: Command, fileGlobs: string[], cliOptions: LinterCliCommandOptions) {
const options = cvtLinterCliCommandOptionsToLinterCliOptions(cliOptions);
const config = await configForNamedFiles(cliOptions.config);
if (config) options.config = config;
// console.error('lint: %o', { fileGlobs, options });
const useExitCode = options.exitCode ?? true;
if (options.skipValidation) {
Expand Down
4 changes: 2 additions & 2 deletions packages/cspell/src/lint/LintRequest.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import type { CSpellUserSettings, UnknownWordsConfiguration } from '@cspell/cspell-types';
import { unknownWordsChoices } from '@cspell/cspell-types';

import type { CSpellConfigFile, LinterCliOptions, LinterOptions } from '../options.js';
import type { LinterCliOptions, LinterOptions } from '../options.js';
import type { FinalizedReporter } from '../reporters/LintFileResult.js';
import { resolveStopFolders } from '../util/configSearchStops.js';
import { applicationAssert } from '../util/errors.js';
Expand Down Expand Up @@ -43,7 +43,7 @@ export async function createLintRequest(
export class LintRequest {
readonly locale: string;

readonly configFile: string | CSpellConfigFile | undefined;
readonly configFile: LinterOptions['config'];
readonly excludes: GlobSrcInfo[];
readonly root: string;
readonly stopConfigSearchAt: URL[] | undefined;
Expand Down
Loading