forked from rstackjs/rstack-cli
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcacheStore.ts
More file actions
182 lines (155 loc) · 5.11 KB
/
Copy pathcacheStore.ts
File metadata and controls
182 lines (155 loc) · 5.11 KB
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
import { randomUUID } from 'node:crypto';
import { mkdir, readFile, rename, rm, writeFile } from 'node:fs/promises';
import path from 'node:path';
const fmtCacheFileName = 'v1.json';
const fmtCacheVersion = 1;
type FmtCacheState = 'clean' | 'dirty' | 'unsupported';
type FmtCacheEntry =
| readonly [contentHash: string, optionsHash: string, state: 'clean' | 'dirty']
| readonly [contentHash: string | null, optionsHash: string, state: 'unsupported'];
interface FmtCacheFile {
version: typeof fmtCacheVersion;
namespace: string;
files: Record<string, FmtCacheEntry>;
}
interface FmtCacheStore {
get(filePath: string): FmtCacheEntry | undefined;
set(filePath: string, entry: FmtCacheEntry): void;
/** Persists changed entries and returns whether the cache file was replaced. */
save(): Promise<boolean>;
}
const createEmptyCache = (namespace: string): FmtCacheFile => ({
version: fmtCacheVersion,
namespace,
files: Object.create(null) as Record<string, FmtCacheEntry>,
});
const parseCacheEntry = (value: unknown): FmtCacheEntry | undefined => {
if (!Array.isArray(value) || value.length !== 3 || typeof value[1] !== 'string') {
return;
}
if (value[2] === 'unsupported') {
return value[0] === null || typeof value[0] === 'string'
? [value[0], value[1], value[2]]
: undefined;
}
if (typeof value[0] !== 'string' || (value[2] !== 'clean' && value[2] !== 'dirty')) {
return;
}
return [value[0], value[1], value[2]];
};
const parseCacheFile = (content: string): FmtCacheFile | undefined => {
let value: unknown;
try {
value = JSON.parse(content);
} catch {
return;
}
if (
typeof value !== 'object' ||
value === null ||
Array.isArray(value) ||
!('version' in value) ||
value.version !== fmtCacheVersion ||
!('namespace' in value) ||
typeof value.namespace !== 'string' ||
!('files' in value) ||
typeof value.files !== 'object' ||
value.files === null ||
Array.isArray(value.files)
) {
return;
}
const files = Object.create(null) as Record<string, FmtCacheEntry>;
for (const [filePath, rawEntry] of Object.entries(value.files)) {
const entry = parseCacheEntry(rawEntry);
if (!entry) {
return;
}
files[filePath] = entry;
}
return {
version: fmtCacheVersion,
namespace: value.namespace,
files,
};
};
const serializeCache = (cache: FmtCacheFile): string => `${JSON.stringify(cache)}\n`;
const isFileNotFoundError = (error: unknown): error is NodeJS.ErrnoException =>
error instanceof Error && 'code' in error && error.code === 'ENOENT';
const getTemporaryPath = (filePath: string): string =>
path.join(
path.dirname(filePath),
`.${path.basename(filePath)}.${process.pid}.${randomUUID()}.tmp`,
);
class FmtCacheStoreImpl implements FmtCacheStore {
readonly #filePath: string;
readonly #cache: FmtCacheFile;
#savedContent: string | undefined;
#changed: boolean;
constructor(
filePath: string,
cache: FmtCacheFile,
savedContent: string | undefined,
changed: boolean,
) {
this.#filePath = filePath;
this.#cache = cache;
this.#savedContent = savedContent;
this.#changed = changed;
}
get(filePath: string): FmtCacheEntry | undefined {
return this.#cache.files[filePath];
}
set(filePath: string, entry: FmtCacheEntry): void {
const current = this.#cache.files[filePath];
if (current?.[0] === entry[0] && current[1] === entry[1] && current[2] === entry[2]) {
return;
}
this.#cache.files[filePath] =
entry[2] === 'unsupported'
? [entry[0], entry[1], 'unsupported']
: [entry[0], entry[1], entry[2]];
this.#changed = true;
}
async save(): Promise<boolean> {
if (!this.#changed) {
return false;
}
const content = serializeCache(this.#cache);
if (content === this.#savedContent) {
this.#changed = false;
return false;
}
const temporaryPath = getTemporaryPath(this.#filePath);
try {
await mkdir(path.dirname(this.#filePath), { recursive: true });
await writeFile(temporaryPath, content);
await rename(temporaryPath, this.#filePath);
this.#savedContent = content;
this.#changed = false;
return true;
} catch {
return false;
} finally {
await rm(temporaryPath, { force: true }).catch(() => undefined);
}
}
}
const loadFmtCacheStore = async (filePath: string, namespace: string): Promise<FmtCacheStore> => {
const emptyCache = createEmptyCache(namespace);
try {
const content = await readFile(filePath, 'utf8');
const cache = parseCacheFile(content);
if (!cache) {
return new FmtCacheStoreImpl(filePath, emptyCache, undefined, true);
}
return cache.namespace === namespace
? new FmtCacheStoreImpl(filePath, cache, content, false)
: new FmtCacheStoreImpl(filePath, emptyCache, undefined, true);
} catch (error) {
const missing = isFileNotFoundError(error);
return new FmtCacheStoreImpl(filePath, emptyCache, undefined, !missing);
}
};
export { fmtCacheFileName, fmtCacheVersion, loadFmtCacheStore };
export type { FmtCacheEntry, FmtCacheFile, FmtCacheState, FmtCacheStore };