feat: add coding project schema v2 migration
This commit is contained in:
27
electron/coding-projects/atomic-json.ts
Normal file
27
electron/coding-projects/atomic-json.ts
Normal file
@@ -0,0 +1,27 @@
|
||||
import { randomUUID } from 'node:crypto';
|
||||
import { mkdir, readFile, rename, rm, writeFile } from 'node:fs/promises';
|
||||
import path from 'node:path';
|
||||
|
||||
export type JsonFileWriter = (filePath: string, value: unknown) => Promise<void>;
|
||||
|
||||
export async function atomicWriteText(filePath: string, source: string): Promise<void> {
|
||||
await mkdir(path.dirname(filePath), { recursive: true });
|
||||
const temporaryPath = path.join(
|
||||
path.dirname(filePath),
|
||||
`.${path.basename(filePath)}.${randomUUID()}.tmp`,
|
||||
);
|
||||
try {
|
||||
await writeFile(temporaryPath, source, { encoding: 'utf8', flag: 'wx' });
|
||||
await rename(temporaryPath, filePath);
|
||||
} finally {
|
||||
await rm(temporaryPath, { force: true }).catch(() => undefined);
|
||||
}
|
||||
}
|
||||
|
||||
export async function atomicWriteJson(filePath: string, value: unknown): Promise<void> {
|
||||
await atomicWriteText(filePath, `${JSON.stringify(value, null, 2)}\n`);
|
||||
}
|
||||
|
||||
export async function readJsonFile(filePath: string): Promise<unknown> {
|
||||
return JSON.parse(await readFile(filePath, 'utf8')) as unknown;
|
||||
}
|
||||
Reference in New Issue
Block a user