| 10 | // storage is unfortunately bound to the vscode extension context |
| 11 | // forcing it to be passed in through activation and down to other tools |
| 12 | class Storage<T> { |
| 13 | private key: string |
| 14 | private filePath: string |
| 15 | private storage: vscode.Memento |
| 16 | private defaultValue: T |
| 17 | constructor({ |
| 18 | key, |
| 19 | filePath, |
| 20 | storage, |
| 21 | defaultValue, |
| 22 | }: { |
| 23 | key: string |
| 24 | filePath: string |
| 25 | storage: vscode.Memento |
| 26 | defaultValue: T |
| 27 | }) { |
| 28 | this.storage = storage |
| 29 | this.key = key |
| 30 | this.filePath = filePath |
| 31 | this.defaultValue = defaultValue |
| 32 | } |
| 33 | public get = async (): Promise<T> => { |
| 34 | if (SESSION_STORAGE_PATH) { |
| 35 | try { |
| 36 | // 1. read from file instead of local storage if specified |
| 37 | const sessionFile = await readFile(SESSION_STORAGE_PATH, `${this.filePath}.json`) |
| 38 | if (!sessionFile) { |
| 39 | throw new Error('No session file found') |
| 40 | } |
| 41 | const data: T = JSON.parse(sessionFile) |
| 42 | |
| 43 | if (data) { |
| 44 | // validate session |
| 45 | const keys = Object.keys(data) |
| 46 | if (keys.length) { |
| 47 | return data |
| 48 | } |
| 49 | } |
| 50 | } catch (err: any) { |
| 51 | logger(`Failed to read or parse session file: ${SESSION_STORAGE_PATH}/${this.filePath}.json: ${err.message}`) |
| 52 | } |
| 53 | } |
| 54 | const value: string | undefined = await this.storage.get(this.key) |
| 55 | if (value) { |
| 56 | // 2. read from local storage |
| 57 | try { |
| 58 | return JSON.parse(value) |
| 59 | } catch (err: any) { |
| 60 | logger(`Failed to parse session state from local storage: ${value}: ${err.message}`) |
| 61 | } |
| 62 | } |
| 63 | // 3. fallback to the default |
| 64 | return this.defaultValue |
| 65 | } |
| 66 | public set = (value: T): void => { |
| 67 | const stringValue = JSON.stringify(value) |
| 68 | this.storage.update(this.key, stringValue) |
| 69 | this.writeToSessionFile(stringValue) |
nothing calls this directly
no test coverage detected