/
CSpellIONode.ts
81 lines (73 loc) · 2.9 KB
/
CSpellIONode.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
import { isServiceResponseSuccess, ServiceBus } from '@cspell/cspell-service-bus';
import { compareStats } from './common/stat';
import { CSpellIO } from './CSpellIO';
import { ErrorNotImplemented } from './errors/ErrorNotImplemented';
import { registerHandlers } from './handlers/node/file';
import type { TextFileResource } from './models/FileResource';
import type { Stats } from './models/Stats';
import { toURL } from './node/file/util';
import {
RequestFsReadFile,
RequestFsReadFileSync,
RequestFsStat,
RequestFsStatSync,
RequestFsWriteFile,
} from './requests';
let defaultCSpellIONode: CSpellIO | undefined = undefined;
export class CSpellIONode implements CSpellIO {
constructor(readonly serviceBus = new ServiceBus()) {
registerHandlers(serviceBus);
}
readFile(uriOrFilename: string | URL, encoding: BufferEncoding = 'utf8'): Promise<TextFileResource> {
const url = toURL(uriOrFilename);
const res = this.serviceBus.dispatch(RequestFsReadFile.create({ url, encoding }));
if (!isServiceResponseSuccess(res)) {
throw genError(res.error, 'readFile');
}
return res.value;
}
readFileSync(uriOrFilename: string | URL, encoding: BufferEncoding = 'utf8'): TextFileResource {
const url = toURL(uriOrFilename);
const res = this.serviceBus.dispatch(RequestFsReadFileSync.create({ url, encoding }));
if (!isServiceResponseSuccess(res)) {
throw genError(res.error, 'readFileSync');
}
return res.value;
}
writeFile(uriOrFilename: string | URL, content: string): Promise<void> {
const url = toURL(uriOrFilename);
const res = this.serviceBus.dispatch(RequestFsWriteFile.create({ url, content }));
if (!isServiceResponseSuccess(res)) {
throw genError(res.error, 'writeFile');
}
return res.value;
}
getStat(uriOrFilename: string | URL): Promise<Stats> {
const url = toURL(uriOrFilename);
const res = this.serviceBus.dispatch(RequestFsStat.create({ url }));
if (!isServiceResponseSuccess(res)) {
throw genError(res.error, 'getStat');
}
return res.value;
}
getStatSync(uriOrFilename: string | URL): Stats {
const url = toURL(uriOrFilename);
const res = this.serviceBus.dispatch(RequestFsStatSync.create({ url }));
if (!isServiceResponseSuccess(res)) {
throw genError(res.error, 'getStatSync');
}
return res.value;
}
compareStats(left: Stats, right: Stats): number {
return compareStats(left, right);
}
}
function genError(err: Error | undefined, alt: string): Error {
return err || new ErrorNotImplemented(alt);
}
export function getDefaultCSpellIO(): CSpellIO {
if (defaultCSpellIONode) return defaultCSpellIONode;
const cspellIO = new CSpellIONode();
defaultCSpellIONode = cspellIO;
return cspellIO;
}