Path: blob/main/extensions/copilot/src/util/node/jsonFile.ts
13397 views
/*---------------------------------------------------------------------------------------------1* Copyright (c) Microsoft Corporation. All rights reserved.2* Licensed under the MIT License. See License.txt in the project root for license information.3*--------------------------------------------------------------------------------------------*/45import { readFile, writeFile } from 'fs/promises';6import { TaskQueue } from '../common/async';7import { deepClone } from '../vs/base/common/objects';89export class JSONFile<T> {10public static async readOrCreate<T>(filePath: string, initialValue: T, indent: string | number = 4): Promise<JSONFile<T>> {11let data: T = initialValue;1213const result = await readFileTextOrUndefined(filePath);14if (result !== undefined) {15const parsed = tryParseJson(result) as T | undefined;16if (parsed !== undefined) {17data = parsed;18}19}2021return new JSONFile(filePath, data, indent);22}2324private _value: T;25public get value(): Readonly<T> { return deepClone(this._value); }2627private constructor(28public readonly filePath: string,29initialValue: T,30private readonly indent: string | number = 4,31) {32this._value = initialValue;33}3435private readonly _writeQueue = new TaskQueue();3637async setValue(value: T): Promise<void> {38this._value = value;39this._writeQueue.clearPending();40await this._writeQueue.scheduleSkipIfCleared(() => this._write());41}4243private async _write(): Promise<void> {44await writeFile(this.filePath, JSON.stringify(this._value, null, this.indent), { encoding: 'utf8' });45}46}4748export async function readFileTextOrUndefined(filePath: string): Promise<string | undefined> {49try {50return await readFile(filePath, 'utf8');51}52catch (e) {53if (e.code === 'ENOENT') {54return undefined;55}56throw e;57}58}5960export function tryParseJson(str: string): unknown | undefined {61try {62return JSON.parse(str);63} catch (e) {64if (e instanceof SyntaxError) {65console.error(e);66return undefined;67}68throw e;69}70}717273