diff --git a/packages/cspell-lib/api/api.d.ts b/packages/cspell-lib/api/api.d.ts index 7c977f64ceb4..936efacb1b35 100644 --- a/packages/cspell-lib/api/api.d.ts +++ b/packages/cspell-lib/api/api.d.ts @@ -356,6 +356,12 @@ interface IConfigLoader { * @param pnpSettings - optional settings related to Using Yarn PNP. */ mergeConfigFileWithImports(cfgFile: CSpellConfigFile$1, pnpSettings?: PnPSettingsOptional | undefined): Promise; + /** + * 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$1 | ICSpellConfigFile$1)[]): Promise; /** * Create an in memory CSpellConfigFile. * @param filename - URL to the file. Used to resolve imports. @@ -396,6 +402,13 @@ export declare function searchForConfig(searchFrom: URL | string | undefined, op export declare function loadConfig(file: string, pnpSettings?: PnPSettingsOptional): Promise; export declare function readConfigFile(filename: string | URL, relativeTo?: string | URL): Promise; export declare function resolveConfigFileImports(configFile: CSpellConfigFile$1 | ICSpellConfigFile$1): Promise; +/** + * 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 declare function resolveConfigFiles(configFiles: readonly (CSpellConfigFile$1 | ICSpellConfigFile$1)[]): Promise; /** * Might throw if the settings have not yet been loaded. * @deprecated use {@link getGlobalSettingsAsync} instead. diff --git a/packages/cspell-lib/src/index.ts b/packages/cspell-lib/src/index.ts index 5fc07909fb44..dc1670859490 100644 --- a/packages/cspell-lib/src/index.ts +++ b/packages/cspell-lib/src/index.ts @@ -102,6 +102,7 @@ export { readSettingsFiles, refreshDictionaryCache, resolveConfigFileImports, + resolveConfigFiles, resolveFile, searchForConfig, sectionCSpell, diff --git a/packages/cspell-lib/src/lib/Settings/Controller/configLoader/configLoader.test.ts b/packages/cspell-lib/src/lib/Settings/Controller/configLoader/configLoader.test.ts index 73a0156baf1c..f7e2b8b14f27 100644 --- a/packages/cspell-lib/src/lib/Settings/Controller/configLoader/configLoader.test.ts +++ b/packages/cspell-lib/src/lib/Settings/Controller/configLoader/configLoader.test.ts @@ -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); } diff --git a/packages/cspell-lib/src/lib/Settings/Controller/configLoader/configLoader.ts b/packages/cspell-lib/src/lib/Settings/Controller/configLoader/configLoader.ts index 3a2fd4dc26d5..c222d6e5b498 100644 --- a/packages/cspell-lib/src/lib/Settings/Controller/configLoader/configLoader.ts +++ b/packages/cspell-lib/src/lib/Settings/Controller/configLoader/configLoader.ts @@ -158,6 +158,13 @@ export interface IConfigLoader { pnpSettings?: PnPSettingsOptional | undefined, ): Promise; + /** + * 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; + /** * Create an in memory CSpellConfigFile. * @param filename - URL to the file. Used to resolve imports. @@ -499,6 +506,16 @@ export class ConfigLoader implements IConfigLoader { return result; } + public async mergeConfigFilesWithImports( + cfgFiles: readonly (CSpellConfigFile | ICSpellConfigFile)[], + ): Promise { + 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, diff --git a/packages/cspell-lib/src/lib/Settings/Controller/configLoader/defaultConfigLoader.test.ts b/packages/cspell-lib/src/lib/Settings/Controller/configLoader/defaultConfigLoader.test.ts index 67fa82b432cd..ce4a08cb44a9 100644 --- a/packages/cspell-lib/src/lib/Settings/Controller/configLoader/defaultConfigLoader.test.ts +++ b/packages/cspell-lib/src/lib/Settings/Controller/configLoader/defaultConfigLoader.test.ts @@ -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', () => { @@ -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'] })); + }); }); diff --git a/packages/cspell-lib/src/lib/Settings/Controller/configLoader/defaultConfigLoader.ts b/packages/cspell-lib/src/lib/Settings/Controller/configLoader/defaultConfigLoader.ts index e40850601145..98cce31ade01 100644 --- a/packages/cspell-lib/src/lib/Settings/Controller/configLoader/defaultConfigLoader.ts +++ b/packages/cspell-lib/src/lib/Settings/Controller/configLoader/defaultConfigLoader.ts @@ -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 { + return gcl().mergeConfigFilesWithImports(configFiles); +} + /** * Might throw if the settings have not yet been loaded. * @deprecated use {@link getGlobalSettingsAsync} instead. diff --git a/packages/cspell-lib/src/lib/Settings/Controller/configLoader/index.ts b/packages/cspell-lib/src/lib/Settings/Controller/configLoader/index.ts index 33a93d1a5c08..cca6ee95dddb 100644 --- a/packages/cspell-lib/src/lib/Settings/Controller/configLoader/index.ts +++ b/packages/cspell-lib/src/lib/Settings/Controller/configLoader/index.ts @@ -19,6 +19,7 @@ export { readConfigFile, readRawSettings, resolveConfigFileImports, + resolveConfigFiles, resolveSettingsImports, searchForConfig, searchForConfigWithResolvedStops, diff --git a/packages/cspell-lib/src/lib/Settings/index.ts b/packages/cspell-lib/src/lib/Settings/index.ts index 7492310f20b1..086ab1f2e587 100644 --- a/packages/cspell-lib/src/lib/Settings/index.ts +++ b/packages/cspell-lib/src/lib/Settings/index.ts @@ -19,6 +19,7 @@ export { readSettings, readSettingsFiles, resolveConfigFileImports, + resolveConfigFiles, resolveSettingsImports, searchForConfig, searchForConfigWithResolvedStops, diff --git a/packages/cspell-lib/src/lib/__snapshots__/index.test.ts.snap b/packages/cspell-lib/src/lib/__snapshots__/index.test.ts.snap index 5c5fe4bcdae0..18d2dc218a2d 100644 --- a/packages/cspell-lib/src/lib/__snapshots__/index.test.ts.snap +++ b/packages/cspell-lib/src/lib/__snapshots__/index.test.ts.snap @@ -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", diff --git a/packages/cspell-lib/src/lib/index.ts b/packages/cspell-lib/src/lib/index.ts index 602c29b18c89..18f0606676dd 100644 --- a/packages/cspell-lib/src/lib/index.ts +++ b/packages/cspell-lib/src/lib/index.ts @@ -60,6 +60,7 @@ export { readSettings, readSettingsFiles, resolveConfigFileImports, + resolveConfigFiles, searchForConfig, sectionCSpell, toCSpellSettingsWithOutSourceTrace, diff --git a/packages/cspell/src/__snapshots__/app.test.ts.snap b/packages/cspell/src/__snapshots__/app.test.ts.snap index 73f15b690c97..0740806df026 100644 --- a/packages/cspell/src/__snapshots__/app.test.ts.snap +++ b/packages/cspell/src/__snapshots__/app.test.ts.snap @@ -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`] = ` @@ -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 diff --git a/packages/cspell/src/app.test.ts b/packages/cspell/src/app.test.ts index 116d4dd0adc3..d0a7437af889 100644 --- a/packages/cspell/src/app.test.ts +++ b/packages/cspell/src/app.test.ts @@ -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(); diff --git a/packages/cspell/src/application.test.ts b/packages/cspell/src/application.test.ts index 97e0c582ab4f..febcd623d28f 100644 --- a/packages/cspell/src/application.test.ts +++ b/packages/cspell/src/application.test.ts @@ -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'; @@ -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'); @@ -635,4 +654,4 @@ function sampleTests(): SampleTest[] { // cspell:enable } -// cspell:ignore rootword ciword nestedword +// cspell:ignore rootword ciword nestedword baseword closeword fooword colour diff --git a/packages/cspell/src/commandLint.ts b/packages/cspell/src/commandLint.ts index 503c122b0c06..728a268c7853 100644 --- a/packages/cspell/src/commandLint.ts +++ b/packages/cspell/src/commandLint.ts @@ -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'; @@ -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) { diff --git a/packages/cspell/src/lint/LintRequest.ts b/packages/cspell/src/lint/LintRequest.ts index cf2e7efaadf2..23fc339a579e 100644 --- a/packages/cspell/src/lint/LintRequest.ts +++ b/packages/cspell/src/lint/LintRequest.ts @@ -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'; @@ -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; diff --git a/packages/cspell/src/lint/lint.ts b/packages/cspell/src/lint/lint.ts index 8f450bffdabb..0ab3d3c478d3 100644 --- a/packages/cspell/src/lint/lint.ts +++ b/packages/cspell/src/lint/lint.ts @@ -212,8 +212,11 @@ export async function runLint(cfg: LintRequest): Promise { } function configOption(configInfo: ConfigInfo): string { - if (typeof cfg.configFile === 'object') return configInfo.urls.map((url) => relativeToCwd(url)).join(', '); - return cfg.configFile || 'default'; + const configFiles = Array.isArray(cfg.configFile) ? cfg.configFile : [cfg.configFile]; + const [first] = configFiles; + if (first === undefined) return 'default'; + if (configFiles.length === 1 && typeof first === 'string') return first; + return configInfo.urls.map((url) => relativeToCwd(url)).join(', '); } function getProcessFileOptions( diff --git a/packages/cspell/src/options.ts b/packages/cspell/src/options.ts index 5bd63d957df4..84882442ea00 100644 --- a/packages/cspell/src/options.ts +++ b/packages/cspell/src/options.ts @@ -138,9 +138,10 @@ export interface LinterOptions extends Omit, CacheOptions skipValidation?: boolean; /** - * Path to configuration file. + * The configuration file to use, or a list of them. + * A list merges in the order given: later files override earlier ones. */ - config?: string | CSpellConfigFile; + config?: string | CSpellConfigFile | (string | CSpellConfigFile)[]; /** * Specify the maximum file size to be checked. @@ -490,7 +491,7 @@ export interface CSpellConfigFile { } export function cvtLinterCliCommandOptionsToLinterCliOptions(options: LinterCliCommandOptions): LinterCliOptions { - const { verbose: verboseLevel, config: _config, ...optionsRest } = options; + const { verbose: verboseLevel, ...optionsRest } = options; const cliOptions: LinterCliOptions = { ...optionsRest }; if (verboseLevel) { cliOptions.verboseLevel = verboseLevel; diff --git a/packages/cspell/src/util/configFileHelper.test.ts b/packages/cspell/src/util/configFileHelper.test.ts index 93692d9648b5..b547cec7b3b8 100644 --- a/packages/cspell/src/util/configFileHelper.test.ts +++ b/packages/cspell/src/util/configFileHelper.test.ts @@ -2,13 +2,12 @@ import * as path from 'node:path'; import { pathToFileURL } from 'node:url'; import { toFileDirURL } from '@cspell/url'; -import { CSpellConfigFileInMemory } from 'cspell-config-lib'; import { searchForConfig } from 'cspell-lib'; import { afterEach, describe, expect, test, vi } from 'vitest'; import { environmentKeys } from '../environment.js'; import { pathPackageRoot } from '../test/test.helper.js'; -import { configForNamedFiles, readConfig } from '../util/configFileHelper.js'; +import { readConfig } from '../util/configFileHelper.js'; const root = pathPackageRoot; const samples = path.resolve(root, 'samples'); @@ -84,35 +83,59 @@ describe('Config File Helper', () => { expect(resultConfig).toHaveProperty('__importRef'); }); - test.each` - files | expected - ${undefined} | ${undefined} - ${[]} | ${undefined} - ${['cspell.json']} | ${'cspell.json'} - `('configForNamedFiles $files', async ({ files, expected }) => { - await expect(configForNamedFiles(files)).resolves.toBe(expected); - }); - - test('several named files are imported by URL, in order', async () => { + test('several named files merge in the order given', async () => { const multiple = path.relative(process.cwd(), j(samples, 'config-search/multiple-configs')); const files = [j(multiple, 'ci/cspell.ci.json'), j(multiple, 'cspell.base.json')]; - const urls = files.map((file) => pathToFileURL(path.resolve(file))); - const configFile = await configForNamedFiles(files); - - expect(configFile).toBeInstanceOf(CSpellConfigFileInMemory); - expect(configFile).toHaveProperty( - ['settings', 'import'], - urls.map((url) => url.href), - ); - const result = await readConfig(configFile, undefined); + const result = await readConfig(files, undefined); - expect(result.urls).toEqual(urls); + expect(result.urls).toEqual(files.map((file) => pathToFileURL(path.resolve(file)))); expect(result.foundBySearch).toBe(false); expect(result.config.language).toBe('en'); expect(result.config.flagWords).toEqual(['ciword', 'baseword']); }); + test('a list can mix names and config files', async () => { + const base = j(samples, 'config-search/multiple-configs/cspell.base.json'); + const configFile = { + url: new URL('memory/cspell.json', pathToFileURL(samples + path.sep)), + settings: { words: ['memory'] }, + }; + + const result = await readConfig([base, configFile], undefined); + + expect(result.urls).toEqual([pathToFileURL(base), configFile.url]); + expect(result.config.flagWords).toEqual(['baseword']); + expect(result.config.words).toEqual(['memory']); + }); + + test.each` + configFile + ${''} + ${['']} + `('an empty config name $configFile is a config error', async ({ configFile }) => { + const result = await readConfig(configFile, environmentSamples); + + expect(result.foundBySearch).toBe(false); + expect(result.config).toHaveProperty(['__importRef', 'error'], expect.any(Error)); + }); + + test('an empty CSPELL_CONFIG_PATH counts as unset', async () => { + process.env[environmentKeys.CSPELL_CONFIG_PATH] = ''; + + const result = await readConfig(undefined, environmentSamples); + + expect(result.urls).toEqual([pathToFileURL(j(environmentSamples, 'cspell.yaml'))]); + expect(result.foundBySearch).toBe(true); + }); + + test('an empty list searches for a config', async () => { + const result = await readConfig([], environmentSamples); + + expect(result.urls).toEqual([pathToFileURL(j(environmentSamples, 'cspell.yaml'))]); + expect(result.foundBySearch).toBe(true); + }); + test('a folder named as the config is listed as given', async () => { const folder = j(samples, 'config-search') + path.sep; diff --git a/packages/cspell/src/util/configFileHelper.ts b/packages/cspell/src/util/configFileHelper.ts index 8019cee0d3c7..3143b6910a4b 100644 --- a/packages/cspell/src/util/configFileHelper.ts +++ b/packages/cspell/src/util/configFileHelper.ts @@ -1,10 +1,8 @@ -import { toFileDirURL, toFileURL } from '@cspell/url'; -import { CSpellConfigFileInMemory } from 'cspell-config-lib'; import type { CSpellUserSettings } from 'cspell-lib'; import * as cspell from 'cspell-lib'; import { environmentKeys, getEnvironmentVariable } from '../environment.js'; -import type { CSpellConfigFile } from '../options.js'; +import type { CSpellConfigFile, LinterOptions } from '../options.js'; import { filenameToUrl } from './fileHelper.js'; export interface ConfigInfo { @@ -27,15 +25,20 @@ export interface FileConfigInfo { } export async function readConfig( - configFile: string | CSpellConfigFile | undefined, + configFile: LinterOptions['config'], root: string | undefined, stopConfigSearchAt?: URL[] | undefined, ): Promise { - configFile ??= getEnvironmentVariable(environmentKeys.CSPELL_CONFIG_PATH); + const envConfigFile = getEnvironmentVariable(environmentKeys.CSPELL_CONFIG_PATH); + const given = toConfigList(configFile); + // An empty environment variable counts as unset. + const named = given.length ? given : envConfigFile ? [envConfigFile] : []; - if (configFile) { - const cfgFile = typeof configFile === 'string' ? await readConfigHandleError(configFile) : configFile; - return configFileToConfigInfo(cfgFile); + if (named.length) { + const cfgFiles = await Promise.all( + named.map((cfg) => (typeof cfg === 'string' ? readConfigHandleError(cfg) : cfg)), + ); + return configFilesToConfigInfo(cfgFiles); } const config = await cspell.searchForConfig(root, { stopSearchAt: stopConfigSearchAt }); @@ -43,7 +46,7 @@ export async function readConfig( if (!config && defaultConfigFile) { const cfgFile = await readConfigFile(defaultConfigFile).catch(() => undefined); if (cfgFile) { - return configFileToConfigInfo(cfgFile); + return configFilesToConfigInfo([cfgFile]); } } @@ -55,30 +58,14 @@ export async function readConfig( }; } -/** - * The config for the `--config` files. - * Several files become an in-memory config that imports them in the order given. - * Each file is read as a single `--config` is, and imported by its URL. - */ -export async function configForNamedFiles(files: string[] | undefined): Promise { - if (!files?.length) return undefined; - if (files.length === 1) return files[0]; - const configFiles = await Promise.all(files.map((file) => readConfigHandleError(file))); - const url = toFileURL('cspell-command-line.json', toFileDirURL(process.cwd())); - return new CSpellConfigFileInMemory(url, { import: configFiles.map((cfgFile) => cfgFile.url.href) }); +async function configFilesToConfigInfo(cfgFiles: CSpellConfigFile[]): Promise { + const config = await cspell.resolveConfigFiles(cfgFiles); + return { config, urls: cfgFiles.map((cfgFile) => cfgFile.url), foundBySearch: false }; } -async function configFileToConfigInfo(cfgFile: CSpellConfigFile): Promise { - const config = await cspell.resolveConfigFileImports(cfgFile); - // An in-memory config has no file of its own: the files it imports are the ones loaded. - const urls = cfgFile instanceof CSpellConfigFileInMemory ? importUrls(cfgFile) : [cfgFile.url]; - return { config, urls, foundBySearch: false }; -} - -function importUrls(cfgFile: CSpellConfigFile): URL[] { - const imports = cfgFile.settings.import; - const names = typeof imports === 'string' ? [imports] : imports || []; - return names.map((name) => toFileURL(name, cfgFile.url)); +function toConfigList(configFile: LinterOptions['config']): (string | CSpellConfigFile)[] { + if (configFile === undefined) return []; + return Array.isArray(configFile) ? configFile : [configFile]; } export function readConfigFile(filename: string | URL): Promise {