/
configLoader.ts
736 lines (628 loc) · 27.4 KB
/
configLoader.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
import type { CSpellUserSettings, ImportFileRef, Source } from '@cspell/cspell-types';
import assert from 'assert';
import type { CSpellConfigFile, CSpellConfigFileReaderWriter, IO, TextFile } from 'cspell-config-lib';
import { createReaderWriter, CSpellConfigFileInMemory } from 'cspell-config-lib';
import { isUrlLike, toFileURL } from 'cspell-io';
import path from 'path';
import { fileURLToPath, pathToFileURL } from 'url';
import { URI, Utils as UriUtils } from 'vscode-uri';
import { srcDirectory } from '../../../../lib-cjs/index.cjs';
import { onClearCache } from '../../../events/index.js';
import type { VFileSystem } from '../../../fileSystem.js';
import { getVirtualFS } from '../../../fileSystem.js';
import { createCSpellSettingsInternal as csi } from '../../../Models/CSpellSettingsInternalDef.js';
import { AutoResolveCache } from '../../../util/AutoResolve.js';
import { logError, logWarning } from '../../../util/logger.js';
import { FileResolver } from '../../../util/resolveFile.js';
import { envToTemplateVars } from '../../../util/templates.js';
import {
addTrailingSlash,
cwdURL,
resolveFileWithURL,
toFilePathOrHref,
toFileUrl,
windowsDriveLetterToUpper,
} from '../../../util/url.js';
import {
configSettingsFileVersion0_1,
configSettingsFileVersion0_2,
currentSettingsFileVersion,
defaultConfigFileModuleRef,
ENV_CSPELL_GLOB_ROOT,
} from '../../constants.js';
import { getMergeStats, mergeSettings } from '../../CSpellSettingsServer.js';
import { getGlobalConfig } from '../../GlobalSettings.js';
import { ImportError } from '../ImportError.js';
import type { LoaderResult } from '../pnpLoader.js';
import { pnpLoader } from '../pnpLoader.js';
import { searchPlaces } from './configLocations.js';
import { ConfigSearch } from './configSearch.js';
import { configToRawSettings } from './configToRawSettings.js';
import { defaultSettings } from './defaultSettings.js';
import {
normalizeCacheSettings,
normalizeDictionaryDefs,
normalizeGitignoreRoot,
normalizeImport,
normalizeLanguageSettings,
normalizeOverrides,
normalizeReporters,
normalizeSettingsGlobs,
} from './normalizeRawSettings.js';
import type { PnPSettingsOptional } from './PnPSettings.js';
import { defaultPnPSettings, normalizePnPSettings } from './PnPSettings.js';
import type { CSpellSettingsI, CSpellSettingsWST } from './types.js';
type CSpellSettingsVersion = Exclude<CSpellUserSettings['version'], undefined>;
const supportedCSpellConfigVersions: CSpellSettingsVersion[] = [configSettingsFileVersion0_2];
const setOfSupportedConfigVersions = Object.freeze(new Set<string>(supportedCSpellConfigVersions));
export const sectionCSpell = 'cSpell';
export const defaultFileName = 'cspell.json';
interface ImportedConfigEntry {
/** href of the configFile URL, this is the key to the cache. */
href: string;
/** The fileRef used. */
fileRef: ImportFileRef;
/** resolved config file */
configFile: CSpellConfigFile | undefined;
/** resolved settings */
settings: CSpellSettingsI | undefined;
isReady: boolean;
/** Resolved when the settings have been fully resolved. */
onReady: Promise<CSpellSettingsI>;
/** Resolved when the config file has been loaded. */
onConfigFileReady: Promise<CSpellConfigFile | Error>;
/** Set of all references used to catch circular references */
referencedSet: Set<string>;
}
let defaultConfigLoader: ConfigLoaderInternal | undefined = undefined;
interface CacheMergeConfigFileWithImports {
// cfgFile: CSpellConfigFile;
pnpSettings: PnPSettingsOptional | undefined;
referencedBy: string[] | undefined;
result: Promise<CSpellSettingsI>;
}
export interface IConfigLoader {
readSettingsAsync(
filename: string | URL,
relativeTo?: string | URL,
pnpSettings?: PnPSettingsOptional,
): Promise<CSpellSettingsI>;
/**
* Read a cspell configuration file.
* @param filenameOrURL - URL, relative path, absolute path, or package name.
* @param relativeTo - optional URL, defaults to `pathToFileURL('./')`
*/
readConfigFile(filenameOrURL: string | URL, relativeTo?: string | URL): Promise<CSpellConfigFile | Error>;
searchForConfigFileLocation(searchFrom: URL | string | undefined): Promise<URL | undefined>;
searchForConfigFile(searchFrom: URL | string | undefined): Promise<CSpellConfigFile | undefined>;
/**
* This is an alias for `searchForConfigFile` and `mergeConfigFileWithImports`.
* @param searchFrom the directory / file URL to start searching from.
* @param pnpSettings - related to Using Yarn PNP.
* @returns the resulting settings
*/
searchForConfig(
searchFrom: URL | string | undefined,
pnpSettings?: PnPSettingsOptional,
): Promise<CSpellSettingsI | undefined>;
resolveConfigFileLocation(filenameOrURL: string | URL, relativeTo?: string | URL): Promise<URL | undefined>;
getGlobalSettingsAsync(): Promise<CSpellSettingsI>;
/**
* The loader caches configuration files for performance. This method clears the cache.
*/
clearCachedSettingsFiles(): void;
/**
* Resolve imports and merge.
* @param cfgFile - configuration file.
* @param pnpSettings - optional settings related to Using Yarn PNP.
*/
mergeConfigFileWithImports(
cfgFile: CSpellConfigFile,
pnpSettings?: PnPSettingsOptional | undefined,
): Promise<CSpellSettingsI>;
/**
* Create an in memory CSpellConfigFile.
* @param filename - URL to the file. Used to resolve imports.
* @param settings - settings to use.
*/
createCSpellConfigFile(filename: URL | string, settings: CSpellUserSettings): CSpellConfigFile;
/**
* Unsubscribe from any events and dispose of any resources including caches.
*/
dispose(): void;
getStats(): Readonly<Record<string, Readonly<Record<string, number>>>>;
readonly isTrusted: boolean;
setIsTrusted(isTrusted: boolean): void;
}
const defaultExtensions = ['.json', '.yaml', '.yml', '.jsonc'];
const defaultJsExtensions = ['.js', '.cjs', '.mjs'];
const trustedSearch: Map<string, readonly string[]> = new Map([
['*', defaultExtensions],
['file:', [...defaultExtensions, ...defaultJsExtensions]],
]);
const unTrustedSearch: Map<string, readonly string[]> = new Map([['*', defaultExtensions]]);
export class ConfigLoader implements IConfigLoader {
public onReady: Promise<void>;
readonly fileResolver: FileResolver;
private _isTrusted = true;
/**
* Use `createConfigLoader`
* @param virtualFs - virtual file system to use.
*/
protected constructor(
readonly fs: VFileSystem,
readonly templateVariables: Record<string, string> = envToTemplateVars(process.env),
) {
this.configSearch = new ConfigSearch(searchPlaces, trustedSearch, fs);
this.cspellConfigFileReaderWriter = createReaderWriter(undefined, undefined, createIO(fs));
this.fileResolver = new FileResolver(fs, this.templateVariables);
this.onReady = this.init();
this.subscribeToEvents();
}
private subscribeToEvents() {
this.toDispose.push(onClearCache(() => this.clearCachedSettingsFiles()));
}
protected cachedConfig = new Map<string, ImportedConfigEntry>();
protected cachedConfigFiles = new Map<string, CSpellConfigFile>();
protected cachedPendingConfigFile = new AutoResolveCache<string, Promise<CSpellConfigFile | Error>>();
protected cachedMergedConfig = new WeakMap<CSpellConfigFile, CacheMergeConfigFileWithImports>();
protected globalSettings: CSpellSettingsI | undefined;
protected cspellConfigFileReaderWriter: CSpellConfigFileReaderWriter;
protected configSearch: ConfigSearch;
protected toDispose: { dispose: () => void }[] = [];
public async readSettingsAsync(
filename: string | URL,
relativeTo?: string | URL,
pnpSettings?: PnPSettingsOptional,
): Promise<CSpellSettingsI> {
await this.onReady;
const ref = await this.resolveFilename(filename, relativeTo || pathToFileURL('./'));
const entry = this.importSettings(ref, pnpSettings || defaultPnPSettings, []);
return entry.onReady;
}
public async readConfigFile(
filenameOrURL: string | URL,
relativeTo?: string | URL,
): Promise<CSpellConfigFile | Error> {
const ref = await this.resolveFilename(filenameOrURL.toString(), relativeTo || pathToFileURL('./'));
const url = toFileURL(ref.filename);
const href = url.href;
if (ref.error) return new ImportError(`Failed to read config file: "${ref.filename}"`, ref.error);
const cached = this.cachedConfigFiles.get(href);
if (cached) return cached;
return this.cachedPendingConfigFile.get(href, async () => {
try {
const file = await this.cspellConfigFileReaderWriter.readConfig(href);
this.cachedConfigFiles.set(href, file);
// validateRawConfigVersion(file);
return file;
} catch (error) {
// console.warn('Debug: %o', { href, error });
return new ImportError(`Failed to read config file: "${ref.filename}"`, error);
} finally {
setTimeout(() => this.cachedPendingConfigFile.delete(href), 1);
}
});
}
async searchForConfigFileLocation(searchFrom: URL | string | undefined): Promise<URL | undefined> {
const url = toFileURL(searchFrom || cwdURL(), cwdURL());
if (typeof searchFrom === 'string' && !isUrlLike(searchFrom) && url.protocol === 'file:') {
// check to see if it is a directory
if (await isDirectory(this.fs, url)) {
return this.configSearch.searchForConfig(addTrailingSlash(url));
}
}
return this.configSearch.searchForConfig(url);
}
async searchForConfigFile(searchFrom: URL | string | undefined): Promise<CSpellConfigFile | undefined> {
const location = await this.searchForConfigFileLocation(searchFrom);
if (!location) return undefined;
const file = await this.readConfigFile(location);
return file instanceof Error ? undefined : file;
}
/**
*
* @param searchFrom the directory / file URL to start searching from.
* @param pnpSettings - related to Using Yarn PNP.
* @returns the resulting settings
*/
async searchForConfig(
searchFrom: URL | string | undefined,
pnpSettings: PnPSettingsOptional = defaultPnPSettings,
): Promise<CSpellSettingsI | undefined> {
const configFile = await this.searchForConfigFile(searchFrom);
if (!configFile) return undefined;
return this.mergeConfigFileWithImports(configFile, pnpSettings);
}
public getGlobalSettings(): CSpellSettingsI {
assert(this.globalSettings, 'Global settings not loaded');
return this.globalSettings;
}
public async getGlobalSettingsAsync(): Promise<CSpellSettingsI> {
if (!this.globalSettings) {
const globalConfFile = await getGlobalConfig();
const normalized = await this.mergeConfigFileWithImports(globalConfFile, undefined);
normalized.id ??= 'global_config';
this.globalSettings = normalized;
}
return this.globalSettings;
}
public clearCachedSettingsFiles(): void {
this.globalSettings = undefined;
this.cachedConfig.clear();
this.cachedConfigFiles.clear();
this.configSearch.clearCache();
this.cachedPendingConfigFile.clear();
this.cspellConfigFileReaderWriter.clearCachedFiles();
this.cachedMergedConfig = new WeakMap<CSpellConfigFile, CacheMergeConfigFileWithImports>();
this.prefetchGlobalSettingsAsync();
}
protected init(): Promise<void> {
this.onReady = Promise.all([this.prefetchGlobalSettingsAsync(), this.resolveDefaultConfig()]).then(
() => undefined,
);
return this.onReady;
}
protected async prefetchGlobalSettingsAsync(): Promise<void> {
await this.getGlobalSettingsAsync().catch((e) => logError(e));
}
protected async resolveDefaultConfig() {
const r = await this.fileResolver.resolveFile(defaultConfigFileModuleRef, srcDirectory);
const url = toFileURL(r.filename);
this.cspellConfigFileReaderWriter.setTrustedUrls([new URL('../..', url)]);
return url;
}
protected importSettings(
fileRef: ImportFileRef,
pnpSettings: PnPSettingsOptional | undefined,
backReferences: string[],
): ImportedConfigEntry {
const url = toFileURL(fileRef.filename);
const cacheKey = url.href;
const cachedImport = this.cachedConfig.get(cacheKey);
if (cachedImport) {
backReferences.forEach((ref) => cachedImport.referencedSet.add(ref));
return cachedImport;
}
if (fileRef.error) {
const settings = csi({
__importRef: fileRef,
source: { name: fileRef.filename, filename: fileRef.filename },
});
const importedConfig: ImportedConfigEntry = {
href: cacheKey,
fileRef,
configFile: undefined,
settings,
isReady: true,
onReady: Promise.resolve(settings),
onConfigFileReady: Promise.resolve(fileRef.error),
referencedSet: new Set(backReferences),
};
this.cachedConfig.set(cacheKey, importedConfig);
return importedConfig;
}
const source: Source = {
name: fileRef.filename,
filename: fileRef.filename,
};
const mergeImports = (cfgFile: CSpellConfigFile | Error) => {
if (cfgFile instanceof Error) {
fileRef.error = cfgFile;
return csi({ __importRef: fileRef, source });
}
return this.mergeConfigFileWithImports(cfgFile, pnpSettings, backReferences);
};
const referencedSet = new Set(backReferences);
const onConfigFileReady = onConfigFileReadyFixUp(this.readConfigFile(fileRef.filename));
const importedConfig: ImportedConfigEntry = {
href: cacheKey,
fileRef,
configFile: undefined,
settings: undefined,
isReady: false,
onReady: onReadyFixUp(onConfigFileReady.then(mergeImports)),
onConfigFileReady,
referencedSet,
};
this.cachedConfig.set(cacheKey, importedConfig);
return importedConfig;
async function onReadyFixUp(pSettings: Promise<CSpellSettingsI>): Promise<CSpellSettingsI> {
const settings = await pSettings;
settings.source ??= source;
settings.__importRef ??= fileRef;
importedConfig.isReady = true;
importedConfig.settings = settings;
return settings;
}
async function onConfigFileReadyFixUp(
pCfgFile: Promise<CSpellConfigFile | Error>,
): Promise<CSpellConfigFile | Error> {
const cfgFile = await pCfgFile;
if (cfgFile instanceof Error) {
importedConfig.fileRef.error = cfgFile;
return cfgFile;
}
source.name = cfgFile.settings.name || source.name;
importedConfig.configFile = cfgFile;
return cfgFile;
}
}
private async setupPnp(cfgFile: CSpellConfigFile, pnpSettings: PnPSettingsOptional | undefined) {
if (!pnpSettings?.usePnP || pnpSettings === defaultPnPSettings) return;
if (cfgFile.url.protocol !== 'file:') return;
// Try to load any .pnp files before reading dictionaries or other config files.
const { usePnP = pnpSettings.usePnP, pnpFiles = pnpSettings.pnpFiles } = cfgFile.settings;
const pnpSettingsToUse: PnPSettingsOptional = normalizePnPSettings({ usePnP, pnpFiles });
const pathToSettingsDir = new URL('.', cfgFile.url);
await loadPnP(pnpSettingsToUse, pathToSettingsDir);
}
public mergeConfigFileWithImports(
cfgFile: CSpellConfigFile,
pnpSettings: PnPSettingsOptional | undefined,
referencedBy?: string[] | undefined,
): Promise<CSpellSettingsI> {
const cached = this.cachedMergedConfig.get(cfgFile);
if (cached && cached.pnpSettings === pnpSettings && cached.referencedBy === referencedBy) {
return cached.result;
}
// console.warn('missing cache %o', cfgFile.url.href);
const result = this._mergeConfigFileWithImports(cfgFile, pnpSettings, referencedBy);
this.cachedMergedConfig.set(cfgFile, { pnpSettings, referencedBy, result });
return result;
}
private async _mergeConfigFileWithImports(
cfgFile: CSpellConfigFile,
pnpSettings: PnPSettingsOptional | undefined,
referencedBy: string[] = [],
): Promise<CSpellSettingsI> {
await this.setupPnp(cfgFile, pnpSettings);
const href = cfgFile.url.href;
const referencedSet = new Set(referencedBy);
const imports = normalizeImport(cfgFile.settings.import);
const __imports = await Promise.all(imports.map((name) => this.resolveFilename(name, cfgFile.url)));
const toImport = __imports.map((ref) => this.importSettings(ref, pnpSettings, [...referencedBy, href]));
// Add ourselves to the import sources.
toImport.forEach((entry) => {
entry.referencedSet.add(href);
});
const pendingImports: (Promise<CSpellSettingsI> | CSpellUserSettings)[] = toImport.map((entry) => {
// Detect circular references, return raw settings if circular.
return referencedSet.has(entry.href)
? entry.settings || configToRawSettings(entry.configFile)
: entry.onReady;
});
const importSettings = await Promise.all(pendingImports);
const cfg = await this.mergeImports(cfgFile, importSettings);
return cfg;
}
/**
* normalizeSettings handles correcting all relative paths, anchoring globs, and importing other config files.
* @param rawSettings - raw configuration settings
* @param pathToSettingsFile - path to the source file of the configuration settings.
*/
protected async mergeImports(
cfgFile: CSpellConfigFile,
importedSettings: CSpellUserSettings[],
): Promise<CSpellSettingsI> {
const rawSettings = configToRawSettings(cfgFile);
const url = cfgFile.url;
const fileRef = rawSettings.__importRef;
const source = rawSettings.source;
assert(source);
// Fix up dictionaryDefinitions
const settings = {
version: defaultSettings.version,
...rawSettings,
globRoot: resolveGlobRoot(rawSettings, cfgFile.url),
languageSettings: normalizeLanguageSettings(rawSettings.languageSettings),
};
const normalizedDictionaryDefs = normalizeDictionaryDefs(settings, url);
const normalizedSettingsGlobs = normalizeSettingsGlobs(settings, url);
const normalizedOverrides = normalizeOverrides(settings, url);
const normalizedReporters = await normalizeReporters(settings, url);
const normalizedGitignoreRoot = normalizeGitignoreRoot(settings, url);
const normalizedCacheSettings = normalizeCacheSettings(settings, url);
const fileSettings: CSpellSettingsI = csi({
...settings,
source,
...normalizedDictionaryDefs,
...normalizedSettingsGlobs,
...normalizedOverrides,
...normalizedReporters,
...normalizedGitignoreRoot,
...normalizedCacheSettings,
});
if (!importedSettings.length) {
return fileSettings;
}
const mergedImportedSettings = importedSettings.reduce((a, b) => mergeSettings(a, b));
const finalizeSettings = mergeSettings(mergedImportedSettings, fileSettings);
finalizeSettings.name = settings.name || finalizeSettings.name || '';
finalizeSettings.id = settings.id || finalizeSettings.id || '';
if (fileRef) {
finalizeSettings.__importRef = fileRef;
}
return finalizeSettings;
}
createCSpellConfigFile(filename: URL | string, settings: CSpellUserSettings): CSpellConfigFile {
return new CSpellConfigFileInMemory(toFileURL(filename), settings);
}
dispose() {
while (this.toDispose.length) {
try {
this.toDispose.pop()?.dispose();
} catch (e) {
logError(e);
}
}
}
getStats() {
return { ...getMergeStats() };
}
async resolveConfigFileLocation(filenameOrURL: string | URL, relativeTo: string | URL): Promise<URL | undefined> {
const r = await this.fileResolver.resolveFile(filenameOrURL, relativeTo);
return r.found ? toFileURL(r.filename) : undefined;
}
private async resolveFilename(filename: string | URL, relativeTo: string | URL): Promise<ImportFileRef> {
if (filename instanceof URL) return { filename: toFilePathOrHref(filename) };
if (isUrlLike(filename)) return { filename: toFilePathOrHref(filename) };
const r = await this.fileResolver.resolveFile(filename, relativeTo);
if (r.warning) {
logWarning(r.warning);
}
return {
filename: r.filename.startsWith('file:/') ? fileURLToPath(r.filename) : r.filename,
error: r.found ? undefined : new ConfigurationLoaderFailedToResolveError(filename, relativeTo),
};
}
get isTrusted() {
return this._isTrusted;
}
setIsTrusted(isTrusted: boolean) {
this._isTrusted = isTrusted;
this.clearCachedSettingsFiles();
this.configSearch = new ConfigSearch(searchPlaces, isTrusted ? trustedSearch : unTrustedSearch, this.fs);
this.cspellConfigFileReaderWriter.setUntrustedExtensions(isTrusted ? [] : defaultJsExtensions);
}
}
class ConfigLoaderInternal extends ConfigLoader {
constructor(vfs: VFileSystem) {
super(vfs);
}
get _cachedFiles() {
return this.cachedConfig;
}
}
export function loadPnP(pnpSettings: PnPSettingsOptional, searchFrom: URL): Promise<LoaderResult> {
if (!pnpSettings.usePnP) {
return Promise.resolve(undefined);
}
const loader = pnpLoader(pnpSettings.pnpFiles);
return loader.load(searchFrom);
}
const nestedConfigDirectories: Record<string, true> = {
'.vscode': true,
'.config': true, // this should be removed in the future, but it is a breaking change.
};
function resolveGlobRoot(settings: CSpellSettingsWST, urlSettingsFile: URL): string {
const urlSettingsFileDir = new URL('.', urlSettingsFile);
const uriSettingsFileDir = URI.parse(urlSettingsFileDir.href);
const settingsFileDirName = UriUtils.basename(uriSettingsFileDir);
const isNestedConfig = settingsFileDirName in nestedConfigDirectories;
const isVSCode = settingsFileDirName === '.vscode';
const settingsFileDir = (isNestedConfig ? UriUtils.dirname(uriSettingsFileDir) : uriSettingsFileDir).toString();
const envGlobRoot = process.env[ENV_CSPELL_GLOB_ROOT];
const defaultGlobRoot = envGlobRoot ?? '${cwd}';
const rawRoot =
settings.globRoot ??
(settings.version === configSettingsFileVersion0_1 ||
(envGlobRoot && !settings.version) ||
(isVSCode && !settings.version)
? defaultGlobRoot
: settingsFileDir);
const globRoot = rawRoot.startsWith('${cwd}') ? rawRoot : resolveFileWithURL(rawRoot, new URL(settingsFileDir));
return typeof globRoot === 'string'
? globRoot
: globRoot.protocol === 'file:'
? windowsDriveLetterToUpper(path.resolve(fileURLToPath(globRoot)))
: addTrailingSlash(globRoot).href;
}
function validationMessage(msg: string, url: URL) {
return msg + `\n File: "${toFilePathOrHref(url)}"`;
}
function validateRawConfigVersion(config: CSpellConfigFile): void {
const { version } = config.settings;
if (version === undefined) return;
if (typeof version !== 'string') {
logError(validationMessage(`Unsupported config file version: "${version}", string expected`, config.url));
return;
}
if (setOfSupportedConfigVersions.has(version)) return;
if (!/^\d+(\.\d+)*$/.test(version)) {
logError(validationMessage(`Unsupported config file version: "${version}"`, config.url));
return;
}
const msg =
version > currentSettingsFileVersion
? `Newer config file version found: "${version}". Supported version is "${currentSettingsFileVersion}"`
: `Legacy config file version found: "${version}", upgrade to "${currentSettingsFileVersion}"`;
logWarning(validationMessage(msg, config.url));
}
function createConfigLoaderInternal(fs?: VFileSystem) {
return new ConfigLoaderInternal(fs ?? getVirtualFS().fs);
}
export function createConfigLoader(fs?: VFileSystem): IConfigLoader {
return createConfigLoaderInternal(fs);
}
export function getDefaultConfigLoaderInternal(): ConfigLoaderInternal {
if (defaultConfigLoader) return defaultConfigLoader;
return (defaultConfigLoader = createConfigLoaderInternal());
}
function createIO(fs: VFileSystem): IO {
const readFile = (url: URL) => fs.readFile(url).then((file) => ({ url: file.url, content: file.getText() }));
const writeFile = (file: TextFile) => fs.writeFile(file);
return {
readFile,
writeFile,
};
}
async function isDirectory(fs: VFileSystem, path: URL): Promise<boolean> {
try {
return (await fs.stat(path)).isDirectory();
} catch (e) {
return false;
}
}
export class ConfigurationLoaderError extends Error {
constructor(
message: string,
public readonly configurationFile?: string,
public readonly relativeTo?: string | URL,
cause?: unknown,
) {
super(message);
this.name = 'Configuration Loader Error';
if (cause) {
this.cause = cause;
}
}
}
export class ConfigurationLoaderFailedToResolveError extends ConfigurationLoaderError {
constructor(
public readonly configurationFile: string,
public readonly relativeTo: string | URL,
cause?: unknown,
) {
const filename = configurationFile.startsWith('file:/') ? fileURLToPath(configurationFile) : configurationFile;
const relSource = relativeToCwd(relativeTo);
const message = `Failed to resolve configuration file: "${filename}" referenced from "${relSource}"`;
super(message, configurationFile, relativeTo, cause);
// this.name = 'Configuration Loader Error';
}
}
function relativeToCwd(file: string | URL): string {
const url = toFileUrl(file);
const cwdPath = cwdURL().pathname.split('/').slice(0, -1);
const urlPath = url.pathname.split('/');
if (urlPath[0] !== cwdPath[0]) return toFilePathOrHref(file);
let i = 0;
for (; i < cwdPath.length; ++i) {
if (cwdPath[i] !== urlPath[i]) break;
}
const segments = cwdPath.length - i;
if (segments > 3) return toFilePathOrHref(file);
const prefix = '.'
.repeat(segments)
.split('')
.map(() => '..')
.join('/');
return [prefix || '.', ...urlPath.slice(i)].join('/');
}
export const __testing__ = {
getDefaultConfigLoaderInternal,
normalizeCacheSettings,
validateRawConfigVersion,
resolveGlobRoot,
relativeToCwd,
};