Skip to content
Open
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
24 changes: 24 additions & 0 deletions packages/cspell/src/app.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -406,6 +406,30 @@ describe('Validate cli', () => {
expect(parsed[1]).toEqual({ filename: pathRoot('missing-file.txt'), error: 'File not found' });
});

test('check reports a config file that cannot be read', async () => {
const commander = getCommander();
const args = argv('check', '--config', pathSamples('missing-config.json'), pathRoot('LICENSE'));
await expect(app.run(commander, args)).rejects.toThrow(app.CheckFailed);

expect(error).toHaveBeenCalledWith(expect.stringContaining('Configuration Error: Failed to read config file'));
});

test('check --json reports a config file that cannot be read', async () => {
const commander = getCommander();
const args = argv('check', '--json', '--config', pathSamples('missing-config.json'), pathRoot('LICENSE'));
await expect(app.run(commander, args)).rejects.toThrow(app.CheckFailed);

const parsed = parseCheckJsonOutput();
expect(parsed).toHaveLength(1);
expect(parsed[0].error).toContain('Configuration Error: Failed to read config file');
});

test('dictionaries reports a config file that cannot be read', async () => {
const commander = getCommander();
const args = argv('dictionaries', '--config', pathSamples('missing-config.json'));
await expect(app.run(commander, args)).rejects.toThrow(/Configuration Error: Failed to read config file/);
});

test('check --json --no-exit-code sets exitCode 0 while still emitting JSON', async () => {
chalk.level = 1;
const commander = getCommander();
Expand Down
6 changes: 4 additions & 2 deletions packages/cspell/src/application.mts
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ import type { BaseOptions, LegacyOptions, LinterCliOptions, SuggestionOptions, T
import { fixLegacy } from './options.js';
import { simpleRepl } from './repl/index.js';
import { finalizeReporter } from './reporters/index.js';
import { readConfig, toConfigList } from './util/configFileHelper.js';
import { assertNoConfigErrors, readConfig, toConfigList } from './util/configFileHelper.js';
import { fileInfoToDocument, readFileInfo } from './util/fileHelper.js';
import { readStdin } from './util/stdin.js';
import { getTimeMeasurer } from './util/timer.js';
Expand Down Expand Up @@ -98,7 +98,9 @@ export async function checkText(filename: string, options: BaseOptions & LegacyO
return checkTextDocument(doc, util.clean({ validateDirectives }), settingsFromCommandLine);
}
// The named configs replace the search for a config near the document.
const { config } = await readConfig(configFiles, undefined);
const configInfo = await readConfig(configFiles, undefined);
assertNoConfigErrors(configInfo);
const { config } = configInfo;
const settings = mergeSettings(settingsFromCommandLine, config);
return checkTextDocument(doc, util.clean({ validateDirectives, noConfigSearch: true }), settings);
}
Expand Down
8 changes: 6 additions & 2 deletions packages/cspell/src/commandCheck.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import { checkText } from './application.mjs';
import { collect } from './commandHelpers.js';
import { console } from './console.js';
import type { BaseOptions } from './options.js';
import { CheckFailed } from './util/errors.js';
import { ApplicationError, CheckFailed } from './util/errors.js';

type CheckCommandOptions = BaseOptions & { json: boolean };

Expand Down Expand Up @@ -71,6 +71,10 @@ async function processRequestAnsi(files: string[], options: CheckCommandOptions)
}
console.log();
} catch (e) {
if (e instanceof ApplicationError && !isErrNoEnt(e)) {
console.error(e.message);
throw new CheckFailed(e.message, e.exitCode);
}
const message = isErrNoEnt(e) ? 'File not found' : String(e);
console.error(`${message} "${filename}"`);
throw new CheckFailed(message, 1);
Expand Down Expand Up @@ -102,7 +106,7 @@ async function processRequestJSON(files: string[], options: CheckCommandOptions)
issueCount += item.isError ? 1 : 0;
}
} catch (e) {
const message = isErrNoEnt(e) ? 'File not found' : String(e);
const message = isErrNoEnt(e) ? 'File not found' : e instanceof ApplicationError ? e.message : String(e);
results.push({ filename, error: message });
console.log(JSON.stringify(results, undefined, 2));
throw new CheckFailed(message, 1);
Expand Down
3 changes: 2 additions & 1 deletion packages/cspell/src/dictionaries/listDictionaries.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import {
} from 'cspell-lib';

import type { DictionariesOptions } from '../options.js';
import { readConfig } from '../util/configFileHelper.js';
import { assertNoConfigErrors, readConfig } from '../util/configFileHelper.js';

export interface ListDictionariesResult {
/**
Expand Down Expand Up @@ -165,6 +165,7 @@ function extractSpecialDictionaries(config: CSpellSettingsWithSourceTrace): List

export async function listDictionaries(options: DictionariesOptions): Promise<ListDictionariesResult[]> {
const configFile = await readConfig(options.config, undefined);
assertNoConfigErrors(configFile);
const loadDefault = options.defaultConfiguration ?? configFile.config.loadDefaultConfiguration ?? true;

const configBase = mergeSettings(
Expand Down
14 changes: 13 additions & 1 deletion packages/cspell/src/util/configFileHelper.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import { afterEach, describe, expect, test, vi } from 'vitest';

import { environmentKeys } from '../environment.js';
import { pathPackageRoot } from '../test/test.helper.js';
import { readConfig } from '../util/configFileHelper.js';
import { assertNoConfigErrors, readConfig } from '../util/configFileHelper.js';

const root = pathPackageRoot;
const samples = path.resolve(root, 'samples');
Expand Down Expand Up @@ -69,6 +69,18 @@ describe('Config File Helper', () => {
expect(readConfigResult.urls).toEqual([pathToFileURL(rootConfig)]);
});

test('assertNoConfigErrors throws for a config file that cannot be read', async () => {
const result = await readConfig(j(samples, 'nonexistent.json'), undefined);

expect(() => assertNoConfigErrors(result)).toThrow(/^Configuration Error: Failed to read config file/);
});

test('assertNoConfigErrors accepts a config file that can be read', async () => {
const result = await readConfig(j(environmentSamples, 'cspell.yaml'), undefined);

expect(() => assertNoConfigErrors(result)).not.toThrow();
});

test('handles malformed config file gracefully', async () => {
const malformedPath = j(samples, 'cspell-bad.json');
process.env[environmentKeys.CSPELL_CONFIG_PATH] = malformedPath;
Expand Down
10 changes: 10 additions & 0 deletions packages/cspell/src/util/configFileHelper.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import * as cspell from 'cspell-lib';

import { environmentKeys, getEnvironmentVariable } from '../environment.js';
import type { BaseOptions, CSpellConfigFile } from '../options.js';
import { ApplicationError } from './errors.js';
import { filenameToUrl } from './fileHelper.js';

export interface ConfigInfo {
Expand Down Expand Up @@ -63,6 +64,15 @@ async function configFilesToConfigInfo(cfgFiles: CSpellConfigFile[]): Promise<Co
return { config, urls: cfgFiles.map((cfgFile) => cfgFile.url), foundBySearch: false };
}

/**
* Throw when a config file could not be read or imported, as `lint` does.
*/
export function assertNoConfigErrors(configInfo: ConfigInfo): void {
const [first] = cspell.extractImportErrors(configInfo.config);
if (!first) return;
throw new ApplicationError(`Configuration Error: ${first.error.message}`, 1, first.error);
}

export function toConfigList(configFile: BaseOptions['config']): (string | CSpellConfigFile)[] {
if (configFile === undefined) return [];
return Array.isArray(configFile) ? configFile : [configFile];
Expand Down