/
configFileReadWrite.ts
278 lines (234 loc) · 9.1 KB
/
configFileReadWrite.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
import type { CSpellPackageSettings, CSpellSettings } from '@cspell/cspell-types';
import { assign as assignJson, parse as parseJsonc, stringify as stringifyJsonc } from 'comment-json';
import { Uri } from 'vscode';
import { Utils as UriUtils } from 'vscode-uri';
import { parse as parseYaml, stringify as stringifyYaml } from 'yaml';
import type { CSpellUserSettings } from '../client';
import type { ConfigReaderWriter, ConfigUpdateFn } from './configReaderWriter';
import { extractKeys } from './configReaderWriter';
import { vscodeFs as fs } from './fs';
export type { ConfigUpdateFn } from './configReaderWriter';
const SymbolFormat = Symbol('format');
type HandlerDef = { match: RegExp; handler: (uri: Uri) => ConfigFileReaderWriter };
const handlers: HandlerDef[] = [
{ match: /package\.json$/i, handler: (uri) => new ConfigFileReaderWriterPackage(uri) },
{ match: /\.jsonc?$/i, handler: (uri) => new ConfigFileReaderWriterJson(uri) },
{ match: /\.ya?ml$/i, handler: (uri) => new ConfigFileReaderWriterYaml(uri) },
];
const spacesJson = 4;
const spacesPackage = 2;
interface ObjectWithFormatting {
[SymbolFormat]?: ContentFormat;
}
/**
*
* @param uri - uri of the configuration file.
* @param updateFn - function to be called with the config data to be updated. It should only return the fields to be update.
* A fields with a value of `undefined` will be removed from the file.
*
* @returns resolves if successful.
*/
export function updateConfigFile(uri: Uri, updateFn: ConfigUpdateFn): Promise<void> {
const rw = createConfigFileReaderWriter(uri);
return rw._update(updateFn);
}
export function readConfigFile(uri: Uri, defaultValueIfNotFound: CSpellSettings): Promise<CSpellSettings>;
export function readConfigFile(uri: Uri, defaultValueIfNotFound?: CSpellSettings): Promise<CSpellSettings | undefined>;
export async function readConfigFile(uri: Uri, defaultValueIfNotFound?: CSpellSettings): Promise<CSpellSettings | undefined> {
try {
const rw = createConfigFileReaderWriter(uri);
return await rw._read();
} catch (e) {
if (fs.isFileNotFoundError(e)) {
return Promise.resolve(defaultValueIfNotFound);
}
return Promise.reject(e);
}
}
export function writeConfigFile(uri: Uri, cfg: Readonly<CSpellSettings>): Promise<void> {
const rw = createConfigFileReaderWriter(uri);
return rw.write(cfg);
}
export function isHandled(uri: Uri): boolean {
return !!matchHandler(uri);
}
export function createConfigFileReaderWriter(uri: Uri): ConfigFileReaderWriter {
return mustMatchHandler(uri);
}
function mustMatchHandler(uri: Uri): ConfigFileReaderWriter {
const h = matchHandler(uri);
if (h) return h.handler(uri);
throw new UnhandledFileType(uri);
}
function matchHandler(uri: Uri): HandlerDef | undefined {
const u = uri.with({ fragment: '', query: '' });
const s = u.toString();
for (const h of handlers) {
if (!h.match.test(s)) continue;
return h;
}
return undefined;
}
const settingsFileTemplate: CSpellSettings = {
version: '0.2',
ignorePaths: [],
dictionaryDefinitions: [],
dictionaries: [],
words: [],
ignoreWords: [],
import: [],
};
interface PackageWithCSpell {
cspell?: CSpellPackageSettings;
}
function orDefault<T>(p: Promise<T>, defaultValue: T): Promise<T> {
return p.catch((e) => {
if (!fs.isFileNotFoundError(e)) throw e;
return defaultValue;
});
}
export class UnhandledFileType extends Error {
constructor(uri: Uri) {
super(`Unhandled file type: "${UriUtils.basename(uri)}"`);
}
}
export class SysLikeError extends Error {
constructor(
msg?: string,
readonly code?: string,
readonly errno?: number,
) {
super(msg);
}
}
export class FormatError extends Error {
constructor(msg: string) {
super(msg);
}
}
export function parseJson(content: string): CSpellSettings {
const formatting = detectFormatting(content);
const json = parseJsonc(content);
if (json === null || json === undefined) return {};
if (typeof json !== 'object') {
throw new FormatError('Invalid cspell JSON file.');
}
return injectFormatting<CSpellSettings>(json as CSpellSettings, formatting);
}
export function stringifyJson(obj: unknown, spaces?: string | number | undefined, keepComments = true): string {
const formatting = retrieveFormatting(obj);
spaces = formatting?.spaces || spaces || spacesJson;
const newlineAtEndOfFile = formatting?.newlineAtEndOfFile ?? true;
const json = keepComments ? stringifyJsonc(obj, null, spaces) : JSON.stringify(obj, null, spaces);
return newlineAtEndOfFile ? json + '\n' : json;
}
function injectFormatting<T>(s: T, format: ContentFormat): T {
if (s === undefined || s === null || typeof s !== 'object') return s;
(<ObjectWithFormatting>s)[SymbolFormat] = format;
return s;
}
function retrieveFormatting<T>(s: T): ContentFormat | undefined {
if (s === undefined || s === null || typeof s !== 'object') return undefined;
return (<ObjectWithFormatting>s)[SymbolFormat];
}
interface ContentFormat {
spaces: string | number | undefined;
newlineAtEndOfFile: boolean;
}
function hasTrailingNewline(content: string): boolean {
return /\n$/.test(content);
}
function detectIndent(json: string): string | undefined {
const s = json.match(/^[ \t]+(?=")/m);
if (!s) return undefined;
return s[0];
}
function detectFormatting(content: string): ContentFormat {
return {
spaces: detectIndent(content),
newlineAtEndOfFile: hasTrailingNewline(content),
};
}
export interface ConfigFileReaderWriter extends ConfigReaderWriter {
readonly uri: Uri;
_update(fn: ConfigUpdateFn): Promise<void>;
_read(): Promise<CSpellUserSettings>;
}
abstract class AbstractConfigFileReaderWriter implements ConfigFileReaderWriter {
constructor(readonly uri: Uri) {}
async read<K extends keyof CSpellUserSettings>(keys: K[]): Promise<Pick<CSpellUserSettings, K>> {
return extractKeys(await this._read(), keys);
}
abstract _read(): Promise<CSpellUserSettings>;
abstract write(settings: CSpellSettings): Promise<void>;
update<K extends keyof CSpellUserSettings>(fn: ConfigUpdateFn, keys: K[]): Promise<void> {
return this._update((cfg) => fn(extractKeys(cfg, keys)));
}
abstract _update(fn: ConfigUpdateFn): Promise<void>;
async mkdir(): Promise<void> {
return await fs.createDirectory(Uri.joinPath(this.uri, '..'));
}
}
class ConfigFileReaderWriterJson extends AbstractConfigFileReaderWriter {
async _update(updateFn: ConfigUpdateFn): Promise<void> {
const cspell = await orDefault(this._read(), settingsFileTemplate);
const updated = assignJson(cspell, updateFn(cspell));
return this.write(updated);
}
async write(cfg: CSpellSettings): Promise<void> {
await this.mkdir();
const json = stringifyJson(cfg);
const content = json[json.length - 1] !== '\n' ? json + '\n' : json;
return fs.writeFile(this.uri, content);
}
async _read(): Promise<CSpellSettings> {
const uri = this.uri;
const content = await fs.readFile(uri, 'utf8');
const s = parseJson(content) as CSpellSettings;
return s;
}
}
class ConfigFileReaderWriterPackage extends AbstractConfigFileReaderWriter {
async _update(updateFn: ConfigUpdateFn): Promise<void> {
const content = await fs.readFile(this.uri, 'utf8');
const pkg = parseJson(content) as PackageWithCSpell;
const cspell = pkg.cspell || { ...settingsFileTemplate };
pkg.cspell = Object.assign(cspell, updateFn(cspell));
return fs.writeFile(this.uri, stringifyJson(pkg, spacesPackage, false));
}
async write(cfg: CSpellSettings): Promise<void> {
const content = await fs.readFile(this.uri, 'utf8');
const pkg = parseJson(content) as PackageWithCSpell;
pkg.cspell = cfg;
return fs.writeFile(this.uri, stringifyJson(pkg, spacesPackage, false));
}
async _read(): Promise<CSpellSettings> {
const content = await fs.readFile(this.uri, 'utf8');
const pkg = parseJson(content) as { cspell?: CSpellPackageSettings };
if (!pkg.cspell || typeof pkg.cspell !== 'object') {
throw new SysLikeError('`cspell` section missing from package.json', 'ENOENT');
}
return pkg.cspell;
}
}
class ConfigFileReaderWriterYaml extends AbstractConfigFileReaderWriter {
async _update(updateFn: ConfigUpdateFn): Promise<void> {
const cspell = await orDefault(this._read(), settingsFileTemplate);
const updated = Object.assign({}, cspell, updateFn(cspell));
return this.write(updated);
}
async write(cfg: CSpellSettings): Promise<void> {
await this.mkdir();
return fs.writeFile(this.uri, stringifyYaml(cfg));
}
async _read(): Promise<CSpellSettings> {
const content = await fs.readFile(this.uri, 'utf8');
return parseYaml(content) as CSpellSettings;
}
}
export const __testing__ = {
settingsFileTemplate,
detectIndent,
injectFormatting,
SymbolFormat,
};